@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,185 +0,0 @@
1
- 'use strict';
2
-
3
- const zlib = require('zlib');
4
- const { promisify } = require('util');
5
-
6
- const gzip = promisify(zlib.gzip);
7
- const deflate = promisify(zlib.deflate);
8
- const brotliCompress = promisify(zlib.brotliCompress);
9
-
10
- const DEFAULT_THRESHOLD = 1024;
11
- const DEFAULT_LEVEL = 6;
12
-
13
- function compression(options = {}) {
14
- const opts = {
15
- threshold: options.threshold || DEFAULT_THRESHOLD,
16
- level: options.level || DEFAULT_LEVEL,
17
- chunkSize: options.chunkSize || 16 * 1024,
18
- windowBits: options.windowBits || 15,
19
- memLevel: options.memLevel || 8,
20
- strategy: options.strategy || zlib.constants.Z_DEFAULT_STRATEGY,
21
- filter: options.filter || shouldCompress,
22
- ...options
23
- };
24
-
25
- return async (ctx, next) => {
26
- const originalSend = ctx.send;
27
-
28
- ctx.send = function(body) {
29
- return compressResponse.call(this, body, opts, originalSend);
30
- };
31
-
32
- await next();
33
- };
34
- }
35
-
36
- async function compressResponse(body, opts, originalSend) {
37
- if (this.headersSent || this.responded) {
38
- return originalSend.call(this, body);
39
- }
40
-
41
- const shouldCompress = opts.filter(this, body);
42
- if (!shouldCompress) {
43
- return originalSend.call(this, body);
44
- }
45
-
46
- const acceptEncoding = this.get('accept-encoding') || '';
47
- const encoding = getPreferredEncoding(acceptEncoding);
48
-
49
- if (!encoding) {
50
- return originalSend.call(this, body);
51
- }
52
-
53
- const bodyBuffer = Buffer.isBuffer(body) ? body : Buffer.from(String(body));
54
-
55
- if (bodyBuffer.length < opts.threshold) {
56
- return originalSend.call(this, body);
57
- }
58
-
59
- try {
60
- const compressed = await compressBuffer(bodyBuffer, encoding, opts);
61
-
62
- this.set('Content-Encoding', encoding);
63
- this.set('Content-Length', compressed.length);
64
- this.removeHeader('Content-Length');
65
- this.set('Vary', 'Accept-Encoding');
66
-
67
- return originalSend.call(this, compressed);
68
- } catch (error) {
69
- return originalSend.call(this, body);
70
- }
71
- }
72
-
73
- function shouldCompress(ctx, body) {
74
- const contentType = ctx.get('content-type');
75
-
76
- if (!contentType) {
77
- return false;
78
- }
79
-
80
- const compressibleTypes = [
81
- 'text/',
82
- 'application/json',
83
- 'application/javascript',
84
- 'application/xml',
85
- 'application/rss+xml',
86
- 'application/atom+xml',
87
- 'image/svg+xml'
88
- ];
89
-
90
- return compressibleTypes.some(type => contentType.includes(type));
91
- }
92
-
93
- function getPreferredEncoding(acceptEncoding) {
94
- const encodings = parseAcceptEncoding(acceptEncoding);
95
-
96
- if (encodings.br && encodings.br.q > 0) {
97
- return 'br';
98
- }
99
-
100
- if (encodings.gzip && encodings.gzip.q > 0) {
101
- return 'gzip';
102
- }
103
-
104
- if (encodings.deflate && encodings.deflate.q > 0) {
105
- return 'deflate';
106
- }
107
-
108
- return null;
109
- }
110
-
111
- function parseAcceptEncoding(acceptEncoding) {
112
- const encodings = {};
113
-
114
- if (!acceptEncoding) {
115
- return encodings;
116
- }
117
-
118
- acceptEncoding.split(',').forEach(encoding => {
119
- const parts = encoding.trim().split(';');
120
- const name = parts[0].trim();
121
-
122
- let q = 1;
123
- if (parts[1]) {
124
- const qMatch = parts[1].match(/q=([0-9.]+)/);
125
- if (qMatch) {
126
- q = parseFloat(qMatch[1]);
127
- }
128
- }
129
-
130
- encodings[name] = { q };
131
- });
132
-
133
- return encodings;
134
- }
135
-
136
- async function compressBuffer(buffer, encoding, opts) {
137
- const options = {
138
- level: opts.level,
139
- chunkSize: opts.chunkSize,
140
- windowBits: opts.windowBits,
141
- memLevel: opts.memLevel,
142
- strategy: opts.strategy
143
- };
144
-
145
- switch (encoding) {
146
- case 'br':
147
- return await brotliCompress(buffer, {
148
- params: {
149
- [zlib.constants.BROTLI_PARAM_QUALITY]: opts.level
150
- }
151
- });
152
- case 'gzip':
153
- return await gzip(buffer, options);
154
- case 'deflate':
155
- return await deflate(buffer, options);
156
- default:
157
- throw new Error(`Unsupported encoding: ${encoding}`);
158
- }
159
- }
160
-
161
- function gzipCompression(options) {
162
- return compression({ ...options, filter: (ctx, body) => {
163
- const acceptEncoding = ctx.get('accept-encoding') || '';
164
- return acceptEncoding.includes('gzip') && shouldCompress(ctx, body);
165
- }});
166
- }
167
-
168
- function deflateCompression(options) {
169
- return compression({ ...options, filter: (ctx, body) => {
170
- const acceptEncoding = ctx.get('accept-encoding') || '';
171
- return acceptEncoding.includes('deflate') && shouldCompress(ctx, body);
172
- }});
173
- }
174
-
175
- function brotliCompression(options) {
176
- return compression({ ...options, filter: (ctx, body) => {
177
- const acceptEncoding = ctx.get('accept-encoding') || '';
178
- return acceptEncoding.includes('br') && shouldCompress(ctx, body);
179
- }});
180
- }
181
-
182
- module.exports = compression;
183
- module.exports.gzip = gzipCompression;
184
- module.exports.deflate = deflateCompression;
185
- module.exports.brotli = brotliCompression;
@@ -1,97 +0,0 @@
1
- 'use strict';
2
-
3
- const DEFAULT_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'HEAD', 'PATCH'];
4
-
5
- function cors(options = {}) {
6
- const opts = {
7
- origin: options.origin !== undefined ? options.origin : false, // Secure default: CORS disabled
8
- methods: options.methods || DEFAULT_METHODS,
9
- allowedHeaders: options.allowedHeaders || ['Content-Type', 'Authorization'],
10
- exposedHeaders: options.exposedHeaders || [],
11
- credentials: options.credentials || false,
12
- maxAge: options.maxAge || 86400,
13
- preflightContinue: options.preflightContinue || false,
14
- optionsSuccessStatus: options.optionsSuccessStatus || 204,
15
- ...options
16
- };
17
-
18
- return async (ctx, next) => {
19
- const origin = getOrigin(ctx, opts.origin);
20
-
21
- if (origin) {
22
- ctx.set('Access-Control-Allow-Origin', origin);
23
- }
24
-
25
- if (opts.credentials) {
26
- ctx.set('Access-Control-Allow-Credentials', 'true');
27
- }
28
-
29
- if (opts.exposedHeaders && opts.exposedHeaders.length > 0) {
30
- ctx.set('Access-Control-Expose-Headers', opts.exposedHeaders.join(', '));
31
- }
32
-
33
- if (ctx.method === 'OPTIONS') {
34
- return handlePreflight(ctx, opts);
35
- }
36
-
37
- await next();
38
- };
39
- }
40
-
41
- function getOrigin(ctx, origin) {
42
- if (origin === false) {
43
- return null; // CORS disabled
44
- }
45
-
46
- if (origin === '*') {
47
- return '*';
48
- }
49
-
50
- if (origin === true) {
51
- // Reflect the request origin
52
- return ctx.get('origin') || '*';
53
- }
54
-
55
- if (typeof origin === 'string') {
56
- return origin;
57
- }
58
-
59
- if (typeof origin === 'function') {
60
- return origin(ctx);
61
- }
62
-
63
- if (Array.isArray(origin)) {
64
- const requestOrigin = ctx.get('origin');
65
- return origin.includes(requestOrigin) ? requestOrigin : null;
66
- }
67
-
68
- return null;
69
- }
70
-
71
- function handlePreflight(ctx, opts) {
72
- ctx.set('Access-Control-Allow-Methods', opts.methods.join(', '));
73
-
74
- const requestedHeaders = ctx.get('Access-Control-Request-Headers');
75
- if (requestedHeaders) {
76
- const allowedHeaders = typeof opts.allowedHeaders === 'function'
77
- ? opts.allowedHeaders(ctx)
78
- : opts.allowedHeaders;
79
-
80
- if (allowedHeaders) {
81
- ctx.set('Access-Control-Allow-Headers',
82
- Array.isArray(allowedHeaders) ? allowedHeaders.join(', ') : allowedHeaders);
83
- }
84
- }
85
-
86
- if (opts.maxAge) {
87
- ctx.set('Access-Control-Max-Age', opts.maxAge);
88
- }
89
-
90
- if (opts.preflightContinue) {
91
- return;
92
- }
93
-
94
- ctx.status(opts.optionsSuccessStatus).end();
95
- }
96
-
97
- module.exports = cors;
@@ -1,221 +0,0 @@
1
- 'use strict';
2
-
3
- const os = require('os');
4
- const fs = require('fs');
5
- const { promisify } = require('util');
6
-
7
- const stat = promisify(fs.stat);
8
-
9
- /**
10
- * Health check middleware with configurable checks
11
- * @param {Object} options - Health check options
12
- * @returns {Function} Middleware function
13
- */
14
- function healthCheck(options = {}) {
15
- const opts = {
16
- path: '/_health',
17
- checks: {
18
- uptime: true,
19
- memory: true,
20
- cpu: true,
21
- disk: false,
22
- custom: []
23
- },
24
- timeout: 5000,
25
- includeDetails: process.env.NODE_ENV !== 'production',
26
- ...options
27
- };
28
-
29
- return async (ctx, next) => {
30
- if (ctx.path !== opts.path) {
31
- return next();
32
- }
33
-
34
- if (ctx.method !== 'GET') {
35
- ctx.status(405).json({ error: 'Method Not Allowed' });
36
- return;
37
- }
38
-
39
- try {
40
- const healthData = await performHealthChecks(opts);
41
-
42
- const status = healthData.checks.every(check => check.status === 'healthy') ? 'healthy' : 'unhealthy';
43
- const statusCode = status === 'healthy' ? 200 : 503;
44
-
45
- ctx.status(statusCode).json({
46
- status,
47
- timestamp: new Date().toISOString(),
48
- ...healthData
49
- });
50
-
51
- } catch (error) {
52
- ctx.status(503).json({
53
- status: 'unhealthy',
54
- timestamp: new Date().toISOString(),
55
- error: error.message,
56
- checks: []
57
- });
58
- }
59
- };
60
- }
61
-
62
- async function performHealthChecks(opts) {
63
- const checks = [];
64
- const details = {};
65
-
66
- // Uptime check
67
- if (opts.checks.uptime) {
68
- const uptime = process.uptime();
69
- checks.push({
70
- name: 'uptime',
71
- status: 'healthy',
72
- value: `${Math.floor(uptime)}s`
73
- });
74
-
75
- if (opts.includeDetails) {
76
- details.uptime = {
77
- seconds: uptime,
78
- formatted: formatUptime(uptime)
79
- };
80
- }
81
- }
82
-
83
- // Memory check
84
- if (opts.checks.memory) {
85
- const memUsage = process.memoryUsage();
86
- const totalMem = os.totalmem();
87
- const freeMem = os.freemem();
88
- const usedMem = totalMem - freeMem;
89
- const memPercentage = (usedMem / totalMem) * 100;
90
-
91
- const memStatus = memPercentage > 90 ? 'unhealthy' : memPercentage > 75 ? 'degraded' : 'healthy';
92
-
93
- checks.push({
94
- name: 'memory',
95
- status: memStatus,
96
- value: `${memPercentage.toFixed(1)}%`
97
- });
98
-
99
- if (opts.includeDetails) {
100
- details.memory = {
101
- usage: memUsage,
102
- system: {
103
- total: totalMem,
104
- free: freeMem,
105
- used: usedMem,
106
- percentage: memPercentage
107
- }
108
- };
109
- }
110
- }
111
-
112
- // CPU check
113
- if (opts.checks.cpu) {
114
- const loadAvg = os.loadavg();
115
- const cpuCount = os.cpus().length;
116
- const avgLoad = loadAvg[0] / cpuCount;
117
-
118
- const cpuStatus = avgLoad > 0.8 ? 'unhealthy' : avgLoad > 0.6 ? 'degraded' : 'healthy';
119
-
120
- checks.push({
121
- name: 'cpu',
122
- status: cpuStatus,
123
- value: `${(avgLoad * 100).toFixed(1)}%`
124
- });
125
-
126
- if (opts.includeDetails) {
127
- details.cpu = {
128
- loadAverage: loadAvg,
129
- cores: cpuCount,
130
- usage: avgLoad
131
- };
132
- }
133
- }
134
-
135
- // Disk check
136
- if (opts.checks.disk) {
137
- try {
138
- const stats = await stat(process.cwd());
139
- checks.push({
140
- name: 'disk',
141
- status: 'healthy',
142
- value: 'accessible'
143
- });
144
- } catch (error) {
145
- checks.push({
146
- name: 'disk',
147
- status: 'unhealthy',
148
- value: 'inaccessible',
149
- error: error.message
150
- });
151
- }
152
- }
153
-
154
- // Custom checks
155
- for (const customCheck of opts.checks.custom) {
156
- try {
157
- const result = await Promise.race([
158
- customCheck.check(),
159
- new Promise((_, reject) =>
160
- setTimeout(() => reject(new Error('Health check timeout')), opts.timeout)
161
- )
162
- ]);
163
-
164
- checks.push({
165
- name: customCheck.name,
166
- status: result.status || 'healthy',
167
- value: result.value || 'ok',
168
- ...result
169
- });
170
- } catch (error) {
171
- checks.push({
172
- name: customCheck.name,
173
- status: 'unhealthy',
174
- value: 'failed',
175
- error: error.message
176
- });
177
- }
178
- }
179
-
180
- const result = { checks };
181
-
182
- if (opts.includeDetails) {
183
- result.details = details;
184
- result.system = {
185
- platform: os.platform(),
186
- arch: os.arch(),
187
- nodeVersion: process.version,
188
- pid: process.pid
189
- };
190
- }
191
-
192
- return result;
193
- }
194
-
195
- function formatUptime(seconds) {
196
- const days = Math.floor(seconds / 86400);
197
- const hours = Math.floor((seconds % 86400) / 3600);
198
- const minutes = Math.floor((seconds % 3600) / 60);
199
- const secs = Math.floor(seconds % 60);
200
-
201
- const parts = [];
202
- if (days > 0) parts.push(`${days}d`);
203
- if (hours > 0) parts.push(`${hours}h`);
204
- if (minutes > 0) parts.push(`${minutes}m`);
205
- if (secs > 0) parts.push(`${secs}s`);
206
-
207
- return parts.join(' ') || '0s';
208
- }
209
-
210
- /**
211
- * Create a custom health check
212
- * @param {string} name - Check name
213
- * @param {Function} checkFn - Function that returns health status
214
- * @returns {Object} Custom check object
215
- */
216
- function createCustomCheck(name, checkFn) {
217
- return { name, check: checkFn };
218
- }
219
-
220
- module.exports = healthCheck;
221
- module.exports.createCustomCheck = createCustomCheck;
@@ -1,23 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * Middleware exports for @oxog/spark
5
- * Aggregates all built-in middleware for convenient importing
6
- */
7
-
8
- module.exports = {
9
- bodyParser: require('./body-parser'),
10
- cache: require('./cache'),
11
- compression: require('./compression'),
12
- cors: require('./cors'),
13
- health: require('./health'),
14
- healthCheck: require('./health'), // alias
15
- logger: require('./logger'),
16
- metrics: require('./metrics'),
17
- rateLimit: require('./rate-limit'),
18
- security: require('./security'),
19
- helmet: require('./security'), // alias for security
20
- session: require('./session'),
21
- static: require('./static'),
22
- serveStatic: require('./static') // alias
23
- };