/** * localStorage-backed state with both an imperative and a reactive face. * * ## Why not `@solid-primitives/storage` * * Not because the ecosystem lags — it doesn't any more: `storage@5.0.0-next.7` declares * `solid-js@^2.0.0-rc.14` as its peer, the same pin this app carries, so the version * argument that used to sit in this comment is simply false. It was re-tested against * that release, and two requirements survive the version bump: * * - **A synchronous read.** `peek()` is what lets a guard (`if (!current) return`), a * request builder and a unit test ask what the value is *now*. The primitive's * accessor is the signal's own, and a Solid 2 signal read in the turn that wrote it * returns the value before the write — which is the race `peek()` exists to remove. * Re-implementing that mirror inside the primitive's wrapper would mean keeping this * file anyway, with a dependency underneath it. * - **A stored value that is checked, and seen to fail.** `deserialize` here is a valibot * parse; in the primitive a throwing `deserialize` is `console.warn`ed in DEV and * swallowed, so a corrupt or drifted value becomes silence plus the initial value. * For `connection` that difference is the login screen: a stored value that is not a * connection has to come back as `null`, not as a half-built object. * * It also hydrates by writing to the signal during construction, which is a write at * module scope on a framework that is particular about where writes happen — the same * class of thing that makes an unowned signal read back stale in dev. * * What is left is ~100 lines: write-through JSON, an optional schema, and the mirror. * * Why the `peek()` mirror: Solid 2.0 rc defers signal commits — reads * outside a tracking scope can observe pinned pre-commit values, which * makes imperative guards (`if (!current) return`) and unit tests race * against the flush. We therefore keep a plain value as the source of * truth, updated synchronously on every write, and use the signal purely * as the *change-notification* channel for components. */ import { safeParse, type BaseIssue, type BaseSchema } from "valibot"; import { createSignal, type Accessor } from "solid-js"; export interface PersistentSignal { /** Reactive accessor — subscribe from components/memos/effects. */ get: Accessor; /** Write-through setter; returns the applied value. */ set: (next: T | ((prev: T) => T)) => T; /** Non-reactive synchronous read — for guards, handlers, and tests. */ peek: () => T; } export interface PersistentSignalOptions { equals?: (prev: T, next: T) => boolean; /** * Runtime shape for the stored value, checked when it is read. * * Read-only on purpose. Every key here is written by this app minutes before it * is read back, so the only values that arrive in a shape nobody declared are ones * localStorage itself produced: another extension with a colliding key, a tab on an * older build, someone poking at DevTools, or a schema that drifted while the value * outlived it. `JSON.parse(raw) as T` used to accept all four and hand them to the * first `peek()` as fact — including a stored `null` reaching `peek().host`, which * throws on the login screen, the one surface with no way out. * * The write path is deliberately not validated: it is hot (volume, scrub, seek all * write through here), and re-checking bytes we just constructed would cost frames * to protect against a mistake we did not make. A bad value can only enter through * `load`, so that is the one door with a guard. * * Typing the option against `T` — rather than `unknown` — makes the compiler check * the schema against the interface at the call site: a schema whose output has a * field the interface lacks, or lacks one it requires, fails the build. */ schema?: BaseSchema>; /** Called when a stored value failed to parse, or no longer fits `schema`. */ onRecover?: () => void; } function load(key: string, fallback: T, options: PersistentSignalOptions): T { const { schema, onRecover } = options; try { const raw = localStorage.getItem(key); if (raw === null) return fallback; const parsed: unknown = JSON.parse(raw); // No schema is the old behaviour, kept as the escape hatch for values whose // shape is genuinely open (a plain number, a record keyed by server id). if (!schema) return parsed as T; // `success` narrows `output` to T; a failure is not an exception to surface to // the caller — the key is junk, and the fallback is what the app would have // wanted had the user never opened DevTools. const result = safeParse(schema, parsed); if (result.success) return result.output; onRecover?.(); return fallback; } catch { onRecover?.(); return fallback; } } export function createPersistentSignal( key: string, initial: T, options: PersistentSignalOptions = {}, ): PersistentSignal { let current = load(key, initial, options); const [get, set] = createSignal(current as unknown as Exclude, { equals: options.equals, }); function write(next: T | ((prev: T) => T)): T { const resolved = typeof next === "function" ? (next as (prev: T) => T)(current) : next; if (options.equals ? options.equals(current, resolved) : current === resolved) { return current; } current = resolved; // Cast: updater-functions were resolved above; never an updater here. set(resolved as never); try { localStorage.setItem(key, JSON.stringify(resolved)); } catch { /* private mode / quota — in-memory state is still correct */ } return current; } return { get, set: write, peek: () => current }; } /** Forget a persisted key (paired with createPersistentSignal). */ export function clearPersistent(key: string): void { try { localStorage.removeItem(key); } catch { /* see above */ } }