tricache 0.7.1 → 0.8.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 (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -1371
  3. package/dashboards/tricache-alerts.yaml +54 -0
  4. package/dashboards/tricache-grafana.json +548 -0
  5. package/dist/cache-service-5MZXFIGK.js +12 -0
  6. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  7. package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  10. package/dist/chunk-QNU7B43J.js +687 -0
  11. package/dist/chunk-UGD4VEPD.js +138 -0
  12. package/dist/chunk-XZL45ABR.js +108 -0
  13. package/dist/chunk-ZTSWCFYO.js +135 -0
  14. package/dist/cli.cjs +2790 -471
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +103 -5
  17. package/dist/dashboard/index.cjs +1065 -0
  18. package/dist/dashboard/index.d.ts +183 -0
  19. package/dist/dashboard/index.js +22 -0
  20. package/dist/drizzle/index.cjs +2553 -470
  21. package/dist/drizzle/index.d.ts +3 -1
  22. package/dist/drizzle/index.js +1 -1
  23. package/dist/edge/index.cjs +1498 -0
  24. package/dist/edge/index.d.ts +127 -0
  25. package/dist/edge/index.js +1109 -0
  26. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  27. package/dist/http/index.cjs +2926 -562
  28. package/dist/http/index.d.ts +109 -23
  29. package/dist/http/index.js +220 -72
  30. package/dist/index.cjs +6936 -2518
  31. package/dist/index.d.ts +547 -30
  32. package/dist/index.js +104 -5
  33. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  34. package/dist/nestjs/index.cjs +2494 -463
  35. package/dist/nestjs/index.d.ts +3 -1
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/next/index.cjs +2517 -483
  38. package/dist/next/index.d.ts +4 -2
  39. package/dist/next/index.js +14 -10
  40. package/dist/prisma/index.d.ts +3 -1
  41. package/dist/serialize-worker.cjs +5 -4
  42. package/dist/serialize-worker.js +1 -1
  43. package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
  44. package/package.json +34 -6
  45. package/src/adapters/auto-pipeliner.ts +206 -0
  46. package/src/adapters/node-redis.ts +370 -0
  47. package/src/cache-service.ts +1339 -402
  48. package/src/cli.ts +120 -2
  49. package/src/codec.ts +72 -0
  50. package/src/cross-region.ts +245 -0
  51. package/src/dashboard/handler.ts +392 -0
  52. package/src/dashboard/html.ts +594 -0
  53. package/src/dashboard/index.ts +195 -0
  54. package/src/dashboard/types.ts +96 -0
  55. package/src/disk-tier.ts +449 -47
  56. package/src/drizzle/index.ts +86 -86
  57. package/src/edge/adapters/cloudflare-do.ts +130 -0
  58. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  59. package/src/edge/adapters/upstash.ts +143 -0
  60. package/src/edge/cache.ts +797 -0
  61. package/src/edge/crypto.ts +182 -0
  62. package/src/edge/hono.ts +203 -0
  63. package/src/edge/index.ts +37 -0
  64. package/src/edge/types.ts +230 -0
  65. package/src/edge/utils/base64.ts +63 -0
  66. package/src/edge/utils/murmur3.ts +179 -0
  67. package/src/encryption.ts +127 -5
  68. package/src/http/express.ts +195 -0
  69. package/src/http/fastify.ts +260 -0
  70. package/src/http/index.ts +39 -258
  71. package/src/http/utils.ts +92 -0
  72. package/src/index.ts +149 -47
  73. package/src/ipc-telemetry.ts +481 -0
  74. package/src/latency-watchdog.ts +282 -0
  75. package/src/nestjs/decorators.ts +161 -161
  76. package/src/nestjs/index.ts +23 -23
  77. package/src/nestjs/tricache.module.ts +104 -104
  78. package/src/nestjs/tricache.store.ts +97 -97
  79. package/src/nestjs/types.ts +79 -79
  80. package/src/next/cache-handler.ts +12 -9
  81. package/src/next/index.ts +37 -37
  82. package/src/next/isr-handler.ts +105 -105
  83. package/src/next/types.ts +130 -130
  84. package/src/remote-snapshot.ts +153 -0
  85. package/src/serialize-worker.ts +120 -120
  86. package/src/sigv4-snapshot-adapter.ts +260 -0
  87. package/src/smart-memory-cache.ts +91 -8
  88. package/src/types.ts +290 -2
  89. package/src/utils/cgroup.ts +100 -0
  90. package/src/utils/tracing.ts +54 -0
  91. package/src/wasm/bloom-filter-wasm.ts +109 -102
  92. package/src/worker-pool.ts +299 -299
  93. package/src/wtiny-lfu.ts +624 -0
  94. package/dist/cache-service-5GATUYAK.js +0 -7
  95. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -1,33 +1,119 @@
1
- import { W as WrapOptions, C as CacheService } from '../cache-service-D8tIXmzb.js';
1
+ import { C as CacheService } from '../cache-service-CyLdpo77.js';
2
+ import { W as WrapOptions } from '../types-B6krw64X.js';
3
+ export { C as CachedEdgeHttpResponse, H as HonoEdgeCacheOptions, b as buildEdgeDeterministicKey, c as computeEdgeETag, h as honoCache } from '../hono-DQRS1Xd7.js';
4
+ import 'crypto';
2
5
 
6
+ interface KeyDerivationOptions {
7
+ /** Custom key derivation function. Overrides default URL and query string serialization. */
8
+ keyGenerator?: (req: any) => string;
9
+ /** Optional list of header names (case-insensitive) to include in the cache key. */
10
+ headerWhitelist?: string[];
11
+ }
12
+ /**
13
+ * Generates a deterministic HTTP cache key from request method, URL path, sorted query parameters,
14
+ * and optional whitelisted headers.
15
+ *
16
+ * Example:
17
+ * GET /api/products?sort=desc&page=2
18
+ * GET /api/products?page=2&sort=desc
19
+ * Both map to: http:GET:/api/products?page=2&sort=desc
20
+ */
21
+ declare function buildDeterministicKey(req: any, options?: KeyDerivationOptions): string;
22
+ /**
23
+ * Checks if request specifies Cache-Control bypass directives (no-cache, no-store)
24
+ * or matches a custom skipCache predicate.
25
+ */
26
+ declare function shouldSkipCache(req: any, customSkip?: (req: any) => boolean): boolean;
27
+ /**
28
+ * Compute a weak ETag (W/"...") from string, Buffer, or JSON-serializable object.
29
+ */
30
+ declare function generateETag(data: unknown): string;
31
+
32
+ interface ExpressCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDerivationOptions {
33
+ /** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
34
+ cache?: CacheService;
35
+ /** Whether to generate and evaluate weak ETags. Default: true. */
36
+ etag?: boolean;
37
+ /** Custom predicate to skip caching dynamically for this request (e.g. authenticated sessions). */
38
+ skipCache?: (req: any) => boolean;
39
+ /** Dynamic tags derivation from request. */
40
+ tags?: string[] | ((req: any) => string[]);
41
+ }
42
+ interface CachedHttpResponse {
43
+ body: unknown;
44
+ contentType?: string;
45
+ etag?: string;
46
+ status: number;
47
+ }
3
48
  /**
4
- * tricache/http — Universal HTTP Caching, ETag generation, and 304 Not Modified middleware
5
- * for Express, Fastify, and Hono.
49
+ * Creates an Express / Connect middleware that provides deterministic response caching,
50
+ * weak ETag generation, conditional 304 Not Modified short-circuiting, and Cache-Control bypass controls.
6
51
  *
7
- * Usage with Express:
8
- * import { expressCache } from 'tricache/http';
9
- * app.get('/api/users', expressCache({ cache, ttl: 300, tags: ['users'] }), handler);
52
+ * @example
53
+ * import express from 'express';
54
+ * import { CacheService } from 'tricache';
55
+ * import { createExpressMiddleware } from 'tricache/http';
10
56
  *
11
- * Usage with Hono:
12
- * import { honoCache } from 'tricache/http';
13
- * app.get('/api/users', honoCache({ cache, ttl: 300, tags: ['users'] }), handler);
57
+ * const app = express();
58
+ * const cache = CacheService.create();
59
+ *
60
+ * app.get(
61
+ * '/api/products',
62
+ * createExpressMiddleware({
63
+ * cache,
64
+ * ttl: 120,
65
+ * tags: ['products'],
66
+ * headerWhitelist: ['accept-language'],
67
+ * }),
68
+ * async (req, res) => {
69
+ * const data = await getProducts();
70
+ * res.json(data);
71
+ * }
72
+ * );
14
73
  */
74
+ declare function createExpressMiddleware(options?: ExpressCacheOptions): (req: any, res: any, next: any) => Promise<any>;
75
+ /** Alias matching legacy nomenclature */
76
+ declare const expressCache: typeof createExpressMiddleware;
15
77
 
16
- interface HttpCacheOptions extends WrapOptions {
17
- /** TriCache instance. If omitted, uses singleton CacheService.create(). */
78
+ interface FastifyCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDerivationOptions {
79
+ /** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
18
80
  cache?: CacheService;
19
- /** Custom key derivation function. Defaults to `${method}:${url}`. */
20
- keyGenerator?: (req: any) => string;
21
- /** Whether to emit weak ETags (default: true). */
81
+ /** Whether to generate and evaluate weak ETags. Default: true. */
22
82
  etag?: boolean;
83
+ /** Custom predicate to skip caching dynamically for this request. */
84
+ skipCache?: (req: any) => boolean;
85
+ /** Dynamic tags derivation from request. */
86
+ tags?: string[] | ((req: any) => string[]);
23
87
  }
24
- /** Compute a weak ETag from a string, Buffer, or object */
25
- declare function generateETag(data: unknown): string;
26
- /** Express / Connect middleware */
27
- declare function expressCache(options?: HttpCacheOptions): (req: any, res: any, next: any) => Promise<any>;
28
- /** Hono / Web Standard middleware */
29
- declare function honoCache(options?: HttpCacheOptions): (c: any, next: any) => Promise<any>;
30
- /** Fastify preHandler hook */
31
- declare function fastifyCache(options?: HttpCacheOptions): (req: any, reply: any) => Promise<any>;
88
+ interface CachedFastifyResponse {
89
+ body: unknown;
90
+ contentType?: string;
91
+ etag?: string;
92
+ status: number;
93
+ }
94
+ /**
95
+ * Creates a Fastify plugin that registers `onRequest` and `onSend` lifecycle hooks.
96
+ *
97
+ * Designed to bypass Fastify's route encapsulation barrier (`skip-override`),
98
+ * allowing caching across global and nested route scopes.
99
+ *
100
+ * @example
101
+ * import Fastify from 'fastify';
102
+ * import { fastifyCachePlugin } from 'tricache/http';
103
+ *
104
+ * const app = Fastify();
105
+ * await app.register(fastifyCachePlugin, {
106
+ * ttl: 300,
107
+ * tags: ['api'],
108
+ * });
109
+ */
110
+ declare function createFastifyPlugin(options?: FastifyCacheOptions): (fastify: any, pluginOpts?: FastifyCacheOptions) => Promise<void>;
111
+ /** Standard Fastify plugin export */
112
+ declare const fastifyCachePlugin: (fastify: any, pluginOpts?: FastifyCacheOptions) => Promise<void>;
113
+ /**
114
+ * Universal Fastify middleware: functions both as a Fastify plugin (`fastify.register(fastifyCache(options))`)
115
+ * and as a route preHandler hook (`fastify.get('/route', { preHandler: fastifyCache(options) })`).
116
+ */
117
+ declare function fastifyCache(options?: FastifyCacheOptions): (first: any, second?: any) => Promise<any>;
32
118
 
33
- export { type HttpCacheOptions, expressCache, fastifyCache, generateETag, honoCache };
119
+ export { type CachedFastifyResponse, type CachedHttpResponse, type ExpressCacheOptions, type FastifyCacheOptions, type ExpressCacheOptions as HttpCacheOptions, type KeyDerivationOptions, buildDeterministicKey, createExpressMiddleware, createFastifyPlugin, expressCache, fastifyCache, fastifyCachePlugin, generateETag, shouldSkipCache };
@@ -1,23 +1,91 @@
1
- // src/http/index.ts
1
+ import {
2
+ buildEdgeDeterministicKey,
3
+ computeEdgeETag,
4
+ honoEdgeCache
5
+ } from "../chunk-ZTSWCFYO.js";
6
+
7
+ // src/http/utils.ts
2
8
  import crypto from "crypto";
9
+ function buildDeterministicKey(req, options) {
10
+ if (options?.keyGenerator) {
11
+ return options.keyGenerator(req);
12
+ }
13
+ const method = (req.method || "GET").toUpperCase();
14
+ const rawUrl = req.originalUrl || req.url || "/";
15
+ const qIdx = rawUrl.indexOf("?");
16
+ const path = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
17
+ let queryString = "";
18
+ if (qIdx >= 0) {
19
+ const rawQuery = rawUrl.slice(qIdx + 1);
20
+ try {
21
+ const params = new URLSearchParams(rawQuery);
22
+ params.sort();
23
+ queryString = params.toString();
24
+ } catch {
25
+ queryString = rawQuery;
26
+ }
27
+ }
28
+ let key = `http:${method}:${path}`;
29
+ if (queryString) {
30
+ key += `?${queryString}`;
31
+ }
32
+ if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.headers) {
33
+ const sortedHeaders = [...options.headerWhitelist].sort();
34
+ for (const h of sortedHeaders) {
35
+ const normalizedHeader = h.toLowerCase();
36
+ const val = req.headers[normalizedHeader];
37
+ if (val !== void 0 && val !== null && val !== "") {
38
+ const headerStr = Array.isArray(val) ? val.join(",") : String(val);
39
+ key += `|h:${normalizedHeader}=${headerStr}`;
40
+ }
41
+ }
42
+ }
43
+ return key;
44
+ }
45
+ function shouldSkipCache(req, customSkip) {
46
+ if (customSkip && customSkip(req)) return true;
47
+ const cc = req.headers ? req.headers["cache-control"] || req.headers["Cache-Control"] : void 0;
48
+ if (typeof cc === "string") {
49
+ const lower = cc.toLowerCase();
50
+ if (lower.includes("no-cache") || lower.includes("no-store")) {
51
+ return true;
52
+ }
53
+ }
54
+ return false;
55
+ }
3
56
  function generateETag(data) {
4
57
  const str = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf8") : JSON.stringify(data);
5
58
  const hash = crypto.createHash("sha1").update(str).digest("hex").slice(0, 16);
6
59
  return `W/"${str.length.toString(16)}-${hash}"`;
7
60
  }
8
- function expressCache(options = {}) {
9
- const { cache, keyGenerator, etag = true, ttl = 300, swr, tags } = options;
61
+
62
+ // src/http/express.ts
63
+ function createExpressMiddleware(options = {}) {
64
+ const {
65
+ cache,
66
+ etag = true,
67
+ ttl = 300,
68
+ swr,
69
+ tags,
70
+ skipCache,
71
+ keyGenerator,
72
+ headerWhitelist
73
+ } = options;
10
74
  return async (req, res, next) => {
11
75
  if (req.method !== "GET" && req.method !== "HEAD") {
12
76
  return next();
13
77
  }
78
+ if (shouldSkipCache(req, skipCache)) {
79
+ return next();
80
+ }
14
81
  let activeCache = cache;
15
82
  if (!activeCache) {
16
- const { CacheService } = await import("../cache-service-5GATUYAK.js");
83
+ const { CacheService } = await import("../cache-service-5MZXFIGK.js");
17
84
  activeCache = CacheService.create();
18
85
  }
19
- const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.originalUrl || req.url}`;
20
- const ifNoneMatch = req.headers ? req.headers["if-none-match"] : void 0;
86
+ const key = buildDeterministicKey(req, { keyGenerator, headerWhitelist });
87
+ const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
88
+ const resolvedTags = typeof tags === "function" ? tags(req) : tags;
21
89
  try {
22
90
  const cached = await activeCache.get(
23
91
  key,
@@ -26,37 +94,47 @@ function expressCache(options = {}) {
26
94
  const origJson = res.json?.bind(res);
27
95
  const origSend = res.send?.bind(res);
28
96
  const origEnd = res.end?.bind(res);
29
- const statusOf = () => res.statusCode;
97
+ const getStatusCode = () => res.statusCode ?? 200;
30
98
  if (origJson) {
31
99
  res.json = (body) => {
100
+ const status = getStatusCode();
32
101
  const bodyEtag = etag ? generateETag(body) : void 0;
33
- resolve({ body, contentType: "application/json; charset=utf-8", etag: bodyEtag, status: statusOf() });
34
- if (ifNoneMatch && ifNoneMatch === bodyEtag) {
102
+ const contentType = res.getHeader?.("content-type") || "application/json; charset=utf-8";
103
+ resolve({ body, contentType, etag: bodyEtag, status });
104
+ if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
35
105
  res.status?.(304);
36
106
  origEnd?.();
37
107
  return;
38
108
  }
39
- if (bodyEtag && res.setHeader) res.setHeader("ETag", bodyEtag);
109
+ if (bodyEtag && res.setHeader) {
110
+ res.setHeader("ETag", bodyEtag);
111
+ }
40
112
  return origJson(body);
41
113
  };
42
114
  }
43
115
  if (origSend) {
44
116
  res.send = (body) => {
117
+ const status = getStatusCode();
45
118
  const bodyEtag = etag ? generateETag(body) : void 0;
46
- resolve({ body, contentType: res.getHeader ? res.getHeader("content-type") : void 0, etag: bodyEtag, status: statusOf() });
47
- if (ifNoneMatch && ifNoneMatch === bodyEtag) {
119
+ const contentType = res.getHeader?.("content-type");
120
+ resolve({ body, contentType, etag: bodyEtag, status });
121
+ if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
48
122
  res.status?.(304);
49
123
  origEnd?.();
50
124
  return;
51
125
  }
52
- if (bodyEtag && res.setHeader) res.setHeader("ETag", bodyEtag);
126
+ if (bodyEtag && res.setHeader) {
127
+ res.setHeader("ETag", bodyEtag);
128
+ }
53
129
  return origSend(body);
54
130
  };
55
131
  }
56
132
  if (origEnd) {
57
133
  res.end = (body) => {
134
+ const status = getStatusCode();
58
135
  const bodyEtag = etag && body != null ? generateETag(body) : void 0;
59
- resolve({ body, contentType: res.getHeader ? res.getHeader("content-type") : void 0, etag: bodyEtag, status: statusOf() });
136
+ const contentType = res.getHeader?.("content-type");
137
+ resolve({ body, contentType, etag: bodyEtag, status });
60
138
  return origEnd(body);
61
139
  };
62
140
  }
@@ -64,10 +142,9 @@ function expressCache(options = {}) {
64
142
  });
65
143
  },
66
144
  ttl,
67
- { swr, tags }
145
+ { swr, tags: resolvedTags }
68
146
  );
69
- const respStatus = cached.status;
70
- if (typeof respStatus === "number" && (respStatus < 200 || respStatus >= 300)) {
147
+ if (typeof cached.status === "number" && (cached.status < 200 || cached.status >= 300)) {
71
148
  await activeCache.delete(key).catch(() => {
72
149
  });
73
150
  return;
@@ -82,10 +159,15 @@ function expressCache(options = {}) {
82
159
  if (cached.contentType && res.setHeader) {
83
160
  res.setHeader("Content-Type", cached.contentType);
84
161
  }
162
+ if (cached.status && res.status) {
163
+ res.status(cached.status);
164
+ }
85
165
  if (typeof cached.body === "object" && cached.body !== null && res.json) {
86
166
  return res.json(cached.body);
87
167
  } else if (res.send) {
88
168
  return res.send(cached.body);
169
+ } else if (res.end) {
170
+ return res.end(cached.body);
89
171
  }
90
172
  }
91
173
  } catch (err) {
@@ -93,67 +175,114 @@ function expressCache(options = {}) {
93
175
  }
94
176
  };
95
177
  }
96
- function honoCache(options = {}) {
97
- const { cache, keyGenerator, etag = true, ttl = 300, swr, tags } = options;
98
- return async (c, next) => {
99
- if (c.req.method !== "GET" && c.req.method !== "HEAD") {
100
- return await next();
101
- }
102
- let activeCache = cache;
178
+ var expressCache = createExpressMiddleware;
179
+
180
+ // src/http/fastify.ts
181
+ function createFastifyPlugin(options = {}) {
182
+ const plugin = async function(fastify, pluginOpts = {}) {
183
+ const mergedOpts = { ...options, ...pluginOpts };
184
+ const etag = mergedOpts.etag ?? true;
185
+ const ttl = mergedOpts.ttl ?? 300;
186
+ let activeCache = mergedOpts.cache;
103
187
  if (!activeCache) {
104
- const { CacheService } = await import("../cache-service-5GATUYAK.js");
188
+ const { CacheService } = await import("../cache-service-5MZXFIGK.js");
105
189
  activeCache = CacheService.create();
106
190
  }
107
- const key = keyGenerator ? keyGenerator(c.req) : `http:${c.req.method}:${c.req.url}`;
108
- const ifNoneMatch = c.req.header ? c.req.header("if-none-match") : void 0;
109
- const cached = await activeCache.get(
110
- key,
111
- async () => {
112
- await next();
113
- const res = c.res;
114
- const text = await res.clone().text();
115
- const bodyEtag = etag ? generateETag(text) : void 0;
116
- return {
117
- body: text,
118
- contentType: res.headers.get("content-type") ?? "text/plain",
119
- etag: bodyEtag,
120
- status: typeof res.status === "number" ? res.status : void 0
121
- };
122
- },
123
- ttl,
124
- { swr, tags }
125
- );
126
- if (typeof cached.status === "number" && (cached.status < 200 || cached.status >= 300)) {
127
- await activeCache.delete(key).catch(() => {
191
+ fastify.addHook("onRequest", async (req, reply) => {
192
+ if (req.method !== "GET" && req.method !== "HEAD") {
193
+ return;
194
+ }
195
+ if (shouldSkipCache(req, mergedOpts.skipCache)) {
196
+ return;
197
+ }
198
+ const key = buildDeterministicKey(req, {
199
+ keyGenerator: mergedOpts.keyGenerator,
200
+ headerWhitelist: mergedOpts.headerWhitelist
128
201
  });
129
- return;
130
- }
131
- if (cached.etag && ifNoneMatch === cached.etag) {
132
- return c.body(null, 304, { ETag: cached.etag });
133
- }
134
- const headers = {};
135
- if (cached.etag) headers["ETag"] = cached.etag;
136
- if (cached.contentType) headers["Content-Type"] = cached.contentType;
137
- return c.body(cached.body, 200, headers);
202
+ const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
203
+ const cached = await activeCache.get(
204
+ key,
205
+ async () => null,
206
+ 0
207
+ );
208
+ if (cached && typeof cached === "object" && cached.body !== null) {
209
+ if (cached.etag) {
210
+ reply.header("ETag", cached.etag);
211
+ if (ifNoneMatch === cached.etag) {
212
+ reply.code(304);
213
+ return reply.send();
214
+ }
215
+ }
216
+ if (cached.contentType) {
217
+ reply.header("Content-Type", cached.contentType);
218
+ }
219
+ reply.code(cached.status ?? 200);
220
+ return reply.send(cached.body);
221
+ }
222
+ req._tricacheKey = key;
223
+ const resolvedTags = typeof mergedOpts.tags === "function" ? mergedOpts.tags(req) : mergedOpts.tags;
224
+ req._tricacheTags = resolvedTags;
225
+ });
226
+ fastify.addHook("onSend", async (req, reply, payload) => {
227
+ const key = req._tricacheKey;
228
+ if (!key) {
229
+ return payload;
230
+ }
231
+ const statusCode = reply.statusCode ?? reply.raw?.statusCode ?? 200;
232
+ if (statusCode >= 200 && statusCode < 300 && payload !== void 0 && payload !== null) {
233
+ const payloadEtag = etag ? generateETag(payload) : void 0;
234
+ const contentType = reply.getHeader("content-type") || (typeof payload === "object" ? "application/json" : "text/plain");
235
+ if (payloadEtag) {
236
+ reply.header("ETag", payloadEtag);
237
+ }
238
+ const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
239
+ if (ifNoneMatch && payloadEtag && ifNoneMatch === payloadEtag) {
240
+ reply.code(304);
241
+ return "";
242
+ }
243
+ const entry = {
244
+ body: payload,
245
+ contentType,
246
+ etag: payloadEtag,
247
+ status: statusCode
248
+ };
249
+ void activeCache.set(key, entry, mergedOpts.ttl ?? ttl, void 0, {
250
+ tags: req._tricacheTags
251
+ });
252
+ }
253
+ return payload;
254
+ });
138
255
  };
256
+ plugin[/* @__PURE__ */ Symbol.for("skip-override")] = true;
257
+ return plugin;
139
258
  }
259
+ var fastifyCachePlugin = createFastifyPlugin();
140
260
  function fastifyCache(options = {}) {
141
- const { cache, keyGenerator, etag = true, ttl = 300, tags } = options;
142
- return async (req, reply) => {
261
+ const plugin = createFastifyPlugin(options);
262
+ const dualHandler = async function(first, second) {
263
+ if (first && typeof first.addHook === "function") {
264
+ return plugin(first, second);
265
+ }
266
+ const req = first;
267
+ const reply = second;
143
268
  if (req.method !== "GET" && req.method !== "HEAD") return;
144
- let activeCache = cache;
269
+ if (shouldSkipCache(req, options.skipCache)) return;
270
+ let activeCache = options.cache;
145
271
  if (!activeCache) {
146
- const { CacheService } = await import("../cache-service-5GATUYAK.js");
272
+ const { CacheService } = await import("../cache-service-5MZXFIGK.js");
147
273
  activeCache = CacheService.create();
148
274
  }
149
- const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.url}`;
150
- const ifNoneMatch = req.headers ? req.headers["if-none-match"] : void 0;
275
+ const key = buildDeterministicKey(req, {
276
+ keyGenerator: options.keyGenerator,
277
+ headerWhitelist: options.headerWhitelist
278
+ });
279
+ const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
151
280
  const cached = await activeCache.get(
152
281
  key,
153
282
  async () => null,
154
283
  0
155
284
  );
156
- if (cached) {
285
+ if (cached && typeof cached === "object" && cached.body !== null) {
157
286
  if (cached.etag) {
158
287
  if (reply.header) reply.header("ETag", cached.etag);
159
288
  if (ifNoneMatch === cached.etag) {
@@ -166,19 +295,29 @@ function fastifyCache(options = {}) {
166
295
  if (cached.contentType && reply.header) {
167
296
  reply.header("Content-Type", cached.contentType);
168
297
  }
298
+ if (cached.status) {
299
+ if (reply.code) reply.code(cached.status);
300
+ else if (reply.status) reply.status(cached.status);
301
+ }
169
302
  if (reply.send) return reply.send(cached.body);
170
303
  return;
171
304
  }
172
305
  const origSend = reply.send?.bind(reply);
173
306
  if (origSend) {
174
- reply.send = function(payload) {
175
- if (payload !== void 0 && payload !== null) {
176
- const payloadEtag = etag ? generateETag(payload) : void 0;
177
- const contentType = reply.getHeader && reply.getHeader("content-type") || (typeof payload === "object" ? "application/json" : "text/plain");
178
- const respStatus = reply.statusCode ?? reply.raw?.statusCode;
179
- if (respStatus === void 0 || respStatus >= 200 && respStatus < 300) {
180
- activeCache.set(key, { body: payload, contentType, etag: payloadEtag }, ttl, void 0, { tags }).catch(() => {
181
- });
307
+ reply.send = function(resPayload) {
308
+ if (resPayload !== void 0 && resPayload !== null) {
309
+ const payloadEtag = options.etag !== false ? generateETag(resPayload) : void 0;
310
+ const contentType = reply.getHeader && reply.getHeader("content-type") || (typeof resPayload === "object" ? "application/json" : "text/plain");
311
+ const respStatus = reply.statusCode ?? reply.raw?.statusCode ?? 200;
312
+ if (respStatus >= 200 && respStatus < 300) {
313
+ const resolvedTags = typeof options.tags === "function" ? options.tags(req) : options.tags;
314
+ void activeCache.set(
315
+ key,
316
+ { body: resPayload, contentType, etag: payloadEtag, status: respStatus },
317
+ options.ttl ?? 300,
318
+ void 0,
319
+ { tags: resolvedTags }
320
+ );
182
321
  }
183
322
  if (ifNoneMatch && ifNoneMatch === payloadEtag) {
184
323
  if (reply.code) reply.code(304);
@@ -187,14 +326,23 @@ function fastifyCache(options = {}) {
187
326
  }
188
327
  if (payloadEtag && reply.header) reply.header("ETag", payloadEtag);
189
328
  }
190
- return origSend(payload);
329
+ return origSend(resPayload);
191
330
  };
192
331
  }
193
332
  };
333
+ dualHandler[/* @__PURE__ */ Symbol.for("skip-override")] = true;
334
+ return dualHandler;
194
335
  }
195
336
  export {
337
+ buildDeterministicKey,
338
+ buildEdgeDeterministicKey,
339
+ computeEdgeETag,
340
+ createExpressMiddleware,
341
+ createFastifyPlugin,
196
342
  expressCache,
197
343
  fastifyCache,
344
+ fastifyCachePlugin,
198
345
  generateETag,
199
- honoCache
346
+ honoEdgeCache as honoCache,
347
+ shouldSkipCache
200
348
  };