tricache 0.8.0 → 1.0.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 (56) hide show
  1. package/README.md +10 -4
  2. package/dashboards/prometheus-scrape.yml +18 -0
  3. package/dist/{cache-service-5MZXFIGK.js → cache-service-26GCO3UU.js} +3 -3
  4. package/dist/{cache-service-CyLdpo77.d.ts → cache-service-pJ-nFcVj.d.ts} +44 -12
  5. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  6. package/dist/{chunk-6PQ5MOWR.js → chunk-7SZSQS55.js} +571 -115
  7. package/dist/chunk-BQRURGGD.js +60 -0
  8. package/dist/chunk-IITRFWHY.js +196 -0
  9. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  10. package/dist/cli.cjs +767 -133
  11. package/dist/cli.js +24 -6
  12. package/dist/dashboard/index.d.ts +2 -2
  13. package/dist/drizzle/index.cjs +734 -132
  14. package/dist/drizzle/index.d.ts +2 -2
  15. package/dist/drizzle/index.js +1 -1
  16. package/dist/edge/index.cjs +163 -46
  17. package/dist/edge/index.d.ts +3 -3
  18. package/dist/edge/index.js +42 -14
  19. package/dist/hono/index.cjs +8093 -0
  20. package/dist/hono/index.d.ts +91 -0
  21. package/dist/hono/index.js +185 -0
  22. package/dist/{hono-DQRS1Xd7.d.ts → hono-DuNvciyq.d.ts} +6 -5
  23. package/dist/http/index.cjs +833 -170
  24. package/dist/http/index.d.ts +6 -30
  25. package/dist/http/index.js +9 -59
  26. package/dist/index.cjs +755 -130
  27. package/dist/index.d.ts +35 -6
  28. package/dist/index.js +16 -6
  29. package/dist/nestjs/index.cjs +725 -130
  30. package/dist/nestjs/index.d.ts +2 -2
  31. package/dist/nestjs/index.js +4 -4
  32. package/dist/next/index.cjs +725 -130
  33. package/dist/next/index.d.ts +2 -2
  34. package/dist/next/index.js +3 -3
  35. package/dist/prisma/index.d.ts +2 -2
  36. package/dist/serialize-worker.cjs +127 -9
  37. package/dist/serialize-worker.js +8 -4
  38. package/dist/{types-B6krw64X.d.ts → types-5HXqBfAf.d.ts} +74 -7
  39. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  40. package/package.json +22 -9
  41. package/src/cache-service.ts +540 -68
  42. package/src/cli.ts +21 -4
  43. package/src/compression.ts +193 -15
  44. package/src/cross-region.ts +1 -1
  45. package/src/edge/cache.ts +38 -11
  46. package/src/edge/hono.ts +123 -42
  47. package/src/env.d.ts +13 -0
  48. package/src/hono/index.ts +316 -0
  49. package/src/http/index.ts +5 -0
  50. package/src/index.ts +9 -1
  51. package/src/ipc-telemetry.ts +29 -1
  52. package/src/serialize-worker.ts +6 -2
  53. package/src/types.ts +68 -5
  54. package/src/utils/tag-matcher.ts +90 -0
  55. package/dist/chunk-ZTSWCFYO.js +0 -135
  56. /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
