cache.ts
1253 bytes
1import { appendFile, mkdir, readFile } from "node:fs/promises";
2import { dirname } from "node:path";
3import { POLICY_VERSION } from "./normalize";
4import type { CacheEntry, Decision, DecisionCache } from "./types";
5
6type StoredCacheEntry = CacheEntry & {
7 policyVersion: number;
8};
9
10export function createJsonlDecisionCache(file: string): DecisionCache {
11 return {
12 async lookup(key: string): Promise<Decision | undefined> {
13 try {
14 const content = await readFile(file, "utf8");
15 for (const line of content.split("\n")) {
16 if (!line) continue;
17 try {
18 const entry = JSON.parse(line) as StoredCacheEntry;
19 if (entry.key === key && entry.policyVersion === POLICY_VERSION) return entry.decision;
20 } catch {}
21 }
22 } catch {}
23 return undefined;
24 },
25 async write(entry: CacheEntry): Promise<void> {
26 try {
27 await mkdir(dirname(file), { recursive: true });
28 const stored: StoredCacheEntry = { ...entry, policyVersion: POLICY_VERSION };
29 await appendFile(file, `${JSON.stringify(stored)}\n`);
30 } catch {}
31 },
32 };
33}
34
35export const disabledDecisionCache: DecisionCache = {
36 lookup: async () => undefined,
37 write: async () => {},
38};