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