@oxog/spark 1.1.1 → 1.3.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 +656 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +90 -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 +705 -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 +538 -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,221 +1,222 @@
1
1
  'use strict';
2
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;
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
+ 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
+ let timer;
158
+ const result = await Promise.race([
159
+ Promise.resolve().then(() => customCheck.check()),
160
+ new Promise((_, reject) => {
161
+ timer = setTimeout(() => reject(new Error('Health check timeout')), opts.timeout);
162
+ })
163
+ ]).finally(() => clearTimeout(timer));
164
+
165
+ checks.push({
166
+ ...(result && typeof result === 'object' ? result : {}),
167
+ name: customCheck.name,
168
+ status: (result && result.status) || 'healthy',
169
+ value: (result && result.value) || 'ok'
170
+ });
171
+ } catch (error) {
172
+ checks.push({
173
+ name: customCheck.name,
174
+ status: 'unhealthy',
175
+ value: 'failed',
176
+ error: error.message
177
+ });
178
+ }
179
+ }
180
+
181
+ const result = { checks };
182
+
183
+ if (opts.includeDetails) {
184
+ result.details = details;
185
+ result.system = {
186
+ platform: os.platform(),
187
+ arch: os.arch(),
188
+ nodeVersion: process.version,
189
+ pid: process.pid
190
+ };
191
+ }
192
+
193
+ return result;
194
+ }
195
+
196
+ function formatUptime(seconds) {
197
+ const days = Math.floor(seconds / 86400);
198
+ const hours = Math.floor((seconds % 86400) / 3600);
199
+ const minutes = Math.floor((seconds % 3600) / 60);
200
+ const secs = Math.floor(seconds % 60);
201
+
202
+ const parts = [];
203
+ if (days > 0) parts.push(`${days}d`);
204
+ if (hours > 0) parts.push(`${hours}h`);
205
+ if (minutes > 0) parts.push(`${minutes}m`);
206
+ if (secs > 0) parts.push(`${secs}s`);
207
+
208
+ return parts.join(' ') || '0s';
209
+ }
210
+
211
+ /**
212
+ * Create a custom health check
213
+ * @param {string} name - Check name
214
+ * @param {Function} checkFn - Function that returns health status
215
+ * @returns {Object} Custom check object
216
+ */
217
+ function createCustomCheck(name, checkFn) {
218
+ return { name, check: checkFn };
219
+ }
220
+
221
+ module.exports = healthCheck;
221
222
  module.exports.createCustomCheck = createCustomCheck;