package/src/cli.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  * npx tricache clear [--redis redis://localhost:6379] [--namespace <ns>] [--prefix <prefix>]
9
9
  */
10
10
 
11
+ import { readFileSync } from 'node:fs';
11
12
  import { parseArgs } from 'node:util';
12
13
  import { CacheService } from './cache-service.js';
13
14
  import {
@@ -59,7 +60,14 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
59
60
  // (bin/tricache.js). Output must go directly to process stdout without logger prefixes
60
61
  // to support UNIX pipes, terminal formatting, and automated tooling.
61
62
  if (values.version || command === 'version') {
62
- console.log('tricache v0.8.0');
63
+ let version = '1.0.0';
64
+ try {
65
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
66
+ if (pkg?.version) version = pkg.version;
67
+ } catch {
68
+ // fallback to default version
69
+ }
70
+ console.log(`tricache v${version}`);
63
71
  return;
64
72
  }
65
73
 
@@ -73,11 +81,20 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
73
81
  const active = await findActiveSockets();
74
82
  if (active.length > 0) {
75
83
  targetSocket = active[0];
76
- } else {
77
- targetSocket = resolveIpcSocketPath(process.pid);
78
84
  }
79
85
  }
80
86
 
87
+ if (!targetSocket) {
88
+ console.error('No active TriCache instances found to monitor.\n');
89
+ console.error('To use `tricache top`:');
90
+ console.error(' 1. Ensure your running application enables IPC telemetry:');
91
+ console.error(" const cache = new CacheService({ namespace: 'my-app', enableIpc: true, ... });\n");
92
+ console.error(' 2. If the application is already running, specify its PID or socket:');
93
+ console.error(' npx tricache top --pid <pid>');
94
+ console.error(' npx tricache top --socket <path>\n');
95
+ process.exit(1);
96
+ }
97
+
81
98
  const client = new IpcTelemetryClient(targetSocket);
82
99
  const intervalMs = typeof values.interval === 'string'
83
100
  ? Math.max(200, parseInt(values.interval, 10))
@@ -148,7 +165,7 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
148
165
  const screen = renderTopDashboard(payload);
149
166
  process.stdout.write('\x1b[H' + screen + '\n Press "q" or Ctrl+C to exit\n');
150
167
  } catch (err) {
151
- process.stdout.write(`\x1b[HConnecting to ${targetSocket}...\nError: ${(err as Error).message}\n`);
168
+ process.stdout.write(`\x1b[HConnecting to ${targetSocket}...\nError: ${(err as Error).message}\n\nWaiting for TriCache IPC server. Ensure the target process is running with enableIpc: true.\nPress "q" or Ctrl+C to exit\n`);
152
169
  }
153
170
  };
154
171
 
@@ -1,6 +1,14 @@
1
1
  import zlib from 'zlib';
2
+ import lz4js from 'lz4js';
3
+ import { ZstdCodec } from 'zstd-codec';
2
4
 
3
- export type CompressionAlgorithm = 'brotli' | 'gzip' | 'none';
5
+ export type CompressionAlgorithm = 'brotli' | 'gzip' | 'zstd' | 'lz4' | 'none';
6
+
7
+ export interface CustomCompressor {
8
+ name: string;
9
+ compress: (buf: Buffer) => Buffer;
10
+ decompress: (buf: Buffer) => Buffer;
11
+ }
4
12
 
5
13
  export const PREFIX_COMPRESSED = 'cmp:v1:';
6
14
  export const PREFIX_ENC_COMPRESSED = 'ecp:v1:';
@@ -8,11 +16,45 @@ export const PREFIX_ENC_COMPRESSED = 'ecp:v1:';
8
16
  /** "TRC\x01" 4-byte marker prefix identifying compressed data */
9
17
  const COMPRESSION_MAGIC = Buffer.from([0x54, 0x52, 0x43, 0x01]);
10
18
 
19
+ let zstdSimple: any = null;
20
+ let zstdInitPromise: Promise<any> | null = null;
21
+
22
+ /**
23
+ * Initializes the WebAssembly Zstandard codec.
24
+ * Resolves immediately if already initialized.
25
+ */
26
+ export function initZstd(): Promise<any> {
27
+ if (zstdSimple) return Promise.resolve(zstdSimple);
28
+ if (!zstdInitPromise) {
29
+ zstdInitPromise = new Promise((resolve) => {
30
+ try {
31
+ ZstdCodec.run((zstd: any) => {
32
+ zstdSimple = new zstd.Simple();
33
+ resolve(zstdSimple);
34
+ });
35
+ } catch {
36
+ resolve(null);
37
+ }
38
+ });
39
+ }
40
+ return zstdInitPromise;
41
+ }
42
+
43
+ // Auto-start initialization immediately in the background
44
+ initZstd().catch(() => {});
45
+
11
46
  export function isCompressed(buf: Buffer): boolean {
12
47
  return buf.length >= 4 && buf[0] === 0x54 && buf[1] === 0x52 && buf[2] === 0x43 && buf[3] === 0x01;
13
48
  }
14
49
 
