import { env, waitUntil } from "cloudflare:workers"; export const IMMUTABLE_TTL_SECONDS = 60 * 60 * 24 * 14; const MAX_CACHED_BYTES = 8 * 1024 * 1024; /** Memoizes results keyed by immutable git ids in KV; oversized values are returned but not stored. */ export async function kvCached(key: string, load: () => Promise, ttl = IMMUTABLE_TTL_SECONDS): Promise { const hit = await env.KV.get(key, "json"); if (hit !== null) return hit; const value = await load(); const serialized = JSON.stringify(value); if (serialized.length < MAX_CACHED_BYTES) { waitUntil(env.KV.put(key, serialized, { expirationTtl: ttl })); } return value; } export async function kvPut(key: string, value: unknown, ttl = IMMUTABLE_TTL_SECONDS): Promise { const serialized = JSON.stringify(value); if (serialized.length < MAX_CACHED_BYTES) await env.KV.put(key, serialized, { expirationTtl: ttl }); }