@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,809 @@
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
+ import * as prom_client from 'prom-client';
26
+ import express, { Express, Router } from 'express';
27
+ import http from 'node:http';
28
+ import https from 'node:https';
29
+ import { CatbeeServerConfig, CatbeeServerHooks } from '@catbee/utils/types';
30
+
31
+ /**
32
+ * Map of critical dependencies to their error messages.
33
+ */
34
+ declare const DependencyErrors: {
35
+ express: string;
36
+ helmet: string;
37
+ cors: string;
38
+ compression: string;
39
+ 'express-rate-limit': string;
40
+ 'cookie-parser': string;
41
+ '@scalar/express-api-reference': string;
42
+ 'prom-client': string;
43
+ };
44
+ /**
45
+ * Production-ready Express server with enterprise features.
46
+ *
47
+ * Core Features:
48
+ * - Security: Helmet, CORS, rate limiting, timeouts
49
+ * - Monitoring: Request logs, metrics, health checks
50
+ * - Performance: Compression, caching, static files
51
+ * - Reliability: Graceful shutdown, error handling
52
+ * - Developer UX: OpenAPI docs, debugging tools
53
+ * - Extensibility: Hooks, middleware, custom routes
54
+ *
55
+ * Designed for microservices and production workloads.
56
+ * Includes K8s readiness probes and zero-downtime support.
57
+ */
58
+ declare class ExpressServer {
59
+ /** Prometheus client registry for metrics collection */
60
+ private readonly register;
61
+ /** HTTP server instance (null when not running) */
62
+ protected server: http.Server | https.Server | null;
63
+ /** Merged configuration with defaults applied */
64
+ protected config: CatbeeServerConfig;
65
+ /** User-defined lifecycle hooks */
66
+ protected hooks: CatbeeServerHooks;
67
+ /** Global API prefix (from config) */
68
+ protected globalPrefix: string;
69
+ /** Internal fallback router */
70
+ private readonly rootRouter;
71
+ /** User-supplied router */
72
+ private externalRouter?;
73
+ /** Internal Express app instance */
74
+ private readonly app;
75
+ /** Set of active WebSocket connections */
76
+ private readonly connections;
77
+ /** Flag indicating if the server is shutting down */
78
+ private isShuttingDown;
79
+ /**
80
+ * Collection of registered health check functions.
81
+ * These are executed when the health check endpoint is accessed.
82
+ */
83
+ private readonly healthChecks;
84
+ /** Prometheus metrics for monitoring */
85
+ private readonly requestCounter?;
86
+ private readonly routeTimings?;
87
+ private readonly requestSizes?;
88
+ private readonly clientIPs?;
89
+ /** Promise that resolves when initialization (middleware + routes) is complete */
90
+ private readonly initPromise;
91
+ /**
92
+ * Initializes server with intelligent defaults and security best practices.
93
+ * All settings can be customized via config and hooks.
94
+ *
95
+ * Default Security:
96
+ * - Secure headers (Helmet)
97
+ * - Rate limiting
98
+ * - Request timeouts
99
+ * - Body size limits
100
+ * - CORS protection
101
+ *
102
+ * Default Monitoring:
103
+ * - Request/Response logging
104
+ * - Prometheus metrics
105
+ * - Health checks
106
+ * - Request tracing
107
+ */
108
+ constructor(config: Partial<CatbeeServerConfig>, hooks?: CatbeeServerHooks);
109
+ /**
110
+ * Execute a lifecycle hook safely with comprehensive error handling.
111
+ * Prevents hook failures from crashing the server while logging issues.
112
+ *
113
+ * @param hook Name of the lifecycle hook to execute
114
+ * @param args Arguments to pass to the hook function
115
+ */
116
+ private runHook;
117
+ /**
118
+ * Initialize the Express server with middleware and routes.
119
+ */
120
+ private initialize;
121
+ /**
122
+ * Configure and register all middlewares in the optimal order.
123
+ *
124
+ * Middleware Order (CRITICAL - don't change without understanding implications):
125
+ * 1. Basic server configuration (trust proxy, x-powered-by)
126
+ * 2. Request ID generation (for tracing)
127
+ * 3. Request context setup (for logging correlation)
128
+ * 4. Timeout protection (prevents hanging requests)
129
+ * 5. Response time tracking (for performance monitoring)
130
+ * 6. Request logging (after ID/context setup)
131
+ * 7. Custom request hooks
132
+ * 8. Security middleware (rate limiting, CORS, Helmet)
133
+ * 9. Response compression
134
+ * 10. Static file serving
135
+ * 11. Request parsing (body parsing, cookies)
136
+ * 12. API documentation (OpenAPI)
137
+ * 13. Global headers
138
+ * 14. Custom response hooks
139
+ */
140
+ protected setupMiddleware(): Promise<void>;
141
+ /**
142
+ * Configure server routes and error handling.
143
+ * Sets up in following order:
144
+ *
145
+ * 1. Built-in routes (health, metrics)
146
+ * 2. Application routes
147
+ * 3. 404 handler
148
+ * 4. Error handler
149
+ */
150
+ protected setupRoutes(): Promise<void>;
151
+ /**
152
+ * Register a new health check function for monitoring service dependencies.
153
+ *
154
+ * Health checks are executed when the health endpoint is accessed and
155
+ * help determine if the service is ready to handle requests.
156
+ *
157
+ * Examples:
158
+ * - Database connectivity
159
+ * - External service availability
160
+ * - File system access
161
+ * - Memory/CPU usage checks
162
+ *
163
+ * @param name Unique identifier for the check (used in detailed responses)
164
+ * @param check Function returning boolean or Promise<boolean> indicating health
165
+ * @returns This instance for method chaining
166
+ */
167
+ registerHealthCheck(name: string, check: () => Promise<boolean> | boolean): this;
168
+ /**
169
+ * Run registered health checks and return whether the service is ready.
170
+ * Useful for readiness probes in deployment tooling.
171
+ *
172
+ * @returns Promise resolving to `true` when all checks pass, otherwise `false`.
173
+ */
174
+ ready(): Promise<boolean>;
175
+ /**
176
+ * Get the underlying Express application instance.
177
+ * Use this for advanced Express features not exposed by this wrapper.
178
+ *
179
+ * @returns The raw Express app instance
180
+ */
181
+ getApp(): Express;
182
+ /**
183
+ * Get the active HTTP/HTTPS server instance.
184
+ * Returns null if the server is not currently running.
185
+ *
186
+ * @returns The HTTP/HTTPS server instance or null
187
+ */
188
+ getServer(): http.Server | https.Server | null;
189
+ /**
190
+ * Start the HTTP server and begin listening for requests.
191
+ *
192
+ * This method:
193
+ * - Executes beforeStart hooks
194
+ * - Binds to the configured host/port
195
+ * - Sets up error handling for startup failures
196
+ * - Executes afterStart hooks on success
197
+ * - Logs startup information
198
+ *
199
+ * @returns Promise resolving to the running HTTP server instance
200
+ * @throws Error if server fails to start or port is already in use
201
+ */
202
+ start(): Promise<http.Server | https.Server>;
203
+ /**
204
+ * Stop the HTTP server gracefully.
205
+ *
206
+ * This method:
207
+ * - Executes beforeStop hooks
208
+ * - Stops accepting new connections
209
+ * - Waits for existing connections to finish
210
+ * - Closes the server
211
+ * - Executes afterStop hooks
212
+ * - Logs shutdown information
213
+ *
214
+ * Graceful shutdown ensures:
215
+ * - No requests are dropped
216
+ * - Resources are properly cleaned up
217
+ * - Monitoring systems are notified
218
+ */
219
+ stop(force?: boolean): Promise<void>;
220
+ /**
221
+ * Enable graceful shutdown on OS signals for production deployment.
222
+ *
223
+ * This is essential for:
224
+ * - Container orchestration (Docker, Kubernetes)
225
+ * - Process managers (PM2, systemd)
226
+ * - Load balancer health checks
227
+ * - Zero-downtime deployments
228
+ *
229
+ * @param signals Array of process signals to listen for (default: SIGINT, SIGTERM)
230
+ */
231
+ enableGracefulShutdown(signals?: NodeJS.Signals[]): this;
232
+ /**
233
+ * Set an externally created base router.
234
+ * This will override the internal rootRouter.
235
+ */
236
+ setBaseRouter(router: Router): this;
237
+ /**
238
+ * Create and register a new router (only used if not injecting one externally - use `setBaseRouter` instead).
239
+ */
240
+ createRouter(prefix?: string): Router;
241
+ /**
242
+ * Register a new route handler with support for multiple HTTP methods.
243
+ * The route is automatically registered under the globalPrefix if set.
244
+ *
245
+ * @param methods Array of HTTP methods (get, post, put, delete, etc.)
246
+ * @param path Route path with Express path patterns support
247
+ * @param handlers One or more Express request handlers (middleware + final handler)
248
+ * @returns This instance for method chaining
249
+ */
250
+ registerRoute(methods: Array<keyof Pick<Express, 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head'>>, path: string, ...handlers: Array<express.RequestHandler>): this;
251
+ /**
252
+ * Register custom middleware with optional path restriction.
253
+ *
254
+ * Use this for:
255
+ * - Adding authentication to specific routes
256
+ * - Custom logging or validation
257
+ * - Request transformation
258
+ * - Third-party middleware integration
259
+ *
260
+ * @param path Optional path prefix or middleware function if no path
261
+ * @param middleware Middleware handler (required if path is provided)
262
+ * @returns This instance for method chaining
263
+ */
264
+ registerMiddleware(path: string | express.RequestHandler, middleware?: express.RequestHandler): this;
265
+ /**
266
+ * Register one or more middleware functions to be applied globally.
267
+ * This is a simpler alternative to registerMiddleware when you just want
268
+ * to add middleware without path restrictions.
269
+ *
270
+ * @param middlewares One or more Express middleware functions
271
+ * @returns This instance for method chaining
272
+ */
273
+ useMiddleware(...middlewares: express.RequestHandler[]): this;
274
+ /**
275
+ * Get Prometheus registry (to add custom counters/histograms)
276
+ *
277
+ * @return {*} {client.Registry}
278
+ */
279
+ getMetricsRegistry(): typeof prom_client.Registry;
280
+ /**
281
+ * Get server configuration
282
+ *
283
+ * @return {*} {CatbeeServerConfig}
284
+ */
285
+ getConfig(): CatbeeServerConfig;
286
+ /**
287
+ * Wait until server initialization (middleware + routes) has completed.
288
+ * Useful for integration tests that inspect app before starting.
289
+ */
290
+ waitUntilReady(): Promise<void>;
291
+ private normalizePath;
292
+ private normalizeRouteForMetrics;
293
+ /**
294
+ * Destroy all active connections (gracefully if possible).
295
+ * If a connection does not close cleanly, it will be force-destroyed.
296
+ */
297
+ private destroyConnections;
298
+ private validateHttpsFiles;
299
+ private hasBuildMarker;
300
+ private throwDependancyError;
301
+ }
302
+
303
+ /**
304
+ * Builder class for creating and configuring an Express server configuration.
305
+ *
306
+ * This class provides a fluent interface to configure all aspects of the Express server
307
+ * including security settings, middleware, routing, and more.
308
+ *
309
+ * @example
310
+ * ```typescript
311
+ * const serverConfig = new ServerConfigBuilder()
312
+ * .withPort(3000)
313
+ * .withHost('localhost')
314
+ * .enableCors()
315
+ * .enableHelmet()
316
+ * .build();
317
+ * ```
318
+ */
319
+ declare class ServerConfigBuilder {
320
+ private config;
321
+ /**
322
+ * Validates that a port number is valid and usable.
323
+ *
324
+ * @private
325
+ * @param port - The port number to validate
326
+ * @throws {Error} If port is not an integer or is outside the valid range (1-65535)
327
+ */
328
+ private validatePort;
329
+ /**
330
+ * Sets the port the server will listen on.
331
+ *
332
+ * @param port - The port number (1-65535)
333
+ * @returns The builder instance for chaining
334
+ * @throws {Error} If port is invalid
335
+ * @default 3000 (can be overridden via PORT env variable)
336
+ *
337
+ * @example
338
+ * ```typescript
339
+ * builder.withPort(3000)
340
+ * ```
341
+ */
342
+ withPort(port: number): this;
343
+ /**
344
+ * Sets the hostname the server will bind to.
345
+ *
346
+ * @param host - The hostname (e.g., 'localhost', '0.0.0.0', '127.0.0.1')
347
+ * @returns The builder instance for chaining
348
+ * @default '0.0.0.0' (can be overridden via HOST env variable)
349
+ *
350
+ * @example
351
+ * ```typescript
352
+ * builder.withHost('0.0.0.0') // Listen on all interfaces
353
+ * ```
354
+ */
355
+ withHost(host: string): this;
356
+ /**
357
+ * Configures Cross-Origin Resource Sharing (CORS) for the server.
358
+ *
359
+ * @param opts - CORS options object or boolean (true to enable with defaults, false to disable)
360
+ * @returns The builder instance for chaining
361
+ * @default false (CORS is disabled by default)
362
+ *
363
+ * @example
364
+ * ```typescript
365
+ * // Enable CORS with default options
366
+ * builder.withCors(true)
367
+ *
368
+ * // Configure CORS with specific options
369
+ * builder.withCors({
370
+ * origin: ['https://example.com'],
371
+ * methods: ['GET', 'POST']
372
+ * })
373
+ * ```
374
+ */
375
+ withCors(opts: CatbeeServerConfig['cors']): this;
376
+ /**
377
+ * Enables CORS with default settings
378
+ *
379
+ * @returns The builder instance for chaining
380
+ */
381
+ enableCors(): this;
382
+ /**
383
+ * Disables CORS
384
+ *
385
+ * @returns The builder instance for chaining
386
+ */
387
+ disableCors(): this;
388
+ /**
389
+ * Configures the Helmet middleware for setting HTTP security headers.
390
+ *
391
+ * @param opts - Helmet options object or boolean (true to enable with defaults, false to disable)
392
+ * @returns The builder instance for chaining
393
+ * @default false (Helmet is disabled by default)
394
+ *
395
+ * @example
396
+ * ```typescript
397
+ * // Enable Helmet with default settings
398
+ * builder.withHelmet(true)
399
+ *
400
+ * // Configure Helmet with specific options
401
+ * builder.withHelmet({
402
+ * contentSecurityPolicy: false,
403
+ * xssFilter: true
404
+ * })
405
+ * ```
406
+ */
407
+ withHelmet(opts: CatbeeServerConfig['helmet']): this;
408
+ /**
409
+ * Enables Helmet with default settings
410
+ *
411
+ * @returns The builder instance for chaining
412
+ */
413
+ enableHelmet(): this;
414
+ /**
415
+ * Disables Helmet
416
+ *
417
+ * @returns The builder instance for chaining
418
+ */
419
+ disableHelmet(): this;
420
+ /**
421
+ * Configures response compression middleware.
422
+ *
423
+ * @param opts - Compression options object or boolean (true to enable with defaults, false to disable)
424
+ * @returns The builder instance for chaining
425
+ * @default false (Compression is disabled by default)
426
+ *
427
+ * @example
428
+ * ```typescript
429
+ * // Enable compression with default settings
430
+ * builder.withCompression(true)
431
+ *
432
+ * // Configure compression with specific options
433
+ * builder.withCompression({
434
+ * level: 6,
435
+ * threshold: 1024
436
+ * })
437
+ * ```
438
+ */
439
+ withCompression(opts: CatbeeServerConfig['compression']): this;
440
+ /**
441
+ * Enables compression with default settings
442
+ *
443
+ * @returns The builder instance for chaining
444
+ */
445
+ enableCompression(): this;
446
+ /**
447
+ * Disables compression
448
+ *
449
+ * @returns The builder instance for chaining
450
+ */
451
+ disableCompression(): this;
452
+ /**
453
+ * Configures rate limiting to protect against brute-force attacks.
454
+ *
455
+ * @param opts - Rate limit configuration options
456
+ * @returns The builder instance for chaining
457
+ * @default - { enable: false, windowMs: 15 * 60 * 1000, max: 100, message: 'Too many requests', standardHeaders: true, legacyHeaders: false }
458
+ *
459
+ * @example
460
+ * ```typescript
461
+ * builder.withRateLimit({
462
+ * enable: true,
463
+ * windowMs: 15 * 60 * 1000, // 15 minutes
464
+ * max: 100 // limit each IP to 100 requests per windowMs
465
+ * })
466
+ * ```
467
+ */
468
+ withRateLimit(opts: Partial<CatbeeServerConfig['rateLimit']>): this;
469
+ /**
470
+ * Enables rate limiting with default or custom settings
471
+ *
472
+ * @param opts - Optional rate limit configuration (max requests, window, etc.)
473
+ * @returns The builder instance for chaining
474
+ */
475
+ enableRateLimit(opts?: Omit<Partial<NonNullable<CatbeeServerConfig['rateLimit']>>, 'enable'>): this;
476
+ /**
477
+ * Disables rate limiting
478
+ *
479
+ * @returns The builder instance for chaining
480
+ */
481
+ disableRateLimit(): this;
482
+ /**
483
+ * Configures HTTP request logging middleware.
484
+ *
485
+ * @param opts - Request logging configuration options
486
+ * @returns The builder instance for chaining
487
+ * @default - { enable: true in dev/false in prod, ignorePaths: ['/healthz', '/favicon.ico', '/metrics', '/docs', '/.well-known'], skipNotFoundRoutes: false }
488
+ *
489
+ * @example
490
+ * ```typescript
491
+ * builder.withRequestLogging({
492
+ * enable: true,
493
+ * ignorePaths: ['/health', '/metrics'],
494
+ * skipNotFoundRoutes: true
495
+ * })
496
+ * ```
497
+ */
498
+ withRequestLogging(opts: Partial<NonNullable<CatbeeServerConfig['requestLogging']>>): this;
499
+ /**
500
+ * Enables request logging with default or custom settings
501
+ *
502
+ * @param opts - Optional request logging configuration
503
+ * @returns The builder instance for chaining
504
+ */
505
+ enableRequestLogging(opts?: Omit<Partial<NonNullable<CatbeeServerConfig['requestLogging']>>, 'enable'>): this;
506
+ /**
507
+ * Disables request logging
508
+ *
509
+ * @returns The builder instance for chaining
510
+ */
511
+ disableRequestLogging(): this;
512
+ /**
513
+ * Configures server metrics collection and endpoints.
514
+ *
515
+ * @param opts - Metrics configuration options
516
+ * @returns The builder instance for chaining
517
+ * @default - { enable: false, path: '/metrics', withGlobalPrefix: false }
518
+ *
519
+ * @example
520
+ * ```typescript
521
+ * builder.withMetrics({
522
+ * enable: true,
523
+ * path: '/metrics'
524
+ * })
525
+ * ```
526
+ */
527
+ withMetrics(opts: Partial<NonNullable<CatbeeServerConfig['metrics']>>): this;
528
+ /**
529
+ * Enables Prometheus metrics collection and endpoint
530
+ *
531
+ * @param opts - Optional metrics configuration
532
+ * @returns The builder instance for chaining
533
+ */
534
+ enableMetrics(opts?: Omit<Partial<NonNullable<CatbeeServerConfig['metrics']>>, 'enable'>): this;
535
+ /**
536
+ * Disables Prometheus metrics
537
+ *
538
+ * @returns The builder instance for chaining
539
+ */
540
+ disableMetrics(): this;
541
+ /**
542
+ * Configures server health check endpoint.
543
+ *
544
+ * @param opts - Health check configuration options
545
+ * @returns The builder instance for chaining
546
+ * @default - { path: '/healthz', detailed: true, withGlobalPrefix: false }
547
+ *
548
+ * @example
549
+ * ```typescript
550
+ * builder.withHealthCheck({
551
+ * path: '/health',
552
+ * detailed: true
553
+ * })
554
+ * ```
555
+ */
556
+ withHealthCheck(opts: Partial<NonNullable<CatbeeServerConfig['healthCheck']>>): this;
557
+ /**
558
+ * Configures OpenAPI/Swagger documentation for the API.
559
+ *
560
+ * @param opts - OpenAPI configuration options
561
+ * @returns The builder instance for chaining
562
+ * @default - { enable: false, mountPath: '/docs', verbose: false, withGlobalPrefix: false }
563
+ *
564
+ * @example
565
+ * ```typescript
566
+ * builder.withOpenApi({
567
+ * enable: true,
568
+ * path: '/api-docs',
569
+ * filePath: './openapi.yaml'
570
+ * })
571
+ * ```
572
+ */
573
+ withOpenApi(opts: Partial<NonNullable<CatbeeServerConfig['openApi']>>): this;
574
+ /**
575
+ * Enables OpenAPI documentation with required file path
576
+ *
577
+ * @param filePath - Path to OpenAPI specification file (required)
578
+ * @param opts - Optional OpenAPI configuration
579
+ * @returns The builder instance for chaining
580
+ */
581
+ enableOpenApi(filePath: string, opts?: Omit<Partial<NonNullable<CatbeeServerConfig['openApi']>>, 'enable' | 'filePath'>): this;
582
+ /**
583
+ * Disables OpenAPI documentation
584
+ *
585
+ * @returns The builder instance for chaining
586
+ */
587
+ disableOpenApi(): this;
588
+ /**
589
+ * Configures the server as a microservice with versioning.
590
+ *
591
+ * @param opts - Microservice configuration options including app name and service version
592
+ * @returns The builder instance for chaining
593
+ * @default - { isMicroservice: false, appName: 'express_app' }
594
+ *
595
+ * @example
596
+ * ```typescript
597
+ * builder.withMicroService({
598
+ * appName: 'user-service',
599
+ * serviceVersion: {
600
+ * enable: true,
601
+ * version: '1.2.3'
602
+ * }
603
+ * })
604
+ * ```
605
+ */
606
+ withMicroService(opts: {
607
+ appName: NonNullable<CatbeeServerConfig['appName']>;
608
+ serviceVersion: Partial<NonNullable<CatbeeServerConfig['serviceVersion']>>;
609
+ }): this;
610
+ /**
611
+ * Configures the trust proxy settings to determine if X-Forwarded-* headers should be trusted.
612
+ *
613
+ * @param opts - Trust proxy configuration options
614
+ * @returns The builder instance for chaining
615
+ * @default false
616
+ *
617
+ * @example
618
+ * ```typescript
619
+ * // Trust proxy headers (useful when behind a load balancer)
620
+ * builder.withTrustProxy(true)
621
+ * ```
622
+ */
623
+ withTrustProxy(opts: NonNullable<CatbeeServerConfig['trustProxy']>): this;
624
+ /**
625
+ * Configures the request ID middleware for tracing requests across services.
626
+ *
627
+ * @param opts - Request ID configuration options
628
+ * @returns The builder instance for chaining
629
+ * @default - { headerName: 'x-request-id', exposeHeader: true }
630
+ *
631
+ * @example
632
+ * ```typescript
633
+ * builder.withRequestId({
634
+ * headerName: 'X-Request-Id',
635
+ * generator: () => crypto.randomUUID()
636
+ * })
637
+ * ```
638
+ */
639
+ withRequestId(opts: Partial<NonNullable<CatbeeServerConfig['requestId']>>): this;
640
+ /**
641
+ * Configures the response time middleware for measuring request processing times.
642
+ *
643
+ * @param opts - Response time configuration options
644
+ * @returns The builder instance for chaining
645
+ * @default - { enable: false, addHeader: true, logOnComplete: false }
646
+ *
647
+ * @example
648
+ * ```typescript
649
+ * builder.withResponseTime({
650
+ * enable: true,
651
+ * addHeader: true,
652
+ * logOnComplete: true
653
+ * })
654
+ * ```
655
+ */
656
+ withResponseTime(opts: Partial<NonNullable<CatbeeServerConfig['responseTime']>>): this;
657
+ /**
658
+ * Enables response time tracking with default or custom settings
659
+ *
660
+ * @param opts - Optional response time configuration
661
+ * @returns The builder instance for chaining
662
+ */
663
+ enableResponseTime(opts?: Omit<Partial<NonNullable<CatbeeServerConfig['responseTime']>>, 'enable'>): this;
664
+ /**
665
+ * Disables response time tracking
666
+ *
667
+ * @returns The builder instance for chaining
668
+ */
669
+ disableResponseTime(): this;
670
+ /**
671
+ * Configures the body parser middleware options for parsing request bodies.
672
+ *
673
+ * @param opts - Body parser configuration options
674
+ * @returns The builder instance for chaining
675
+ * @default - { json: { limit: '1mb' }, urlencoded: { extended: true, limit: '1mb' } }
676
+ *
677
+ * @example
678
+ * ```typescript
679
+ * builder.withBodyParser({
680
+ * json: {
681
+ * limit: '1mb'
682
+ * },
683
+ * urlencoded: {
684
+ * extended: true,
685
+ * limit: '1mb'
686
+ * }
687
+ * })
688
+ * ```
689
+ */
690
+ withBodyParser(opts: NonNullable<CatbeeServerConfig['bodyParser']>): this;
691
+ /**
692
+ * Configures cookie parsing middleware.
693
+ *
694
+ * @param opts - Cookie parser options or boolean (true to enable with defaults, false to disable)
695
+ * @returns The builder instance for chaining
696
+ * @default false
697
+ *
698
+ * @example
699
+ * ```typescript
700
+ * // Enable cookie parsing with default options
701
+ * builder.withCookies(true)
702
+ *
703
+ * // Enable cookie parsing with specific options
704
+ * builder.withCookies({
705
+ * secret: 'your-secret-key',
706
+ * secure: true
707
+ * })
708
+ * ```
709
+ */
710
+ withCookies(opts: CatbeeServerConfig['cookieParser']): this;
711
+ /**
712
+ * Adds a static folder to serve files from.
713
+ *
714
+ * @param folder - Static folder configuration
715
+ * @returns The builder instance for chaining
716
+ *
717
+ * @example
718
+ * ```typescript
719
+ * builder.withStaticFolder({
720
+ * path: '/assets',
721
+ * directory: './public',
722
+ * options: { maxAge: '1d' }
723
+ * })
724
+ * ```
725
+ */
726
+ withStaticFolder(folder: NonNullable<CatbeeServerConfig['staticFolders']>[number]): this;
727
+ /**
728
+ * Sets global headers to be included in all responses.
729
+ *
730
+ * @param headers - Object containing header name/value pairs or functions that return values
731
+ * @returns The builder instance for chaining
732
+ * @default - {}
733
+ *
734
+ * @example
735
+ * ```typescript
736
+ * builder.withGlobalHeaders({
737
+ * 'X-Powered-By': 'Catbee',
738
+ * 'Server-Time': () => new Date().toISOString()
739
+ * })
740
+ * ```
741
+ */
742
+ withGlobalHeaders(headers: NonNullable<CatbeeServerConfig['globalHeaders']>): this;
743
+ /**
744
+ * Sets a global prefix for all routes.
745
+ *
746
+ * @param prefix - The prefix to prepend to all routes (e.g., '/api/v1')
747
+ * @returns The builder instance for chaining
748
+ * @default '/'
749
+ *
750
+ * @example
751
+ * ```typescript
752
+ * builder.withGlobalPrefix('/api/v1')
753
+ * ```
754
+ */
755
+ withGlobalPrefix(prefix: string): this;
756
+ /**
757
+ * Applies custom configuration overrides directly.
758
+ *
759
+ * @param overrides - Custom configuration options to merge
760
+ * @returns The builder instance for chaining
761
+ *
762
+ * @example
763
+ * ```typescript
764
+ * builder.withCustom({
765
+ * port: 8080,
766
+ * customMiddleware: myMiddlewareFunction
767
+ * })
768
+ * ```
769
+ */
770
+ withCustom(overrides: Partial<CatbeeServerConfig>): this;
771
+ /**
772
+ * Configures HTTPS server options.
773
+ *
774
+ * @param opts - HTTPS configuration (key, cert, ca, passphrase, etc.)
775
+ * @returns The builder instance for chaining
776
+ *
777
+ * @example
778
+ * ```typescript
779
+ * builder.withHttps({
780
+ * key: './localhost-key.pem',
781
+ * cert: './localhost-cert.pem'
782
+ * })
783
+ * ```
784
+ */
785
+ withHttps(opts: NonNullable<CatbeeServerConfig['https']>): this;
786
+ /**
787
+ * Builds and returns the final server configuration.
788
+ *
789
+ * This method merges the user-specified configuration with default values,
790
+ * ensures all sections with 'enable' flags are properly structured, and
791
+ * produces the final configuration to be used by the server.
792
+ *
793
+ * @returns The complete ServerConfig object
794
+ *
795
+ * @example
796
+ * ```typescript
797
+ * const config = new ServerConfigBuilder()
798
+ * .withPort(3000)
799
+ * .withHost('localhost')
800
+ * .withCors(true)
801
+ * .build();
802
+ * ```
803
+ */
804
+ build(): Readonly<CatbeeServerConfig>;
805
+ private mergeConfig;
806
+ private setEnabled;
807
+ }
808
+
809
+ export { DependencyErrors, ExpressServer, ServerConfigBuilder };