@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.
Files changed (63) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/LICENSE +21 -0
  3. package/README.md +242 -0
  4. package/dist/LICENSE +21 -0
  5. package/dist/README.md +242 -0
  6. package/dist/core/application.js +957 -0
  7. package/dist/core/context.js +831 -0
  8. package/dist/core/middleware.js +218 -0
  9. package/dist/core/request.js +333 -0
  10. package/dist/core/response.js +375 -0
  11. package/dist/index.js +278 -0
  12. package/dist/middleware/body-parser.js +526 -0
  13. package/dist/middleware/cache.js +171 -0
  14. package/dist/middleware/compression.js +183 -0
  15. package/dist/middleware/cors.js +95 -0
  16. package/dist/middleware/health.js +219 -0
  17. package/dist/middleware/index.js +21 -0
  18. package/dist/middleware/logger.js +195 -0
  19. package/dist/middleware/metrics.js +328 -0
  20. package/dist/middleware/rate-limit.js +320 -0
  21. package/dist/middleware/security.js +333 -0
  22. package/dist/middleware/session.js +530 -0
  23. package/dist/middleware/static.js +299 -0
  24. package/dist/package.json +62 -0
  25. package/dist/router/layer.js +117 -0
  26. package/dist/router/route.js +123 -0
  27. package/dist/router/router.js +756 -0
  28. package/dist/types/index.d.ts +291 -0
  29. package/dist/utils/async-handler.js +145 -0
  30. package/dist/utils/cache.js +441 -0
  31. package/dist/utils/context-pool.js +83 -0
  32. package/dist/utils/error-types.js +132 -0
  33. package/dist/utils/http.js +413 -0
  34. package/dist/utils/regex-validator.js +177 -0
  35. package/package.json +89 -0
  36. package/src/core/application.js +957 -0
  37. package/src/core/context.js +831 -0
  38. package/src/core/middleware.js +218 -0
  39. package/src/core/request.js +333 -0
  40. package/src/core/response.js +375 -0
  41. package/src/index.js +278 -0
  42. package/src/middleware/body-parser.js +526 -0
  43. package/src/middleware/cache.js +171 -0
  44. package/src/middleware/compression.js +183 -0
  45. package/src/middleware/cors.js +95 -0
  46. package/src/middleware/health.js +219 -0
  47. package/src/middleware/index.js +21 -0
  48. package/src/middleware/logger.js +195 -0
  49. package/src/middleware/metrics.js +328 -0
  50. package/src/middleware/rate-limit.js +320 -0
  51. package/src/middleware/security.js +333 -0
  52. package/src/middleware/session.js +530 -0
  53. package/src/middleware/static.js +299 -0
  54. package/src/router/layer.js +117 -0
  55. package/src/router/route.js +123 -0
  56. package/src/router/router.js +756 -0
  57. package/src/utils/async-handler.js +145 -0
  58. package/src/utils/cache.js +441 -0
  59. package/src/utils/context-pool.js +83 -0
  60. package/src/utils/error-types.js +132 -0
  61. package/src/utils/http.js +413 -0
  62. package/src/utils/regex-validator.js +177 -0
  63. package/types/index.d.ts +291 -0
