The best way to control Claude Code, Codex and more from any computer or phone

main
ts 68 lines 2.23 KB
Raw
1 /**
2 * vinext data-cache adapter backed by a Cloudflare KV namespace.
3 * Default export is the factory `virtual:vinext-cache-adapters` calls as
4 * `({ env, options }) => CacheHandler`.
5 *
6 * Reads `env[binding]` (default `VINEXT_KV_CACHE`). Same codec as Redis
7 * and S3 via {@link makeDataCacheHandler}. Prerender pairs are uploaded
8 * at `alchemy deploy` — this runtime does not walk the filesystem.
9 */
10 import { makeDataCacheHandler, type DataCacheStore } from "./handler.ts";
11
12 export interface KvAdapterOptions extends Record<string, unknown> {
13 /** Worker binding name. @default "VINEXT_KV_CACHE" */
14 readonly binding?: string;
15 readonly appPrefix?: string;
16 readonly ttlSeconds?: number;
17 readonly tagCacheTtlMs?: number;
18 }
19
20 const DEFAULT_BINDING = "VINEXT_KV_CACHE";
21 /** Cloudflare KV rejects expirationTtl below 60 seconds. */
22 const MIN_KV_TTL_SECONDS = 60;
23
24 interface KvNamespaceLike {
25 get(key: string): Promise<string | null>;
26 put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>;
27 delete(key: string): Promise<void>;
28 }
29
30 const isKvNamespace = (value: unknown): value is KvNamespaceLike =>
31 typeof value === "object" &&
32 value !== null &&
33 typeof (value as KvNamespaceLike).get === "function" &&
34 typeof (value as KvNamespaceLike).put === "function" &&
35 typeof (value as KvNamespaceLike).delete === "function";
36
37 const kvStore = (ns: KvNamespaceLike): DataCacheStore => ({
38 async getText(key) {
39 return (await ns.get(key)) ?? undefined;
40 },
41 async putText(key, value, ttlMs) {
42 const expirationTtl =
43 ttlMs !== undefined && ttlMs > 0
44 ? Math.max(MIN_KV_TTL_SECONDS, Math.ceil(ttlMs / 1000))
45 : undefined;
46 await ns.put(key, value, expirationTtl !== undefined ? { expirationTtl } : undefined);
47 },
48 async delete(key) {
49 await ns.delete(key);
50 },
51 });
52
53 const createKvDataCacheAdapter = ({
54 env,
55 options,
56 }: {
57 env?: Record<string, unknown>;
58 options?: KvAdapterOptions;
59 }) => {
60 const binding = options?.binding ?? DEFAULT_BINDING;
61 const ns = env?.[binding];
62 if (!isKvNamespace(ns)) {
63 throw new Error(`[vinext] The KV data cache adapter requires Worker binding \`${binding}\`.`);
64 }
65 return makeDataCacheHandler(kvStore(ns), options);
66 };
67
68 export default createKvDataCacheAdapter;