@oxog/spark 1.1.0 → 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 -293
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1070 -956
  6. package/src/core/context.js +1100 -830
  7. package/src/core/middleware.js +305 -217
  8. package/src/index.js +183 -278
  9. package/src/middleware/body-parser.js +484 -526
  10. package/src/middleware/cache.js +179 -170
  11. package/src/middleware/compression.js +179 -182
  12. package/src/middleware/cors.js +178 -95
  13. package/src/middleware/health.js +221 -218
  14. package/src/middleware/logger.js +197 -194
  15. package/src/middleware/metrics.js +341 -327
  16. package/src/middleware/rate-limit.js +369 -319
  17. package/src/middleware/security.js +444 -332
  18. package/src/middleware/session.js +649 -529
  19. package/src/middleware/static.js +406 -299
  20. package/src/router/layer.js +199 -117
  21. package/src/router/route.js +151 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +147 -144
  24. package/src/utils/context-pool.js +85 -82
  25. package/src/utils/regex-validator.js +189 -176
  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 -957
  31. package/dist/core/context.js +0 -831
  32. package/dist/core/middleware.js +0 -218
  33. package/dist/core/request.js +0 -333
  34. package/dist/core/response.js +0 -375
  35. package/dist/index.js +0 -278
  36. package/dist/middleware/body-parser.js +0 -526
  37. package/dist/middleware/cache.js +0 -171
  38. package/dist/middleware/compression.js +0 -183
  39. package/dist/middleware/cors.js +0 -95
  40. package/dist/middleware/health.js +0 -219
  41. package/dist/middleware/index.js +0 -21
  42. package/dist/middleware/logger.js +0 -195
  43. package/dist/middleware/metrics.js +0 -328
  44. package/dist/middleware/rate-limit.js +0 -320
  45. package/dist/middleware/security.js +0 -333
  46. package/dist/middleware/session.js +0 -530
  47. package/dist/middleware/static.js +0 -299
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -117
  50. package/dist/router/route.js +0 -123
  51. package/dist/router/router.js +0 -756
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -145
  54. package/dist/utils/cache.js +0 -441
  55. package/dist/utils/context-pool.js +0 -83
  56. package/dist/utils/error-types.js +0 -132
  57. package/dist/utils/http.js +0 -413
  58. package/dist/utils/regex-validator.js +0 -177
  59. package/src/core/request.js +0 -333
  60. package/src/core/response.js +0 -375
  61. package/src/middleware/index.js +0 -21
  62. package/src/utils/cache.js +0 -441
  63. package/src/utils/error-types.js +0 -132
  64. package/src/utils/http.js +0 -413
