@molecule/app-storage

Core interface · storage · App (browser) · v1.1.0 · Apache-2.0

Key-value storage with provider adapters

npm install @molecule/app-storage

npm · Source on GitHub

How it works

@molecule/app-storage is the storage core interface on the app (browser) side: the API your app calls, with no vendor inside.

Choose the implementation by bonding one of its 2 providers: @molecule/app-storage-async-storage, @molecule/app-storage-localstorage.

import { get, getPreferenceStore, set, remove } from '@molecule/app-storage'

// Async handlers: await the provider.
await set('theme', 'dark') // non-sensitive preference — fine
const theme = await get<string>('theme')
await remove('theme')
// await set('authToken', token) // ❌ NEVER — tokens/secrets are not client-persisted

// Render-time preference reads: a synchronous snapshot + subscription.
const store = getPreferenceStore()
const width = store.get<number>('sidebar_width') // correct on the first paint
store.set('sidebar_width', 240) // persists through the bonded provider
const stop = store.subscribe('sidebar_width', () => setWidth(store.get('sidebar_width')))

Providers (2): @molecule/app-storage-async-storage, @molecule/app-storage-localstorage

Works with: @molecule/app-bond, @molecule/app-i18n

Reference

Client storage interface for molecule.dev.

Provides a unified storage API that works across web and native platforms.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { get, getPreferenceStore, set, remove } from '@molecule/app-storage'

// Async handlers: await the provider.
await set('theme', 'dark') // non-sensitive preference — fine
const theme = await get<string>('theme')
await remove('theme')
// await set('authToken', token) // ❌ NEVER — tokens/secrets are not client-persisted

// Render-time preference reads: a synchronous snapshot + subscription.
const store = getPreferenceStore()
const width = store.get<number>('sidebar_width') // correct on the first paint
store.set('sidebar_width', 240) // persists through the bonded provider
const stop = store.subscribe('sidebar_width', () => setWidth(store.get('sidebar_width')))

Type

core

Installation

npm install @molecule/app-storage @molecule/app-bond @molecule/app-i18n

API

Interfaces

StorageProvider

Storage provider interface.

All storage providers must implement this interface.

interface StorageProvider {
  /**
   * Gets a value from storage.
   */
  get<T = unknown>(key: string): Promise<T | null>

  /**
   * Sets a value in storage.
   */
  set<T = unknown>(key: string, value: T): Promise<void>

  /**
   * Removes a value from storage.
   */
  remove(key: string): Promise<void>

  /**
   * Clears all values from storage.
   */
  clear(): Promise<void>

  /**
   * Gets all keys in storage.
   */
  keys(): Promise<string[]>

  /**
   * Gets multiple values from storage.
   */
  getMany?<T = unknown>(keys: string[]): Promise<Map<string, T | null>>

  /**
   * Sets multiple values in storage.
   */
  setMany?<T = unknown>(entries: Array<[string, T]>): Promise<void>

  /**
   * Removes multiple values from storage.
   */
  removeMany?(keys: string[]): Promise<void>

  /**
   * Reads a value synchronously.
   *
   * Optional: only a provider backed by a SYNCHRONOUS store (browser
   * `localStorage`, an in-memory map) can answer without I/O. A render-time
   * caller reads through `getPreferenceStore()`, which uses this method to see
   * the persisted value on the first paint; a provider without it is read
   * through `StorageProvider.get` and subscribers update when the value
   * lands.
   * @param key - The storage key.
   * @returns The stored value, or `null` when it is absent, unreadable or corrupt.
   */
  getSync?<T = unknown>(key: string): T | null

  /**
   * Subscribes to changes made to a key OUTSIDE this provider instance — for
   * example another browser tab's `localStorage` write.
   *
   * Writes made through the same provider instance do not re-emit here; a
   * synchronous caller observes them through `getPreferenceStore()`'s own
   * subscribers.
   * @param key - The storage key.
   * @param listener - Called with the new value, or `null` when it was removed.
   * @returns A function that stops the subscription.
   */
  subscribe?(key: string, listener: (value: unknown) => void): () => void
}

StorageCodec

Chooses how ONE key's value becomes the raw string a synchronous backend holds, and how that string becomes a value again.

A provider applies a codec to get, getSync, set and the change subscription for every key the codec matches, before the provider's own default serialize/deserialize pair. That is how a typed preference and a value written by an OLDER raw-string helper can share one key without either one being reset: an app declares a string codec for the keys its previous storage layer wrote verbatim (a prompt, a conversation id) and leaves everything else on the JSON codec.

