diff --git a/src/lib/stores/accessibility.ts b/src/lib/stores/accessibility.ts index 2490eca..42138a7 100644 --- a/src/lib/stores/accessibility.ts +++ b/src/lib/stores/accessibility.ts @@ -1,5 +1,6 @@ import { writable } from 'svelte/store'; import { browser } from '$app/environment'; +import { storage } from '$lib/utils/localStorage'; export interface AccessibilityOption { id: string; @@ -113,16 +114,9 @@ function createAccessibilityStore() { init: () => { if (browser) { - const stored = localStorage.getItem(STORAGE_KEY); - let storedSettings: Partial = {}; - - if (stored) { - try { - storedSettings = JSON.parse(stored); - } catch { - storedSettings = {}; - } - } + const storedSettings = storage.getItem(STORAGE_KEY, { + defaultValue: { options: [] } as Partial, + }); // Merge stored settings with defaults, checking system preferences const options = DEFAULT_OPTIONS.map((defaultOption) => { @@ -155,7 +149,7 @@ function createAccessibilityStore() { const newSettings = { ...settings, options: newOptions }; if (browser) { - localStorage.setItem(STORAGE_KEY, JSON.stringify(newSettings)); + storage.setItem(STORAGE_KEY, newSettings); // Load dyslexic font if dyslexia-font option was just enabled if (optionId === 'dyslexia-font') { @@ -179,7 +173,7 @@ function createAccessibilityStore() { const newSettings = { ...settings, options: newOptions }; if (browser) { - localStorage.setItem(STORAGE_KEY, JSON.stringify(newSettings)); + storage.setItem(STORAGE_KEY, newSettings); } return newSettings; @@ -195,7 +189,7 @@ function createAccessibilityStore() { const newSettings = { ...settings, options: newOptions }; if (browser) { - localStorage.setItem(STORAGE_KEY, JSON.stringify(newSettings)); + storage.setItem(STORAGE_KEY, newSettings); } return newSettings; @@ -226,7 +220,7 @@ function createAccessibilityStore() { set(defaultSettings); if (browser) { - localStorage.setItem(STORAGE_KEY, JSON.stringify(defaultSettings)); + storage.setItem(STORAGE_KEY, defaultSettings); } }, }; diff --git a/src/lib/stores/bookmarks.ts b/src/lib/stores/bookmarks.ts index 0a3777b..3f69d72 100644 --- a/src/lib/stores/bookmarks.ts +++ b/src/lib/stores/bookmarks.ts @@ -1,5 +1,6 @@ import { writable } from 'svelte/store'; import { browser } from '$app/environment'; +import { storage } from '$lib/utils/localStorage'; import { cacheBookmark, cacheAllBookmarks } from './offline'; export interface BookmarkedTool { @@ -13,17 +14,7 @@ const STORAGE_KEY = 'bookmarked-tools'; // Get initial bookmarks from localStorage (runs immediately on import) function getInitialBookmarks(): BookmarkedTool[] { - if (browser) { - try { - const stored = localStorage.getItem(STORAGE_KEY); - if (stored) { - return JSON.parse(stored); - } - } catch { - return []; - } - } - return []; + return storage.getItem(STORAGE_KEY, { defaultValue: [] }); } function createBookmarksStore() { @@ -48,7 +39,7 @@ function createBookmarksStore() { if (!bookmarks.find((b) => b.href === tool.href)) { const newBookmarks = [...bookmarks, tool]; if (browser) { - localStorage.setItem(STORAGE_KEY, JSON.stringify(newBookmarks)); + storage.setItem(STORAGE_KEY, newBookmarks); // Cache the bookmarked tool for offline access cacheBookmark(tool.href); } @@ -61,7 +52,7 @@ function createBookmarksStore() { update((bookmarks) => { const newBookmarks = bookmarks.filter((b) => b.href !== href); if (browser) { - localStorage.setItem(STORAGE_KEY, JSON.stringify(newBookmarks)); + storage.setItem(STORAGE_KEY, newBookmarks); } return newBookmarks; }); @@ -71,7 +62,7 @@ function createBookmarksStore() { const existing = bookmarks.find((b) => b.href === tool.href); const newBookmarks = existing ? bookmarks.filter((b) => b.href !== tool.href) : [...bookmarks, tool]; if (browser) { - localStorage.setItem(STORAGE_KEY, JSON.stringify(newBookmarks)); + storage.setItem(STORAGE_KEY, newBookmarks); // Cache the bookmarked tool for offline access when adding if (!existing) { cacheBookmark(tool.href); diff --git a/src/lib/stores/customCss.ts b/src/lib/stores/customCss.ts index 1551b82..afb52d6 100644 --- a/src/lib/stores/customCss.ts +++ b/src/lib/stores/customCss.ts @@ -1,5 +1,5 @@ import { writable } from 'svelte/store'; -import { browser } from '$app/environment'; +import { storage } from '$lib/utils/localStorage'; const STORAGE_KEY = 'user-custom-css'; @@ -61,20 +61,18 @@ function createCustomCssStore() { return { subscribe, init: () => { - if (!browser) return; - const stored = localStorage.getItem(STORAGE_KEY); - if (stored) { - set(stored); - } + const stored = storage.getItem(STORAGE_KEY, { + defaultValue: '', + serialize: false, + }); + if (stored) set(stored); }, set: (css: string) => { - if (!browser) return; - localStorage.setItem(STORAGE_KEY, css); + storage.setItem(STORAGE_KEY, css, { serialize: false }); set(css); }, clear: () => { - if (!browser) return; - localStorage.removeItem(STORAGE_KEY); + storage.removeItem(STORAGE_KEY); set(''); }, validate: validateCustomCss, diff --git a/src/lib/stores/homepageLayout.ts b/src/lib/stores/homepageLayout.ts index 97c3eb4..787c586 100644 --- a/src/lib/stores/homepageLayout.ts +++ b/src/lib/stores/homepageLayout.ts @@ -1,5 +1,5 @@ import { writable } from 'svelte/store'; -import { browser } from '$app/environment'; +import { storage } from '$lib/utils/localStorage'; import { DEFAULT_HOMEPAGE_LAYOUT } from '$lib/config/customizable-settings'; export type HomepageLayoutMode = @@ -81,15 +81,11 @@ function getInitialLayout(): HomepageLayoutMode { // Validate DEFAULT_HOMEPAGE_LAYOUT, fallback to 'categories' if invalid const validDefault = isValidLayout(DEFAULT_HOMEPAGE_LAYOUT) ? DEFAULT_HOMEPAGE_LAYOUT : 'categories'; - if (browser) { - try { - const stored = localStorage.getItem('homepage-layout'); - return isValidLayout(stored) ? (stored as HomepageLayoutMode) : validDefault; - } catch { - return validDefault; - } - } - return validDefault; + return storage.getItem(STORAGE_KEY, { + defaultValue: validDefault, + validate: (val): val is HomepageLayoutMode => isValidLayout(val as string), + serialize: false, + }); } function createHomepageLayoutStore() { @@ -114,10 +110,7 @@ function createHomepageLayoutStore() { } set(mode); - - if (browser) { - localStorage.setItem(STORAGE_KEY, mode); - } + storage.setItem(STORAGE_KEY, mode, { serialize: false }); }, // Get option configuration diff --git a/src/lib/stores/navbarDisplay.ts b/src/lib/stores/navbarDisplay.ts index 599f921..214cbcb 100644 --- a/src/lib/stores/navbarDisplay.ts +++ b/src/lib/stores/navbarDisplay.ts @@ -1,7 +1,6 @@ import { writable } from 'svelte/store'; -import { browser } from '$app/environment'; import { DEFAULT_NAVBAR_DISPLAY } from '$lib/config/customizable-settings'; - +import { storage } from '$lib/utils/localStorage'; export type NavbarDisplayMode = 'default' | 'bookmarked' | 'frequent' | 'none'; export interface NavbarDisplayOption { @@ -45,15 +44,12 @@ function isValidNavbarDisplay(mode: string | null): boolean { // Get initial value from localStorage (runs immediately on import) function getInitialNavbarDisplay(): NavbarDisplayMode { const validDefault = isValidNavbarDisplay(DEFAULT_NAVBAR_DISPLAY) ? DEFAULT_NAVBAR_DISPLAY : 'default'; - if (browser) { - try { - const stored = localStorage.getItem('navbar-display'); - return isValidNavbarDisplay(stored) ? (stored as NavbarDisplayMode) : validDefault; - } catch { - return validDefault; - } - } - return validDefault; + + return storage.getItem(STORAGE_KEY, { + defaultValue: validDefault, + validate: (val): val is NavbarDisplayMode => isValidNavbarDisplay(val as string), + serialize: false, + }); } function createNavbarDisplayStore() { @@ -78,10 +74,7 @@ function createNavbarDisplayStore() { } set(mode); - - if (browser) { - localStorage.setItem(STORAGE_KEY, mode); - } + storage.setItem(STORAGE_KEY, mode, { serialize: false }); }, // Get option configuration diff --git a/src/lib/stores/primaryColor.ts b/src/lib/stores/primaryColor.ts index a628b90..b0c6e7c 100644 --- a/src/lib/stores/primaryColor.ts +++ b/src/lib/stores/primaryColor.ts @@ -1,52 +1,39 @@ import { writable } from 'svelte/store'; -import { browser } from '$app/environment'; +import { storage } from '$lib/utils/localStorage'; const STORAGE_KEY = 'user-primary-color'; const HEX_PATTERN = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/; +const isValidHexColor = (value: unknown): value is string => { + return typeof value === 'string' && HEX_PATTERN.test(value); +}; + function createPrimaryColorStore() { const { subscribe, set } = writable(''); return { subscribe, init: () => { - if (!browser) return; - try { - const stored = localStorage.getItem(STORAGE_KEY); - // Only load if it's a valid hex color - if (stored && HEX_PATTERN.test(stored)) { - set(stored); - } - } catch (e) { - console.error('Failed to load primary color:', e); - } + const stored = storage.getItem(STORAGE_KEY, { + defaultValue: '', + validate: isValidHexColor, + serialize: false, + }); + if (stored) set(stored); }, set: (color: string) => { - if (!browser) return; - try { - if (color && color.trim()) { - const trimmed = color.trim(); - // Only save valid hex colors - if (HEX_PATTERN.test(trimmed)) { - localStorage.setItem(STORAGE_KEY, trimmed); - set(trimmed); - } - } else { - localStorage.removeItem(STORAGE_KEY); - set(''); - } - } catch (e) { - console.error('Failed to save primary color:', e); + const trimmed = color?.trim() || ''; + if (trimmed && isValidHexColor(trimmed)) { + storage.setItem(STORAGE_KEY, trimmed, { serialize: false }); + set(trimmed); + } else if (!trimmed) { + storage.removeItem(STORAGE_KEY); + set(''); } }, clear: () => { - if (!browser) return; - try { - localStorage.removeItem(STORAGE_KEY); - set(''); - } catch (e) { - console.error('Failed to clear primary color:', e); - } + storage.removeItem(STORAGE_KEY); + set(''); }, }; } diff --git a/src/lib/stores/siteCustomization.ts b/src/lib/stores/siteCustomization.ts index 99bafb6..7ba06ea 100644 --- a/src/lib/stores/siteCustomization.ts +++ b/src/lib/stores/siteCustomization.ts @@ -1,5 +1,5 @@ import { writable } from 'svelte/store'; -import { browser } from '$app/environment'; +import { storage } from '$lib/utils/localStorage'; const STORAGE_KEY = 'user-site-customization'; @@ -52,26 +52,16 @@ function createSiteCustomizationStore() { return { subscribe, init: () => { - if (!browser) return; - const stored = localStorage.getItem(STORAGE_KEY); - if (stored) { - try { - const parsed = JSON.parse(stored); - const loadedData = { ...defaults, ...parsed }; - set(loadedData); - } catch (e) { - console.error('Failed to parse site customization:', e); - } - } + const stored = storage.getItem(STORAGE_KEY, { defaultValue: defaults }); + const loadedData = { ...defaults, ...stored }; + set(loadedData); }, set: (data: SiteCustomization) => { - if (!browser) return; - localStorage.setItem(STORAGE_KEY, JSON.stringify(data)); + storage.setItem(STORAGE_KEY, data); set(data); }, clear: () => { - if (!browser) return; - localStorage.removeItem(STORAGE_KEY); + storage.removeItem(STORAGE_KEY); set(defaults); }, validate: validateSiteCustomization, diff --git a/src/lib/stores/theme.ts b/src/lib/stores/theme.ts index 72224d9..7fc2157 100644 --- a/src/lib/stores/theme.ts +++ b/src/lib/stores/theme.ts @@ -1,5 +1,6 @@ import { writable } from 'svelte/store'; import { browser } from '$app/environment'; +import { storage } from '$lib/utils/localStorage'; import { DEFAULT_THEME } from '$lib/config/customizable-settings'; export type ThemeOption = string; @@ -177,8 +178,8 @@ export const themes: Theme[] = [ }, ]; -function isValidTheme(theme: string | null) { - if (!theme) return false; +function isValidTheme(theme: unknown): theme is string { + if (typeof theme !== 'string' || !theme) return false; return themes.some((t) => t.id === theme && t.available); } @@ -192,8 +193,12 @@ function createThemeStore() { // Initialize theme from localStorage or default init: () => { if (browser) { - const saved = localStorage.getItem(STORAGE_KEY); - const initialTheme = isValidTheme(saved) ? (saved as ThemeOption) : defaultTheme; + const saved = storage.getItem(STORAGE_KEY, { + defaultValue: defaultTheme, + validate: isValidTheme, + serialize: false, + }); + const initialTheme = saved as ThemeOption; set(initialTheme); @@ -217,7 +222,7 @@ function createThemeStore() { set(theme); if (browser) { - localStorage.setItem(STORAGE_KEY, theme); + storage.setItem(STORAGE_KEY, theme, { serialize: false }); // Apply theme classes to document applyThemeClasses(theme); @@ -230,7 +235,7 @@ function createThemeStore() { const newTheme = currentTheme === 'light' ? 'dark' : 'light'; if (browser) { - localStorage.setItem(STORAGE_KEY, newTheme); + storage.setItem(STORAGE_KEY, newTheme, { serialize: false }); applyThemeClasses(newTheme); } diff --git a/src/lib/stores/toolUsage.ts b/src/lib/stores/toolUsage.ts index 54ca84c..fcf32ec 100644 --- a/src/lib/stores/toolUsage.ts +++ b/src/lib/stores/toolUsage.ts @@ -1,5 +1,6 @@ import { writable, derived } from 'svelte/store'; import { browser } from '$app/environment'; +import { storage } from '$lib/utils/localStorage'; export interface ToolUsage { [toolHref: string]: { @@ -18,17 +19,7 @@ const maxItems = 12; // Get initial tool usage from localStorage (runs immediately on import) function getInitialToolUsage(): ToolUsage { - if (browser) { - try { - const stored = localStorage.getItem(STORAGE_KEY); - if (stored) { - return JSON.parse(stored); - } - } catch (error) { - console.error('Failed to load tool usage data:', error); - } - } - return {}; + return storage.getItem(STORAGE_KEY, { defaultValue: {} }); } function createToolUsageStore() { @@ -44,17 +35,8 @@ function createToolUsageStore() { */ init() { if (!browser) return; - - try { - const stored = localStorage.getItem(STORAGE_KEY); - if (stored) { - const parsed = JSON.parse(stored); - set(parsed); - } - } catch (error) { - console.error('Failed to load tool usage data:', error); - set({}); - } + const stored = storage.getItem(STORAGE_KEY, { defaultValue: {} }); + set(stored); }, /** @@ -85,11 +67,7 @@ function createToolUsageStore() { if (description) newUsage[href].description = description; // Save to localStorage - try { - localStorage.setItem(STORAGE_KEY, JSON.stringify(newUsage)); - } catch (error) { - console.error('Failed to save tool usage data:', error); - } + storage.setItem(STORAGE_KEY, newUsage); return newUsage; }); @@ -100,13 +78,8 @@ function createToolUsageStore() { */ clear() { if (!browser) return; - set({}); - try { - localStorage.removeItem(STORAGE_KEY); - } catch (error) { - console.error('Failed to clear tool usage data:', error); - } + storage.removeItem(STORAGE_KEY); }, /** @@ -119,11 +92,7 @@ function createToolUsageStore() { const newUsage = { ...usage }; delete newUsage[href]; - try { - localStorage.setItem(STORAGE_KEY, JSON.stringify(newUsage)); - } catch (error) { - console.error('Failed to save tool usage data:', error); - } + storage.setItem(STORAGE_KEY, newUsage); return newUsage; }); diff --git a/src/lib/utils/localStorage.ts b/src/lib/utils/localStorage.ts new file mode 100644 index 0000000..fec51b8 --- /dev/null +++ b/src/lib/utils/localStorage.ts @@ -0,0 +1,132 @@ +import { browser } from '$app/environment'; + +/** + * Safe, robust localStorage helper + * Handles SSR, errors, validation, and serialization automatically + */ + +interface StorageOptions { + /** Default value if storage is empty or fails */ + defaultValue: T; + /** Optional validation function */ + validate?: (value: unknown) => value is T; + /** Whether to serialize/deserialize as JSON (default: true for objects, false for strings) */ + serialize?: boolean; +} + +class LocalStorageHelper { + /** + * Get item from localStorage with error handling + */ + getItem(key: string, options: StorageOptions): T { + const { defaultValue, validate, serialize = typeof defaultValue !== 'string' } = options; + + if (!browser) return defaultValue; + + try { + const raw = localStorage.getItem(key); + if (raw === null) return defaultValue; + + const parsed = serialize ? JSON.parse(raw) : raw; + + // Validate if validation function provided + if (validate && !validate(parsed)) { + console.warn(`Invalid data in localStorage key "${key}", using default`); + return defaultValue; + } + + return parsed as T; + } catch (error) { + console.error(`Failed to get localStorage key "${key}":`, error); + return defaultValue; + } + } + + /** + * Set item in localStorage with error handling + */ + setItem(key: string, value: T, options?: { serialize?: boolean }): boolean { + const serialize = options?.serialize ?? typeof value !== 'string'; + + if (!browser) return false; + + try { + const data = serialize ? JSON.stringify(value) : String(value); + localStorage.setItem(key, data); + return true; + } catch (error) { + console.error(`Failed to set localStorage key "${key}":`, error); + return false; + } + } + + /** + * Remove item from localStorage with error handling + */ + removeItem(key: string): boolean { + if (!browser) return false; + + try { + localStorage.removeItem(key); + return true; + } catch (error) { + console.error(`Failed to remove localStorage key "${key}":`, error); + return false; + } + } + + /** + * Check if localStorage is available and working + */ + isAvailable(): boolean { + if (!browser) return false; + + try { + const testKey = '__localStorage_test__'; + localStorage.setItem(testKey, 'test'); + localStorage.removeItem(testKey); + return true; + } catch { + return false; + } + } + + /** + * Clear all items from localStorage (use with caution!) + */ + clear(): boolean { + if (!browser) return false; + + try { + localStorage.clear(); + return true; + } catch (error) { + console.error('Failed to clear localStorage:', error); + return false; + } + } + + /** + * Get all keys from localStorage + */ + getAllKeys(): string[] { + if (!browser) return []; + + try { + const keys: string[] = []; + for (let i = 0; i < localStorage.length; i++) { + const key = localStorage.key(i); + if (key !== null) { + keys.push(key); + } + } + return keys; + } catch (error) { + console.error('Failed to get localStorage keys:', error); + return []; + } + } +} + +// Export singleton instance +export const storage = new LocalStorageHelper(); diff --git a/tests/unit/utils/localStorage.test.ts b/tests/unit/utils/localStorage.test.ts new file mode 100644 index 0000000..b8df1f2 --- /dev/null +++ b/tests/unit/utils/localStorage.test.ts @@ -0,0 +1,674 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { storage } from '../../../src/lib/utils/localStorage'; + +// Mock browser environment - default to true +let mockBrowser = true; +vi.mock('$app/environment', () => ({ + get browser() { + return mockBrowser; + } +})); + +// Mock localStorage +const mockLocalStorage = (() => { + let store: Record = {}; + + return { + getItem: vi.fn((key: string) => { + return key in store ? store[key] : null; + }), + setItem: vi.fn((key: string, value: string) => { + store[key] = value; + }), + removeItem: vi.fn((key: string) => { + delete store[key]; + }), + clear: vi.fn(() => { + store = {}; + }), + get length() { + return Object.keys(store).length; + }, + key(index: number) { + return Object.keys(store)[index] || null; + }, + // Helper to reset internal store + _reset() { + store = {}; + }, + // Helper to get internal store + _getStore() { + return store; + }, + }; +})(); + +// Use Object.defineProperty to properly expose localStorage with all properties +Object.defineProperty(global, 'localStorage', { + value: mockLocalStorage, + writable: true, + configurable: true, +}); + +describe('LocalStorage Helper', () => { + beforeEach(() => { + mockBrowser = true; + vi.clearAllMocks(); + mockLocalStorage._reset(); + }); + + describe('getItem()', () => { + it('should return default value when key does not exist', () => { + const result = storage.getItem('non-existent', { defaultValue: 'default' }); + + expect(result).toBe('default'); + expect(mockLocalStorage.getItem).toHaveBeenCalledWith('non-existent'); + }); + + it('should retrieve and deserialize JSON objects', () => { + const testData = { foo: 'bar', nested: { value: 123 } }; + mockLocalStorage._getStore()['test-key'] = JSON.stringify(testData); + + const result = storage.getItem('test-key', { defaultValue: {} }); + + expect(result).toEqual(testData); + }); + + it('should retrieve strings without deserialization when serialize is false', () => { + mockLocalStorage._getStore()['test-key'] = 'plain-string'; + + const result = storage.getItem('test-key', { + defaultValue: '', + serialize: false + }); + + expect(result).toBe('plain-string'); + }); + + it('should use validation function to reject invalid data', () => { + mockLocalStorage._getStore()['test-key'] = JSON.stringify({ invalid: true }); + + const validate = (val: unknown): val is { valid: boolean } => { + return typeof val === 'object' && val !== null && 'valid' in val; + }; + + const result = storage.getItem('test-key', { + defaultValue: { valid: false }, + validate + }); + + expect(result).toEqual({ valid: false }); + }); + + it('should use validation function to accept valid data', () => { + const validData = { valid: true }; + mockLocalStorage._getStore()['test-key'] = JSON.stringify(validData); + + const validate = (val: unknown): val is { valid: boolean } => { + return typeof val === 'object' && val !== null && 'valid' in val; + }; + + const result = storage.getItem('test-key', { + defaultValue: { valid: false }, + validate + }); + + expect(result).toEqual(validData); + }); + + it('should handle corrupted JSON gracefully', () => { + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + mockLocalStorage._getStore()['test-key'] = '{invalid-json}'; + + const result = storage.getItem('test-key', { defaultValue: { fallback: true } }); + + expect(result).toEqual({ fallback: true }); + expect(consoleErrorSpy).toHaveBeenCalled(); + + consoleErrorSpy.mockRestore(); + }); + + it('should return default value in SSR context (browser = false)', () => { + mockBrowser = false; + mockLocalStorage._getStore()['test-key'] = 'should-not-be-read'; + + const result = storage.getItem('test-key', { defaultValue: 'ssr-default' }); + + expect(result).toBe('ssr-default'); + expect(mockLocalStorage.getItem).not.toHaveBeenCalled(); + }); + + it('should auto-detect serialization for objects', () => { + const testData = [1, 2, 3]; + mockLocalStorage._getStore()['test-key'] = JSON.stringify(testData); + + const result = storage.getItem('test-key', { defaultValue: [] }); + + expect(result).toEqual(testData); + }); + + it('should handle empty strings correctly', () => { + mockLocalStorage._getStore()['test-key'] = ''; + + const result = storage.getItem('test-key', { + defaultValue: 'default', + serialize: false + }); + + expect(result).toBe(''); + }); + + it('should handle arrays correctly', () => { + const testArray = ['a', 'b', 'c']; + mockLocalStorage._getStore()['test-key'] = JSON.stringify(testArray); + + const result = storage.getItem('test-key', { defaultValue: [] }); + + expect(result).toEqual(testArray); + }); + + it('should handle nested objects correctly', () => { + const testData = { + level1: { + level2: { + level3: { + value: 'deep' + } + } + } + }; + mockLocalStorage._getStore()['test-key'] = JSON.stringify(testData); + + const result = storage.getItem('test-key', { defaultValue: {} }); + + expect(result).toEqual(testData); + }); + + it('should handle null values in stored data', () => { + mockLocalStorage._getStore()['test-key'] = JSON.stringify({ value: null }); + + const result = storage.getItem('test-key', { defaultValue: {} }); + + expect(result).toEqual({ value: null }); + }); + + it('should handle boolean values', () => { + mockLocalStorage._getStore()['test-key'] = JSON.stringify(true); + + const result = storage.getItem('test-key', { defaultValue: false }); + + expect(result).toBe(true); + }); + + it('should handle number values', () => { + mockLocalStorage._getStore()['test-key'] = JSON.stringify(42); + + const result = storage.getItem('test-key', { defaultValue: 0 }); + + expect(result).toBe(42); + }); + }); + + describe('setItem()', () => { + it('should store objects with JSON serialization', () => { + const testData = { foo: 'bar', num: 123 }; + + const result = storage.setItem('test-key', testData); + + expect(result).toBe(true); + expect(mockLocalStorage.setItem).toHaveBeenCalledWith( + 'test-key', + JSON.stringify(testData) + ); + }); + + it('should store strings without serialization when serialize is false', () => { + const result = storage.setItem('test-key', 'plain-string', { serialize: false }); + + expect(result).toBe(true); + expect(mockLocalStorage.setItem).toHaveBeenCalledWith('test-key', 'plain-string'); + }); + + it('should auto-detect serialization for objects', () => { + const testData = { auto: 'detected' }; + + storage.setItem('test-key', testData); + + expect(mockLocalStorage.setItem).toHaveBeenCalledWith( + 'test-key', + JSON.stringify(testData) + ); + }); + + it('should handle quota exceeded errors', () => { + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + mockLocalStorage.setItem.mockImplementationOnce(() => { + throw new DOMException('QuotaExceededError'); + }); + + const result = storage.setItem('test-key', 'value'); + + expect(result).toBe(false); + expect(consoleErrorSpy).toHaveBeenCalled(); + + consoleErrorSpy.mockRestore(); + }); + + it('should return false in SSR context (browser = false)', () => { + mockBrowser = false; + + const result = storage.setItem('test-key', 'value'); + + expect(result).toBe(false); + expect(mockLocalStorage.setItem).not.toHaveBeenCalled(); + }); + + it('should handle arrays correctly', () => { + const testArray = [1, 2, 3]; + + storage.setItem('test-key', testArray); + + expect(mockLocalStorage.setItem).toHaveBeenCalledWith( + 'test-key', + JSON.stringify(testArray) + ); + }); + + it('should handle nested objects', () => { + const testData = { + outer: { + inner: { + deep: 'value' + } + } + }; + + storage.setItem('test-key', testData); + + expect(mockLocalStorage.setItem).toHaveBeenCalledWith( + 'test-key', + JSON.stringify(testData) + ); + }); + + it('should handle special characters in strings', () => { + const specialString = 'Test\n\t"quotes"\\backslash'; + + storage.setItem('test-key', specialString, { serialize: false }); + + expect(mockLocalStorage.setItem).toHaveBeenCalledWith('test-key', specialString); + }); + + it('should handle empty strings', () => { + storage.setItem('test-key', '', { serialize: false }); + + expect(mockLocalStorage.setItem).toHaveBeenCalledWith('test-key', ''); + }); + + it('should handle boolean values', () => { + storage.setItem('test-key', true); + + expect(mockLocalStorage.setItem).toHaveBeenCalledWith( + 'test-key', + JSON.stringify(true) + ); + }); + + it('should handle number values', () => { + storage.setItem('test-key', 42); + + expect(mockLocalStorage.setItem).toHaveBeenCalledWith( + 'test-key', + JSON.stringify(42) + ); + }); + + it('should handle null values', () => { + storage.setItem('test-key', null); + + expect(mockLocalStorage.setItem).toHaveBeenCalledWith( + 'test-key', + JSON.stringify(null) + ); + }); + }); + + describe('removeItem()', () => { + it('should successfully remove items', () => { + mockLocalStorage._getStore()['test-key'] = 'value'; + + const result = storage.removeItem('test-key'); + + expect(result).toBe(true); + expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('test-key'); + expect(mockLocalStorage._getStore()['test-key']).toBeUndefined(); + }); + + it('should handle errors gracefully', () => { + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + mockLocalStorage.removeItem.mockImplementationOnce(() => { + throw new Error('Remove error'); + }); + + const result = storage.removeItem('test-key'); + + expect(result).toBe(false); + expect(consoleErrorSpy).toHaveBeenCalled(); + + consoleErrorSpy.mockRestore(); + }); + + it('should return false in SSR context (browser = false)', () => { + mockBrowser = false; + + const result = storage.removeItem('test-key'); + + expect(result).toBe(false); + expect(mockLocalStorage.removeItem).not.toHaveBeenCalled(); + }); + + it('should handle removing non-existent keys', () => { + const result = storage.removeItem('non-existent'); + + expect(result).toBe(true); + expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('non-existent'); + }); + }); + + describe('clear()', () => { + it('should successfully clear all items', () => { + mockLocalStorage._getStore()['key1'] = 'value1'; + mockLocalStorage._getStore()['key2'] = 'value2'; + + const result = storage.clear(); + + expect(result).toBe(true); + expect(mockLocalStorage.clear).toHaveBeenCalled(); + expect(Object.keys(mockLocalStorage._getStore()).length).toBe(0); + }); + + it('should handle errors gracefully', () => { + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + mockLocalStorage.clear.mockImplementationOnce(() => { + throw new Error('Clear error'); + }); + + const result = storage.clear(); + + expect(result).toBe(false); + expect(consoleErrorSpy).toHaveBeenCalled(); + + consoleErrorSpy.mockRestore(); + }); + + it('should return false in SSR context (browser = false)', () => { + mockBrowser = false; + + const result = storage.clear(); + + expect(result).toBe(false); + expect(mockLocalStorage.clear).not.toHaveBeenCalled(); + }); + }); + + describe('getAllKeys()', () => { + it('should return all keys in localStorage', () => { + mockLocalStorage._getStore()['key1'] = 'value1'; + mockLocalStorage._getStore()['key2'] = 'value2'; + mockLocalStorage._getStore()['key3'] = 'value3'; + + const keys = storage.getAllKeys(); + + expect(keys).toEqual(['key1', 'key2', 'key3']); + }); + + it('should return empty array when no keys exist', () => { + const keys = storage.getAllKeys(); + + expect(keys).toEqual([]); + }); + + it('should handle errors gracefully', () => { + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + + // Add a key so length > 0 + mockLocalStorage._getStore()['test-key'] = 'value'; + + // Mock localStorage.key to throw + const originalKey = mockLocalStorage.key; + mockLocalStorage.key = vi.fn(() => { + throw new Error('Keys error'); + }); + + const keys = storage.getAllKeys(); + + expect(keys).toEqual([]); + expect(consoleErrorSpy).toHaveBeenCalled(); + + mockLocalStorage.key = originalKey; + consoleErrorSpy.mockRestore(); + }); + + it('should return empty array in SSR context (browser = false)', () => { + mockBrowser = false; + mockLocalStorage._getStore()['key1'] = 'value1'; + + const keys = storage.getAllKeys(); + + expect(keys).toEqual([]); + }); + }); + + describe('isAvailable()', () => { + it('should return true when localStorage is available', () => { + const result = storage.isAvailable(); + + expect(result).toBe(true); + }); + + it('should return false in SSR context (browser = false)', () => { + mockBrowser = false; + + const result = storage.isAvailable(); + + expect(result).toBe(false); + }); + + it('should return false when localStorage throws errors', () => { + mockLocalStorage.setItem.mockImplementationOnce(() => { + throw new Error('Not available'); + }); + + const result = storage.isAvailable(); + + expect(result).toBe(false); + }); + + it('should clean up test key after checking availability', () => { + storage.isAvailable(); + + expect(mockLocalStorage.setItem).toHaveBeenCalledWith('__localStorage_test__', 'test'); + expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('__localStorage_test__'); + }); + }); + + describe('Integration Tests', () => { + it('should handle full lifecycle: set, get, remove', () => { + const testData = { lifecycle: 'test', value: 123 }; + + // Set + const setResult = storage.setItem('lifecycle-key', testData); + expect(setResult).toBe(true); + + // Get + const getData = storage.getItem('lifecycle-key', { defaultValue: {} }); + expect(getData).toEqual(testData); + + // Remove + const removeResult = storage.removeItem('lifecycle-key'); + expect(removeResult).toBe(true); + + // Verify removed + const afterRemove = storage.getItem('lifecycle-key', { defaultValue: null }); + expect(afterRemove).toBe(null); + }); + + it('should handle multiple keys independently', () => { + storage.setItem('key1', { value: 1 }); + storage.setItem('key2', { value: 2 }); + storage.setItem('key3', { value: 3 }); + + expect(storage.getItem('key1', { defaultValue: {} })).toEqual({ value: 1 }); + expect(storage.getItem('key2', { defaultValue: {} })).toEqual({ value: 2 }); + expect(storage.getItem('key3', { defaultValue: {} })).toEqual({ value: 3 }); + + const keys = storage.getAllKeys(); + expect(keys.length).toBe(3); + }); + + it('should handle overwriting existing keys', () => { + storage.setItem('overwrite', 'original'); + expect(storage.getItem('overwrite', { defaultValue: '', serialize: false })).toBe('original'); + + storage.setItem('overwrite', 'updated'); + expect(storage.getItem('overwrite', { defaultValue: '', serialize: false })).toBe('updated'); + }); + + it('should maintain type safety with validation', () => { + type UserData = { name: string; age: number }; + + const validate = (val: unknown): val is UserData => { + return ( + typeof val === 'object' && + val !== null && + 'name' in val && + 'age' in val && + typeof (val as UserData).name === 'string' && + typeof (val as UserData).age === 'number' + ); + }; + + const validUser: UserData = { name: 'Alice', age: 30 }; + storage.setItem('user', validUser); + + const retrieved = storage.getItem('user', { + defaultValue: { name: '', age: 0 }, + validate + }); + + expect(retrieved).toEqual(validUser); + + // Test invalid data + mockLocalStorage._getStore()['user'] = JSON.stringify({ name: 'Bob' }); // Missing age + + const invalidRetrieve = storage.getItem('user', { + defaultValue: { name: 'Default', age: 0 }, + validate + }); + + expect(invalidRetrieve).toEqual({ name: 'Default', age: 0 }); + }); + }); + + describe('Edge Cases', () => { + it('should handle very large objects', () => { + const largeObject = { + data: Array.from({ length: 1000 }, (_, i) => ({ + id: i, + value: `value-${i}`, + nested: { deep: { deeper: i } } + })) + }; + + const setResult = storage.setItem('large-object', largeObject); + expect(setResult).toBe(true); + + const retrieved = storage.getItem('large-object', { defaultValue: {} }); + expect(retrieved).toEqual(largeObject); + }); + + it('should handle Unicode characters', () => { + const unicodeData = { + emoji: '🚀🎉💻', + chinese: '你好世界', + arabic: 'مرحبا بالعالم', + special: '§±!@#$%^&*()' + }; + + storage.setItem('unicode', unicodeData); + const retrieved = storage.getItem('unicode', { defaultValue: {} }); + + expect(retrieved).toEqual(unicodeData); + }); + + it('should handle keys with special characters', () => { + const specialKey = 'key-with-special_chars.123:test'; + + storage.setItem(specialKey, 'value'); + const retrieved = storage.getItem(specialKey, { defaultValue: '', serialize: false }); + + expect(retrieved).toBe('value'); + }); + + it('should handle empty objects', () => { + storage.setItem('empty-object', {}); + const retrieved = storage.getItem('empty-object', { defaultValue: null }); + + expect(retrieved).toEqual({}); + }); + + it('should handle empty arrays', () => { + storage.setItem('empty-array', []); + const retrieved = storage.getItem('empty-array', { defaultValue: null }); + + expect(retrieved).toEqual([]); + }); + + it('should handle date objects (which get stringified)', () => { + const date = new Date('2024-01-01'); + storage.setItem('date', date); + + const retrieved = storage.getItem('date', { defaultValue: null }); + // Date gets converted to string in JSON + expect(retrieved).toBe(date.toJSON()); + }); + }); + + describe('Error Recovery', () => { + it('should recover from one-time localStorage failures', () => { + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + + // First call fails + mockLocalStorage.setItem.mockImplementationOnce(() => { + throw new Error('Temporary failure'); + }); + + const firstResult = storage.setItem('test', 'value'); + expect(firstResult).toBe(false); + + // Second call succeeds + const secondResult = storage.setItem('test', 'value'); + expect(secondResult).toBe(true); + + consoleErrorSpy.mockRestore(); + }); + + it('should maintain state after errors', () => { + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + + storage.setItem('key1', 'value1'); + + // Cause error on key2 + mockLocalStorage.setItem.mockImplementationOnce(() => { + throw new Error('Error'); + }); + storage.setItem('key2', 'value2'); + + // key1 should still be retrievable + const retrieved = storage.getItem('key1', { defaultValue: '', serialize: false }); + expect(retrieved).toBe('value1'); + + consoleErrorSpy.mockRestore(); + }); + }); +});