@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,333 +0,0 @@
1
- const { URL } = require('url');
2
- const querystring = require('querystring');
3
-
4
- class Request {
5
- constructor(req) {
6
- this.req = req;
7
- this.method = req.method;
8
- this.url = req.url;
9
- this.headers = req.headers;
10
- this.httpVersion = req.httpVersion;
11
- this.httpVersionMajor = req.httpVersionMajor;
12
- this.httpVersionMinor = req.httpVersionMinor;
13
- this.connection = req.connection;
14
- this.socket = req.socket;
15
- this.complete = req.complete;
16
- this.trailers = req.trailers;
17
- this.rawTrailers = req.rawTrailers;
18
- this.aborted = req.aborted;
19
- this.upgrade = req.upgrade;
20
-
21
- this.parsedUrl = new URL(this.url, `http://${this.headers.host}`);
22
- this.pathname = this.parsedUrl.pathname;
23
- this.query = querystring.parse(this.parsedUrl.search.slice(1));
24
- this.search = this.parsedUrl.search;
25
- this.hash = this.parsedUrl.hash;
26
-
27
- this.body = null;
28
- this.rawBody = null;
29
- this.files = {};
30
- this.params = {};
31
-
32
- this.parseHeaders();
33
- this.parseCookies();
34
- }
35
-
36
- parseHeaders() {
37
- this.host = this.headers.host;
38
- this.hostname = this.host ? this.host.split(':')[0] : 'localhost';
39
- this.protocol = this.connection.encrypted ? 'https' : 'http';
40
- this.secure = this.connection.encrypted;
41
- this.ip = this.connection.remoteAddress;
42
- this.ips = this.getIPs();
43
- this.userAgent = this.headers['user-agent'];
44
- this.contentType = this.headers['content-type'];
45
- this.contentLength = parseInt(this.headers['content-length']) || 0;
46
- this.accept = this.headers.accept;
47
- this.authorization = this.headers.authorization;
48
- this.referer = this.headers.referer || this.headers.referrer;
49
- this.origin = this.headers.origin;
50
- }
51
-
52
- parseCookies() {
53
- this.cookies = {};
54
- const cookieHeader = this.headers.cookie;
55
-
56
- if (cookieHeader) {
57
- cookieHeader.split(';').forEach(cookie => {
58
- const [name, value] = cookie.trim().split('=');
59
- if (name && value) {
60
- this.cookies[name] = decodeURIComponent(value);
61
- }
62
- });
63
- }
64
- }
65
-
66
- getIPs() {
67
- const forwarded = this.headers['x-forwarded-for'];
68
- if (forwarded) {
69
- return forwarded.split(',').map(ip => ip.trim());
70
- }
71
- return [this.ip];
72
- }
73
-
74
- get(headerName) {
75
- return this.headers[headerName.toLowerCase()];
76
- }
77
-
78
- header(headerName) {
79
- return this.get(headerName);
80
- }
81
-
82
- is(type) {
83
- if (!this.contentType) return false;
84
-
85
- const mimeTypes = {
86
- json: 'application/json',
87
- form: 'application/x-www-form-urlencoded',
88
- multipart: 'multipart/form-data',
89
- text: 'text/plain',
90
- html: 'text/html',
91
- xml: 'application/xml'
92
- };
93
-
94
- const targetType = mimeTypes[type] || type;
95
- return this.contentType.includes(targetType);
96
- }
97
-
98
- accepts(types) {
99
- if (!this.accept) return false;
100
-
101
- if (typeof types === 'string') {
102
- types = [types];
103
- }
104
-
105
- for (const type of types) {
106
- if (this.accept.includes(type) || this.accept.includes('*/*')) {
107
- return type;
108
- }
109
- }
110
-
111
- return false;
112
- }
113
-
114
- acceptsCharsets(charsets) {
115
- const acceptCharset = this.headers['accept-charset'];
116
- if (!acceptCharset) return charsets[0];
117
-
118
- if (typeof charsets === 'string') {
119
- charsets = [charsets];
120
- }
121
-
122
- for (const charset of charsets) {
123
- if (acceptCharset.includes(charset)) {
124
- return charset;
125
- }
126
- }
127
-
128
- return false;
129
- }
130
-
131
- acceptsEncodings(encodings) {
132
- const acceptEncoding = this.headers['accept-encoding'];
133
- if (!acceptEncoding) return encodings[0];
134
-
135
- if (typeof encodings === 'string') {
136
- encodings = [encodings];
137
- }
138
-
139
- for (const encoding of encodings) {
140
- if (acceptEncoding.includes(encoding)) {
141
- return encoding;
142
- }
143
- }
144
-
145
- return false;
146
- }
147
-
148
- acceptsLanguages(languages) {
149
- const acceptLanguage = this.headers['accept-language'];
150
- if (!acceptLanguage) return languages[0];
151
-
152
- if (typeof languages === 'string') {
153
- languages = [languages];
154
- }
155
-
156
- for (const language of languages) {
157
- if (acceptLanguage.includes(language)) {
158
- return language;
159
- }
160
- }
161
-
162
- return false;
163
- }
164
-
165
- range(size) {
166
- const range = this.headers.range;
167
- if (!range) return null;
168
-
169
- const ranges = parseRange(size, range);
170
- return ranges.length > 0 ? ranges : null;
171
- }
172
-
173
- param(name, defaultValue) {
174
- if (this.params.hasOwnProperty(name)) {
175
- return this.params[name];
176
- }
177
-
178
- if (this.body && this.body.hasOwnProperty(name)) {
179
- return this.body[name];
180
- }
181
-
182
- if (this.query.hasOwnProperty(name)) {
183
- return this.query[name];
184
- }
185
-
186
- return defaultValue;
187
- }
188
-
189
- fresh() {
190
- const method = this.method;
191
- const status = this.statusCode;
192
-
193
- if (method !== 'GET' && method !== 'HEAD') return false;
194
- if ((status >= 200 && status < 300) || status === 304) return true;
195
-
196
- return false;
197
- }
198
-
199
- stale() {
200
- return !this.fresh();
201
- }
202
-
203
- xhr() {
204
- return this.get('x-requested-with') === 'XMLHttpRequest';
205
- }
206
-
207
- subdomains() {
208
- const parts = this.hostname.split('.');
209
- return parts.length > 2 ? parts.slice(0, -2).reverse() : [];
210
- }
211
-
212
- route() {
213
- return this.route;
214
- }
215
-
216
- baseUrl() {
217
- return `${this.protocol}://${this.host}`;
218
- }
219
-
220
- originalUrl() {
221
- return this.url;
222
- }
223
-
224
- path() {
225
- return this.pathname;
226
- }
227
-
228
- async readBody() {
229
- if (this.body !== null) {
230
- return this.body;
231
- }
232
-
233
- return new Promise((resolve, reject) => {
234
- let body = '';
235
- this.req.on('data', chunk => {
236
- body += chunk;
237
- });
238
-
239
- this.req.on('end', () => {
240
- this.rawBody = body;
241
- try {
242
- if (this.is('json')) {
243
- this.body = JSON.parse(body);
244
- } else if (this.is('form')) {
245
- this.body = querystring.parse(body);
246
- } else {
247
- this.body = body;
248
- }
249
- resolve(this.body);
250
- } catch (error) {
251
- reject(error);
252
- }
253
- });
254
-
255
- this.req.on('error', reject);
256
- });
257
- }
258
-
259
- pipe(destination) {
260
- return this.req.pipe(destination);
261
- }
262
-
263
- unpipe(destination) {
264
- return this.req.unpipe(destination);
265
- }
266
-
267
- pause() {
268
- return this.req.pause();
269
- }
270
-
271
- resume() {
272
- return this.req.resume();
273
- }
274
-
275
- setTimeout(msecs, callback) {
276
- return this.req.setTimeout(msecs, callback);
277
- }
278
-
279
- destroy() {
280
- return this.req.destroy();
281
- }
282
-
283
- toString() {
284
- return `${this.method} ${this.url}`;
285
- }
286
-
287
- toJSON() {
288
- return {
289
- method: this.method,
290
- url: this.url,
291
- headers: this.headers,
292
- query: this.query,
293
- params: this.params,
294
- cookies: this.cookies,
295
- body: this.body,
296
- ip: this.ip,
297
- ips: this.ips,
298
- secure: this.secure,
299
- xhr: this.xhr()
300
- };
301
- }
302
- }
303
-
304
- function parseRange(size, range) {
305
- if (!range || !range.startsWith('bytes=')) {
306
- return [];
307
- }
308
-
309
- const ranges = [];
310
- const parts = range.slice(6).split(',');
311
-
312
- for (const part of parts) {
313
- const [start, end] = part.trim().split('-');
314
- const startNum = parseInt(start);
315
- const endNum = parseInt(end);
316
-
317
- if (isNaN(startNum) && isNaN(endNum)) {
318
- continue;
319
- }
320
-
321
- if (isNaN(startNum)) {
322
- ranges.push({ start: Math.max(0, size - endNum), end: size - 1 });
323
- } else if (isNaN(endNum)) {
324
- ranges.push({ start: startNum, end: size - 1 });
325
- } else {
326
- ranges.push({ start: startNum, end: Math.min(endNum, size - 1) });
327
- }
328
- }
329
-
330
- return ranges;
331
- }
332
-
333
- module.exports = Request;
@@ -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;
@@ -1,21 +0,0 @@
1
- /**
2
- * Middleware exports for @oxog/spark
3
- * Aggregates all built-in middleware for convenient importing
4
- */
5
-
6
- module.exports = {
7
- bodyParser: require('./body-parser'),
8
- cache: require('./cache'),
9
- compression: require('./compression'),
10
- cors: require('./cors'),
11
- health: require('./health'),
12
- healthCheck: require('./health'), // alias
13
- logger: require('./logger'),
14
- metrics: require('./metrics'),
15
- rateLimit: require('./rate-limit'),
16
- security: require('./security'),
17
- helmet: require('./security'), // alias for security
18
- session: require('./session'),
19
- static: require('./static'),
20
- serveStatic: require('./static') // alias
21
- };