@@ -1,831 +0,0 @@
1
- /**
2
- * @fileoverview Context class for handling HTTP requests and responses in Spark Framework
3
- * @author Spark Framework Team
4
- * @since 1.0.0
5
- * @version 1.0.0
6
- */
7
-
8
- const { URL } = require('url');
9
- const querystring = require('querystring');
10
-
11
- /**
12
- * Context class that wraps HTTP request and response objects
13
- *
14
- * The Context class provides a unified interface for handling HTTP requests and responses.
15
- * It parses incoming request data, provides helper methods for setting headers and status codes,
16
- * and includes convenience methods for sending various types of responses.
17
- *
18
- * @class Context
19
- * @since 1.0.0
20
- *
21
- * @example
22
- * // In a middleware or route handler
23
- * app.get('/users/:id', (ctx) => {
24
- * const userId = ctx.params.id;
25
- * const userAgent = ctx.get('user-agent');
26
- *
27
- * ctx.set('X-Response-Time', '10ms');
28
- * ctx.json({ id: userId, userAgent });
29
- * });
30
- *
31
- * @example
32
- * // Working with cookies
33
- * app.post('/login', (ctx) => {
34
- * const { username, password } = ctx.body;
35
- *
36
- * if (authenticate(username, password)) {
37
- * ctx.setCookie('session', 'abc123', {
38
- * httpOnly: true,
39
- * secure: true,
40
- * maxAge: 3600000
41
- * });
42
- * ctx.json({ success: true });
43
- * } else {
44
- * ctx.status(401).json({ error: 'Invalid credentials' });
45
- * }
46
- * });
47
- */
48
- class Context {
49
- /**
50
- * Create a new Context instance
51
- *
52
- * @param {http.IncomingMessage} req - The HTTP request object
53
- * @param {http.ServerResponse} res - The HTTP response object
54
- * @param {Application} app - The Spark application instance
55
- *
56
- * @since 1.0.0
57
- *
58
- * @example
59
- * // Context is typically created automatically by the framework
60
- * const ctx = new Context(req, res, app);
61
- */
62
- constructor(req, res, app) {
63
- /**
64
- * The HTTP request object
65
- * @type {http.IncomingMessage}
66
- * @readonly
67
- */
68
- this.req = req;
69
-
70
- /**
71
- * The HTTP response object
72
- * @type {http.ServerResponse}
73
- * @readonly
74
- */
75
- this.res = res;
76
-
77
- /**
78
- * The Spark application instance
79
- * @type {Application}
80
- * @readonly
81
- */
82
- this.app = app;
83
-
84
- /**
85
- * Whether a response has been sent
86
- * @type {boolean}
87
- * @readonly
88
- */
89
- this.responded = false;
90
-
91
- /**
92
- * The HTTP status code for the response
93
- * @type {number}
94
- */
95
- this.statusCode = 200;
96
-
97
- this.initializeUrl();
98
- this.initializeHeaders();
99
- this.initializeQuery();
100
- this.initializeCookies();
101
-
102
- /**
103
- * Route parameters extracted from the URL
104
- * @type {Object}
105
- * @example
106
- * // For route '/users/:id' with URL '/users/123'
107
- * ctx.params.id // '123'
108
- */
109
- this.params = {};
110
-
111
- /**
112
- * Parsed request body
113
- * @type {*}
114
- */
115
- this.body = null;
116
-
117
- /**
118
- * Uploaded files (when using multipart/form-data)
119
- * @type {Object|null}
120
- */
121
- this.files = null;
122
-
123
- /**
124
- * Session data (when session middleware is used)
125
- * @type {Object|null}
126
- */
127
- this.session = null;
128
-
129
- /**
130
- * Application state for storing custom data
131
- * @type {Object}
132
- */
133
- this.state = {};
134
- }
135
-
136
- /**
137
- * Initialize URL-related properties from the request
138
- *
139
- * Parses the request URL and extracts path, method, and other URL components.
140
- * Handles malformed URLs by throwing an appropriate error.
141
- *
142
- * @private
143
- * @throws {Error} When the URL cannot be parsed
144
- * @since 1.0.0
145
- */
146
- initializeUrl() {
147
- const protocol = this.req.connection.encrypted ? 'https' : 'http';
148
- const host = this.req.headers.host || 'localhost';
149
-
150
- try {
151
- /**
152
- * Parsed URL object
153
- * @type {URL|null}
154
- * @readonly
155
- */
156
- this.url = new URL(this.req.url, `${protocol}://${host}`);
157
-
158
- /**
159
- * Request path (pathname without query string)
160
- * @type {string}
161
- * @readonly
162
- */
163
- this.path = this.url.pathname;
164
- } catch (error) {
165
- // Handle malformed URLs - throw proper error instead of just logging
166
- this.url = null;
167
- this.path = '/';
168
- this.statusCode = 400;
169
- this.body = { error: 'Invalid URL format' };
170
- throw new Error(`Failed to parse URL: ${error.message}`);
171
- }
172
-
173
- /**
174
- * HTTP method (GET, POST, PUT, etc.)
175
- * @type {string}
176
- * @readonly
177
- */
178
- this.method = this.req.method ? this.req.method.toUpperCase() : 'GET';
179
-
180
- /**
181
- * Original request URL including query string
182
- * @type {string}
183
- * @readonly
184
- */
185
- this.originalUrl = this.req.url;
186
- }
187
-
188
- /**
189
- * Initialize request and response headers
190
- *
191
- * Copies request headers and initializes response headers object.
192
- *
193
- * @private
194
- * @since 1.0.0
195
- */
196
- initializeHeaders() {
197
- /**
198
- * Request headers (lowercase keys)
199
- * @type {Object}
200
- * @readonly
201
- */
202
- this.headers = { ...this.req.headers };
203
-
204
- /**
205
- * Response headers to be sent
206
- * @type {Object}
207
- * @private
208
- */
209
- this.responseHeaders = {};
210
- }
211
-
212
- /**
213
- * Initialize query string parameters
214
- *
215
- * Parses the URL query string into an object.
216
- *
217
- * @private
218
- * @since 1.0.0
219
- */
220
- initializeQuery() {
221
- /**
222
- * Parsed query string parameters
223
- * @type {Object}
224
- * @readonly
225
- * @example
226
- * // For URL '/search?q=hello&limit=10'
227
- * ctx.query.q // 'hello'
228
- * ctx.query.limit // '10'
229
- */
230
- this.query = {};
231
- if (this.url.search) {
232
- this.query = querystring.parse(this.url.search.slice(1));
233
- }
234
- }
235
-
236
- /**
237
- * Initialize cookies from the request
238
- *
239
- * Parses the Cookie header and decodes cookie values.
240
- * Malformed cookies are skipped and logged.
241
- *
242
- * @private
243
- * @since 1.0.0
244
- */
245
- initializeCookies() {
246
- /**
247
- * Parsed cookies from the request
248
- * @type {Object}
249
- * @readonly
250
- * @example
251
- * // For Cookie header 'session=abc123; theme=dark'
252
- * ctx.cookies.session // 'abc123'
253
- * ctx.cookies.theme // 'dark'
254
- */
255
- this.cookies = {};
256
- const cookieHeader = this.req.headers.cookie;
257
- if (cookieHeader) {
258
- cookieHeader.split(';').forEach(cookie => {
259
- const [name, value] = cookie.trim().split('=');
260
- if (name && value) {
261
- try {
262
- this.cookies[name] = decodeURIComponent(value);
263
- } catch (error) {
264
- // Skip malformed cookie values
265
- console.error(`Failed to decode cookie ${name}: ${error.message}`);
266
- }
267
- }
268
- });
269
- }
270
- }
271
-
272
- /**
273
- * Get a request header value
274
- *
275
- * @param {string} headerName - The header name (case-insensitive)
276
- * @returns {string|undefined} The header value or undefined if not present
277
- *
278
- * @since 1.0.0
279
- *
280
- * @example
281
- * const userAgent = ctx.get('User-Agent');
282
- * const contentType = ctx.get('content-type');
283
- */
284
- get(headerName) {
285
- return this.headers[headerName.toLowerCase()];
286
- }
287
-
288
- /**
289
- * Set a response header
290
- *
291
- * Sets a response header with validation for security and RFC compliance.
292
- * Header names and values are validated to prevent injection attacks.
293
- *
294
- * @param {string} headerName - The header name
295
- * @param {string|number} value - The header value
296
- * @returns {Context} The context instance for method chaining
297
- *
298
- * @throws {Error} When header name or value is invalid
299
- *
300
- * @since 1.0.0
301
- *
302
- * @example
303
- * ctx.set('Content-Type', 'application/json');
304
- * ctx.set('X-Response-Time', '10ms');
305
- *
306
- * @example
307
- * // Method chaining
308
- * ctx.set('Content-Type', 'text/html')
309
- * .set('Cache-Control', 'no-cache');
310
- */
311
- set(headerName, value) {
312
- // Validate header name
313
- if (!headerName || typeof headerName !== 'string') {
314
- throw new Error('Header name must be a non-empty string');
315
- }
316
-
317
- // Validate header name format (RFC 7230)
318
- if (!/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(headerName)) {
319
- throw new Error(`Invalid header name: ${headerName}`);
320
- }
321
-
322
- // Validate header value
323
- if (value !== undefined && value !== null) {
324
- const stringValue = String(value);
325
- // Check for invalid characters in header value (CRLF and null byte)
326
- if (/[\r\n\x00]/.test(stringValue)) {
327
- throw new Error('Header value cannot contain CRLF or null characters');
328
- }
329
- // Check header value length
330
- if (stringValue.length > 8192) {
331
- throw new Error('Header value too long (max 8192 characters)');
332
- }
333
- this.responseHeaders[headerName.toLowerCase()] = stringValue;
334
- }
335
-
336
- return this;
337
- }
338
-
339
- /**
340
- * Alias for set() method
341
- *
342
- * @param {string} name - The header name
343
- * @param {string|number} value - The header value
344
- * @returns {Context} The context instance for method chaining
345
- *
346
- * @since 1.0.0
347
- * @see {@link Context#set}
348
- */
349
- setHeader(name, value) {
350
- return this.set(name, value);
351
- }
352
-
353
- /**
354
- * Get a response header value
355
- *
356
- * @param {string} name - The header name (case-insensitive)
357
- * @returns {string|undefined} The header value or undefined if not set
358
- *
359
- * @since 1.0.0
360
- *
361
- * @example
362
- * ctx.set('Content-Type', 'application/json');
363
- * const contentType = ctx.getHeader('content-type'); // 'application/json'
364
- */
365
- getHeader(name) {
366
- return this.responseHeaders[name.toLowerCase()];
367
- }
368
-
369
- /**
370
- * Remove a response header
371
- *
372
- * @param {string} name - The header name (case-insensitive)
373
- * @returns {Context} The context instance for method chaining
374
- *
375
- * @since 1.0.0
376
- *
377
- * @example
378
- * ctx.removeHeader('X-Powered-By');
379
- */
380
- removeHeader(name) {
381
- delete this.responseHeaders[name.toLowerCase()];
382
- return this;
383
- }
384
-
385
- /**
386
- * Set the HTTP status code
387
- *
388
- * @param {number|string} code - HTTP status code (100-599)
389
- * @returns {Context} The context instance for method chaining
390
- *
391
- * @throws {Error} When status code is invalid
392
- *
393
- * @since 1.0.0
394
- *
395
- * @example
396
- * ctx.status(200); // OK
397
- * ctx.status(404); // Not Found
398
- * ctx.status(500); // Internal Server Error
399
- *
400
- * @example
401
- * // Method chaining
402
- * ctx.status(201).json({ id: 123, name: 'User' });
403
- */
404
- status(code) {
405
- // Validate status code
406
- const statusCode = parseInt(code);
407
- if (isNaN(statusCode) || statusCode < 100 || statusCode > 599) {
408
- throw new Error(`Invalid status code: ${code}. Must be between 100 and 599`);
409
- }
410
- this.statusCode = statusCode;
411
- return this;
412
- }
413
-
414
- /**
415
- * Redirect to a URL
416
- *
417
- * Sets the Location header and status code, then ends the response.
418
- *
419
- * @param {string} url - The URL to redirect to
420
- * @param {number} [status=302] - HTTP status code for redirect
421
- * @returns {Context} The context instance for method chaining
422
- *
423
- * @since 1.0.0
424
- *
425
- * @example
426
- * // Temporary redirect (302)
427
- * ctx.redirect('/login');
428
- *
429
- * @example
430
- * // Permanent redirect (301)
431
- * ctx.redirect('/new-path', 301);
432
- */
433
- redirect(url, status = 302) {
434
- this.status(status);
435
- this.set('Location', url);
436
- this.end();
437
- return this;
438
- }
439
-
440
- /**
441
- * Send a JSON response
442
- *
443
- * Sets the Content-Type header to application/json and sends the data as JSON.
444
- *
445
- * @param {*} data - The data to send as JSON
446
- * @returns {Context} The context instance for method chaining
447
- *
448
- * @since 1.0.0
449
- *
450
- * @example
451
- * ctx.json({ message: 'Hello World' });
452
- *
453
- * @example
454
- * // With status code
455
- * ctx.status(201).json({ id: 123, name: 'User' });
456
- */
457
- json(data) {
458
- this.set('Content-Type', 'application/json');
459
- this.send(JSON.stringify(data));
460
- return this;
461
- }
462
-
463
- /**
464
- * Send a plain text response
465
- *
466
- * Sets the Content-Type header to text/plain and sends the data as text.
467
- *
468
- * @param {string} data - The text data to send
469
- * @returns {Context} The context instance for method chaining
470
- *
471
- * @since 1.0.0
472
- *
473
- * @example
474
- * ctx.text('Hello World');
475
- *
476
- * @example
477
- * // With status code
478
- * ctx.status(200).text('Success');
479
- */
480
- text(data) {
481
- this.set('Content-Type', 'text/plain');
482
- this.send(data);
483
- return this;
484
- }
485
-
486
- /**
487
- * Send an HTML response
488
- *
489
- * Sets the Content-Type header to text/html and sends the data as HTML.
490
- *
491
- * @param {string} data - The HTML data to send
492
- * @returns {Context} The context instance for method chaining
493
- *
494
- * @since 1.0.0
495
- *
496
- * @example
497
- * ctx.html('<h1>Hello World</h1>');
498
- *
499
- * @example
500
- * // With status code
501
- * ctx.status(200).html('<p>Welcome!</p>');
502
- */
503
- html(data) {
504
- this.set('Content-Type', 'text/html');
505
- this.send(data);
506
- return this;
507
- }
508
-
509
- /**
510
- * Send a response with data
511
- *
512
- * Sends the response with the specified data. This method is called by other
513
- * response methods like json(), text(), and html(). Once called, no further
514
- * response methods can be used.
515
- *
516
- * @param {*} data - The data to send
517
- * @returns {Context} The context instance for method chaining
518
- *
519
- * @since 1.0.0
520
- *
521
- * @example
522
- * ctx.send('Hello World');
523
- * ctx.send(Buffer.from('binary data'));
524
- */
525
- send(data) {
526
- if (this.responded) {
527
- return this;
528
- }
529
-
530
- this.responded = true;
531
- this.res.statusCode = this.statusCode;
532
-
533
- Object.keys(this.responseHeaders).forEach(name => {
534
- this.res.setHeader(name, this.responseHeaders[name]);
535
- });
536
-
537
- if (data === null || data === undefined) {
538
- this.res.end();
539
- } else if (typeof data === 'string' || Buffer.isBuffer(data)) {
540
- this.res.end(data);
541
- } else {
542
- this.res.end(String(data));
543
- }
544
-
545
- return this;
546
- }
547
-
548
- /**
549
- * End the response
550
- *
551
- * Ends the response optionally with data. This is an alias for send().
552
- *
553
- * @param {*} [data] - Optional data to send before ending
554
- * @returns {Context} The context instance for method chaining
555
- *
556
- * @since 1.0.0
557
- *
558
- * @example
559
- * ctx.status(204).end(); // No content
560
- * ctx.end('Final message');
561
- */
562
- end(data) {
563
- if (data) {
564
- this.send(data);
565
- } else {
566
- this.send();
567
- }
568
- return this;
569
- }
570
-
571
- setCookie(name, value, options = {}) {
572
- // Validate cookie name
573
- if (!name || typeof name !== 'string') {
574
- throw new Error('Cookie name must be a non-empty string');
575
- }
576
-
577
- // Validate cookie name format (RFC 6265)
578
- if (!/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(name)) {
579
- throw new Error(`Invalid cookie name: ${name}`);
580
- }
581
-
582
- // Check for control characters in cookie name
583
- if (/[\x00-\x1F\x7F]/.test(name)) {
584
- throw new Error('Cookie name cannot contain control characters');
585
- }
586
-
587
- // Validate cookie value
588
- if (value === null || value === undefined) {
589
- value = '';
590
- }
591
-
592
- // Convert value to string and check for invalid characters
593
- const stringValue = String(value);
594
- if (/[\x00-\x1F\x7F]/.test(stringValue)) {
595
- throw new Error('Cookie value cannot contain control characters');
596
- }
597
-
598
- let cookieString = `${name}=${encodeURIComponent(value)}`;
599
-
600
- if (options.domain) {
601
- cookieString += `; Domain=${options.domain}`;
602
- }
603
-
604
- if (options.path) {
605
- cookieString += `; Path=${options.path}`;
606
- }
607
-
608
- if (options.expires) {
609
- cookieString += `; Expires=${options.expires.toUTCString()}`;
610
- }
611
-
612
- if (options.maxAge) {
613
- cookieString += `; Max-Age=${options.maxAge}`;
614
- }
615
-
616
- if (options.httpOnly) {
617
- cookieString += '; HttpOnly';
618
- }
619
-
620
- if (options.secure) {
621
- cookieString += '; Secure';
622
- }
623
-
624
- if (options.sameSite) {
625
- const validSameSite = ['Strict', 'Lax', 'None'];
626
- const sameSiteValue = options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1).toLowerCase();
627
- if (!validSameSite.includes(sameSiteValue)) {
628
- throw new Error(`Invalid SameSite value: ${options.sameSite}. Must be 'Strict', 'Lax', or 'None'`);
629
- }
630
- cookieString += `; SameSite=${sameSiteValue}`;
631
- }
632
-
633
- const existingCookies = this.responseHeaders['set-cookie'] || [];
634
- if (Array.isArray(existingCookies)) {
635
- existingCookies.push(cookieString);
636
- this.responseHeaders['set-cookie'] = existingCookies;
637
- } else if (existingCookies) {
638
- this.responseHeaders['set-cookie'] = [existingCookies, cookieString];
639
- } else {
640
- this.responseHeaders['set-cookie'] = [cookieString];
641
- }
642
-
643
- return this;
644
- }
645
-
646
- clearCookie(name, options = {}) {
647
- const clearOptions = {
648
- ...options,
649
- expires: new Date(0),
650
- maxAge: 0
651
- };
652
- return this.setCookie(name, '', clearOptions);
653
- }
654
-
655
- is(type) {
656
- const contentType = this.get('content-type');
657
- if (!contentType) return false;
658
-
659
- const mimeTypes = {
660
- json: 'application/json',
661
- form: 'application/x-www-form-urlencoded',
662
- multipart: 'multipart/form-data',
663
- text: 'text/plain',
664
- html: 'text/html'
665
- };
666
-
667
- const targetType = mimeTypes[type] || type;
668
- return contentType.includes(targetType);
669
- }
670
-
671
- accepts(types) {
672
- const accept = this.get('accept') || '*/*';
673
-
674
- if (typeof types === 'string') {
675
- types = [types];
676
- }
677
-
678
- for (const type of types) {
679
- if (accept.includes(type) || accept.includes('*/*')) {
680
- return type;
681
- }
682
- }
683
-
684
- return false;
685
- }
686
-
687
- fresh() {
688
- const method = this.method;
689
- const status = this.statusCode;
690
-
691
- if (method !== 'GET' && method !== 'HEAD') return false;
692
- if ((status >= 200 && status < 300) || status === 304) return true;
693
-
694
- return false;
695
- }
696
-
697
- stale() {
698
- return !this.fresh();
699
- }
700
-
701
- secure() {
702
- return this.req.connection.encrypted;
703
- }
704
-
705
- xhr() {
706
- return this.get('x-requested-with') === 'XMLHttpRequest';
707
- }
708
-
709
- ip() {
710
- return this.get('x-forwarded-for') ||
711
- this.get('x-real-ip') ||
712
- this.req.connection.remoteAddress ||
713
- this.req.socket.remoteAddress;
714
- }
715
-
716
- ips() {
717
- const forwarded = this.get('x-forwarded-for');
718
- return forwarded ? forwarded.split(/\s*,\s*/) : [this.ip()];
719
- }
720
-
721
- protocol() {
722
- return this.req.connection.encrypted ? 'https' : 'http';
723
- }
724
-
725
- host() {
726
- return this.get('host') || 'localhost';
727
- }
728
-
729
- hostname() {
730
- return this.host().split(':')[0];
731
- }
732
-
733
- port() {
734
- const host = this.host();
735
- const portMatch = host.match(/:(\d+)$/);
736
- return portMatch ? parseInt(portMatch[1]) : (this.secure() ? 443 : 80);
737
- }
738
-
739
- subdomains() {
740
- const hostname = this.hostname();
741
- const parts = hostname.split('.');
742
- return parts.length > 2 ? parts.slice(0, -2).reverse() : [];
743
- }
744
-
745
- type() {
746
- const contentType = this.get('content-type');
747
- return contentType ? contentType.split(';')[0] : '';
748
- }
749
-
750
- charset() {
751
- const contentType = this.get('content-type');
752
- if (!contentType) return '';
753
-
754
- const match = contentType.match(/charset=([^;]+)/);
755
- return match ? match[1] : '';
756
- }
757
-
758
- length() {
759
- const contentLength = this.get('content-length');
760
- return contentLength ? parseInt(contentLength) : 0;
761
- }
762
-
763
- toString() {
764
- return `${this.method} ${this.originalUrl}`;
765
- }
766
-
767
- toJSON() {
768
- return {
769
- method: this.method,
770
- url: this.originalUrl,
771
- path: this.path,
772
- query: this.query,
773
- params: this.params,
774
- headers: this.headers,
775
- cookies: this.cookies,
776
- statusCode: this.statusCode,
777
- responded: this.responded
778
- };
779
- }
780
-
781
- /**
782
- * Initialize context with new request/response (for object pooling)
783
- * @param {IncomingMessage} req - HTTP request
784
- * @param {ServerResponse} res - HTTP response
785
- * @param {Application} app - Spark application
786
- */
787
- init(req, res, app) {
788
- this.req = req;
789
- this.res = res;
790
- this.app = app;
791
- this.responded = false;
792
- this.statusCode = 200;
793
-
794
- this.initializeUrl();
795
- this.initializeHeaders();
796
- this.initializeQuery();
797
- this.initializeCookies();
798
-
799
- this.params = {};
800
- this.body = null;
801
- this.files = null;
802
- this.session = null;
803
- this.state = {};
804
- }
805
-
806
- /**
807
- * Reset context for object pooling
808
- */
809
- reset() {
810
- this.req = null;
811
- this.res = null;
812
- this.app = null;
813
- this.responded = false;
814
- this.statusCode = 200;
815
- this.url = null;
816
- this.path = null;
817
- this.method = null;
818
- this.originalUrl = null;
819
- this.headers = {};
820
- this.responseHeaders = {};
821
- this.query = {};
822
- this.cookies = {};
823
- this.params = {};
824
- this.body = null;
825
- this.files = null;
826
- this.session = null;
827
- this.state = {};
828
- }
829
- }
830
-
831
- module.exports = Context;