Skip to content

Commit d078e3b

Browse files
committed
Simplify types
1 parent 4e51487 commit d078e3b

File tree

10 files changed

+173
-214
lines changed

10 files changed

+173
-214
lines changed

demos/cache-handlers/src/worker.ts

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
import { App } from "astro/app";
22
import type { SSRManifest } from "astro";
33
import { handle, type Runtime } from "@astrojs/cloudflare/handler";
4-
import type { ExportedHandlerFetchHandler } from "@cloudflare/workers-types";
4+
import type {
5+
ExportedHandler,
6+
Response as CFResponse,
7+
} from "@cloudflare/workers-types";
58
import { createCacheHandler } from "cache-handlers";
69

7-
type CFRequest = Parameters<ExportedHandlerFetchHandler>[0];
8-
910
export function createExports(manifest: SSRManifest) {
1011
const app = new App(manifest);
1112
return {
1213
default: {
1314
async fetch(
14-
request: CFRequest,
15-
env: Runtime["runtime"]["env"],
16-
ctx: Runtime["runtime"]["ctx"],
15+
request,
16+
env,
17+
ctx,
1718
) {
1819
if (request.method !== "GET") {
1920
// Directly invoke Astro for non-GET (no cache)
@@ -23,14 +24,18 @@ export function createExports(manifest: SSRManifest) {
2324
request,
2425
env,
2526
ctx,
26-
);
27+
) as unknown as Promise<CFResponse>;
2728
}
2829
const url = new URL(request.url);
2930
const cacheHandle = createCacheHandler<
30-
CFRequest
31+
typeof request,
32+
CFResponse
3133
>({
3234
swr: "background",
33-
handler: (req) => handle(manifest, app, req, env, ctx),
35+
handler: (req) =>
36+
handle(manifest, app, req, env, ctx) as unknown as Promise<
37+
CFResponse
38+
>,
3439
features: {
3540
conditionalRequests: { etag: "generate" },
3641
cacheStatusHeader: "demo-cache",
@@ -53,8 +58,10 @@ export function createExports(manifest: SSRManifest) {
5358
runInBackground: ctx.waitUntil.bind(ctx),
5459
});
5560
}
56-
return cacheHandle(request, { runInBackground: ctx.waitUntil.bind(ctx) });
61+
return cacheHandle(request, {
62+
runInBackground: ctx.waitUntil.bind(ctx),
63+
});
5764
},
58-
},
65+
} satisfies ExportedHandler<Runtime["runtime"]["env"]>,
5966
};
6067
}

packages/cache-handlers/README.md

Lines changed: 0 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -196,32 +196,6 @@ createCacheHandler({
196196
});
197197
```
198198

199-
### Stand‑alone Helpers
200-
201-
Exported for advanced/manual workflows:
202-
203-
```ts
204-
import {
205-
compareETags,
206-
create304Response,
207-
generateETag,
208-
getDefaultConditionalConfig,
209-
parseETag,
210-
validateConditionalRequest,
211-
} from "cache-handlers";
212-
```
213-
214-
Example manual validation:
215-
216-
```ts
217-
const cached = new Response("data", {
218-
headers: { etag: await generateETag(new Response("data")) },
219-
});
220-
const validation = validateConditionalRequest(request, cached);
221-
if (validation.shouldReturn304) {
222-
return create304Response(cached);
223-
}
224-
```
225199

226200
## Backend-Driven Variations (`Cache-Vary` – custom header)
227201

@@ -273,9 +247,7 @@ Notes:
273247
import type {
274248
CacheConfig,
275249
CacheHandle,
276-
CacheInvokeOptions,
277250
ConditionalRequestConfig,
278-
ConditionalValidationResult,
279251
HandlerFunction,
280252
HandlerInfo,
281253
HandlerMode,
@@ -320,7 +292,6 @@ Different platforms implement the Web Standard `CacheStorage` API with varying c
320292
// ✅ Works via undici polyfill
321293
// ⚠️ In-memory only by default - not persistent across restarts
322294
// ⚠️ Limited to single process - no cross-process sharing
323-
// 💡 Consider using Redis or similar for production Node.js deployments
324295
```
325296

326297
#### Netlify Edge Functions

packages/cache-handlers/src/conditional.ts

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@
1111
import type {
1212
ConditionalRequestConfig,
1313
ConditionalValidationResult,
14-
MinimalRequest,
15-
MinimalResponse,
1614
} from "./types.ts";
1715

