@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,171 +1,180 @@
1
- /**
2
- * Cache middleware for @oxog/spark
3
- * Provides response caching functionality
4
- */
5
-
6
- /**
7
- * Creates a cache middleware
8
- * @param {Object} options - Cache configuration options
9
- * @param {number} [options.maxAge=3600] - Cache max age in seconds
10
- * @param {Function} [options.key] - Function to generate cache key
11
- * @param {Function} [options.condition] - Function to determine if response should be cached
12
- * @param {Object} [options.store] - Custom cache store (default: in-memory)
13
- * @returns {Function} Cache middleware function
14
- */
15
- function cache(options = {}) {
16
- const {
17
- maxAge = 3600,
18
- key = defaultKeyGenerator,
19
- condition = defaultCondition,
20
- store = new Map()
21
- } = options;
22
-
23
- return async function cacheMiddleware(ctx, next) {
24
- // Only cache GET and HEAD requests
25
- if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
26
- return next();
27
- }
28
-
29
- // Check if caching should be applied
30
- if (!condition(ctx)) {
31
- return next();
32
- }
33
-
34
- // Generate cache key
35
- const cacheKey = key(ctx);
36
-
37
- // Check if cached response exists
38
- const cached = store.get(cacheKey);
39
- if (cached && cached.expires > Date.now()) {
40
- // Serve from cache
41
- ctx.status = cached.status;
42
- ctx.body = cached.body;
43
- ctx.set(cached.headers);
44
- ctx.set('X-Cache', 'HIT');
45
- ctx.set('Age', Math.floor((Date.now() - cached.created) / 1000));
46
- return;
47
- }
48
-
49
- // Not in cache, proceed with request
50
- await next();
51
-
52
- // Store response in cache if successful
53
- if (ctx.status >= 200 && ctx.status < 300 && ctx.body) {
54
- const cacheEntry = {
55
- status: ctx.status,
56
- body: ctx.body,
57
- headers: filterHeaders(ctx.headers),
58
- created: Date.now(),
59
- expires: Date.now() + (maxAge * 1000)
60
- };
61
-
62
- store.set(cacheKey, cacheEntry);
63
-
64
- // Set cache headers
65
- ctx.set('Cache-Control', `public, max-age=${maxAge}`);
66
- ctx.set('X-Cache', 'MISS');
67
- }
68
- };
69
- }
70
-
71
- /**
72
- * Default cache key generator
73
- * @param {Object} ctx - Koa context
74
- * @returns {string} Cache key
75
- */
76
- function defaultKeyGenerator(ctx) {
77
- return ctx.url;
78
- }
79
-
80
- /**
81
- * Default condition to determine if response should be cached
82
- * @param {Object} ctx - Koa context
83
- * @returns {boolean} Whether to cache the response
84
- */
85
- function defaultCondition(ctx) {
86
- // Don't cache if no-cache header is present
87
- const cacheControl = ctx.get('Cache-Control');
88
- if (cacheControl && cacheControl.includes('no-cache')) {
89
- return false;
90
- }
91
-
92
- // Don't cache authenticated requests by default
93
- if (ctx.get('Authorization')) {
94
- return false;
95
- }
96
-
97
- return true;
98
- }
99
-
100
- /**
101
- * Filter headers to store in cache
102
- * @param {Object} headers - Response headers
103
- * @returns {Object} Filtered headers
104
- */
105
- function filterHeaders(headers) {
106
- const filtered = {};
107
- const allowedHeaders = [
108
- 'content-type',
109
- 'content-encoding',
110
- 'content-language',
111
- 'vary',
112
- 'etag',
113
- 'last-modified'
114
- ];
115
-
116
- for (const [key, value] of Object.entries(headers)) {
117
- if (allowedHeaders.includes(key.toLowerCase())) {
118
- filtered[key] = value;
119
- }
120
- }
121
-
122
- return filtered;
123
- }
124
-
125
- /**
126
- * Memory cache store with size limits
127
- */
128
- class MemoryCacheStore {
129
- constructor(maxSize = 100) {
130
- this.cache = new Map();
131
- this.maxSize = maxSize;
132
- }
133
-
134
- get(key) {
135
- const entry = this.cache.get(key);
136
- if (entry && entry.expires > Date.now()) {
137
- // Move to end (LRU)
138
- this.cache.delete(key);
139
- this.cache.set(key, entry);
140
- return entry;
141
- }
142
- // Remove expired entry
143
- if (entry) {
144
- this.cache.delete(key);
145
- }
146
- return null;
147
- }
148
-
149
- set(key, value) {
150
- // Remove oldest entry if at capacity
151
- if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
152
- const firstKey = this.cache.keys().next().value;
153
- this.cache.delete(firstKey);
154
- }
155
-
156
- this.cache.set(key, value);
157
- }
158
-
159
- clear() {
160
- this.cache.clear();
161
- }
162
-
163
- size() {
164
- return this.cache.size;
165
- }
166
- }
167
-
168
- // Export factory function and store class
169
- cache.MemoryCacheStore = MemoryCacheStore;
170
-
1
+ 'use strict';
2
+
3
+ /**
4
+ * Cache middleware for @oxog/spark
5
+ * Provides response caching functionality
6
+ */
7
+
8
+ /**
9
+ * Creates a cache middleware
10
+ * @param {Object} options - Cache configuration options
11
+ * @param {number} [options.maxAge=3600] - Cache max age in seconds
12
+ * @param {Function} [options.key] - Function to generate cache key
13
+ * @param {Function} [options.condition] - Function to determine if response should be cached
14
+ * @param {Object} [options.store] - Custom cache store (default: in-memory)
15
+ * @returns {Function} Cache middleware function
16
+ */
17
+ function cache(options = {}) {
18
+ const {
19
+ maxAge = 3600,
20
+ key = defaultKeyGenerator,
21
+ condition = defaultCondition,
22
+ // Bounded by default: an unbounded Map keyed by URL lets clients exhaust
23
+ // memory with unique query strings.
24
+ store = new MemoryCacheStore(options.maxEntries || 1000)
25
+ } = options;
26
+
27
+ return async function cacheMiddleware(ctx, next) {
28
+ // Only cache GET and HEAD requests
29
+ if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
30
+ return next();
31
+ }
32
+
33
+ // Check if caching should be applied
34
+ if (!condition(ctx)) {
35
+ return next();
36
+ }
37
+
38
+ const cacheKey = key(ctx);
39
+ const cached = store.get(cacheKey);
40
+
41
+ if (cached && cached.expires > Date.now()) {
42
+ ctx.status(cached.status);
43
+ for (const [name, value] of Object.entries(cached.headers)) {
44
+ ctx.set(name, value);
45
+ }
46
+ ctx.set('X-Cache', 'HIT');
47
+ ctx.set('Age', Math.floor((Date.now() - cached.created) / 1000));
48
+ ctx.send(cached.body);
49
+ return undefined;
50
+ }
51
+
52
+ // Capture what the handler sends (ctx.body holds the request body)
53
+ const originalSend = ctx.send;
54
+ ctx.send = function(body) {
55
+ if (!ctx.responded && ctx.statusCode >= 200 && ctx.statusCode < 300 &&
56
+ (typeof body === 'string' || Buffer.isBuffer(body)) &&
57
+ !ctx.getHeader('set-cookie') && !/no-store|private/i.test(String(ctx.getHeader('cache-control') || ''))) {
58
+ ctx.set('Cache-Control', `public, max-age=${maxAge}`);
59
+ ctx.set('X-Cache', 'MISS');
60
+ store.set(cacheKey, {
61
+ status: ctx.statusCode,
62
+ body,
63
+ headers: filterHeaders(ctx.responseHeaders),
64
+ created: Date.now(),
65
+ expires: Date.now() + (maxAge * 1000)
66
+ });
67
+ }
68
+ return originalSend.call(this, body);
69
+ };
70
+
71
+ try {
72
+ await next();
73
+ } finally {
74
+ ctx.send = originalSend;
75
+ }
76
+ return undefined;
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Default cache key generator
82
+ * @param {Object} ctx - Koa context
83
+ * @returns {string} Cache key
84
+ */
85
+ function defaultKeyGenerator(ctx) {
86
+ return ctx.originalUrl || ctx.url.toString();
87
+ }
88
+
89
+ /**
90
+ * Default condition to determine if response should be cached
91
+ * @param {Object} ctx - Koa context
92
+ * @returns {boolean} Whether to cache the response
93
+ */
94
+ function defaultCondition(ctx) {
95
+ // Don't cache if no-cache header is present
96
+ const cacheControl = ctx.get('Cache-Control');
97
+ if (cacheControl && cacheControl.includes('no-cache')) {
98
+ return false;
99
+ }
100
+
101
+ // Don't cache authenticated requests by default
102
+ if (ctx.get('Authorization')) {
103
+ return false;
104
+ }
105
+
106
+ return true;
107
+ }
108
+
109
+ /**
110
+ * Filter headers to store in cache
111
+ * @param {Object} headers - Response headers
112
+ * @returns {Object} Filtered headers
113
+ */
114
+ function filterHeaders(headers) {
115
+ const filtered = {};
116
+ const allowedHeaders = [
117
+ 'content-type',
118
+ 'content-encoding',
119
+ 'content-language',
120
+ 'vary',
121
+ 'etag',
122
+ 'last-modified'
123
+ ];
124
+
125
+ for (const [key, value] of Object.entries(headers)) {
126
+ if (allowedHeaders.includes(key.toLowerCase())) {
127
+ filtered[key] = value;
128
+ }
129
+ }
130
+
131
+ return filtered;
132
+ }
133
+
134
+ /**
135
+ * Memory cache store with size limits
136
+ */
137
+ class MemoryCacheStore {
138
+ constructor(maxSize = 100) {
139
+ this.cache = new Map();
140
+ this.maxSize = maxSize;
141
+ }
142
+
143
+ get(key) {
144
+ const entry = this.cache.get(key);
145
+ if (entry && entry.expires > Date.now()) {
146
+ // Move to end (LRU)
147
+ this.cache.delete(key);
148
+ this.cache.set(key, entry);
149
+ return entry;
150
+ }
151
+ // Remove expired entry
152
+ if (entry) {
153
+ this.cache.delete(key);
154
+ }
155
+ return null;
156
+ }
157
+
158
+ set(key, value) {
159
+ // Remove oldest entry if at capacity
160
+ if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
161
+ const firstKey = this.cache.keys().next().value;
162
+ this.cache.delete(firstKey);
163
+ }
164
+
165
+ this.cache.set(key, value);
166
+ }
167
+
168
+ clear() {
169
+ this.cache.clear();
170
+ }
171
+
172
+ size() {
173
+ return this.cache.size;
174
+ }
175
+ }
176
+
177
+ // Export factory function and store class
178
+ cache.MemoryCacheStore = MemoryCacheStore;
179
+
171
180
  module.exports = cache;