// lib/pathCache.mjs: one entry per key, a new signature replaces the old, and // the count and byte bounds evict the least recently used. And the memo it // was made for: report.mjs readCues keeps ONE parse per cue file however often // the file changes. // // Run with: pnpm test:scripts import assert from "node:assert/strict"; import test from "node:test"; import { mkdtemp, rm, utimes, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { fileSig, pathCache } from "./pathCache.mjs"; import { cueMemoStats, readCues } from "./projects/report.mjs"; test("a new signature replaces the entry; a stale read is a miss that frees it", () => { const c = pathCache(); c.set("/a.json", "1|10", "first", 10); assert.equal(c.get("/a.json", "1|10"), "first"); c.set("/a.json", "2|10", "second", 10); assert.equal(c.size, 1, "one entry per path, never one per version"); assert.equal(c.bytes, 10); assert.equal(c.get("/a.json", "1|10"), undefined); assert.equal(c.size, 0, "the stale version is let go"); assert.equal(c.bytes, 0); }); test("bounded by count and by bytes, least recently used out first; the newest is always kept", () => { const c = pathCache({ max: 3, maxBytes: 100 }); c.set("a", "", 1, 10); c.set("b", "", 2, 10); c.set("c", "", 3, 10); c.get("a"); // a is now the most recent c.set("d", "", 4, 10); assert.deepEqual(["a", "b", "c", "d"].filter((k) => c.has(k)), ["a", "c", "d"], "b, the least recent, went"); c.set("big", "", 5, 95); assert.deepEqual(["a", "c", "d", "big"].filter((k) => c.has(k)), ["big"], "evicted down to the byte bound"); c.set("huge", "", 6, 500); assert.equal(c.get("huge"), 6, "one entry over the bound alone is still kept"); assert.equal(c.size, 1); const s = pathCache({ sizeOf: (v) => v.length }); s.set("x", "", "abcd"); assert.equal(s.bytes, 4); }); test("fileSig is mtime (rounded) and size", () => { assert.equal(fileSig({ mtimeMs: 1234.6, size: 9 }), "1235|9"); }); test("readCues holds one parse per cue file across many changes to it", async () => { const dir = await mkdtemp(path.join(os.tmpdir(), "cue-memo-")); try { const file = path.join(dir, "transcript.cues.json"); const before = cueMemoStats().size; for (let i = 0; i < 25; i++) { await writeFile(file, JSON.stringify({ title: `v${i}`, cues: [{ start: 0, end: 1, text: `line ${i}.` }] })); await utimes(file, 1_700_000_000 + i, 1_700_000_000 + i); const doc = await readCues(file); assert.equal(doc.title, `v${i}`, "the current version, never a stale one"); } assert.equal(cueMemoStats().size - before, 1, "25 versions of one file: one entry"); } finally { await rm(dir, { recursive: true, force: true }); } });