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