fix(store): guard localStorage calls for Node/SSR builds
This commit is contained in:
@@ -34,27 +34,37 @@ export const AE_LOC_VERSION = 1;
|
||||
export const AE_EVENTS_LOC_VERSION = 1;
|
||||
|
||||
// Version check side-effect: runs on import, before any persisted() call.
|
||||
// Guards typeof localStorage for safety (SSR environments, test runners).
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
// Guard presence of `localStorage` and its functions for safety (SSR, Node flags).
|
||||
if (
|
||||
typeof localStorage !== 'undefined' &&
|
||||
typeof (localStorage as any).getItem === 'function' &&
|
||||
typeof (localStorage as any).removeItem === 'function'
|
||||
) {
|
||||
_check_and_wipe('ae_loc', AE_LOC_VERSION);
|
||||
_check_and_wipe('ae_events_loc', AE_EVENTS_LOC_VERSION);
|
||||
}
|
||||
|
||||
function _check_and_wipe(key: string, expected_version: number): void {
|
||||
try {
|
||||
// Defensive: ensure methods still exist at call time.
|
||||
if (typeof (localStorage as any).getItem !== 'function') return;
|
||||
const raw = localStorage.getItem(key);
|
||||
if (!raw) return; // No stored value — nothing to wipe.
|
||||
|
||||
const parsed = JSON.parse(raw);
|
||||
if (parsed?.__version !== expected_version) {
|
||||
localStorage.removeItem(key);
|
||||
if (typeof (localStorage as any).removeItem === 'function') {
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
console.info(
|
||||
`[store_versions] '${key}' wiped — schema v${parsed?.__version ?? 'none'} → v${expected_version}`
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// Corrupt JSON — wipe unconditionally.
|
||||
localStorage.removeItem(key);
|
||||
// Corrupt JSON — wipe unconditionally if possible.
|
||||
if (typeof (localStorage as any).removeItem === 'function') {
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
console.warn(
|
||||
`[store_versions] '${key}' wiped — corrupt JSON in localStorage`
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user