import { PersistedClient, Persister, } from "@tanstack/react-query-persist-client"; export const TANSTACK_QUERY_CACHE_KEY = "tanstack-query-cache-key"; // Declare chrome namespace for TypeScript declare const chrome: { storage: { local: { set: (items: Record) => Promise; get: (keys: string | string[]) => Promise>; remove: (keys: string | string[]) => Promise; }; }; }; /** * Creates an AsyncStorage-like interface for Chrome's extension storage. * * @param storage The Chrome storage area to use (e.g., `chrome.storage.local`). * @returns An object that mimics the AsyncStorage interface. */ export const createChromeStorage = ( storage: typeof chrome.storage.local = globalThis.chrome?.storage?.local, ): Persister => { // Check if we are in a Chrome extension environment if (typeof chrome === "undefined" || !chrome.storage) { // Return a noop persister for non-extension environments return { persistClient: async () => { return; }, restoreClient: async () => undefined, removeClient: async () => { return; }, }; } return { persistClient: async (client: PersistedClient) => { await storage.set({ [TANSTACK_QUERY_CACHE_KEY]: JSON.stringify(client) }); }, restoreClient: async () => { const result = await storage.get(TANSTACK_QUERY_CACHE_KEY); return result[TANSTACK_QUERY_CACHE_KEY] ? JSON.parse(result[TANSTACK_QUERY_CACHE_KEY]) : undefined; }, removeClient: async () => { await storage.remove(TANSTACK_QUERY_CACHE_KEY); }, }; };