import assert from "node:assert/strict"; import { mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; import { z } from "zod"; import { CultCache, SingleFileMessagePackBackingStore, defineDocumentType } from "../src/index"; const settings = defineDocumentType({ type: "settings", schemaId: "gamecult.clock_settings.v1", schemaName: "gamecult.clock_settings", schemaVersion: "gamecult.clock_settings.v1", schema: z.object({ theme: z.string(), retries: z.number().int() }), }); const pinned = () => new Date("2026-03-04T05:06:07.000Z"); async function withDir(run: (dir: string) => Promise): Promise { const dir = await mkdtemp(join(tmpdir(), "cultcache-clock-")); try { await run(dir); } finally { await rm(dir, { recursive: true, force: true }); } } async function pinnedCache(path: string | null, clock = pinned): Promise { const cache = new CultCache({ clock }); await cache.registerDocumentType(settings); if (path !== null) { await cache.addGenericBackingStore(new SingleFileMessagePackBackingStore(path)); } await cache.pullAllBackingStores(); return cache; } test("a cache with no clock stamps near now", async () => { const cache = new CultCache(); await cache.registerDocumentType(settings); await cache.put(settings, "app", { theme: "green", retries: 1 }); const stamped = Date.parse(cache.getEnvelope(settings, "app")!.storedAt); assert.ok(Math.abs(Date.now() - stamped) < 5000); }); test("two replays with a pinned clock write identical bytes", async () => { await withDir(async (dir) => { for (const name of ["a.cc", "b.cc"]) { const cache = await pinnedCache(join(dir, name)); await cache.put(settings, "app", { theme: "green", retries: 1 }); await cache.put(settings, "app", { theme: "blue", retries: 2 }); await cache.put(settings, "other", { theme: "green", retries: 1 }); } assert.deepEqual(await readFile(join(dir, "a.cc")), await readFile(join(dir, "b.cc"))); }); }); test("a pinned clock still stamps a replacing write later", async () => { await withDir(async (dir) => { const cache = await pinnedCache(join(dir, "later.cc")); await cache.put(settings, "app", { theme: "green", retries: 1 }); assert.equal(cache.getEnvelope(settings, "app")!.storedAt, "2026-03-04T05:06:07.000Z"); await cache.put(settings, "app", { theme: "blue", retries: 2 }); assert.equal(cache.getEnvelope(settings, "app")!.storedAt, "2026-03-04T05:06:07.001Z"); }); }); test("the clock property is settable and the next write reads it", async () => { const cache = await pinnedCache(null); cache.clock = () => new Date("2030-01-01T00:00:00.000Z"); await cache.put(settings, "app", { theme: "green", retries: 1 }); assert.equal(cache.getEnvelope(settings, "app")!.storedAt, "2030-01-01T00:00:00.000Z"); });