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