@@ -0,0 +1,441 @@
1
+ const { EventEmitter } = require('events');
2
+
3
+ const DEFAULT_TTL = 300000; // 5 minutes
4
+ const DEFAULT_MAX_SIZE = 1000;
5
+
6
+ class MemoryCache extends EventEmitter {
7
+ constructor(options = {}) {
8
+ super();
9
+ this.options = {
10
+ ttl: options.ttl || DEFAULT_TTL,
11
+ maxSize: options.maxSize || DEFAULT_MAX_SIZE,
12
+ checkPeriod: options.checkPeriod || 60000, // 1 minute
13
+ maxEventListeners: options.maxEventListeners || 100,
14
+ ...options
15
+ };
16
+
17
+ // Set max event listeners to prevent warning
18
+ this.setMaxListeners(this.options.maxEventListeners);
19
+
20
+ this.cache = new Map();
21
+ this.timers = new Map();
22
+ this.stats = {
23
+ hits: 0,
24
+ misses: 0,
25
+ keys: 0,
26
+ ksize: 0,
27
+ vsize: 0
28
+ };
29
+
30
+ this.cleanupInterval = null;
31
+ this.startCleanup();
32
+ }
33
+
34
+ get(key) {
35
+ const entry = this.cache.get(key);
36
+
37
+ if (!entry) {
38
+ this.stats.misses++;
39
+ return undefined;
40
+ }
41
+
42
+ if (Date.now() > entry.expires) {
43
+ this.del(key);
44
+ this.stats.misses++;
45
+ return undefined;
46
+ }
47
+
48
+ this.stats.hits++;
49
+ entry.accessed = Date.now();
50
+ return entry.value;
51
+ }
52
+
53
+ set(key, value, ttl) {
54
+ const expiresAt = Date.now() + (ttl || this.options.ttl);
55
+
56
+ if (this.cache.has(key)) {
57
+ this.del(key);
58
+ }
59
+
60
+ if (this.cache.size >= this.options.maxSize) {
61
+ this.evictLRU();
62
+ }
63
+
64
+ const entry = {
65
+ value,
66
+ expires: expiresAt,
67
+ created: Date.now(),
68
+ accessed: Date.now()
69
+ };
70
+
71
+ this.cache.set(key, entry);
72
+ this.stats.keys++;
73
+ this.stats.ksize += key.length;
74
+ this.stats.vsize += this.getSize(value);
75
+
76
+ this.scheduleExpiration(key, expiresAt);
77
+ this.emit('set', key, value);
78
+
79
+ return true;
80
+ }
81
+
82
+ del(key) {
83
+ const entry = this.cache.get(key);
84
+
85
+ if (!entry) {
86
+ return false;
87
+ }
88
+
89
+ this.cache.delete(key);
90
+ this.stats.keys--;
91
+ this.stats.ksize -= key.length;
92
+ this.stats.vsize -= this.getSize(entry.value);
93
+
94
+ if (this.timers.has(key)) {
95
+ clearTimeout(this.timers.get(key));
96
+ this.timers.delete(key);
97
+ }
98
+
99
+ this.emit('del', key);
100
+ return true;
101
+ }
102
+
103
+ has(key) {
104
+ const entry = this.cache.get(key);
105
+
106
+ if (!entry) {
107
+ return false;
108
+ }
109
+
110
+ if (Date.now() > entry.expires) {
111
+ this.del(key);
112
+ return false;
113
+ }
114
+
115
+ return true;
116
+ }
117
+
118
+ clear() {
119
+ for (const timer of this.timers.values()) {
120
+ clearTimeout(timer);
121
+ }
122
+
123
+ this.cache.clear();
124
+ this.timers.clear();
125
+ this.stats = {
126
+ hits: 0,
127
+ misses: 0,
128
+ keys: 0,
129
+ ksize: 0,
130
+ vsize: 0
131
+ };
132
+
133
+ this.emit('flush');
134
+ }
135
+
136
+ keys() {
137
+ const keys = [];
138
+ const now = Date.now();
139
+
140
+ for (const [key, entry] of this.cache) {
141
+ if (now <= entry.expires) {
142
+ keys.push(key);
143
+ } else {
144
+ this.del(key);
145
+ }
146
+ }
147
+
148
+ return keys;
149
+ }
150
+
151
+ values() {
152
+ const values = [];
153
+ const now = Date.now();
154
+
155
+ for (const [key, entry] of this.cache) {
156
+ if (now <= entry.expires) {
157
+ values.push(entry.value);
158
+ } else {
159
+ this.del(key);
160
+ }
161
+ }
162
+
163
+ return values;
164
+ }
165
+
166
+ entries() {
167
+ const entries = [];
168
+ const now = Date.now();
169
+
170
+ for (const [key, entry] of this.cache) {
171
+ if (now <= entry.expires) {
172
+ entries.push([key, entry.value]);
173
+ } else {
174
+ this.del(key);
175
+ }
176
+ }
177
+
178
+ return entries;
179
+ }
180
+
181
+ size() {
182
+ return this.cache.size;
183
+ }
184
+
185
+ getStats() {
186
+ return {
187
+ ...this.stats,
188
+ hitRate: this.stats.hits / (this.stats.hits + this.stats.misses) || 0,
189
+ memoryUsage: this.stats.ksize + this.stats.vsize
190
+ };
191
+ }
192
+
193
+ getTTL(key) {
194
+ const entry = this.cache.get(key);
195
+
196
+ if (!entry) {
197
+ return -1;
198
+ }
199
+
200
+ const remaining = entry.expires - Date.now();
201
+ return remaining > 0 ? remaining : -1;
202
+ }
203
+
204
+ touch(key, ttl) {
205
+ const entry = this.cache.get(key);
206
+
207
+ if (!entry) {
208
+ return false;
209
+ }
210
+
211
+ const newExpires = Date.now() + (ttl || this.options.ttl);
212
+ entry.expires = newExpires;
213
+ entry.accessed = Date.now();
214
+
215
+ this.scheduleExpiration(key, newExpires);
216
+ return true;
217
+ }
218
+
219
+ scheduleExpiration(key, expiresAt) {
220
+ if (this.timers.has(key)) {
221
+ clearTimeout(this.timers.get(key));
222
+ }
223
+
224
+ const delay = expiresAt - Date.now();
225
+
226
+ // Only set timer if delay is positive and reasonable
227
+ if (delay > 0 && delay < 2147483647) { // Max 32-bit signed integer for setTimeout
228
+ const timeout = setTimeout(() => {
229
+ this.del(key);
230
+ }, delay);
231
+
232
+ // Allow timer to be garbage collected if process exits
233
+ if (timeout.unref) {
234
+ timeout.unref();
235
+ }
236
+
237
+ this.timers.set(key, timeout);
238
+ } else if (delay <= 0) {
239
+ // If already expired, delete immediately
240
+ setImmediate(() => this.del(key));
241
+ }
242
+ }
243
+
244
+ evictLRU() {
245
+ let oldestKey = null;
246
+ let oldestTime = Infinity;
247
+
248
+ for (const [key, entry] of this.cache) {
249
+ if (entry.accessed < oldestTime) {
250
+ oldestTime = entry.accessed;
251
+ oldestKey = key;
252
+ }
253
+ }
254
+
255
+ if (oldestKey) {
256
+ this.del(oldestKey);
257
+ this.emit('evict', oldestKey);
258
+ }
259
+ }
260
+
261
+ getSize(value) {
262
+ if (typeof value === 'string') {
263
+ return value.length;
264
+ }
265
+
266
+ if (Buffer.isBuffer(value)) {
267
+ return value.length;
268
+ }
269
+
270
+ if (typeof value === 'object') {
271
+ return JSON.stringify(value).length;
272
+ }
273
+
274
+ return 0;
275
+ }
276
+
277
+ startCleanup() {
278
+ if (this.cleanupInterval) {
279
+ clearInterval(this.cleanupInterval);
280
+ }
281
+
282
+ this.cleanupInterval = setInterval(() => {
283
+ this.cleanup();
284
+ }, this.options.checkPeriod);
285
+
286
+ // Allow cleanup interval to be garbage collected if process exits
287
+ if (this.cleanupInterval.unref) {
288
+ this.cleanupInterval.unref();
289
+ }
290
+ }
291
+
292
+ cleanup() {
293
+ const now = Date.now();
294
+ const expiredKeys = [];
295
+
296
+ for (const [key, entry] of this.cache) {
297
+ if (now > entry.expires) {
298
+ expiredKeys.push(key);
299
+ }
300
+ }
301
+
302
+ for (const key of expiredKeys) {
303
+ this.del(key);
304
+ }
305
+
306
+ this.emit('cleanup', expiredKeys.length);
307
+ }
308
+
309
+ stop() {
310
+ if (this.cleanupInterval) {
311
+ clearInterval(this.cleanupInterval);
312
+ this.cleanupInterval = null;
313
+ }
314
+
315
+ this.clear();
316
+
317
+ // Remove all event listeners to prevent memory leaks
318
+ this.removeAllListeners();
319
+ }
320
+ }
321
+
322
+ class LRUCache extends MemoryCache {
323
+ constructor(options = {}) {
324
+ super(options);
325
+ this.maxSize = options.maxSize || DEFAULT_MAX_SIZE;
326
+
327
+ // Override parent's max size to ensure consistency
328
+ this.options.maxSize = this.maxSize;
329
+ }
330
+
331
+ get(key) {
332
+ const value = super.get(key);
333
+
334
+ if (value !== undefined) {
335
+ this.moveToFront(key);
336
+ }
337
+
338
+ return value;
339
+ }
340
+
341
+ set(key, value, ttl) {
342
+ const result = super.set(key, value, ttl);
343
+ this.moveToFront(key);
344
+ return result;
345
+ }
346
+
347
+ moveToFront(key) {
348
+ const entry = this.cache.get(key);
349
+ if (entry) {
350
+ this.cache.delete(key);
351
+ this.cache.set(key, entry);
352
+ }
353
+ }
354
+ }
355
+
356
+ function createCache(options = {}) {
357
+ const type = options.type || 'memory';
358
+
359
+ switch (type) {
360
+ case 'memory':
361
+ return new MemoryCache(options);
362
+ case 'lru':
363
+ return new LRUCache(options);
364
+ default:
365
+ throw new Error(`Unknown cache type: ${type}`);
366
+ }
367
+ }
368
+
369
+ function memoize(fn, options = {}) {
370
+ const cache = createCache(options);
371
+
372
+ const memoized = function(...args) {
373
+ const key = options.keyGenerator ?
374
+ options.keyGenerator(...args) :
375
+ JSON.stringify(args);
376
+
377
+ if (cache.has(key)) {
378
+ return cache.get(key);
379
+ }
380
+
381
+ const result = fn.apply(this, args);
382
+ cache.set(key, result, options.ttl);
383
+
384
+ return result;
385
+ };
386
+
387
+ // Attach cache cleanup method
388
+ memoized.clear = () => cache.clear();
389
+ memoized.stop = () => cache.stop();
390
+
391
+ return memoized;
392
+ }
393
+
394
+ function asyncMemoize(fn, options = {}) {
395
+ const cache = createCache(options);
396
+ const pending = new Map();
397
+
398
+ const memoized = async function(...args) {
399
+ const key = options.keyGenerator ?
400
+ options.keyGenerator(...args) :
401
+ JSON.stringify(args);
402
+
403
+ if (cache.has(key)) {
404
+ return cache.get(key);
405
+ }
406
+
407
+ if (pending.has(key)) {
408
+ return pending.get(key);
409
+ }
410
+
411
+ const promise = fn.apply(this, args);
412
+ pending.set(key, promise);
413
+
414
+ try {
415
+ const result = await promise;
416
+ cache.set(key, result, options.ttl);
417
+ pending.delete(key);
418
+ return result;
419
+ } catch (error) {
420
+ pending.delete(key);
421
+ throw error;
422
+ }
423
+ };
424
+
425
+ // Attach cache cleanup method
426
+ memoized.clear = () => {
427
+ cache.clear();
428
+ pending.clear();
429
+ };
430
+ memoized.stop = () => cache.stop();
431
+
432
+ return memoized;
433
+ }
434
+
435
+ module.exports = {
436
+ MemoryCache,
437
+ LRUCache,
438
+ createCache,
439
+ memoize,
440
+ asyncMemoize
441
+ };
@@ -0,0 +1,83 @@
1
+ const Context = require('../core/context');
2
+
3
+ /**
4
+ * Context Object Pool for performance optimization
5
+ * Reuses Context objects to reduce garbage collection pressure
6
+ */
7
+ class ContextPool {
8
+ constructor(maxSize = 100) {
9
+ this.pool = [];
10
+ this.maxSize = maxSize;
11
+ this.created = 0;
12
+ this.reused = 0;
13
+ }
14
+
15
+ /**
16
+ * Acquire a Context object from the pool or create new one
17
+ * @param {IncomingMessage} req - HTTP request object
18
+ * @param {ServerResponse} res - HTTP response object
19
+ * @param {Application} app - Spark application instance
20
+ * @returns {Context} Context instance
21
+ */
22
+ acquire(req, res, app) {
23
+ let ctx;
24
+
25
+ if (this.pool.length > 0) {
26
+ ctx = this.pool.pop();
27
+ ctx.init(req, res, app);
28
+ this.reused++;
29
+ } else {
30
+ ctx = new Context(req, res, app);
31
+ this.created++;
32
+ }
33
+
34
+ return ctx;
35
+ }
36
+
37
+ /**
38
+ * Release a Context object back to the pool
39
+ * @param {Context} ctx - Context to release
40
+ */
41
+ release(ctx) {
42
+ if (this.pool.length < this.maxSize) {
43
+ ctx.reset();
44
+ this.pool.push(ctx);
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Get pool statistics
50
+ * @returns {Object} Pool stats
51
+ */
52
+ getStats() {
53
+ return {
54
+ poolSize: this.pool.length,
55
+ maxSize: this.maxSize,
56
+ created: this.created,
57
+ reused: this.reused,
58
+ reuseRatio: this.created > 0 ? (this.reused / this.created * 100).toFixed(2) + '%' : '0%'
59
+ };
60
+ }
61
+
62
+ /**
63
+ * Clear the pool
64
+ */
65
+ clear() {
66
+ this.pool.length = 0;
67
+ }
68
+
69
+ /**
70
+ * Resize the pool
71
+ * @param {number} newSize - New maximum pool size
72
+ */
73
+ resize(newSize) {
74
+ this.maxSize = newSize;
75
+
76
+ // Trim pool if new size is smaller
77
+ if (this.pool.length > newSize) {
78
+ this.pool.length = newSize;
79
+ }
80
+ }
81
+ }
82
+
83
+ module.exports = ContextPool;
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Custom error classes for Spark framework
3
+ */
4
+
5
+ class SparkError extends Error {
6
+ constructor(message, status = 500, code = null) {
7
+ super(message);
8
+ this.name = 'SparkError';
9
+ this.status = status;
10
+ this.statusCode = status;
11
+ if (code) {
12
+ this.code = code;
13
+ }
14
+
15
+ // Capture stack trace
16
+ if (Error.captureStackTrace) {
17
+ Error.captureStackTrace(this, this.constructor);
18
+ }
19
+ }
20
+
21
+ toJSON() {
22
+ return {
23
+ name: this.name,
24
+ message: this.message,
25
+ status: this.status,
26
+ code: this.code,
27
+ stack: this.stack
28
+ };
29
+ }
30
+ }
31
+
32
+ class ValidationError extends SparkError {
33
+ constructor(message, details = null) {
34
+ super(message, 400, 'VALIDATION_ERROR');
35
+ this.name = 'ValidationError';
36
+ this.details = details;
37
+ }
38
+ }
39
+
40
+ class AuthenticationError extends SparkError {
41
+ constructor(message = 'Authentication required') {
42
+ super(message, 401, 'AUTHENTICATION_ERROR');
43
+ this.name = 'AuthenticationError';
44
+ }
45
+ }
46
+
47
+ class AuthorizationError extends SparkError {
48
+ constructor(message = 'Insufficient permissions') {
49
+ super(message, 403, 'AUTHORIZATION_ERROR');
50
+ this.name = 'AuthorizationError';
51
+ }
52
+ }
53
+
54
+ class NotFoundError extends SparkError {
55
+ constructor(message = 'Resource not found') {
56
+ super(message, 404, 'NOT_FOUND');
57
+ this.name = 'NotFoundError';
58
+ }
59
+ }
60
+
61
+ class ConflictError extends SparkError {
62
+ constructor(message = 'Resource conflict') {
63
+ super(message, 409, 'CONFLICT');
64
+ this.name = 'ConflictError';
65
+ }
66
+ }
67
+
68
+ class RateLimitError extends SparkError {
69
+ constructor(message = 'Rate limit exceeded', retryAfter = null) {
70
+ super(message, 429, 'RATE_LIMIT_EXCEEDED');
71
+ this.name = 'RateLimitError';
72
+ this.retryAfter = retryAfter;
73
+ }
74
+ }
75
+
76
+ class PayloadTooLargeError extends SparkError {
77
+ constructor(message = 'Payload too large') {
78
+ super(message, 413, 'PAYLOAD_TOO_LARGE');
79
+ this.name = 'PayloadTooLargeError';
80
+ }
81
+ }
82
+
83
+ class TimeoutError extends SparkError {
84
+ constructor(message = 'Request timeout') {
85
+ super(message, 408, 'REQUEST_TIMEOUT');
86
+ this.name = 'TimeoutError';
87
+ }
88
+ }
89
+
90
+ class InternalServerError extends SparkError {
91
+ constructor(message = 'Internal server error') {
92
+ super(message, 500, 'INTERNAL_SERVER_ERROR');
93
+ this.name = 'InternalServerError';
94
+ }
95
+ }
96
+
97
+ class ServiceUnavailableError extends SparkError {
98
+ constructor(message = 'Service unavailable') {
99
+ super(message, 503, 'SERVICE_UNAVAILABLE');
100
+ this.name = 'ServiceUnavailableError';
101
+ }
102
+ }
103
+
104
+ class BadGatewayError extends SparkError {
105
+ constructor(message = 'Bad gateway') {
106
+ super(message, 502, 'BAD_GATEWAY');
107
+ this.name = 'BadGatewayError';
108
+ }
109
+ }
110
+
111
+ class GatewayTimeoutError extends SparkError {
112
+ constructor(message = 'Gateway timeout') {
113
+ super(message, 504, 'GATEWAY_TIMEOUT');
114
+ this.name = 'GatewayTimeoutError';
115
+ }
116
+ }
117
+
118
+ module.exports = {
119
+ SparkError,
120
+ ValidationError,
121
+ AuthenticationError,
122
+ AuthorizationError,
123
+ NotFoundError,
124
+ ConflictError,
125
+ RateLimitError,
126
+ PayloadTooLargeError,
127
+ TimeoutError,
128
+ InternalServerError,
129
+ ServiceUnavailableError,
130
+ BadGatewayError,
131
+ GatewayTimeoutError
132
+ };