import { test } from "node:test"; import assert from "node:assert/strict"; import { OFFSET_LIMIT_SECONDS, formatOffset, nudgeOffset, offsetFromSync, offsetKey, readOffset, toCueTime, toFileTime, writeOffset, } from "./localFileClock"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test lib/localFileClock.test.ts function memoryStore() { const m = new Map(); return { m, getItem: (k: string) => m.get(k) ?? null, setItem: (k: string, v: string) => void m.set(k, v), removeItem: (k: string) => void m.delete(k), }; } test("the two clocks round-trip through the offset, and never go below 0", () => { assert.equal(toFileTime(10, 2.5), 12.5); assert.equal(toCueTime(12.5, 2.5), 10); assert.equal(toFileTime(1, -3), 0); assert.equal(toCueTime(1, 3), 0); for (const off of [-7.25, 0, 0.1, 42]) assert.equal(toCueTime(toFileTime(100, off), off), 100); }); test("nudge and sync round to centiseconds and stay in range", () => { assert.equal(nudgeOffset(0, 0.1), 0.1); assert.equal(nudgeOffset(0.1, 0.1), 0.2); assert.equal(nudgeOffset(0.2, -1), -0.8); assert.equal(nudgeOffset(OFFSET_LIMIT_SECONDS, 1), OFFSET_LIMIT_SECONDS); // The line that starts at 30 s is what the file plays at 32.346 s. assert.equal(offsetFromSync(32.346, 30), 2.35); assert.equal(offsetFromSync(5, 30), -25); }); test("the offset display", () => { assert.equal(formatOffset(0), "0.00 s"); assert.equal(formatOffset(1.5), "+1.50 s"); assert.equal(formatOffset(-0.1), "−0.10 s"); }); test("storage holds only a number under the video's key; junk and refusals read as 0", () => { const s = memoryStore(); assert.equal(readOffset(s, "chan/vid"), 0); writeOffset(s, "chan/vid", 2.345); assert.deepEqual([...s.m.entries()], [[offsetKey("chan/vid"), "2.35"]]); assert.equal(readOffset(s, "chan/vid"), 2.35); writeOffset(s, "chan/vid", 0); assert.equal(s.m.size, 0, "0 removes the key"); s.m.set(offsetKey("chan/vid"), "not a number"); assert.equal(readOffset(s, "chan/vid"), 0); s.m.set(offsetKey("chan/vid"), String(OFFSET_LIMIT_SECONDS * 2)); assert.equal(readOffset(s, "chan/vid"), 0); const refusing = { getItem: () => { throw new Error("SecurityError"); }, setItem: () => { throw new Error("QuotaExceededError"); }, removeItem: () => { throw new Error("SecurityError"); }, }; assert.equal(readOffset(refusing, "chan/vid"), 0); writeOffset(refusing, "chan/vid", 1); assert.equal(readOffset(null, "chan/vid"), 0); });