@oxog/spark 1.1.0 → 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 -293
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1070 -956
  6. package/src/core/context.js +1100 -830
  7. package/src/core/middleware.js +305 -217
  8. package/src/index.js +183 -278
  9. package/src/middleware/body-parser.js +484 -526
  10. package/src/middleware/cache.js +179 -170
  11. package/src/middleware/compression.js +179 -182
  12. package/src/middleware/cors.js +178 -95
  13. package/src/middleware/health.js +221 -218
  14. package/src/middleware/logger.js +197 -194
  15. package/src/middleware/metrics.js +341 -327
  16. package/src/middleware/rate-limit.js +369 -319
  17. package/src/middleware/security.js +444 -332
  18. package/src/middleware/session.js +649 -529
  19. package/src/middleware/static.js +406 -299
  20. package/src/router/layer.js +199 -117
  21. package/src/router/route.js +151 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +147 -144
  24. package/src/utils/context-pool.js +85 -82
  25. package/src/utils/regex-validator.js +189 -176
  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 -957
  31. package/dist/core/context.js +0 -831
  32. package/dist/core/middleware.js +0 -218
  33. package/dist/core/request.js +0 -333
  34. package/dist/core/response.js +0 -375
  35. package/dist/index.js +0 -278
  36. package/dist/middleware/body-parser.js +0 -526
  37. package/dist/middleware/cache.js +0 -171
  38. package/dist/middleware/compression.js +0 -183
  39. package/dist/middleware/cors.js +0 -95
  40. package/dist/middleware/health.js +0 -219
  41. package/dist/middleware/index.js +0 -21
  42. package/dist/middleware/logger.js +0 -195
  43. package/dist/middleware/metrics.js +0 -328
  44. package/dist/middleware/rate-limit.js +0 -320
  45. package/dist/middleware/security.js +0 -333
  46. package/dist/middleware/session.js +0 -530
  47. package/dist/middleware/static.js +0 -299
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -117
  50. package/dist/router/route.js +0 -123
  51. package/dist/router/router.js +0 -756
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -145
  54. package/dist/utils/cache.js +0 -441
  55. package/dist/utils/context-pool.js +0 -83
  56. package/dist/utils/error-types.js +0 -132
  57. package/dist/utils/http.js +0 -413
  58. package/dist/utils/regex-validator.js +0 -177
  59. package/src/core/request.js +0 -333
  60. package/src/core/response.js +0 -375
  61. package/src/middleware/index.js +0 -21
  62. package/src/utils/cache.js +0 -441
  63. package/src/utils/error-types.js +0 -132
  64. package/src/utils/http.js +0 -413
@@ -1,441 +0,0 @@
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
- };
@@ -1,132 +0,0 @@
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
- };