Implementations live with the provider bond (a browser bond needs strings; a native bond may not serialize at all), not in consumer code.

interface StorageCodec {
  /**
   * Whether this codec owns the key.
   * @param key - The UNPREFIXED storage key the caller used.
   * @returns `true` when this codec encodes and decodes that key.
   */
  matches(key: string): boolean

  /**
   * Encodes a value to the raw string the backend stores.
   * @param value - The value the caller wrote.
   * @returns The raw string to store.
   */
  encode(value: unknown): string

  /**
   * Decodes a raw string read from the backend.
   * @param raw - The raw string as stored.
   * @returns The value the caller reads. Throwing is allowed: the provider
   *   treats a thrown decode as absent, the same contract as a corrupt entry.
   */
  decode(raw: string): unknown
}

PreferenceStore

Synchronous snapshot + subscription over an asynchronous storage provider.

A render-time read cannot await, and a preference (a theme, a layout width, a feature toggle) is read DURING the first render — so the value must already be in memory when the component paints. This store keeps that memory: it fills from the provider's synchronous read when the provider has one, hydrates asynchronously otherwise, and notifies subscribers on every change (a write in this tab, or a storage event from another tab relayed by the provider's subscribe).

Writes are optimistic and best-effort: the cache and subscribers update immediately, and persistence failures (quota, a locked/absent store) are ignored exactly like the browser-global helpers this replaces.

Coherence: every write, remove and externally observed change makes the reads that started before it stale, and those reads are dropped instead of applied. A provider swap likewise retires every read that started against the old provider. So "last write wins" holds across slow hydration, and a stale asynchronous read can never resurrect an older value.

interface PreferenceStore {
  /**
   * Reads the last known value for a key, synchronously.
   * @param key - The storage key.
   * @returns The cached value, `null` when absent or unreadable, or the last
   *   known value while an asynchronous provider's first read is in flight.
   */
  get<T = unknown>(key: string): T | null

  /**
   * Updates the cached value, notifies subscribers, then persists best-effort.
   * @param key - The storage key.
   * @param value - The value to store.
   */
  set<T = unknown>(key: string, value: T): void

  /**
   * Removes a value from the cache and from the provider, notifying subscribers.
   * @param key - The storage key.
   */
  remove(key: string): void

  /**
   * Subscribes to changes of one key in this tab or another.
   * @param key - The storage key.
   * @param listener - Called with the new value after every change.
   * @returns A function that stops the subscription.
   */
  subscribe(key: string, listener: PreferenceListener): () => void

  /**
   * Loads values into the cache from the provider.
   *
   * Call once at boot for every key a synchronous reader may ask about. A
   * provider with a synchronous read fills the cache immediately; an
   * asynchronous one resolves later and notifies subscribers.
   *
   * A read that resolves AFTER a newer write, remove or external change to the
   * same key is discarded, and so is a read that started against a provider
   * that has since been swapped out — a slow hydration can never replace the
   * newer value (or another provider's value) with an older snapshot.
   *
   * Keys already in the snapshot are NOT re-read: hydration fills what is
   * unknown, `refresh()` re-reads what changed behind this store.
   * @param keys - The keys to load.
   * @returns A promise that resolves once every key has been loaded.
   */
  hydrate(keys: readonly string[]): Promise<void>

  /**
   * Re-reads keys from the CURRENT provider and notifies subscribers.
   *
   * This is the explicit contract for a write that does not go through this
   * store — a caller using the provider's own `set`/`remove`, or a backend
   * change the provider cannot observe through `subscribe`. Without it the
   * snapshot keeps serving the value it cached before that write. Any read
   * still in flight for those keys is discarded first, so a slower older read
   * cannot land on top of the re-read.
   * @param keys - The keys to re-read; omitted means every key this store
   *   currently holds a snapshot for (the `clear()` shape).
   * @returns A promise that resolves once the re-read has been applied.
   */
  refresh(keys?: string | readonly string[]): Promise<void>
}

Types

StorageCodecMatch

Which keys a codec owns: one exact key, or a predicate over the key.

type StorageCodecMatch = string | ((key: string) => boolean)

PreferenceListener

Called when the value a preference key holds changes.

Receives the new value, or null when the key was removed or became unreadable.

type PreferenceListener = (value: unknown) => void

Functions

createStringCodec(match)

Creates a codec for keys whose value is a plain string.

