import { del, get, set } from 'idb-keyval' /** How long a saved scan is shown without re-reading the account. */ export const SCAN_CACHE_TTL_MS = 15 * 60 * 1000 /** * Kept in the key, not inside the stored scan, so a bump leaves old rows * unreadable rather than open to a new shape or score tree. */ export const SCAN_CACHE_VERSION = 2 const PREFIX = 'threadbare:scan' export function scanCacheKey(did: string): string { return `${PREFIX}:v${SCAN_CACHE_VERSION}:${did}` } interface StoredScan { savedAt: number result: T } export interface CachedScan { result: T savedAt: number fresh: boolean } /** A short age for the saved scan, never negative. */ export function scanAgeLabel(savedAt: number, now = Date.now()): string { const minutes = Math.max(0, Math.floor((now - savedAt) / 60_000)) if (minutes < 1) return 'just now' if (minutes < 60) return `${minutes} min ago` const hours = Math.floor(minutes / 60) if (hours < 24) return `${hours} h ago` return `${Math.floor(hours / 24)} d ago` } /** Read the saved scan for an account. Storage failures behave as a miss. */ export async function readScan( did: string, now = Date.now(), ): Promise | undefined> { try { const stored = await get>(scanCacheKey(did)) if (!stored || typeof stored.savedAt !== 'number' || !stored.result) return undefined return { result: stored.result, savedAt: stored.savedAt, fresh: now - stored.savedAt >= 0 && now - stored.savedAt <= SCAN_CACHE_TTL_MS, } } catch { return undefined } } /** Save a complete scan. Quota and private-mode failures are non-fatal. */ export async function writeScan(did: string, result: T): Promise { try { await set(scanCacheKey(did), { savedAt: Date.now(), result } satisfies StoredScan) } catch { // The next visit simply re-reads the account. } } /** Forget an account's scan, for example when the session ends. */ export async function clearScan(did: string): Promise { try { await del(scanCacheKey(did)) } catch { // A failed delete only leaves rows the next sign-in would replace. } }