UNPKG

seitu

Version:
65 lines (64 loc) • 2.47 kB
import { createReadableSubscription, createSubscription } from "../../core/subscription/index.mjs"; import { n as validateSchema } from "../../schema-store-Dfbr678J.mjs"; import { tryParseJson } from "../../utils/json/index.mjs"; import { repairValueObjectWithDefault } from "../../utils/validation/index.mjs"; import { n as listenStorage, t as dispatchStorageEvent } from "../../storage-event-D-A553TB.mjs"; //#region src/web/web-storage-value/index.ts function createWebStorageValue(options) { const { type, schema, key: storageKey } = options; const defaultValue = options.defaultValue ?? null; const isDefaultValueObject = typeof defaultValue === "object" && defaultValue !== null; const label = `createWebStorageValue:${storageKey}`; const { subscribe, notify } = createSubscription({ onFirstSubscribe: () => listenStorage((event) => event.key === null || event.key === storageKey, notify) }); let cachedRaw; let cachedValue; const get = () => { if (typeof window === "undefined") return defaultValue; const raw = window[type].getItem(storageKey); if (cachedRaw !== void 0 && raw === cachedRaw) return cachedValue; cachedRaw = raw; if (raw === null) { cachedValue = defaultValue; return cachedValue; } const parsed = tryParseJson(raw); try { cachedValue = validateSchema(schema, parsed, { defaultValue, label, key: options.key, onError: (props) => { const toReturn = options.onValidationError?.(props); return toReturn === void 0 && isDefaultValueObject ? repairValueObjectWithDefault(props) : toReturn; } }); } catch (error) { console.warn(`[${label}] Validation failed, returned default value instead`, error); cachedValue = defaultValue; } return cachedValue; }; const readable = createReadableSubscription(get, subscribe, notify, () => defaultValue); const write = (mutate) => { if (typeof window === "undefined") return; const storage = window[type]; const oldRaw = storage.getItem(storageKey); const newRaw = mutate(storage); cachedRaw = void 0; dispatchStorageEvent(storage, storageKey, oldRaw, newRaw); }; return { ...readable, set: (value) => write((storage) => { const newRaw = JSON.stringify(typeof value === "function" ? value(get()) : value); storage.setItem(storageKey, newRaw); return newRaw; }), clear: () => write((storage) => { storage.removeItem(storageKey); return null; }) }; } //#endregion export { createWebStorageValue };