/** * Storage utilities * * Helper functions for reading, writing, and clearing storage. */ import type { StorageEntry } from '../types'; /** * Get all entries from localStorage */ export function getLocalStorageEntries(): StorageEntry[] { if (typeof window === 'undefined') { return []; } const entries: StorageEntry[] = []; try { for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (key !== null) { const value = localStorage.getItem(key); if (value !== null) { entries.push({ key, value, type: 'localStorage', }); } } } } catch (error) { console.error('[StorageUtils] Failed to read localStorage:', error); } return entries; } /** * Get all entries from sessionStorage */ export function getSessionStorageEntries(): StorageEntry[] { if (typeof window === 'undefined') { return []; } const entries: StorageEntry[] = []; try { for (let i = 0; i < sessionStorage.length; i++) { const key = sessionStorage.key(i); if (key !== null) { const value = sessionStorage.getItem(key); if (value !== null) { entries.push({ key, value, type: 'sessionStorage', }); } } } } catch (error) { console.error('[StorageUtils] Failed to read sessionStorage:', error); } return entries; } /** * Clear a specific key or all keys from storage */ export function clearStorage( type: 'localStorage' | 'sessionStorage', key?: string, ): void { if (typeof window === 'undefined') { return; } const storage = type === 'localStorage' ? localStorage : sessionStorage; try { if (key) { storage.removeItem(key); console.log(`[StorageUtils] Cleared ${type} key: ${key}`); } else { storage.clear(); console.log(`[StorageUtils] Cleared all ${type}`); } } catch (error) { console.error(`[StorageUtils] Failed to clear ${type}:`, error); } } /** * Clear all cookies */ export function clearCookies(): void { if (typeof window === 'undefined' || typeof document === 'undefined') { return; } try { const cookies = document.cookie.split(';'); for (const cookie of cookies) { const eqPos = cookie.indexOf('='); const name = eqPos > -1 ? cookie.substring(0, eqPos).trim() : cookie.trim(); // Clear for all paths and domains document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`; document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=${window.location.hostname}`; // Try with leading dot const domainParts = window.location.hostname.split('.'); if (domainParts.length > 1) { const baseDomain = domainParts.slice(-2).join('.'); document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=.${baseDomain}`; } } console.log('[StorageUtils] Cleared all cookies'); } catch (error) { console.error('[StorageUtils] Failed to clear cookies:', error); } }