15
- export function compressBuffer(buf: Buffer, algorithm: CompressionAlgorithm): Buffer {
50
+ export function compressBuffer(
51
+ buf: Buffer,
52
+ algorithm: CompressionAlgorithm,
53
+ custom?: CustomCompressor,
54
+ ): Buffer {
55
+ if (custom) {
56
+ return custom.compress(buf);
57
+ }
16
58
  if (algorithm === 'brotli') {
17
59
  return zlib.brotliCompressSync(buf, {
18
60
  params: {
@@ -23,34 +65,170 @@ export function compressBuffer(buf: Buffer, algorithm: CompressionAlgorithm): Bu
23
65
  if (algorithm === 'gzip') {
24
66
  return zlib.gzipSync(buf, { level: 6 });
25
67
  }
68
+ if (algorithm === 'lz4') {
69
+ return Buffer.from(lz4js.compress(buf));
70
+ }
71
+ if (algorithm === 'zstd') {
72
+ if (!zstdSimple) {
73
+ // If zstd WASM compile has not yet finished, fallback to fast Brotli level 4
74
+ return zlib.brotliCompressSync(buf, {
75
+ params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4 },
76
+ });
77
+ }
78
+ return Buffer.from(zstdSimple.compress(buf));
79
+ }
26
80
  return buf;
27
81
  }
28
82
 
29
- export function decompressBuffer(buf: Buffer, algorithm: CompressionAlgorithm = 'brotli'): Buffer {
30
- // Try the configured algorithm first, then the other one as recovery (covers
31
- // entries written under a different compression setting). If BOTH fail, the
32
- // payload is corrupt: THROW instead of returning the raw bytes. Returning raw
33
- // surfaced corruption as garbage JSON.parse errors deep downstream; every
34
- // call site maps a thrown error to a clean cache miss instead.
35
- const tryBrotli = (): Buffer | null => { try { return zlib.brotliDecompressSync(buf); } catch { return null; } };
36
- const tryGzip = (): Buffer | null => { try { return zlib.gunzipSync(buf); } catch { return null; } };
83
+ export const MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024; // 25 MB decompression bomb safety ceiling
84
+
85
+ export function decompressBuffer(
86
+ buf: Buffer,
87
+ algorithm: CompressionAlgorithm = 'zstd',
88
+ custom?: CustomCompressor,
89
+ ): Buffer {
90
+ if (custom) {
91
+ const res = custom.decompress(buf);
92
+ if (res.length > MAX_DECOMPRESS_BYTES) {
93
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
94
+ }
95
+ return res;
96
+ }
97
+
98
+ const checkSafety = (decomp: Buffer): Buffer => {
99
+ if (decomp.length > MAX_DECOMPRESS_BYTES) {
100
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
101
+ }
102
+ return decomp;
103
+ };
104
+
105
+ // 1. Zstandard magic header: 0x28 0xB5 0x2F 0xFD
106
+ if (buf.length >= 4 && buf[0] === 0x28 && buf[1] === 0xb5 && buf[2] === 0x2f && buf[3] === 0xfd) {
107
+ if (zstdSimple) {
108
+ try {
109
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
110
+ } catch (err: any) {
111
+ if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
112
+ /* try recovery */
113
+ }
114
+ }
115
+ }
116
+
117
+ // 2. LZ4 frame magic header: 0x04 0x22 0x4D 0x18
118
+ if (buf.length >= 4 && buf[0] === 0x04 && buf[1] === 0x22 && buf[2] === 0x4d && buf[3] === 0x18) {
119
+ try {
120
+ return checkSafety(Buffer.from(lz4js.decompress(buf)));
121
+ } catch (err: any) {
122
+ if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
123
+ /* try recovery */
124
+ }
125
+ }
126
+
127
+ // 3. Gzip magic header: 0x1F 0x8B
128
+ if (buf.length >= 2 && buf[0] === 0x1f && buf[1] === 0x8b) {
129
+ try {
130
+ return zlib.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
131
+ } catch (err: any) {
132
+ if (err?.code === 'ERR_BUFFER_TOO_LARGE') {
133
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
134
+ }
135
+ /* try recovery */
136
+ }
137
+ }
138
+
139
+ if (algorithm === 'none') {
140
+ return buf;
141
+ }
142
+
143
+ // 4. Algorithm-specific attempts
144
+ if (algorithm === 'lz4') {
145
+ try {
146
+ return checkSafety(Buffer.from(lz4js.decompress(buf)));
147
+ } catch (err: any) {
148
+ if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
149
+ /* fallback */
150
+ }
151
+ }
152
+
153
+ if (algorithm === 'zstd' && zstdSimple) {
154
+ try {
155
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
156
+ } catch (err: any) {
157
+ if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
158
+ /* fallback */
159
+ }
160
+ }
161
+
162
+ // 5. Universal fallback & recovery
163
+ const tryBrotli = (): Buffer | null => {
164
+ try {
165
+ return zlib.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
166
+ } catch (err: any) {
167
+ if (err?.code === 'ERR_BUFFER_TOO_LARGE') {
168
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
169
+ }
170
+ return null;
171
+ }
172
+ };
173
+ const tryGzip = (): Buffer | null => {
174
+ try {
175
+ return zlib.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
176
+ } catch (err: any) {
177
+ if (err?.code === 'ERR_BUFFER_TOO_LARGE') {
178
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
179
+ }
180
+ return null;
181
+ }
182
+ };
183
+ const tryLz4 = (): Buffer | null => {
184
+ try {
185
+ return checkSafety(Buffer.from(lz4js.decompress(buf)));
186
+ } catch (err: any) {
187
+ if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
188
+ return null;
189
+ }
190
+ };
191
+ const tryZstd = (): Buffer | null => {
192
+ if (!zstdSimple) return null;
193
+ try {
194
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
195
+ } catch (err: any) {
196
+ if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
197
+ return null;
198
+ }
199
+ };
200
+
201
+ const result = (algorithm === 'gzip' ? tryGzip() : null) ??
202
+ (algorithm === 'lz4' ? tryLz4() : null) ??
203
+ (algorithm === 'zstd' ? tryZstd() : null) ??
204
+ tryBrotli() ??
205
+ tryGzip() ??
206
+ tryLz4() ??
207
+ tryZstd();
37
208
 
38
- const result = algorithm === 'gzip' ? (tryGzip() ?? tryBrotli()) : (tryBrotli() ?? tryGzip());
39
209
  if (result === null) {
40
210
  throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
41
211
  }
42
212
  return result;
43
213
  }
44
214
 
45
- export function compressWithHeader(buf: Buffer, algorithm: CompressionAlgorithm): Buffer {
215
+ export function compressWithHeader(
216
+ buf: Buffer,
217
+ algorithm: CompressionAlgorithm,
218
+ custom?: CustomCompressor,
219
+ ): Buffer {
46
220
  if (algorithm === 'none') return buf;
47
- const compressed = compressBuffer(buf, algorithm);
221
+ const compressed = compressBuffer(buf, algorithm, custom);
48
222
  return Buffer.concat([COMPRESSION_MAGIC, compressed]);
49
223
  }
50
224
 
51
- export function decompressWithHeader(buf: Buffer, algorithm: CompressionAlgorithm = 'brotli'): Buffer {
225
+ export function decompressWithHeader(
226
+ buf: Buffer,
227
+ algorithm: CompressionAlgorithm = 'zstd',
228
+ custom?: CustomCompressor,
229
+ ): Buffer {
52
230
  if (isCompressed(buf)) {
53
- return decompressBuffer(buf.subarray(4), algorithm);
231
+ return decompressBuffer(buf.subarray(4), algorithm, custom);
54
232
  }
55
233
  return buf;
56
234
  }
@@ -14,7 +14,7 @@ export interface CrossRegionInvalidationEvent {
14
14
  /** Instance ID that initiated the invalidation */
15
15
  originInstanceId: string;
16
16
  /** Invalidation operation */
17
- op: 'del' | 'del-glob' | 'tag_incr';
17
+ op: 'del' | 'del-glob' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del';
18
18
  /** Cache key or tag name */
19
19
  key: string;
20
20
  /** New tag version for generational tag invalidation */
package/src/edge/cache.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ICacheSpan, ICacheTracer } from '../types';
1
+ import type { ICacheSpan, ICacheTracer, InvalidateTagOptions } from '../types';
2
2
  import type {
3
3
  EdgeCacheOptions,
4
4
  EdgeGetOptions,
@@ -13,6 +13,7 @@ import type {
13
13
  import { WebCryptoEncryption } from './crypto';
14
14
  import { WasmBloomFilter } from '../wasm/bloom-filter-wasm';
15
15
  import { Murmur3BloomFilter } from './utils/murmur3';
16
+ import { isWildcardTag, matchesTagPattern, isChildTag } from '../utils/tag-matcher';
16
17
 
17
18
  interface EdgeL1Entry<T = unknown> {
18
19
  value: T;
@@ -398,19 +399,20 @@ export class EdgeCacheService {
398
399
  key: string,
399
400
  value: T,
400
401
  ttlSeconds?: number,
401
- options?: { tags?: string[]; swr?: number },
402
+ options?: { tags?: string[]; swr?: number } | string[],
402
403
  ): Promise<void> {
403
404
  const span = this._startSpan('tricache.set');
404
405
  span.setAttribute('cache.key', key);
405
406
  const nsKey = this.nk(key);
406
407
  const resolvedTtl = ttlSeconds ?? this.defaultTtl;
407
408
  const now = Date.now();
408
- const swrSeconds = options?.swr ?? 0;
409
+ const optObj = Array.isArray(options) ? { tags: options } : options;
410
+ const swrSeconds = optObj?.swr ?? 0;
409
411
 
410
412
  try {
411
413
  let activeTagVersions: Record<string, number> | undefined;
412
- if (options?.tags?.length) {
413
- activeTagVersions = await this._batchGetTagVersions(options.tags);
414
+ if (optObj?.tags?.length) {
415
+ activeTagVersions = await this._batchGetTagVersions(optObj.tags);
414
416
  }
415
417
 
416
418
  const serialized = JSON.stringify(value);
@@ -426,7 +428,7 @@ export class EdgeCacheService {
426
428
  bytes,
427
429
  expiresAt: now + resolvedTtl * 1000,
428
430
  staleUntil: now + (resolvedTtl + swrSeconds) * 1000,
429
- tags: options?.tags,
431
+ tags: optObj?.tags,
430
432
  tagVersions: activeTagVersions,
431
433
  };
432
434
 
@@ -434,8 +436,8 @@ export class EdgeCacheService {
434
436
  this.currentBytes += bytes;
435
437
 
436
438
  // Index tags
437
- if (options?.tags) {
438
- for (const tag of options.tags) {
439
+ if (optObj?.tags) {
440
+ for (const tag of optObj.tags) {
439
441
  let s = this.tagIndex.get(tag);
440
442
  if (!s) {
441
443
  s = new Set<string>();
@@ -492,11 +494,35 @@ export class EdgeCacheService {
492
494
  /**
493
495
  * Invalidates all cached entries associated with a tag.
494
496
  */
495
- async invalidateTag(tag: string): Promise<void> {
497
+ async invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void> {
496
498
  const span = this._startSpan('tricache.invalidate_tag');
497
499
  span.setAttribute('cache.tag', tag);
500
+ if (opts?.cascade) span.setAttribute('cache.cascade', true);
498
501
 
499
502
  try {
503
+ const isPattern = isWildcardTag(tag);
504
+ const shouldCascade = Boolean(opts?.cascade);
505
+ if (isPattern || shouldCascade) {
506
+ const matched = new Set<string>();
507
+ const tagMatches = (t: string) => {
508
+ if (t === tag) return true;
509
+ if (isPattern && matchesTagPattern(tag, t)) return true;
510
+ if (shouldCascade && isChildTag(tag, t, ':')) return true;
511
+ return false;
512
+ };
513
+ for (const t of this.tagIndex.keys()) {
514
+ if (tagMatches(t)) matched.add(t);
515
+ }
516
+ for (const t of this.tagVersionCache.keys()) {
517
+ if (tagMatches(t)) matched.add(t);
518
+ }
519
+ if (shouldCascade && !isPattern) matched.add(tag);
520
+ for (const t of matched) {
521
+ await this.invalidateTag(t);
522
+ }
523
+ return;
524
+ }
525
+
500
526
  let newVer = 1;
501
527
  if (this.remoteStorage) {
502
528
  try {
@@ -568,7 +594,7 @@ export class EdgeCacheService {
568
594
  */
569
595
  async mget<T>(
570
596
  keys: string[],
571
- fetchFn?: (missKeys: string[]) => Promise<Record<string, T>>,
597
+ fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>,
572
598
  ttlSeconds?: number,
573
599
  ): Promise<(T | null)[]> {
574
600
  const span = this._startSpan('tricache.mget');
@@ -594,9 +620,10 @@ export class EdgeCacheService {
594
620
 
595
621
  if (missKeys.length > 0 && fetchFn) {
596
622
  const fetchedMap = await fetchFn(missKeys);
623
+ const isMap = fetchedMap instanceof Map;
597
624
  for (let j = 0; j < missKeys.length; j++) {
598
625
  const k = missKeys[j];
599
- const fetchedVal = fetchedMap[k];
626
+ const fetchedVal = isMap ? (fetchedMap as Map<string, T>).get(k) : (fetchedMap as Record<string, T>)[k];
600
627
  if (fetchedVal !== undefined) {
601
628
  results[missIndices[j]] = fetchedVal;
602
629
  await this.set(k, fetchedVal, ttlSeconds);
package/src/edge/hono.ts CHANGED
@@ -22,6 +22,7 @@ export interface HonoEdgeCacheOptions {
22
22
  export interface CachedEdgeHttpResponse {
23
23
  body: string;
24
24
  contentType: string;
25
+ headers?: Record<string, string>;
25
26
  etag?: string;
26
27
  status: number;
27
28
  }
@@ -95,6 +96,14 @@ export function buildEdgeDeterministicKey(c: any, options?: { keyGenerator?: (c:
95
96
  return key;
96
97
  }
97
98
 
99
+ class NonCacheableEdgeResponseError extends Error {
100
+ readonly isNonCacheable = true;
101
+ constructor(readonly response: CachedEdgeHttpResponse) {
102
+ super(`Non-cacheable status: ${response.status}`);
103
+ this.name = 'NonCacheableEdgeResponseError';
104
+ }
105
+ }
106
+
98
107
  /**
99
108
  * Pure Web Standards Hono middleware for V8 Edge Isolates (Cloudflare Workers, Fastly, Vercel Edge).
100
109
  *
@@ -150,54 +159,126 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
150
159
  const ifNoneMatch = c.req.header?.('if-none-match') || c.req.header?.('If-None-Match');
151
160
  const resolvedTags = typeof tags === 'function' ? tags(c) : tags;
152
161
 
153
- const cached = await cache.get(
154
- key,
155
- async () => {
156
- await next();
157
- const res = c.res;
158
- if (!res) {
159
- return null;
162
+ let ranNext = false;
163
+ try {
164
+ const cached = await cache.get(
165
+ key,
166
+ async () => {
167
+ ranNext = true;
168
+ await next();
169
+ const res = c.res;
170
+ if (!res) {
171
+ return null;
172
+ }
173
+
174
+ const contentType = res.headers?.get?.('content-type') || 'text/plain; charset=utf-8';
175
+ if (contentType.toLowerCase().includes('text/event-stream')) {
176
+ throw new NonCacheableEdgeResponseError({
177
+ body: '',
178
+ contentType,
179
+ status: 0,
180
+ });
181
+ }
182
+
183
+ const cc = res.headers?.get?.('cache-control');
184
+ if (cc) {
185
+ const lowerCc = cc.toLowerCase();
186
+ if (lowerCc.includes('no-store') || lowerCc.includes('no-cache') || lowerCc.includes('private')) {
187
+ throw new NonCacheableEdgeResponseError({
188
+ body: '',
189
+ contentType,
190
+ status: 0,
191
+ });
192
+ }
193
+ }
194
+
195
+ const statusCode = res.status ?? 200;
196
+ if (statusCode < 200 || statusCode >= 300 || statusCode === 206) {
197
+ throw new NonCacheableEdgeResponseError({
198
+ body: '',
199
+ contentType,
200
+ status: statusCode,
201
+ });
202
+ }
203
+
204
+ const clone = res.clone();
205
+ const text = await clone.text();
206
+ const bodyEtag = etag ? await computeEdgeETag(text) : undefined;
207
+
208
+ const capturedHeaders: Record<string, string> = {};
209
+ if (res.headers && typeof res.headers.forEach === 'function') {
210
+ res.headers.forEach((value: string, name: string) => {
211
+ const lower = name.toLowerCase();
212
+ if (
213
+ lower !== 'content-length' &&
214
+ lower !== 'transfer-encoding' &&
215
+ lower !== 'connection' &&
216
+ lower !== 'etag' &&
217
+ lower !== 'content-type'
218
+ ) {
219
+ capturedHeaders[name] = value;
220
+ }
221
+ });
222
+ }
223
+
224
+ const snapshot: CachedEdgeHttpResponse = {
225
+ body: text,
226
+ contentType,
227
+ headers: capturedHeaders,
228
+ etag: bodyEtag,
229
+ status: statusCode,
230
+ };
231
+
232
+ return snapshot;
233
+ },
234
+ ttl,
235
+ {
236
+ swr,
237
+ tags: resolvedTags,
238
+ ctx: c.executionCtx,
160
239
  }
240
+ );
161
241
 
162
- const clone = res.clone();
163
- const text = await clone.text();
164
- const statusCode = res.status ?? 200;
165
- const bodyEtag = etag ? await computeEdgeETag(text) : undefined;
166
- const contentType = res.headers.get('content-type') || 'text/plain; charset=utf-8';
167
-
168
- return {
169
- body: text,
170
- contentType,
171
- etag: bodyEtag,
172
- status: statusCode,
173
- };
174
- },
175
- ttl,
176
- {
177
- swr,
178
- tags: resolvedTags,
179
- ctx: c.executionCtx,
242
+ if (!cached) {
243
+ return;
180
244
  }
181
- );
182
245
 
183
- if (!cached) {
184
- return;
185
- }
246
+ if (cached.etag && ifNoneMatch === cached.etag) {
247
+ const notModifiedHeaders: Record<string, string> = { ETag: cached.etag };
248
+ if (cached.headers?.['cache-control']) notModifiedHeaders['Cache-Control'] = cached.headers['cache-control'];
249
+ if (cached.headers?.['vary']) notModifiedHeaders['Vary'] = cached.headers['vary'];
250
+ return applyEdgeResponse(c, null, 304, notModifiedHeaders);
251
+ }
186
252
 
187
- // Status gate: never cache error responses
188
- if (typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300)) {
189
- await cache.delete?.(key);
190
- return;
191
- }
253
+ const headers: Record<string, string> = { ...cached.headers };
254
+ if (cached.etag) headers['ETag'] = cached.etag;
255
+ if (cached.contentType) headers['Content-Type'] = cached.contentType;
192
256
 
193
- if (cached.etag && ifNoneMatch === cached.etag) {
194
- return c.body(null, 304, { ETag: cached.etag });
257
+ return applyEdgeResponse(c, cached.body, cached.status ?? 200, headers);
258
+ } catch (err: unknown) {
259
+ if (err instanceof NonCacheableEdgeResponseError) {
260
+ if (!ranNext) {
261
+ return await next();
262
+ }
263
+ return;
264
+ }
265
+ throw err;
195
266
  }
196
-
197
- const headers: Record<string, string> = {};
198
- if (cached.etag) headers['ETag'] = cached.etag;
199
- if (cached.contentType) headers['Content-Type'] = cached.contentType;
200
-
201
- return c.body(cached.body, cached.status ?? 200, headers);
202
267
  };
203
268
  }
269
+
270
+ /**
271
+ * Hono's `compose` ignores a middleware return value once `next()` has set
272
+ * `c.res` (`finalized === true`). Assigning `c.res` replaces the downstream
273
+ * body so weak ETags and 304s are visible on both cache miss and hit.
274
+ */
275
+ function applyEdgeResponse(
276
+ c: any,
277
+ body: string | null,
278
+ status: number,
279
+ headers: Record<string, string>,
280
+ ): Response {
281
+ const response = c.body(body, status, headers);
282
+ c.res = response;
283
+ return response;
284
+ }
package/src/env.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ declare module 'lz4js' {
2
+ const lz4js: {
3
+ compress: (buf: Uint8Array | Buffer) => Uint8Array;
4
+ decompress: (buf: Uint8Array | Buffer) => Uint8Array;
5
+ };
6
+ export default lz4js;
7
+ }
8
+
9
+ declare module 'zstd-codec' {
10
+ export const ZstdCodec: {
11
+ run: (callback: (zstd: any) => void) => void;
12
+ };
13
+ }