1816
/**
@@ -143,12 +141,9 @@ export function parseHttpDate(dateString: string): Date | null {
143141
* @param config - Conditional request configuration
144142
* @returns Validation result indicating whether to return 304
145143
*/
146-
export function validateConditionalRequest<
147-
TRequest extends MinimalRequest,
148-
TResponse extends MinimalResponse,
149-
>(
150-
request: TRequest,
151-
cachedResponse: TResponse,
144+
export function validateConditionalRequest(
145+
request: Request,
146+
cachedResponse: Response,
152147
config: ConditionalRequestConfig = {},
153148
): ConditionalValidationResult {
154149
const ifNoneMatch = request.headers.get("if-none-match");
@@ -220,9 +215,9 @@ export function validateConditionalRequest<
220215
* @param cachedResponse - The cached response to base the 304 response on
221216
* @returns A 304 Not Modified response
222217
*/
223-
export function create304Response<TResponse extends MinimalResponse>(
224-
cachedResponse: TResponse,
225-
): TResponse {
218+
export function create304Response(
219+
cachedResponse: Response,
220+
): Response {
226221
const headers = new Headers();
227222

228223
// Headers that MUST be included if they would have been sent in a 200 response
@@ -270,7 +265,7 @@ export function create304Response<TResponse extends MinimalResponse>(
270265
status: 304,
271266
statusText: "Not Modified",
272267
headers,
273-
}) as unknown as TResponse;
268+
});
274269
}
275270

