Skip to content

Commit 8259dec

Browse files
committed
Update tests and types
1 parent e1fdbc6 commit 8259dec

21 files changed

+263
-634
lines changed

deno.lock

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

packages/cache-handlers/README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,6 @@ console.log(stats.totalEntries, stats.entriesByTag);
174174
| `cacheName` | Named cache to open (default `cache-primitives-default`) |
175175
| `cache` | Provide a `Cache` instance directly |
176176
| `handler` | Function invoked on misses / background revalidation |
177-
| `revalidationHandler` | Alternate function used only for background refresh |
178177
| `defaultTtl` | Fallback TTL (seconds) when no cache headers present |
179178
| `maxTtl` | Upper bound to clamp any TTL (seconds) |
180179
| `getCacheKey` | Custom key generator `(request) => string` |

packages/cache-handlers/src/handlers.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import type {
2-
CacheConfig,
32
CacheHandle,
43
CacheHandleOptions,
54
CreateCacheHandlerOptions,
65
HandlerFunction,
76
} from "./types.ts";
8-
import { defaultGetCacheKey } from "./utils.ts";
97
import { readFromCache } from "./read.ts";
108
import { writeToCache } from "./write.ts";
119

@@ -14,7 +12,6 @@ export function createCacheHandler(
1412
options: CreateCacheHandlerOptions = {},
1513
): CacheHandle {
1614
const baseHandler: HandlerFunction | undefined = options.handler;
17-
const getCacheKey = options.getCacheKey || defaultGetCacheKey;
1815

1916
const handle: CacheHandle = async (
2017
request: Request,

packages/cache-handlers/src/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,5 @@ export type {
2929
HandlerInfo,
3030
HandlerMode,
3131
InvalidationOptions,
32-
RevalidationHandler,
3332
SWRPolicy,
3433
} from "./types.ts";

packages/cache-handlers/src/metadata.ts

Lines changed: 32 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,15 @@
33
*/
44

55
import { getErrorHandler, safeJsonParse } from "./errors.ts";
6+
import type { CacheVary } from "./types.ts";
7+
8+
// Strongly typed metadata entry for Vary data (LRU tracking via timestamp)
9+
interface VaryEntry {
10+
// Arbitrary vary data structure (headers/cookies/query lists etc.)
11+
// Use unknown to avoid any; callers narrow as needed
12+
[key: string]: unknown;
13+
timestamp: number; // LRU timestamp (ms)
14+
}
615

716
const METADATA_LOCK_PREFIX = "https://cache-internal/lock-";
817
const METADATA_LOCK_TIMEOUT = 5000; // 5 seconds
@@ -46,12 +55,7 @@ export async function atomicMetadataUpdate<T>(
4655
const updatedData = updateFn(currentData);
4756

4857
// Write back updated metadata
49-
await cache.put(
50-
metadataKey,
51-
new Response(JSON.stringify(updatedData), {
52-
headers: { "Content-Type": "application/json" },
53-
}),
54-
);
58+
await cache.put(metadataKey, Response.json(updatedData));
5559

5660
return; // Success
5761
} finally {
@@ -106,12 +110,7 @@ async function tryAcquireLock(cache: Cache, lockKey: string): Promise<boolean> {
106110
pid: Math.random().toString(36).substring(2), // Simple process identifier
107111
};
108112

109-
await cache.put(
110-
lockKey,
111-
new Response(JSON.stringify(lockData), {
112-
headers: { "Content-Type": "application/json" },
113-
}),
114-
);
113+
await cache.put(lockKey, Response.json(lockData));
115114

116115
return true;
117116
} catch (error) {
@@ -180,37 +179,37 @@ export async function updateVaryMetadata(
180179
cache: Cache,
181180
metadataKey: string,
182181
requestUrl: string,
183-
varyData: any,
182+
varyData: CacheVary,
184183
maxEntries = 1000,
185184
): Promise<void> {
186185
await atomicMetadataUpdate(
187186
cache,
188187
metadataKey,
189-
(metadata: Record<string, any>) => {
188+
(metadata: Record<string, VaryEntry>) => {
190189
// Add timestamp for LRU cleanup
191-
metadata[requestUrl] = {
190+
const entry: VaryEntry = {
192191
...varyData,
193192
timestamp: Date.now(),
194193
};
194+
metadata[requestUrl] = entry;
195195

196196
// Implement LRU cleanup if we exceed maxEntries
197-
const entries = Object.entries(metadata);
197+
const entries: Array<[string, VaryEntry]> = Object.entries(
198+
metadata,
199+
) as Array<[string, VaryEntry]>;
198200
if (entries.length > maxEntries) {
199-
// Sort by timestamp (oldest first) and remove oldest entries
200-
entries.sort(([, a], [, b]) => (a.timestamp || 0) - (b.timestamp || 0));
201+
// Sort by timestamp (oldest first) and keep newest maxEntries
202+
entries.sort(([, a], [, b]) => a.timestamp - b.timestamp);
201203
const toKeep = entries.slice(-maxEntries);
202-
203-
// Rebuild metadata with only the entries to keep
204-
const cleanedMetadata: Record<string, any> = {};
205-
for (const [key, value] of toKeep) {
206-
cleanedMetadata[key] = value;
204+
const cleanedMetadata: Record<string, VaryEntry> = {};
205+
for (const [k, v] of toKeep) {
206+
cleanedMetadata[k] = v;
207207
}
208208
return cleanedMetadata;
209209
}
210-
211210
return metadata;
212211
},
213-
{} as Record<string, any>,
212+
{} as Record<string, VaryEntry>,
214213
);
215214
}
216215

@@ -225,19 +224,18 @@ export async function cleanupVaryMetadata(
225224
await atomicMetadataUpdate(
226225
cache,
227226
metadataKey,
228-
(metadata: Record<string, any>) => {
227+
(metadata: Record<string, VaryEntry>) => {
229228
const now = Date.now();
230-
const cleanedMetadata: Record<string, any> = {};
231-
232-
for (const [key, value] of Object.entries(metadata)) {
233-
const timestamp = value.timestamp || 0;
234-
if (now - timestamp < maxAge) {
235-
cleanedMetadata[key] = value;
229+
const cleanedMetadata: Record<string, VaryEntry> = {};
230+
for (
231+
const [k, v] of Object.entries(metadata) as Array<[string, VaryEntry]>
232+
) {
233+
if (now - v.timestamp < maxAge) {
234+
cleanedMetadata[k] = v;
236235
}
237236
}
238-
239237
return cleanedMetadata;
240238
},
241-
{} as const,
239+
{} as Record<string, VaryEntry>,
242240
);
243241
}

packages/cache-handlers/src/read.ts

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,31 @@ export async function readFromCache(
1919
const getCacheKey = config.getCacheKey || defaultGetCacheKey;
2020
const cache = await getCache(config);
2121
const varyMetadataResponse = await cache.match(VARY_METADATA_KEY);
22-
// deno-lint-ignore no-explicit-any
23-
let varyMetadata: Record<string, any> = {};
22+
interface VaryEntry {
23+
timestamp?: number;
24+
headers?: unknown;
25+
cookies?: unknown;
26+
query?: unknown;
27+
}
28+
function isStringArray(value: unknown): value is string[] {
29+
return Array.isArray(value) && value.every((v) => typeof v === "string");
30+
}
31+
let varyMetadata: Record<string, VaryEntry> = {};
2432
varyMetadata = await safeJsonParse(
2533
varyMetadataResponse?.clone() || null,
26-
// deno-lint-ignore no-explicit-any
27-
{} as Record<string, any>,
34+
{} as Record<string, VaryEntry>,
2835
"vary metadata parsing in cache handler",
2936
);
30-
const vary = varyMetadata[request.url];
31-
const cacheKey = await getCacheKey(request, vary);
37+
const vary = varyMetadata[request.url] as VaryEntry | undefined;
38+
// Only pass vary data if present; defaultGetCacheKey expects CacheVary shape
39+
const varyArg = vary
40+
? {
41+
headers: isStringArray(vary.headers) ? vary.headers : [],
42+
cookies: isStringArray(vary.cookies) ? vary.cookies : [],
43+
query: isStringArray(vary.query) ? vary.query : [],
44+
}
45+
: undefined;
46+
const cacheKey = await getCacheKey(request, varyArg);
3247
const cacheRequest = new Request(cacheKey);
3348
let cachedResponse: Response | null = (await cache.match(cacheKey)) ?? null;
3449
let needsBackgroundRevalidation = false;

packages/cache-handlers/src/types.ts

Lines changed: 4 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -85,20 +85,13 @@ export interface CacheConfig {
8585
*/
8686
maxTtl?: number;
8787

88-
/**
89-
* Revalidation handler for stale-while-revalidate support.
90-
* Called when cached content is stale but within the SWR window.
91-
* If not provided, revalidation will be skipped.
92-
*/
93-
revalidationHandler?: RevalidationHandler;
94-
9588
/**
9689
* WaitUntil handler for background tasks (like revalidation).
9790
* Similar to Cloudflare Workers' ctx.waitUntil().
9891
* Allows the platform to keep processes alive for background work.
9992
* If not provided, queueMicrotask will be used as fallback.
10093
*/
101-
waitUntil?: (promise: Promise<any>) => void;
94+
waitUntil?: (promise: Promise<unknown>) => void;
10295
}
10396

10497
/**
@@ -264,21 +257,6 @@ export interface ParsedCacheHeaders {
264257
shouldGenerateETag?: boolean;
265258
}
266259

267-
/**
268-
* Revalidation handler function for stale-while-revalidate support.
269-
* Called when content needs to be revalidated in the background.
270-
*
271-
* @example
272-
* ```typescript
273-
* const revalidateHandler: RevalidationHandler = async (request) => fetch(request.url);
274-
* ```
275-
*/
276-
export interface RevalidationHandler {
277-
(request: Request): Promise<Response>;
278-
}
279-
280-
// --- Higher-level handler API ---
281-
282260
/**
283261
* Render / handling mode information passed to user handler.
284262
* - miss: cache miss foreground render
@@ -298,7 +276,7 @@ export interface HandlerInfo {
298276
export type HandlerFunction = (
299277
request: Request,
300278
info: HandlerInfo,
301-
) => Promise<Response>;
279+
) => Promise<Response> | Response;
302280

303281
/**
304282
* SWR policy (reserved for future strategies).
@@ -323,12 +301,12 @@ export interface CreateCacheHandlerOptions extends CacheConfig {
323301
/**
324302
* Background scheduler analogous to waitUntil.
325303
*/
326-
runInBackground?: (p: Promise<any>) => void;
304+
runInBackground?: (p: Promise<unknown>) => void;
327305
}
328306

329307
export interface CacheHandleFunctionOptions {
330308
handler?: HandlerFunction;
331-
runInBackground?: (p: Promise<any>) => void;
309+
runInBackground?: (p: Promise<unknown>) => void;
332310
swr?: SWRPolicy;
333311
}
334312
/**

0 commit comments

Comments
 (0)