{"id":51454317,"url":"https://github.com/stainless-code/persist","last_synced_at":"2026-07-05T23:30:32.577Z","repository":{"id":369078730,"uuid":"1288196173","full_name":"stainless-code/persist","owner":"stainless-code","description":"Hydration-aware persistence for reactive stores — pluggable storage × codec seams, TanStack Store adapters, React hydration hook","archived":false,"fork":false,"pushed_at":"2026-07-03T14:23:55.000Z","size":220,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-07-03T14:27:50.454Z","etag":null,"topics":["bun","hydration","indexeddb","localstorage","persist","persistence","react","sessionstorage","state-management","tanstack","tanstack-store","typescript"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/stainless-code.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":"docs/roadmap.md","authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null},"funding":{"github":["SutuSebastian"]}},"created_at":"2026-07-03T11:10:12.000Z","updated_at":"2026-07-03T14:23:59.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/stainless-code/persist","commit_stats":null,"previous_names":["stainless-code/persist"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/stainless-code/persist","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stainless-code%2Fpersist","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stainless-code%2Fpersist/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stainless-code%2Fpersist/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stainless-code%2Fpersist/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/stainless-code","download_url":"https://codeload.github.com/stainless-code/persist/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stainless-code%2Fpersist/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35172975,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-07-05T02:00:06.290Z","response_time":100,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bun","hydration","indexeddb","localstorage","persist","persistence","react","sessionstorage","state-management","tanstack","tanstack-store","typescript"],"created_at":"2026-07-05T23:30:31.752Z","updated_at":"2026-07-05T23:30:32.571Z","avatar_url":"https://github.com/stainless-code.png","language":"TypeScript","funding_links":["https://github.com/sponsors/SutuSebastian"],"categories":[],"sub_categories":[],"readme":"# @stainless-code/persist\n\nHydration-aware persistence middleware for any reactive store — storage × codec seams, TanStack Store adapters, and a React hydration hook. Store-agnostic via a structural `PersistableSource`; every \"can it do X?\" is a one-line composition instead of a feature request.\n\n## Install\n\n```bash\nbun add @stainless-code/persist\n```\n\nEach subpath owns its dependency as an **optional peer** — import only the entries you use, install the matching peer only when you do:\n\n| Subpath                                  | Optional peer        |\n| ---------------------------------------- | -------------------- |\n| `@stainless-code/persist`                | none (zero-dep core) |\n| `@stainless-code/persist/seroval`        | `seroval`            |\n| `@stainless-code/persist/idb`            | `idb-keyval`         |\n| `@stainless-code/persist/tanstack-store` | `@tanstack/store`    |\n| `@stainless-code/persist/react`          | `react`              |\n\n```bash\n# only when you use the matching entry\nbun add seroval idb-keyval @tanstack/store react\n```\n\n## Quick start\n\n```ts\nimport { Store } from \"@tanstack/store\";\nimport { createSerovalStorage } from \"@stainless-code/persist/seroval\";\nimport { persistStore } from \"@stainless-code/persist/tanstack-store\";\nimport { toHydrationSignal } from \"@stainless-code/persist\";\nimport { useHydrated } from \"@stainless-code/persist/react\";\n\nconst store = new Store({ theme: \"light\" });\nconst persist = persistStore(store, {\n  name: \"app:prefs:v1\",\n  storage: createSerovalStorage(() =\u003e localStorage),\n});\nexport const prefsHydration = toHydrationSignal(persist);\n\n// in a component:\nconst { hydrated } = useHydrated(prefsHydration);\n```\n\n## Relationship to TanStack Persist / zustand persist\n\nBoth TanStack Persist and zustand persist wire a single store library to a single storage with a flat options bag. `@stainless-code/persist` is a **middleware model with a first-class hydration lifecycle**: persistence is bound to a structural `PersistableSource` (`getState`/`setState`/`subscribe`) rather than a specific store, so the same middleware persists TanStack Store, zustand, Redux, or a hand-rolled atom. Three seams — backend (`StateStorage`), codec (`StorageCodec`), source (`PersistableSource`) — make every backend × codec cell a one-line composition. The hydration lifecycle (`onHydrate` / `onFinishHydration` / `hasHydrated`, surfaced via `HydrationSignal` and `useHydrated`) gates UI flash without coupling to the store's read path, versioned `migrate` handles schema evolution, `crossTab` + `onCrossTabRemove` syncs tabs, and `retryWrite` shrinks-or-gives-up on quota errors with a write-generation guard so stale retries never clobber newer state.\n\n---\n\n# Extensibility guide\n\nPersistence middleware for any `getState`/`setState`/`subscribe` store (TanStack Store adapters included), built around three seams that make every \"can it do X?\" a one-line answer instead of a feature request. The full API contract lives in the JSDoc of each module.\n\n## Entry points (one subpath = one optional peer)\n\n| Subpath                                  | Symbols                                                                                                                 | Optional peer                  |\n| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------ |\n| `@stainless-code/persist`                | `persistSource`, `PersistApi`, `createStorage`, `jsonCodec`, `identityCodec`, registry, `HydrationSignal` (`hydration`) | none                           |\n| `@stainless-code/persist/seroval`        | `serovalCodec`, `createSerovalStorage`                                                                                  | `seroval`                      |\n| `@stainless-code/persist/idb`            | `idbStateStorage`, `createIdbStorage` (structured-clone mode)                                                           | `idb-keyval`                   |\n| `@stainless-code/persist/tanstack-store` | `persistStore`, `persistAtom`                                                                                           | `@tanstack/store` (types only) |\n| `@stainless-code/persist/react`          | `useHydrated` React hook                                                                                                | `react`                        |\n\nNo barrel — importing a subpath is the dependency opt-in.\n\n## The three seams\n\n**1. Backend (`StateStorage\u003cTRaw = string\u003e`)** — anything with `getItem`/`setItem`/`removeItem`, sync or Promise-returning, string-wire by default, generic for structured backends.\n\n```ts\nimport { createSerovalStorage } from \"@stainless-code/persist/seroval\";\nimport { createIdbStorage } from \"@stainless-code/persist/idb\";\nimport { createJSONStorage } from \"@stainless-code/persist\";\n\ncreateSerovalStorage(() =\u003e localStorage); // durable prefs\ncreateSerovalStorage(() =\u003e sessionStorage); // per-visit state (dies with the tab)\ncreateIdbStorage(); // IndexedDB, structured-clone mode\ncreateJSONStorage(() =\u003e AsyncStorage); // React Native — satisfies StateStorage as-is\n// custom: in-memory for tests, remote KV, encrypted wrapper — implement 3 methods\n```\n\n**2. Codec (`StorageCodec\u003cS, TRaw = string\u003e`)** — pure `encode`/`decode` between the persisted envelope and the backend's wire type.\n\n```ts\nimport {\n  jsonCodec,\n  identityCodec,\n  createStorage,\n} from \"@stainless-code/persist\";\nimport { serovalCodec } from \"@stainless-code/persist/seroval\";\nimport { idbStateStorage } from \"@stainless-code/persist/idb\";\n\njsonCodec(); // core default — plain JSON\nserovalCodec(); // Set / Map / Date / cycles, inert JSON-shaped output\nidentityCodec(); // structured-clone backends only — zero serialization\n// custom — any pair of pure functions:\nconst superjsonCodec = { encode: superjson.stringify, decode: superjson.parse }; // class instances via registerCustom\nconst encryptedCodec = {\n  encode: (v) =\u003e encrypt(JSON.stringify(v)),\n  decode: (raw) =\u003e JSON.parse(decrypt(raw)),\n};\n```\n\n**3. Store source (`PersistableSource`)** — structural, so the middleware persists anything reactive:\n\n```ts\nimport {\n  persistStore,\n  persistAtom,\n} from \"@stainless-code/persist/tanstack-store\";\nimport { persistSource } from \"@stainless-code/persist\";\n\npersistStore(store, opts); // @tanstack/store Store\npersistAtom(atom, opts); // writable Atom (replace-merge default)\npersistSource({ getState, setState, subscribe }, opts); // zustand-like, redux, hand-rolled\n```\n\nCompose freely: `createStorage(backend, codec, options)` covers every backend × codec cell. **Factory policy:** codec factories take the backend as an argument; a backend earns its own factory only when it needs real adaptation (IndexedDB); everything else composes — no factory-per-combination.\n\n## Recipes\n\n```ts\nimport { createStorage } from \"@stainless-code/persist\";\nimport { idbStateStorage, createIdbStorage } from \"@stainless-code/persist/idb\";\nimport { serovalCodec } from \"@stainless-code/persist/seroval\";\nimport { persistStore } from \"@stainless-code/persist/tanstack-store\";\n\n// Encryption at rest over IndexedDB\ncreateStorage(() =\u003e idbStateStorage(), encryptedCodec, {\n  clearCorruptOnFailure: true,\n});\n\n// Legacy string payloads in IDB (written by an older version)\ncreateStorage(() =\u003e idbStateStorage(), serovalCodec());\n\n// Namespaced IDB store away from other idb-keyval users\ncreateIdbStorage({ store: createStore(\"my-db\", \"persist\") });\n\n// Cross-tab sync (localStorage): pair crossTab with onCrossTabRemove when using skipPersist\npersistStore(store, {\n  name,\n  storage,\n  crossTab: true,\n  onCrossTabRemove: () =\u003e store.actions.reset(),\n});\n\n// Cross-tab over IDB: no storage events — bridge a BroadcastChannel via crossTabEventTarget\n```\n\nCaveats that matter per backend: async backends (IDB) can't settle hydration before first paint → gate UI on `useHydrated` (`@stainless-code/persist/react`); `sessionStorage` is per-tab (crossTab is meaningless); `identityCodec` never with string-only backends.\n\n## Writing a framework adapter\n\nThe React hook (`@stainless-code/persist/react`) is ~20 lines over `HydrationSignal` — every adapter is the same shape. The contract (full version on `HydrationSignal`'s JSDoc): subscribe returns an idempotent unsubscribe; each subscribe call is an independent subscription; **no initial notification and no payload** — pull `isHydrated()` after attach and on every notification; transitions while detached aren't replayed (the snapshot re-read recovers); **render `hydrated: true` on the server** (no storage server-side); `null` signal = no persistence = hydrated.\n\n```ts\nimport type { HydrationSignal } from \"@stainless-code/persist\";\n\n// Svelte 5 sketch\nexport function hydratedRune(signal: HydrationSignal | null) {\n  if (!signal)\n    return {\n      get current() {\n        return true;\n      },\n    };\n  const subscribe = createSubscriber((update) =\u003e\n    signal.subscribeHydrated(update),\n  );\n  return {\n    get current() {\n      subscribe();\n      return signal.isHydrated();\n    },\n  };\n}\n```\n\n## Lifecycle in one paragraph\n\n`persistSource` hydrates on create (skip with `skipHydration`; `rehydrate()` is awaitable), subscribe-writes on every `setState` (gated until hydrated; optional trailing `throttleMs`), and tears down completely via `destroy()` — required for non-singleton stores. Failures route to `onError` with a phase (`write`/`hydrate`/`migrate`/`crossTab`); the console fallback is dev-only. Payloads carry `version` (→ `migrate`), `timestamp` (→ `maxAge`), and `buster`; `retryWrite` implements shrink-or-give-up on quota errors with a write-generation guard so stale retries never clobber newer state.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstainless-code%2Fpersist","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstainless-code%2Fpersist","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstainless-code%2Fpersist/lists"}