Decoding accepts BOTH shapes that exist in the wild for such a key:

  • the JSON string this codec writes ("build me a thing"), and
  • the verbatim text an older storage helper wrote (build me a thing).

So a value persisted before the switch is read back rather than reset, and a value written now stays readable by either shape. A legacy text that happens to BE valid JSON is decoded as the JSON value it is (a bare 42 stays the string "42", a quoted "hi" reads as hi), which is the only reading that keeps both shapes consistent.

Use it only for keys that hold plain strings: a key that holds structured data belongs on the provider's JSON codec, where a corrupt entry still reads as absent.

function createStringCodec(match: StorageCodecMatch): StorageCodec
  • match — The exact key, or a predicate receiving the unprefixed key.

Returns: A codec owning those keys.

createMemoryStorageProvider()

Creates an in-memory StorageProvider backed by a Map.

Values are stored by reference (no serialization). Each call returns an isolated instance with its own backing store.

function createMemoryStorageProvider(): StorageProvider

Returns: An isolated StorageProvider backed by an in-memory Map.

createPreferenceStore(resolveProvider)

Creates a preference store around a provider resolver.

The resolver runs on every operation so a provider swapped at runtime (a test host, a native build, a different backend) becomes the source of truth immediately: a swap drops every cached value and re-attaches the change subscriptions to the new provider.

function createPreferenceStore(resolveProvider?: () => StorageProvider | null): PreferenceStore
  • resolveProvider — Returns the current provider, or null for "none". Defaults to the bonded @molecule/app-storage provider.

Returns: A preference store backed by that provider.

getPreferenceStore()

The application's preference store, created on first use.

Always call it inside a component, hook or event handler — never at module scope, which runs before the app's bonds are set up. Reading or writing while no provider is bonded works against an in-memory cache and simply does not persist.

function getPreferenceStore(): PreferenceStore

Returns: The shared preference store.

setProvider(provider)

Registers a storage provider as the active singleton.

function setProvider(provider: StorageProvider): void
  • provider — The storage provider implementation to bond.

getProvider()

Retrieves the bonded storage provider, throwing if none is configured.

function getProvider(): StorageProvider

Returns: The bonded storage provider.

hasProvider()

Checks whether a storage provider is currently bonded.

function hasProvider(): boolean

Returns: true if a storage provider is bonded.

get(key)

Gets a value from storage by key.

function get<T = unknown>(key: string): Promise<T | null>
  • key — The storage key to look up.

Returns: The stored value, or null if not found.

set(key, value)

Sets a value in storage.

function set<T = unknown>(key: string, value: T): Promise<void>
  • key — The storage key.
  • value — The value to store.

Returns: A promise that resolves when the value is stored and the preference snapshot for the key has been refreshed.

remove(key)

Removes a value from storage by key.

function remove(key: string): Promise<void>
  • key — The storage key to remove.

Returns: A promise that resolves when the key is removed and the preference snapshot for it has been refreshed.

clear()

Clears all values from storage.

function clear(): Promise<void>

Returns: A promise that resolves when storage is cleared and every key the preference store holds a snapshot for has been re-read.

keys()

Returns all keys currently stored.

function keys(): Promise<string[]>

Returns: An array of storage keys.

Available Providers

ProviderPackage
AsyncStorage@molecule/app-storage-async-storage
localStorage@molecule/app-storage-localstorage

Injection Notes

Requirements

Peer dependencies:

  • @molecule/app-bond ^1.0.1
  • @molecule/app-i18n ^1.0.1

Runtime Dependencies

  • @molecule/app-bond
  • @molecule/app-i18n

Use this abstraction — get/set/remove/clear/keys (all async) — for client persistence. Do NOT touch localStorage / sessionStorage / AsyncStorage directly: raw web storage doesn't exist on native, and hardcoding it breaks the platform swap. The default provider is IN-MEMORY (a safe default — no accidental persistence); a web/native bond persists.

NEVER store a secret or an auth token in client storage. localStorage / sessionStorage are readable by any injected script, so a token there is XSS-exfiltratable — the bearer token is deliberately held in memory only (see @molecule/api-resource-user). Persist only NON-sensitive UI state / preferences here.

Read a preference DURING render through getPreferenceStore(), never by touching web storage directly. It returns the last known value synchronously (seeded from the provider's getSync, hydrated asynchronously otherwise), notifies subscribers on a write in this tab or another, and persists through the SAME bonded provider — so swapping the provider swaps every preference, including render-time reads. Values you only read inside an async handler can just await get.

Translations

Translation strings are provided by @molecule/app-locales-storage.