276271
/**

packages/cache-handlers/src/handlers.ts

Lines changed: 71 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,80 @@
1-
import type {
2-
CacheConfig,
3-
CacheHandle,
4-
HandlerFunction,
5-
MinimalRequest,
6-
MinimalResponse,
7-
SWRPolicy,
8-
} from "./types.ts";
1+
import type { CacheConfig, CacheHandle, SWRPolicy } from "./types.ts";
92
import { readFromCache } from "./read.ts";
103
import { writeToCache } from "./write.ts";
114
import { createDebugLogger } from "./debug.ts";
125

136
export function createCacheHandler<
14-
TRequest extends MinimalRequest = Request,
15-
TResponse extends MinimalResponse = Response,
7+
TRequest = Request,
8+
TResponse = Response,
169
>(
1710
options: CacheConfig<TRequest, TResponse> = {},
1811
): CacheHandle<TRequest, TResponse> {
19-
const baseHandler: HandlerFunction<TRequest, TResponse> | undefined =
20-
options.handler;
21-
const debug = createDebugLogger(options.debug);
12+
const opts = options as unknown as CacheConfig<Request, Response>;
2213

23-
const handle: CacheHandle<TRequest, TResponse> = async (
14+
const baseHandler = opts.handler;
15+
const debug = createDebugLogger(opts.debug);
16+
17+
const handle: CacheHandle<Request, Response> = async (
2418
request,
2519
callOpts = {},
26-
): Promise<TResponse> => {
20+
): Promise<Response> => {
2721
// Only cache GET
2822
if (request.method !== "GET") {
29-
debug.log('handler', `Non-GET request (${request.method}), bypassing cache: ${request.url}`);
23+
debug.log(
24+
"handler",
25+
`Non-GET request (${request.method}), bypassing cache: ${request.url}`,
26+
);
3027
const handler = callOpts.handler || baseHandler;
3128
if (!handler) {
3229
return new Response("No handler provided", {
3330
status: 500,
34-
}) as unknown as TResponse;
31+
});
3532
}
3633
return handler(request, { mode: "miss", background: false });
3734
}
3835

3936
const { cached, needsBackgroundRevalidation } = await readFromCache(
40-
request,
41-
options,
37+
request as Request,
38+
opts,
4239
);
43-
40+
4441
if (cached) {
45-
debug.logCacheRead(request.url, needsBackgroundRevalidation ? 'stale' : 'hit');
42+
debug.logCacheRead(
43+
request.url,
44+
needsBackgroundRevalidation ? "stale" : "hit",
45+
);
4646
} else {
47-
debug.logCacheRead(request.url, 'miss');
47+
debug.logCacheRead(request.url, "miss");
4848
}
49-
const statusSetting = options.features?.cacheStatusHeader;
49+
const statusSetting = opts.features?.cacheStatusHeader;
5050
const enableStatus = !!statusSetting;
5151
const cacheStatusName =
5252
typeof statusSetting === "string" && statusSetting.trim()
5353
? statusSetting.trim()
5454
: "cache-handlers";
5555
if (cached) {
56-
const policy: SWRPolicy = callOpts.swr || options.swr || "background";
56+
const policy: SWRPolicy = callOpts.swr || opts.swr || "background";
5757
if (needsBackgroundRevalidation) {
5858
if (policy === "blocking") {
5959
const handler = baseHandler || callOpts.handler;
6060
if (handler) {
6161
try {
62-
debug.log('handler', `Blocking revalidation for ${request.url}`);
62+
debug.log("handler", `Blocking revalidation for ${request.url}`);
6363
const fresh = await handler(request, {
6464
mode: "stale",
6565
background: false,
6666
});
67-
return await writeToCache(request, fresh, options);
67+
return await writeToCache(
68+
request,
69+
fresh,
70+
opts,
71+
);
6872
} catch (err) {
69-
debug.logError('handler', err as Error, 'SWR blocking revalidation');
73+
debug.logError(
74+
"handler",
75+
err as Error,
76+
"SWR blocking revalidation",
77+
);
7078
console.warn(
7179
"SWR blocking revalidation failed; serving stale",
7280
err,
@@ -78,18 +86,32 @@ export function createCacheHandler<
7886
if (handler) {
7987
debug.logBackgroundRevalidation(request.url, true);
8088
const scheduler = callOpts.runInBackground ||
81-
options.runInBackground;
89+
opts.runInBackground;
8290
const revalidatePromise = (async () => {
8391
try {
84-
debug.log('handler', `Background revalidation starting for ${request.url}`);
92+
debug.log(
93+
"handler",
94+
`Background revalidation starting for ${request.url}`,
95+
);
8596
const response = await handler(request, {
8697
mode: "stale",
8798
background: true,
8899
});
89-
await writeToCache(request, response, options);
90-
debug.log('handler', `Background revalidation completed for ${request.url}`);
100+
await writeToCache(
101+
request,
102+
response,
103+
opts,
104+
);
105+
debug.log(
106+
"handler",
107+
`Background revalidation completed for ${request.url}`,
108+
);
91109
} catch (err) {
92-
debug.logError('handler', err as Error, 'SWR background revalidation');
110+
debug.logError(
111+
"handler",
112+
err as Error,
113+
"SWR background revalidation",
114+
);
93115
console.warn("SWR background revalidation failed", err);
94116
}
95117
})();
@@ -101,10 +123,13 @@ export function createCacheHandler<
101123
}
102124
} else if (policy === "off") {
103125
// Treat stale-while-revalidate as disabled: delete and proceed as miss
104-
debug.log('handler', `SWR disabled, deleting stale entry for ${request.url}`);
126+
debug.log(
127+
"handler",
128+
`SWR disabled, deleting stale entry for ${request.url}`,
129+
);
105130
try {
106-
await caches.open(options.cacheName || "cache-primitives-default")
107-
.then((c) => c.delete(request as unknown as Request));
131+
await caches.open(opts.cacheName || "cache-primitives-default")
132+
.then((c) => c.delete(request));
108133
} catch (_) {
109134
// ignore
110135
}
@@ -132,7 +157,7 @@ export function createCacheHandler<
132157
status: cached.status,
133158
statusText: cached.statusText,
134159
headers,
135-
}) as unknown as TResponse;
160+
});
136161
}
137162
return cached;
138163
}
@@ -152,25 +177,29 @@ export function createCacheHandler<
152177
status: cached.status,
153178
statusText: cached.statusText,
154179
headers,
155-
}) as unknown as TResponse;
180+
});
156181
}
157182
return cached;
158183
}
159184
}
160185

161186
// Cache miss
162-
debug.log('handler', `Cache miss, calling handler for ${request.url}`);
187+
debug.log("handler", `Cache miss, calling handler for ${request.url}`);
163188
const handler = callOpts.handler || baseHandler;
164189
if (!handler) {
165190
return new Response("Cache miss and no handler provided", {
166191
status: 500,
167-
}) as unknown as TResponse;
192+
});
168193
}
169194
const response = await handler(request, {
170195
mode: "miss",
171196
background: false,
172197
});
173-
const stored = await writeToCache(request, response, options);
198+
const stored = await writeToCache(
199+
request as Request,
200+
response as Response,
201+
opts,
202+
);
174203
if (enableStatus) {
175204
const headers = new Headers(stored.headers as HeadersInit);
176205
const parts = [cacheStatusName, "miss"];
@@ -186,10 +215,10 @@ export function createCacheHandler<
186215
status: stored.status,
187216
statusText: stored.statusText,
188217
headers,
189-
}) as unknown as TResponse;
218+
});
190219
}
191220
return stored;
192221
};
193222

194-
return handle;
223+
return handle as unknown as CacheHandle<TRequest, TResponse>;
195224
}

0 commit comments

Comments
 (0)