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