import { browser } from "$app/environment"; import anime from "$stores/anime"; import lastPruneTimes from "$stores/lastPruneTimes"; import manga from "$stores/manga"; import localforage from "localforage"; type MediaCacheKind = "anime" | "manga"; const cacheStorageKey = (kind: MediaCacheKind) => `${kind}:v3`; interface StoredLastPruneTimes { anime: number; chapters: number; manga: number; } const hydration = new Map>(); const isStoredLastPruneTimes = ( value: unknown, ): value is StoredLastPruneTimes => typeof value === "object" && value !== null && typeof (value as StoredLastPruneTimes).anime === "number" && typeof (value as StoredLastPruneTimes).chapters === "number" && typeof (value as StoredLastPruneTimes).manga === "number"; export const hydrateMediaListCache = (kind: MediaCacheKind) => { if (!browser) return Promise.resolve(); const existing = hydration.get(kind); if (existing) return existing; const promise = (async () => { const [cache, pruneTimes] = await Promise.all([ localforage.getItem(cacheStorageKey(kind)), localforage.getItem("lastPruneTimes"), ]); if (typeof cache === "string" && cache.length) (kind === "anime" ? anime : manga).set(cache); if (isStoredLastPruneTimes(pruneTimes)) lastPruneTimes.set(pruneTimes); })(); hydration.set(kind, promise); return promise; };