@oxog/spark 1.1.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 (63) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/LICENSE +21 -0
  3. package/README.md +242 -0
  4. package/dist/LICENSE +21 -0
  5. package/dist/README.md +242 -0
  6. package/dist/core/application.js +957 -0
  7. package/dist/core/context.js +831 -0
  8. package/dist/core/middleware.js +218 -0
  9. package/dist/core/request.js +333 -0
  10. package/dist/core/response.js +375 -0
  11. package/dist/index.js +278 -0
  12. package/dist/middleware/body-parser.js +526 -0
  13. package/dist/middleware/cache.js +171 -0
  14. package/dist/middleware/compression.js +183 -0
  15. package/dist/middleware/cors.js +95 -0
  16. package/dist/middleware/health.js +219 -0
  17. package/dist/middleware/index.js +21 -0
  18. package/dist/middleware/logger.js +195 -0
  19. package/dist/middleware/metrics.js +328 -0
  20. package/dist/middleware/rate-limit.js +320 -0
  21. package/dist/middleware/security.js +333 -0
  22. package/dist/middleware/session.js +530 -0
  23. package/dist/middleware/static.js +299 -0
  24. package/dist/package.json +62 -0
  25. package/dist/router/layer.js +117 -0
  26. package/dist/router/route.js +123 -0
  27. package/dist/router/router.js +756 -0
  28. package/dist/types/index.d.ts +291 -0
  29. package/dist/utils/async-handler.js +145 -0
  30. package/dist/utils/cache.js +441 -0
  31. package/dist/utils/context-pool.js +83 -0
  32. package/dist/utils/error-types.js +132 -0
  33. package/dist/utils/http.js +413 -0
  34. package/dist/utils/regex-validator.js +177 -0
  35. package/package.json +89 -0
  36. package/src/core/application.js +957 -0
  37. package/src/core/context.js +831 -0
  38. package/src/core/middleware.js +218 -0
  39. package/src/core/request.js +333 -0
  40. package/src/core/response.js +375 -0
  41. package/src/index.js +278 -0
  42. package/src/middleware/body-parser.js +526 -0
  43. package/src/middleware/cache.js +171 -0
  44. package/src/middleware/compression.js +183 -0
  45. package/src/middleware/cors.js +95 -0
  46. package/src/middleware/health.js +219 -0
  47. package/src/middleware/index.js +21 -0
  48. package/src/middleware/logger.js +195 -0
  49. package/src/middleware/metrics.js +328 -0
  50. package/src/middleware/rate-limit.js +320 -0
  51. package/src/middleware/security.js +333 -0
  52. package/src/middleware/session.js +530 -0
  53. package/src/middleware/static.js +299 -0
  54. package/src/router/layer.js +117 -0
  55. package/src/router/route.js +123 -0
  56. package/src/router/router.js +756 -0
  57. package/src/utils/async-handler.js +145 -0
  58. package/src/utils/cache.js +441 -0
  59. package/src/utils/context-pool.js +83 -0
  60. package/src/utils/error-types.js +132 -0
  61. package/src/utils/http.js +413 -0
  62. package/src/utils/regex-validator.js +177 -0
  63. package/types/index.d.ts +291 -0
