@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,375 +0,0 @@
1
- const { STATUS_CODES } = require('http');
2
- const path = require('path');
3
- const fs = require('fs');
4
- const { promisify } = require('util');
5
- const stat = promisify(fs.stat);
6
- const readFile = promisify(fs.readFile);
7
-
8
- class Response {
9
- constructor(res) {
10
- this.res = res;
11
- this.statusCode = 200;
12
- this.headers = {};
13
- this.locals = {};
14
- this.finished = false;
15
- this.headersSent = false;
16
- }
17
-
18
- status(code) {
19
- this.statusCode = code;
20
- return this;
21
- }
22
-
23
- set(field, value) {
24
- if (typeof field === 'object') {
25
- Object.assign(this.headers, field);
26
- } else {
27
- this.headers[field.toLowerCase()] = value;
28
- }
29
- return this;
30
- }
31
-
32
- get(field) {
33
- return this.headers[field.toLowerCase()];
34
- }
35
-
36
- header(field, value) {
37
- return this.set(field, value);
38
- }
39
-
40
- setHeader(name, value) {
41
- return this.set(name, value);
42
- }
43
-
44
- getHeader(name) {
45
- return this.get(name);
46
- }
47
-
48
- removeHeader(name) {
49
- delete this.headers[name.toLowerCase()];
50
- return this;
51
- }
52
-
53
- append(field, value) {
54
- const existing = this.get(field);
55
- if (existing) {
56
- this.set(field, Array.isArray(existing) ? existing.concat(value) : [existing, value]);
57
- } else {
58
- this.set(field, value);
59
- }
60
- return this;
61
- }
62
-
63
- cookie(name, value, options = {}) {
64
- let cookieString = `${name}=${encodeURIComponent(value)}`;
65
-
66
- if (options.domain) {
67
- cookieString += `; Domain=${options.domain}`;
68
- }
69
-
70
- if (options.path) {
71
- cookieString += `; Path=${options.path}`;
72
- }
73
-
74
- if (options.expires) {
75
- cookieString += `; Expires=${options.expires.toUTCString()}`;
76
- }
77
-
78
- if (options.maxAge) {
79
- cookieString += `; Max-Age=${options.maxAge}`;
80
- }
81
-
82
- if (options.httpOnly) {
83
- cookieString += '; HttpOnly';
84
- }
85
-
86
- if (options.secure) {
87
- cookieString += '; Secure';
88
- }
89
-
90
- if (options.sameSite) {
91
- cookieString += `; SameSite=${options.sameSite}`;
92
- }
93
-
94
- this.append('Set-Cookie', cookieString);
95
- return this;
96
- }
97
-
98
- clearCookie(name, options = {}) {
99
- const clearOptions = {
100
- ...options,
101
- expires: new Date(0),
102
- maxAge: 0
103
- };
104
- return this.cookie(name, '', clearOptions);
105
- }
106
-
107
- redirect(url, status = 302) {
108
- this.status(status);
109
- this.set('Location', url);
110
- this.end();
111
- return this;
112
- }
113
-
114
- location(url) {
115
- this.set('Location', url);
116
- return this;
117
- }
118
-
119
- links(links) {
120
- let linkHeader = this.get('Link') || '';
121
-
122
- Object.keys(links).forEach(rel => {
123
- if (linkHeader) linkHeader += ', ';
124
- linkHeader += `<${links[rel]}>; rel="${rel}"`;
125
- });
126
-
127
- this.set('Link', linkHeader);
128
- return this;
129
- }
130
-
131
- type(type) {
132
- const mimeTypes = {
133
- html: 'text/html',
134
- json: 'application/json',
135
- xml: 'application/xml',
136
- text: 'text/plain',
137
- png: 'image/png',
138
- jpg: 'image/jpeg',
139
- jpeg: 'image/jpeg',
140
- gif: 'image/gif',
141
- css: 'text/css',
142
- js: 'application/javascript',
143
- pdf: 'application/pdf'
144
- };
145
-
146
- const contentType = mimeTypes[type] || type;
147
- this.set('Content-Type', contentType);
148
- return this;
149
- }
150
-
151
- format(obj) {
152
- const keys = Object.keys(obj);
153
- const accepts = this.req.accepts(keys);
154
-
155
- if (accepts) {
156
- this.type(accepts);
157
- obj[accepts](this.req, this);
158
- } else {
159
- this.status(406).send('Not Acceptable');
160
- }
161
-
162
- return this;
163
- }
164
-
165
- attachment(filename) {
166
- if (filename) {
167
- this.type(path.extname(filename));
168
- this.set('Content-Disposition', `attachment; filename="${filename}"`);
169
- } else {
170
- this.set('Content-Disposition', 'attachment');
171
- }
172
- return this;
173
- }
174
-
175
- json(obj) {
176
- this.type('json');
177
- this.send(JSON.stringify(obj));
178
- return this;
179
- }
180
-
181
- jsonp(obj) {
182
- const callback = this.req.query.callback || 'callback';
183
- this.type('text/javascript');
184
- this.send(`${callback}(${JSON.stringify(obj)})`);
185
- return this;
186
- }
187
-
188
- send(body) {
189
- if (this.finished) {
190
- return this;
191
- }
192
-
193
- this.writeHead();
194
-
195
- if (body === null || body === undefined) {
196
- this.res.end();
197
- } else if (typeof body === 'string') {
198
- if (!this.get('Content-Type')) {
199
- this.type('html');
200
- }
201
- this.res.end(body);
202
- } else if (Buffer.isBuffer(body)) {
203
- if (!this.get('Content-Type')) {
204
- this.type('application/octet-stream');
205
- }
206
- this.res.end(body);
207
- } else {
208
- this.json(body);
209
- }
210
-
211
- this.finished = true;
212
- return this;
213
- }
214
-
215
- async sendFile(filePath, options = {}) {
216
- try {
217
- const stats = await stat(filePath);
218
-
219
- if (!stats.isFile()) {
220
- return this.status(404).send('File not found');
221
- }
222
-
223
- const ext = path.extname(filePath);
224
- this.type(ext);
225
-
226
- if (options.maxAge) {
227
- this.set('Cache-Control', `public, max-age=${options.maxAge}`);
228
- }
229
-
230
- this.set('Content-Length', stats.size);
231
- this.set('Last-Modified', stats.mtime.toUTCString());
232
-
233
- const etag = `"${stats.size}-${stats.mtime.getTime()}"`;
234
- this.set('ETag', etag);
235
-
236
- if (this.req.headers['if-none-match'] === etag) {
237
- return this.status(304).end();
238
- }
239
-
240
- if (options.headers) {
241
- this.set(options.headers);
242
- }
243
-
244
- this.writeHead();
245
-
246
- const stream = fs.createReadStream(filePath);
247
- stream.pipe(this.res);
248
-
249
- stream.on('end', () => {
250
- this.finished = true;
251
- });
252
-
253
- stream.on('error', (error) => {
254
- this.status(500).send('Internal Server Error');
255
- });
256
-
257
- } catch (error) {
258
- this.status(404).send('File not found');
259
- }
260
-
261
- return this;
262
- }
263
-
264
- async sendStatus(statusCode) {
265
- this.status(statusCode);
266
- this.send(STATUS_CODES[statusCode] || 'Unknown Status');
267
- return this;
268
- }
269
-
270
- download(filePath, filename, options = {}) {
271
- const name = filename || path.basename(filePath);
272
- this.attachment(name);
273
- return this.sendFile(filePath, options);
274
- }
275
-
276
- render(view, locals = {}, callback) {
277
- if (typeof locals === 'function') {
278
- callback = locals;
279
- locals = {};
280
- }
281
-
282
- const renderLocals = { ...this.locals, ...locals };
283
-
284
- if (this.app.render) {
285
- this.app.render(view, renderLocals, (err, html) => {
286
- if (err) {
287
- if (callback) return callback(err);
288
- throw err;
289
- }
290
-
291
- this.send(html);
292
- if (callback) callback(null, html);
293
- });
294
- } else {
295
- const error = new Error('No template engine configured');
296
- if (callback) return callback(error);
297
- throw error;
298
- }
299
-
300
- return this;
301
- }
302
-
303
- vary(field) {
304
- this.append('Vary', field);
305
- return this;
306
- }
307
-
308
- writeHead() {
309
- if (this.headersSent) {
310
- return;
311
- }
312
-
313
- this.res.statusCode = this.statusCode;
314
-
315
- Object.keys(this.headers).forEach(name => {
316
- this.res.setHeader(name, this.headers[name]);
317
- });
318
-
319
- this.headersSent = true;
320
- }
321
-
322
- write(chunk, encoding) {
323
- if (!this.headersSent) {
324
- this.writeHead();
325
- }
326
- return this.res.write(chunk, encoding);
327
- }
328
-
329
- end(data, encoding) {
330
- if (!this.headersSent) {
331
- this.writeHead();
332
- }
333
-
334
- this.finished = true;
335
- this.res.end(data, encoding);
336
- return this;
337
- }
338
-
339
- destroy() {
340
- this.res.destroy();
341
- return this;
342
- }
343
-
344
- setTimeout(msecs, callback) {
345
- this.res.setTimeout(msecs, callback);
346
- return this;
347
- }
348
-
349
- headersSent() {
350
- return this.headersSent;
351
- }
352
-
353
- writableEnded() {
354
- return this.res.writableEnded;
355
- }
356
-
357
- writable() {
358
- return this.res.writable;
359
- }
360
-
361
- toString() {
362
- return `Response ${this.statusCode}`;
363
- }
364
-
365
- toJSON() {
366
- return {
367
- statusCode: this.statusCode,
368
- headers: this.headers,
369
- finished: this.finished,
370
- headersSent: this.headersSent
371
- };
372
- }
373
- }
374
-
375
- module.exports = Response;
package/dist/index.js DELETED
@@ -1,278 +0,0 @@
1
- /**
2
- * @fileoverview Main entry point for the Spark Web Framework
3
- * @author Spark Framework Team
4
- * @since 1.0.0
5
- * @version 1.0.0
6
- */
7
-
8
- const Application = require('./core/application');
9
- const Router = require('./router/router');
10
- const Context = require('./core/context');
11
-
12
- const bodyParser = require('./middleware/body-parser');
13
- const cors = require('./middleware/cors');
14
- const compression = require('./middleware/compression');
15
- const staticFiles = require('./middleware/static');
16
- const session = require('./middleware/session');
17
- const rateLimit = require('./middleware/rate-limit');
18
- const security = require('./middleware/security');
19
- const healthCheck = require('./middleware/health');
20
- const metrics = require('./middleware/metrics');
21
- const logger = require('./middleware/logger');
22
-
23
- // Error handling utilities
24
- const { asyncHandler, errorHandler, createError, errors } = require('./utils/async-handler');
25
-
26
- // Utility classes
27
- const ContextPool = require('./utils/context-pool');
28
- const { RegexValidator, SafeRegexCache } = require('./utils/regex-validator');
29
-
30
- /**
31
- * Spark Web Framework - A fast, secure, and modern Node.js web framework
32
- *
33
- * Spark extends the base Application class to provide a complete web framework
34
- * with built-in security, middleware support, and modern development features.
35
- *
36
- * @class Spark
37
- * @extends Application
38
- * @since 1.0.0
39
- *
40
- * @example
41
- * // Basic usage
42
- * const { Spark } = require('spark-framework');
43
- *
44
- * const app = new Spark({
45
- * port: 3000,
46
- * security: {
47
- * cors: { origin: true },
48
- * rateLimit: { max: 100, window: 60000 }
49
- * }
50
- * });
51
- *
52
- * app.get('/', (ctx) => {
53
- * ctx.json({ message: 'Hello Spark!' });
54
- * });
55
- *
56
- * app.listen();
57
- *
58
- * @example
59
- * // With middleware
60
- * const app = new Spark();
61
- *
62
- * app.use(bodyParser.json());
63
- * app.use(cors({ origin: 'https://example.com' }));
64
- *
65
- * app.post('/api/users', (ctx) => {
66
- * const userData = ctx.body;
67
- * ctx.json({ success: true, data: userData });
68
- * });
69
- *
70
- * app.listen(8080);
71
- */
72
- class Spark extends Application {
73
- /**
74
- * Create a new Spark application instance
75
- *
76
- * @param {Object} [options={}] - Configuration options for the application
77
- * @param {number} [options.port=3000] - Port number to listen on
78
- * @param {string} [options.host='127.0.0.1'] - Host address to bind to
79
- * @param {boolean} [options.cluster=false] - Enable cluster mode
80
- * @param {Object} [options.security] - Security configuration
81
- * @param {Object} [options.https] - HTTPS configuration with key and cert
82
- *
83
- * @since 1.0.0
84
- *
85
- * @example
86
- * const app = new Spark({
87
- * port: 8080,
88
- * host: '0.0.0.0',
89
- * security: {
90
- * cors: { origin: ['https://example.com'] },
91
- * rateLimit: { max: 200, window: 60000 }
92
- * }
93
- * });
94
- */
95
- constructor(options) {
96
- super(options);
97
- }
98
- }
99
-
100
- // Export both Spark and App for backwards compatibility
101
- const App = Spark;
102
-
103
- /**
104
- * Main exports for the Spark Web Framework
105
- *
106
- * @namespace SparkExports
107
- * @since 1.0.0
108
- *
109
- * @example
110
- * // ES6 destructuring
111
- * const { Spark, Router, bodyParser } = require('spark-framework');
112
- *
113
- * @example
114
- * // CommonJS
115
- * const Spark = require('spark-framework').Spark;
116
- *
117
- * @example
118
- * // Access middleware
119
- * const { middleware } = require('spark-framework');
120
- * app.use(middleware.bodyParser.json());
121
- */
122
- module.exports = {
123
- /**
124
- * Main Spark application class
125
- * @type {typeof Spark}
126
- */
127
- Spark,
128
-
129
- /**
130
- * Backwards compatibility alias for Spark
131
- * @deprecated Use Spark instead
132
- * @type {typeof Spark}
133
- */
134
- App, // Deprecated: Use Spark instead
135
-
136
- /**
137
- * Base Application class
138
- * @type {typeof Application}
139
- */
140
- Application,
141
-
142
- /**
143
- * Router class for handling routes
144
- * @type {typeof Router}
145
- */
146
- Router,
147
-
148
- /**
149
- * Context class for request/response handling
150
- * @type {typeof Context}
151
- */
152
- Context,
153
-
154
- /**
155
- * Middleware collection
156
- * @namespace middleware
157
- * @property {Function} bodyParser - Body parsing middleware
158
- * @property {Function} cors - CORS middleware
159
- * @property {Function} compression - Response compression middleware
160
- * @property {Function} static - Static file serving middleware
161
- * @property {Function} session - Session management middleware
162
- * @property {Function} rateLimit - Rate limiting middleware
163
- * @property {Function} security - Security headers middleware
164
- * @property {Function} healthCheck - Health check endpoint middleware
165
- * @property {Function} metrics - Metrics collection middleware
166
- * @property {Function} logger - Request logging middleware
167
- */
168
- middleware: {
169
- bodyParser,
170
- cors,
171
- compression,
172
- static: staticFiles,
173
- session,
174
- rateLimit,
175
- security,
176
- helmet: security.helmet || security, // Alias for security middleware
177
- healthCheck,
178
- health: healthCheck, // Alias
179
- metrics,
180
- logger,
181
- cache: require('./middleware/cache'), // Add cache middleware
182
- compress: compression // Alias for compression
183
- },
184
-
185
- /**
186
- * Body parsing middleware - Direct export
187
- * @type {Function}
188
- */
189
- bodyParser,
190
-
191
- /**
192
- * CORS middleware - Direct export
193
- * @type {Function}
194
- */
195
- cors,
196
-
197
- /**
198
- * Compression middleware - Direct export
199
- * @type {Function}
200
- */
201
- compression,
202
-
203
- /**
204
- * Static file middleware - Direct export
205
- * @type {Function}
206
- */
207
- static: staticFiles,
208
-
209
- /**
210
- * Session middleware - Direct export
211
- * @type {Function}
212
- */
213
- session,
214
-
215
- /**
216
- * Rate limiting middleware - Direct export
217
- * @type {Function}
218
- */
219
- rateLimit,
220
-
221
- /**
222
- * Security headers middleware - Direct export
223
- * @type {Function}
224
- */
225
- security,
226
-
227
- /**
228
- * Health check middleware - Direct export
229
- * @type {Function}
230
- */
231
- healthCheck,
232
-
233
- /**
234
- * Metrics collection middleware - Direct export
235
- * @type {Function}
236
- */
237
- metrics,
238
-
239
- /**
240
- * Logger middleware - Direct export
241
- * @type {Function}
242
- */
243
- logger,
244
-
245
- /**
246
- * Error handling utilities
247
- * @namespace errorHandling
248
- * @property {Function} asyncHandler - Wraps async functions for error handling
249
- * @property {Function} errorHandler - Global error handler middleware
250
- * @property {Function} createError - Creates custom errors with status codes
251
- * @property {Object} errors - Predefined error types
252
- */
253
- errorHandling: {
254
- asyncHandler,
255
- errorHandler,
256
- createError,
257
- errors
258
- },
259
-
260
- /**
261
- * Utility classes and functions
262
- * @namespace utils
263
- * @property {Class} ContextPool - Object pool for Context instances
264
- * @property {Class} RegexValidator - Regex validation utilities
265
- * @property {Class} SafeRegexCache - Safe regex caching system
266
- */
267
- utils: {
268
- ContextPool,
269
- RegexValidator,
270
- SafeRegexCache
271
- }
272
- };
273
-
274
- /**
275
- * Default export for ES6 compatibility
276
- * @type {Object}
277
- */
278
- module.exports.default = module.exports;