Kumbatio

Persistence

localStoragePersistence and memoryPersistence from @kumbatio/energy-system/persistence

import { localStoragePersistence, memoryPersistence } from '@kumbatio/energy-system/persistence'

Two built-in implementations of the EnergyPersistence contract. Pass them to createEnergyEngine or EnergyProvider.

localStoragePersistence

function localStoragePersistence(key?: string): EnergyPersistence

localStorage-based persistence adapter. Stores the full EnergyState as JSON under key.

Prop

Type

Behavior:

  • load() - returns null when localStorage is unavailable, the key is empty, the JSON is malformed, or any field fails validation (level, source, timestamp, revision, origin). Valid data is rebuilt through createEnergyState.
  • save(state) - writes JSON.stringify(state). Failures (quota exceeded, missing localStorage) reject with Error("Failed to save energy state to localStorage key '<key>'", { cause }) rather than being swallowed, so the engine's persistence queue can observe the failure and retry with backoff.
  • observe(onState) - listens to the window storage event, so state changes from other tabs propagate into this engine (same-tab writes do not fire storage). Events for other keys or storage areas are ignored; invalid payloads are dropped. Returns an unsubscribe function; in environments without addEventListener/localStorage it is a no-op.
import { createEnergyEngine } from '@kumbatio/energy-system'
import { localStoragePersistence } from '@kumbatio/energy-system/persistence'

const engine = createEnergyEngine({
  persistence: localStoragePersistence('my-app:energy'),
})

memoryPersistence

function memoryPersistence(initial?: EnergyState): EnergyPersistence

In-memory persistence adapter. Useful for tests, SSR, or ephemeral sessions.

Prop

Type

Behavior:

  • load() - resolves the stored state, or null when never saved and no initial was given.
  • save(state) - stores a validated copy and synchronously notifies all observe listeners.
  • observe(onState) - registers a listener that fires on every save. Returns an unsubscribe function. This makes two engines sharing one memoryPersistence instance converge, which is handy for simulating cross-context sync in tests.
import { createEnergyEngine, createEnergyState } from '@kumbatio/energy-system'
import { memoryPersistence } from '@kumbatio/energy-system/persistence'

const store = memoryPersistence(createEnergyState(50, 'scheduled'))
const engine = createEnergyEngine({ persistence: store })
await engine.hydrate()
engine.getState().level // 50