@@ -0,0 +1,957 @@
1
+ /**
2
+ * @fileoverview Core Application class for the Spark Web Framework
3
+ * @author Spark Framework Team
4
+ * @since 1.0.0
5
+ * @version 1.0.0
6
+ */
7
+
8
+ const http = require('http');
9
+ const https = require('https');
10
+ const cluster = require('cluster');
11
+ const os = require('os');
12
+ const EventEmitter = require('events');
13
+ const { URL } = require('url');
14
+
15
+ const Context = require('./context');
16
+ const Router = require('../router/router');
17
+ const { createMiddleware } = require('./middleware');
18
+ const { errorHandler } = require('../utils/async-handler');
19
+
20
+ /**
21
+ * Core Application class that extends EventEmitter to provide a web server framework
22
+ *
23
+ * The Application class is the foundation of the Spark framework, providing HTTP/HTTPS server
24
+ * capabilities, middleware support, routing, error handling, and graceful shutdown mechanisms.
25
+ * It supports both single-process and cluster modes for high-performance applications.
26
+ *
27
+ * @class Application
28
+ * @extends EventEmitter
29
+ * @since 1.0.0
30
+ *
31
+ * @fires Application#error - Emitted when an application error occurs
32
+ * @fires Application#listening - Emitted when the server starts listening
33
+ * @fires Application#close - Emitted when the server closes
34
+ * @fires Application#uncaughtException - Emitted when an uncaught exception occurs
35
+ * @fires Application#unhandledRejection - Emitted when an unhandled promise rejection occurs
36
+ *
37
+ * @example
38
+ * // Basic HTTP server
39
+ * const app = new Application({ port: 3000 });
40
+ *
41
+ * app.use((ctx, next) => {
42
+ * console.log(`${ctx.method} ${ctx.path}`);
43
+ * return next();
44
+ * });
45
+ *
46
+ * app.get('/', (ctx) => {
47
+ * ctx.json({ message: 'Hello World!' });
48
+ * });
49
+ *
50
+ * app.listen();
51
+ *
52
+ * @example
53
+ * // HTTPS server with security options
54
+ * const fs = require('fs');
55
+ * const app = new Application({
56
+ * port: 443,
57
+ * https: {
58
+ * key: fs.readFileSync('private-key.pem'),
59
+ * cert: fs.readFileSync('certificate.pem')
60
+ * },
61
+ * security: {
62
+ * cors: { origin: 'https://example.com' },
63
+ * rateLimit: { max: 100, window: 60000 }
64
+ * }
65
+ * });
66
+ *
67
+ * app.listen();
68
+ *
69
+ * @example
70
+ * // Cluster mode for multi-core systems
71
+ * const app = new Application({
72
+ * port: 8080,
73
+ * cluster: true
74
+ * });
75
+ *
76
+ * app.listen();
77
+ */
78
+ class Application extends EventEmitter {
79
+ /**
80
+ * Create a new Application instance
81
+ *
82
+ * @param {Object} [options={}] - Configuration options for the application
83
+ * @param {number} [options.port=3000] - Port number to listen on (also reads from PORT env var)
84
+ * @param {string} [options.host='127.0.0.1'] - Host address to bind to (also reads from HOST env var)
85
+ * @param {boolean} [options.cluster=false] - Enable cluster mode for multi-core systems
86
+ * @param {boolean} [options.compression=true] - Enable response compression
87
+ * @param {Object} [options.https] - HTTPS configuration with key and cert properties
88
+ * @param {Object} [options.security] - Security configuration options
89
+ * @param {Object} [options.security.cors] - CORS configuration
90
+ * @param {Object} [options.security.rateLimit] - Rate limiting configuration
91
+ * @param {boolean} [options.security.csrf=true] - Enable CSRF protection
92
+ * @param {boolean} [options.security.helmet=true] - Enable security headers
93
+ * @param {boolean} [options.exitOnUncaughtException=true] - Exit process on uncaught exceptions
94
+ * @param {boolean} [options.exitOnUnhandledRejection=false] - Exit process on unhandled rejections
95
+ *
96
+ * @since 1.0.0
97
+ *
98
+ * @example
99
+ * // Basic configuration
100
+ * const app = new Application({
101
+ * port: 8080,
102
+ * host: '0.0.0.0'
103
+ * });
104
+ *
105
+ * @example
106
+ * // With security options
107
+ * const app = new Application({
108
+ * port: 443,
109
+ * security: {
110
+ * cors: { origin: ['https://example.com'] },
111
+ * rateLimit: { max: 200, window: 60000 },
112
+ * csrf: true
113
+ * }
114
+ * });
115
+ */
116
+ constructor(options = {}) {
117
+ super();
118
+
119
+ // Set max event listeners to prevent warning
120
+ this.setMaxListeners(50);
121
+
122
+ this.options = {
123
+ port: process.env.PORT || 3000,
124
+ host: process.env.HOST || '127.0.0.1', // Secure default: localhost only
125
+ cluster: false,
126
+ compression: true,
127
+ security: {
128
+ cors: {
129
+ origin: false, // Secure default: CORS disabled
130
+ credentials: true,
131
+ maxAge: 86400
132
+ },
133
+ rateLimit: { max: 100, window: 60000 }, // More restrictive default
134
+ csrf: true, // Secure default: CSRF protection enabled
135
+ helmet: true, // Enable security headers by default
136
+ contentSecurityPolicy: true,
137
+ hsts: {
138
+ maxAge: 31536000,
139
+ includeSubDomains: true,
140
+ preload: true
141
+ }
142
+ },
143
+ ...options
144
+ };
145
+
146
+ /**
147
+ * Array of middleware functions
148
+ * @type {Function[]}
149
+ * @private
150
+ */
151
+ this.middlewares = [];
152
+
153
+ /**
154
+ * Router instance for handling routes
155
+ * @type {Router}
156
+ * @private
157
+ */
158
+ this.router = new Router();
159
+
160
+ /**
161
+ * HTTP/HTTPS server instance
162
+ * @type {http.Server|https.Server|null}
163
+ * @private
164
+ */
165
+ this.server = null;
166
+
167
+ /**
168
+ * Whether the server is currently listening
169
+ * @type {boolean}
170
+ * @private
171
+ */
172
+ this.listening = false;
173
+
174
+ /**
175
+ * Array of cleanup handler functions
176
+ * @type {Function[]}
177
+ * @private
178
+ */
179
+ this.cleanupHandlers = [];
180
+
181
+ /**
182
+ * Middleware factory instance
183
+ * @type {Object}
184
+ * @private
185
+ */
186
+ this.middleware = createMiddleware(this);
187
+
188
+ this.setupErrorHandling();
189
+ this.setupShutdownHandlers();
190
+ }
191
+
192
+ /**
193
+ * Set up error handling for the application
194
+ *
195
+ * Configures event listeners for application errors, uncaught exceptions,
196
+ * and unhandled promise rejections. Provides graceful error handling
197
+ * and optional automatic shutdown on critical errors.
198
+ *
199
+ * @private
200
+ * @since 1.0.0
201
+ */
202
+ setupErrorHandling() {
203
+ this.on('error', (error) => {
204
+ console.error('Application error:', error);
205
+ });
206
+
207
+ // Handle uncaught exceptions with recovery option
208
+ process.on('uncaughtException', (error) => {
209
+ console.error('Uncaught Exception:', error);
210
+
211
+ // Emit error event for application-level handling
212
+ this.emit('uncaughtException', error);
213
+
214
+ // Only shutdown if explicitly configured or error is critical
215
+ if (this.options.exitOnUncaughtException !== false) {
216
+ console.error('Shutting down due to uncaught exception...');
217
+ this.gracefulShutdown();
218
+ } else {
219
+ console.error('Continuing after uncaught exception (not recommended for production)');
220
+ }
221
+ });
222
+
223
+ process.on('unhandledRejection', (reason, promise) => {
224
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
225
+
226
+ // Emit error event for application-level handling
227
+ this.emit('unhandledRejection', reason, promise);
228
+
229
+ // Only shutdown if explicitly configured
230
+ if (this.options.exitOnUnhandledRejection === true) {
231
+ console.error('Shutting down due to unhandled rejection...');
232
+ this.gracefulShutdown();
233
+ }
234
+ });
235
+ }
236
+
237
+ /**
238
+ * Set up graceful shutdown handlers for process signals
239
+ *
240
+ * Configures signal handlers for SIGTERM, SIGINT, and SIGBREAK (Windows)
241
+ * to enable graceful shutdown of the application when receiving termination signals.
242
+ *
243
+ * @private
244
+ * @since 1.0.0
245
+ */
246
+ setupShutdownHandlers() {
247
+ // Graceful shutdown on SIGTERM and SIGINT
248
+ const shutdownHandler = (signal) => {
249
+ console.log(`\nReceived ${signal}, starting graceful shutdown...`);
250
+ this.gracefulShutdown();
251
+ };
252
+
253
+ process.once('SIGTERM', () => shutdownHandler('SIGTERM'));
254
+ process.once('SIGINT', () => shutdownHandler('SIGINT'));
255
+
256
+ // Windows-specific shutdown handling
257
+ if (process.platform === 'win32') {
258
+ process.once('SIGBREAK', () => shutdownHandler('SIGBREAK'));
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Add middleware to the application
264
+ *
265
+ * Middleware functions are executed in the order they are added. Each middleware
266
+ * function receives the context object and a next function to continue to the next middleware.
267
+ *
268
+ * @param {string|Function|Router} pathOrMiddleware - Path prefix, middleware function, or router instance
269
+ * @param {Function} [middleware] - Middleware function when first parameter is a path
270
+ * @returns {Application} The application instance for method chaining
271
+ *
272
+ * @since 1.0.0
273
+ *
274
+ * @example
275
+ * // Global middleware
276
+ * app.use((ctx, next) => {
277
+ * console.log(`${ctx.method} ${ctx.path}`);
278
+ * return next();
279
+ * });
280
+ *
281
+ * @example
282
+ * // Path-specific middleware
283
+ * app.use('/api', (ctx, next) => {
284
+ * ctx.set('X-API-Version', '1.0');
285
+ * return next();
286
+ * });
287
+ *
288
+ * @example
289
+ * // Router middleware
290
+ * const router = new Router();
291
+ * router.get('/users', (ctx) => ctx.json({ users: [] }));
292
+ * app.use('/api', router);
293
+ */
294
+ use(pathOrMiddleware, middleware) {
295
+ if (typeof pathOrMiddleware === 'function') {
296
+ this.middlewares.push(pathOrMiddleware);
297
+
298
+ // Register cleanup handler if middleware has one
299
+ if (pathOrMiddleware.cleanup) {
300
+ this.cleanupHandlers.push(pathOrMiddleware.cleanup);
301
+ }
302
+ } else if (typeof middleware === 'function') {
303
+ const wrappedMiddleware = async (ctx, next) => {
304
+ if (ctx.path.startsWith(pathOrMiddleware)) {
305
+ // Store the original path and prefix
306
+ const originalPath = ctx.path;
307
+ const strippedPath = ctx.path.slice(pathOrMiddleware.length) || '/';
308
+
309
+ // Set the path for the middleware
310
+ ctx.path = strippedPath;
311
+ ctx.mountpath = pathOrMiddleware;
312
+
313
+ try {
314
+ await middleware(ctx, next);
315
+ } finally {
316
+ // Restore the original state
317
+ ctx.path = originalPath;
318
+ delete ctx.mountpath;
319
+ }
320
+ } else {
321
+ await next();
322
+ }
323
+ };
324
+ this.middlewares.push(wrappedMiddleware);
325
+
326
+ // Register cleanup handler if middleware has one
327
+ if (middleware.cleanup) {
328
+ this.cleanupHandlers.push(middleware.cleanup);
329
+ }
330
+ } else if (typeof pathOrMiddleware === 'string' && middleware && typeof middleware === 'object' && middleware.handle) {
331
+ // This is a router being mounted with a path prefix
332
+ const mountPath = pathOrMiddleware;
333
+ const router = middleware;
334
+ this.middlewares.push((ctx, next) => {
335
+ if (ctx.path.startsWith(mountPath)) {
336
+ // Temporarily modify the path for the router
337
+ const originalPath = ctx.path;
338
+ ctx.path = ctx.path.slice(mountPath.length) || '/';
339
+
340
+ return router.handle(ctx, next).finally(() => {
341
+ // Restore original path
342
+ ctx.path = originalPath;
343
+ });
344
+ }
345
+ return next();
346
+ });
347
+ } else if (pathOrMiddleware && typeof pathOrMiddleware === 'object' && pathOrMiddleware.handle) {
348
+ // This is a router being mounted without path prefix
349
+ const router = pathOrMiddleware;
350
+ this.middlewares.push((ctx, next) => {
351
+ return router.handle(ctx, next);
352
+ });
353
+ }
354
+ return this;
355
+ }
356
+
357
+ /**
358
+ * Register a GET route handler
359
+ *
360
+ * @param {string} path - Route path pattern
361
+ * @param {...Function} handlers - One or more handler functions
362
+ * @returns {Application} The application instance for method chaining
363
+ *
364
+ * @since 1.0.0
365
+ *
366
+ * @example
367
+ * app.get('/', (ctx) => {
368
+ * ctx.json({ message: 'Hello World!' });
369
+ * });
370
+ *
371
+ * @example
372
+ * // With middleware
373
+ * app.get('/protected', authenticate, (ctx) => {
374
+ * ctx.json({ user: ctx.user });
375
+ * });
376
+ */
377
+ get(path, ...handlers) {
378
+ this.router.get(path, ...handlers);
379
+ return this;
380
+ }
381
+
382
+ /**
383
+ * Register a POST route handler
384
+ *
385
+ * @param {string} path - Route path pattern
386
+ * @param {...Function} handlers - One or more handler functions
387
+ * @returns {Application} The application instance for method chaining
388
+ *
389
+ * @since 1.0.0
390
+ *
391
+ * @example
392
+ * app.post('/users', (ctx) => {
393
+ * const userData = ctx.body;
394
+ * ctx.json({ id: 123, ...userData });
395
+ * });
396
+ */
397
+ post(path, ...handlers) {
398
+ this.router.post(path, ...handlers);
399
+ return this;
400
+ }
401
+
402
+ /**
403
+ * Register a PUT route handler
404
+ *
405
+ * @param {string} path - Route path pattern
406
+ * @param {...Function} handlers - One or more handler functions
407
+ * @returns {Application} The application instance for method chaining
408
+ *
409
+ * @since 1.0.0
410
+ *
411
+ * @example
412
+ * app.put('/users/:id', (ctx) => {
413
+ * const id = ctx.params.id;
414
+ * const userData = ctx.body;
415
+ * ctx.json({ id, ...userData });
416
+ * });
417
+ */
418
+ put(path, ...handlers) {
419
+ this.router.put(path, ...handlers);
420
+ return this;
421
+ }
422
+
423
+ /**
424
+ * Register a DELETE route handler
425
+ *
426
+ * @param {string} path - Route path pattern
427
+ * @param {...Function} handlers - One or more handler functions
428
+ * @returns {Application} The application instance for method chaining
429
+ *
430
+ * @since 1.0.0
431
+ *
432
+ * @example
433
+ * app.delete('/users/:id', (ctx) => {
434
+ * const id = ctx.params.id;
435
+ * // Delete user logic here
436
+ * ctx.status(204).end();
437
+ * });
438
+ */
439
+ delete(path, ...handlers) {
440
+ this.router.delete(path, ...handlers);
441
+ return this;
442
+ }
443
+
444
+ /**
445
+ * Register a PATCH route handler
446
+ *
447
+ * @param {string} path - Route path pattern
448
+ * @param {...Function} handlers - One or more handler functions
449
+ * @returns {Application} The application instance for method chaining
450
+ *
451
+ * @since 1.0.0
452
+ *
453
+ * @example
454
+ * app.patch('/users/:id', (ctx) => {
455
+ * const id = ctx.params.id;
456
+ * const updates = ctx.body;
457
+ * ctx.json({ id, ...updates });
458
+ * });
459
+ */
460
+ patch(path, ...handlers) {
461
+ this.router.patch(path, ...handlers);
462
+ return this;
463
+ }
464
+
465
+ /**
466
+ * Register a HEAD route handler
467
+ *
468
+ * @param {string} path - Route path pattern
469
+ * @param {...Function} handlers - One or more handler functions
470
+ * @returns {Application} The application instance for method chaining
471
+ *
472
+ * @since 1.0.0
473
+ *
474
+ * @example
475
+ * app.head('/users/:id', (ctx) => {
476
+ * // Check if user exists
477
+ * ctx.status(200).end();
478
+ * });
479
+ */
480
+ head(path, ...handlers) {
481
+ this.router.head(path, ...handlers);
482
+ return this;
483
+ }
484
+
485
+ /**
486
+ * Register an OPTIONS route handler
487
+ *
488
+ * @param {string} path - Route path pattern
489
+ * @param {...Function} handlers - One or more handler functions
490
+ * @returns {Application} The application instance for method chaining
491
+ *
492
+ * @since 1.0.0
493
+ *
494
+ * @example
495
+ * app.options('/api/*', (ctx) => {
496
+ * ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
497
+ * ctx.status(200).end();
498
+ * });
499
+ */
500
+ options(path, ...handlers) {
501
+ this.router.options(path, ...handlers);
502
+ return this;
503
+ }
504
+
505
+ /**
506
+ * Register a route handler for all HTTP methods
507
+ *
508
+ * @param {string} path - Route path pattern
509
+ * @param {...Function} handlers - One or more handler functions
510
+ * @returns {Application} The application instance for method chaining
511
+ *
512
+ * @since 1.0.0
513
+ *
514
+ * @example
515
+ * app.all('/api/*', (ctx, next) => {
516
+ * ctx.set('X-API-Version', '1.0');
517
+ * return next();
518
+ * });
519
+ */
520
+ all(path, ...handlers) {
521
+ this.router.all(path, ...handlers);
522
+ return this;
523
+ }
524
+
525
+ /**
526
+ * Handle an incoming HTTP request
527
+ *
528
+ * Creates a new context object and executes the middleware chain.
529
+ * Catches and handles any errors that occur during request processing.
530
+ *
531
+ * @param {http.IncomingMessage} req - The HTTP request object
532
+ * @param {http.ServerResponse} res - The HTTP response object
533
+ * @returns {Promise<void>}
534
+ *
535
+ * @private
536
+ * @since 1.0.0
537
+ */
538
+ async handleRequest(req, res) {
539
+ const ctx = new Context(req, res, this);
540
+
541
+ try {
542
+ await this.executeMiddleware(ctx);
543
+ } catch (error) {
544
+ await this.handleError(error, ctx);
545
+ }
546
+ }
547
+
548
+ /**
549
+ * Execute the middleware chain for a request
550
+ *
551
+ * Runs all registered middleware functions in order, followed by the router.
552
+ * If no middleware handles the request, returns a 404 Not Found response.
553
+ *
554
+ * @param {Context} ctx - The request context object
555
+ * @returns {Promise<void>}
556
+ *
557
+ * @private
558
+ * @since 1.0.0
559
+ */
560
+ async executeMiddleware(ctx) {
561
+ const middlewares = [...this.middlewares];
562
+
563
+ middlewares.push((ctx, next) => {
564
+ return this.router.handle(ctx, next);
565
+ });
566
+
567
+ let index = 0;
568
+
569
+ const next = async (error) => {
570
+ // If an error is passed, handle it
571
+ if (error) {
572
+ await this.handleError(error, ctx);
573
+ return;
574
+ }
575
+
576
+ if (index >= middlewares.length) {
577
+ if (!ctx.responded) {
578
+ ctx.status(404).json({ error: 'Not Found' });
579
+ }
580
+ return;
581
+ }
582
+
583
+ const middleware = middlewares[index++];
584
+ await middleware(ctx, next);
585
+ };
586
+
587
+ await next();
588
+ }
589
+
590
+ /**
591
+ * Handle errors that occur during request processing
592
+ *
593
+ * Emits an 'error' event and sends an appropriate error response to the client.
594
+ * In development mode, includes the error message in the response.
595
+ *
596
+ * @param {Error} error - The error that occurred
597
+ * @param {Context} ctx - The request context object
598
+ * @returns {Promise<void>}
599
+ *
600
+ * @private
601
+ * @since 1.0.0
602
+ */
603
+ async handleError(error, ctx) {
604
+ // Only emit error event if not in test mode
605
+ if (!process.env.TEST_MODE) {
606
+ this.emit('error', error, ctx);
607
+ }
608
+
609
+ if (!ctx.responded) {
610
+ try {
611
+ // Get status code from error or default to 500
612
+ const statusCode = error.status || error.statusCode || 500;
613
+
614
+ // Prepare error response
615
+ const errorResponse = {
616
+ error: error.message || 'Internal Server Error',
617
+ status: statusCode
618
+ };
619
+
620
+ // Add additional error properties if they exist
621
+ if (error.code) {
622
+ errorResponse.code = error.code;
623
+ }
624
+
625
+ if (error.details) {
626
+ errorResponse.details = error.details;
627
+ }
628
+
629
+ // Add stack trace in development
630
+ if (process.env.NODE_ENV === 'development') {
631
+ errorResponse.stack = error.stack;
632
+ }
633
+
634
+ ctx.status(statusCode).json(errorResponse);
635
+ } catch (responseError) {
636
+ console.error('Error sending error response:', responseError);
637
+ }
638
+ }
639
+ }
640
+
641
+ /**
642
+ * Create an HTTP or HTTPS server instance
643
+ *
644
+ * Creates either an HTTP or HTTPS server based on the configuration.
645
+ * Sets up error handling for server and client errors.
646
+ *
647
+ * @returns {http.Server|https.Server} The created server instance
648
+ *
649
+ * @private
650
+ * @since 1.0.0
651
+ */
652
+ createServer() {
653
+ if (this.options.https) {
654
+ this.server = https.createServer(this.options.https, (req, res) => {
655
+ this.handleRequest(req, res);
656
+ });
657
+ } else {
658
+ this.server = http.createServer((req, res) => {
659
+ this.handleRequest(req, res);
660
+ });
661
+ }
662
+
663
+ this.server.on('error', (error) => {
664
+ this.emit('error', error);
665
+ });
666
+
667
+ this.server.on('clientError', (error, socket) => {
668
+ if (error.code === 'ECONNRESET' || !socket.writable) {
669
+ return;
670
+ }
671
+ socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
672
+ });
673
+
674
+ return this.server;
675
+ }
676
+
677
+ /**
678
+ * Start listening for incoming requests
679
+ *
680
+ * Starts the server in either cluster mode (if configured) or single-process mode.
681
+ * Supports various parameter combinations for flexibility.
682
+ *
683
+ * @param {number|Function} [port] - Port number or callback function
684
+ * @param {string|Function} [host] - Host address or callback function
685
+ * @param {Function} [callback] - Callback function called when server starts listening
686
+ * @returns {Application} The application instance for method chaining
687
+ *
688
+ * @since 1.0.0
689
+ *
690
+ * @example
691
+ * // Use default port and host
692
+ * app.listen();
693
+ *
694
+ * @example
695
+ * // Specify port
696
+ * app.listen(8080);
697
+ *
698
+ * @example
699
+ * // Specify port and host
700
+ * app.listen(8080, '0.0.0.0');
701
+ *
702
+ * @example
703
+ * // With callback
704
+ * app.listen(3000, () => {
705
+ * console.log('Server started on port 3000');
706
+ * });
707
+ */
708
+ listen(port, host, callback) {
709
+ if (typeof port === 'function') {
710
+ callback = port;
711
+ port = this.options.port;
712
+ host = this.options.host;
713
+ } else if (typeof host === 'function') {
714
+ callback = host;
715
+ host = this.options.host;
716
+ }
717
+
718
+ port = port !== undefined ? port : this.options.port;
719
+ host = host || this.options.host;
720
+
721
+ if (this.options.cluster && cluster.isMaster) {
722
+ return this.startCluster(port, host, callback);
723
+ }
724
+
725
+ return this.startServer(port, host, callback);
726
+ }
727
+
728
+ /**
729
+ * Start the application in cluster mode
730
+ *
731
+ * Creates worker processes equal to the number of CPU cores.
732
+ * Automatically restarts workers if they die.
733
+ *
734
+ * @param {number} port - Port number to listen on
735
+ * @param {string} host - Host address to bind to
736
+ * @param {Function} [callback] - Callback function called when cluster starts
737
+ * @returns {Application} The application instance for method chaining
738
+ *
739
+ * @private
740
+ * @since 1.0.0
741
+ */
742
+ startCluster(port, host, callback) {
743
+ const numCPUs = os.cpus().length;
744
+
745
+ console.log(`Starting cluster with ${numCPUs} workers...`);
746
+
747
+ for (let i = 0; i < numCPUs; i++) {
748
+ cluster.fork();
749
+ }
750
+
751
+ cluster.on('exit', (worker, code, signal) => {
752
+ console.log(`Worker ${worker.process.pid} died. Starting a new worker...`);
753
+ cluster.fork();
754
+ });
755
+
756
+ if (callback) {
757
+ callback();
758
+ }
759
+
760
+ return this;
761
+ }
762
+
763
+ /**
764
+ * Start the server in single-process mode
765
+ *
766
+ * Creates the server and starts listening on the specified port and host.
767
+ * Emits a 'listening' event when the server is ready.
768
+ *
769
+ * @param {number} port - Port number to listen on
770
+ * @param {string} host - Host address to bind to
771
+ * @param {Function} [callback] - Callback function called when server starts listening
772
+ * @returns {Application} The application instance for method chaining
773
+ *
774
+ * @throws {Error} Throws an error if the server is already listening
775
+ *
776
+ * @private
777
+ * @since 1.0.0
778
+ */
779
+ startServer(port, host, callback) {
780
+ if (this.listening) {
781
+ throw new Error('Server is already listening');
782
+ }
783
+
784
+ this.createServer();
785
+
786
+ this.server.listen(port, host, () => {
787
+ this.listening = true;
788
+ const address = this.server.address();
789
+ console.log(`Server listening on ${address.address}:${address.port}`);
790
+
791
+ if (callback) {
792
+ callback();
793
+ }
794
+
795
+ this.emit('listening');
796
+ });
797
+
798
+ return this;
799
+ }
800
+
801
+ /**
802
+ * Close the server and clean up resources
803
+ *
804
+ * Runs all registered cleanup handlers and gracefully closes the server.
805
+ * Forces connection termination after a timeout to prevent hanging.
806
+ *
807
+ * @returns {Promise<void>} Promise that resolves when the server is closed
808
+ *
809
+ * @since 1.0.0
810
+ *
811
+ * @example
812
+ * // Graceful shutdown
813
+ * await app.close();
814
+ * console.log('Server closed successfully');
815
+ */
816
+ async close() {
817
+ if (!this.server) {
818
+ return;
819
+ }
820
+
821
+ // Run all cleanup handlers
822
+ await this.runCleanupHandlers();
823
+
824
+ return new Promise((resolve, reject) => {
825
+ // Set a timeout for server close
826
+ const closeTimeout = setTimeout(() => {
827
+ console.error('Server close timeout, forcing shutdown...');
828
+ resolve();
829
+ }, 30000); // 30 seconds timeout
830
+
831
+ this.server.close((error) => {
832
+ clearTimeout(closeTimeout);
833
+
834
+ if (error) {
835
+ reject(error);
836
+ } else {
837
+ this.listening = false;
838
+ this.emit('close');
839
+ resolve();
840
+ }
841
+ });
842
+
843
+ // Force close all connections after 10 seconds
844
+ setTimeout(() => {
845
+ if (this.server && this.server.listening) {
846
+ console.log('Force closing remaining connections...');
847
+ this.server.unref();
848
+ }
849
+ }, 10000);
850
+ });
851
+ }
852
+
853
+ /**
854
+ * Run all registered cleanup handlers
855
+ *
856
+ * Executes cleanup functions registered by middleware in the order they were added.
857
+ * Errors in cleanup handlers are logged but do not prevent other handlers from running.
858
+ *
859
+ * @returns {Promise<void>}
860
+ *
861
+ * @private
862
+ * @since 1.0.0
863
+ */
864
+ async runCleanupHandlers() {
865
+ console.log('Running cleanup handlers...');
866
+
867
+ for (const handler of this.cleanupHandlers) {
868
+ try {
869
+ await handler();
870
+ } catch (error) {
871
+ console.error('Error in cleanup handler:', error);
872
+ }
873
+ }
874
+
875
+ // Clear the handlers array
876
+ this.cleanupHandlers = [];
877
+ }
878
+
879
+ /**
880
+ * Perform a graceful shutdown of the application
881
+ *
882
+ * Stops accepting new connections, waits for existing requests to complete,
883
+ * runs cleanup handlers, and exits the process. Prevents multiple shutdown attempts.
884
+ *
885
+ * @returns {Promise<void>}
886
+ *
887
+ * @since 1.0.0
888
+ *
889
+ * @example
890
+ * // Trigger graceful shutdown
891
+ * process.on('SIGTERM', () => {
892
+ * app.gracefulShutdown();
893
+ * });
894
+ */
895
+ async gracefulShutdown() {
896
+ console.log('Graceful shutdown initiated...');
897
+
898
+ // Prevent multiple shutdown attempts
899
+ if (this.shuttingDown) {
900
+ console.log('Shutdown already in progress...');
901
+ return;
902
+ }
903
+ this.shuttingDown = true;
904
+
905
+ try {
906
+ // Stop accepting new connections immediately
907
+ if (this.server && this.server.listening) {
908
+ this.server.close();
909
+ }
910
+
911
+ // Give ongoing requests time to complete
912
+ await Promise.race([
913
+ this.close(),
914
+ new Promise(resolve => setTimeout(resolve, 30000)) // 30 seconds max
915
+ ]);
916
+
917
+ console.log('Server closed successfully');
918
+ process.exit(0);
919
+ } catch (error) {
920
+ console.error('Error during shutdown:', error);
921
+ process.exit(1);
922
+ }
923
+ }
924
+
925
+ /**
926
+ * Register a cleanup handler for application shutdown
927
+ *
928
+ * Cleanup handlers are called during graceful shutdown to clean up resources
929
+ * like database connections, file handles, or external service connections.
930
+ *
931
+ * @param {Function} handler - Async function to call during shutdown
932
+ * @returns {Application} The application instance for method chaining
933
+ *
934
+ * @since 1.0.0
935
+ *
936
+ * @example
937
+ * // Register database cleanup
938
+ * app.onShutdown(async () => {
939
+ * await database.close();
940
+ * console.log('Database connection closed');
941
+ * });
942
+ *
943
+ * @example
944
+ * // Register multiple cleanup handlers
945
+ * app.onShutdown(() => cache.disconnect())
946
+ * .onShutdown(() => logger.flush());
947
+ */
948
+ onShutdown(handler) {
949
+ if (typeof handler === 'function') {
950
+ this.cleanupHandlers.push(handler);
951
+ }
952
+ return this;
953
+ }
954
+
955
+ }
956
+
957
+ module.exports = Application;