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