@hecto/state
v3.0.0
Published
Reactive immutable state with fine-grained subscriptions, patches, history, and persistence.
Readme
@hecto/state
Reactive state store built on structural diffs. Accessor-based subscriptions, middleware, undo/redo, devtools.
pnpm add @hecto/stateimport { create } from '@hecto/state'
const store = create({ user: { name: 'Tom', score: 0 } })
store.subscribe(
(s) => s.user.score,
(next, prev) => {
console.log(`score: ${prev} -> ${next}`)
},
)
store.set((s) => s.user.score, 42)
store.over(
(s) => s.user.score,
(n) => n + 1,
)What's in the box
- create: create a store from an initial state
- get / set / over / update / replace: read and write with accessor functions or mutable drafts
- subscribe: listen to the whole store or a specific slice via
s => s.path - batch: group multiple writes into a single notification
- at: get a
Handlefor a path segment with its own get/set/subscribe - computed: derived values that update when their source slice changes
- middleware: intercept and transform patches before they apply
- logger: console middleware with grouped, color-coded operation logs
- history: undo/redo middleware backed by patch inversion
- devtools: Redux DevTools integration with time travel
- asyncAction: wire async tasks into the store lifecycle
- spliceText: record a
spliceon a string path insideupdate/recordMutations(UTF-16 index and remove count). Plain assignment still recordsreplace.
import { create, spliceText } from '@hecto/state'
const store = create({ note: 'hello' })
store.update((draft) => {
spliceText(draft, ['note'], 5, 0, ' world')
})
store.get() // { note: 'hello world' }Compiled path optics
compile owns the traced state path and exposes its lens as an explicit
@hecto/fp/optic integration seam:
import { compile } from '@hecto/state'
import { set, view } from '@hecto/fp/optic'
type State = { user: { name: string } }
const name = compile<State, string>((state) => state.user.name)
const source: State = { user: { name: 'Tom' } }
view(name.lens, source) // 'Tom'
set(name.lens, source, 'Ada') // { user: { name: 'Ada' } }Stable and dynamic paths
An accessor such as state => state.user.name is a stable path description,
traced once per function identity. It is not a selector that executes on each read.
Do not capture a changing key in a reused accessor. Accessors also cannot express
arbitrary calculations, method calls, or conditional paths.
Use explicit segments for Map entries or keys whose type matters. at(['items', '1'])
and at(['items', 1]) address different Map entries; an object or array treats those
keys as the same property. That behavior is resolved against the current container,
including after a parent is replaced. "01" stays a distinct key. Supported segment
types are string and number; object and symbol Map keys are not path segments.
An empty path addresses the root, and empty/NUL-containing string segments retain
their boundaries. Paths are copied and frozen, so mutating an input array cannot
retarget an existing handle.
const selected = store.dynamicAt<string>(['users', 'ada', 'name'])
const stop = selected.subscribe((next, previous) => console.log(next, previous))
selected.setPath(['users', 'grace', 'name']) // Rebinds and publishes a changed value.
selected.set('Grace Hopper')
stop()dynamicAt makes path replacement explicit. setPath removes the old subscriptions
and attaches them to the new path; retained handles continue to read and write the
current selection. Use compilePath<S, A>(segments) for an owned explicit-path optic.
compile(accessor) retains weak function-identity caching. The strong explicit-path
cache keeps at most 1,024 entries and evicts in insertion order. clearCompileCache()
clears both lookup caches; previously retained handles continue working. Canonical numeric property accessors retain their existing numeric path
representation because JavaScript property proxies cannot distinguish state[1]
from state['1']. Use at or compilePath to distinguish Map key types.
Migration: replace closure-dependent accessors such as const read = s => s.rows[id]
with store.dynamicAt(['rows', id]), calling setPath(['rows', nextId]) when the
selection changes. Explicit paths no longer coerce "01" or "1" into numeric Map
keys; pass 1 when the intended Map key is numeric.
Runtime reader integration
swapReader(next) returns the actual previous reader. Restore that exact function
in finally, including when a nested effect throws. setReader(next) remains
available for unscoped installation. pathKey(path) provides typed, boundary-safe
tracking identities; numbers use Map's SameValueZero identity (-0 and 0 coincide,
while NaN, infinities, and their string spellings remain distinct).
subscribeInternal(store, path, invalidate) is the runtime invalidation phase.
Native State stores call every matching invalidation before ordinary subscribers,
regardless of registration order. Invalidation callbacks should mark cached reads
stale; public side effects belong in ordinary subscriptions. Foreign structural
Store implementations use ordinary subscription fallback and do not acquire the
native ordering guarantee.
Separate View modules can nest correctly when they share one State module instance. Independent State module copies have independent reader hooks; they do not automatically share tracking. Use a shared dependency instance when composing multiple View bundles.
subscriptionCount(store) reports the actual number of live subscriptions,
including runtime readers, for diagnostics. It reads the existing store count;
there are no profiling counters on the notification path. A destroyed native store
reports zero; an unrelated structural Store implementation reports undefined.
A computed root-commit experiment was rejected: an unchanged class getter subscribed
through a Store captured by the public reader was read 0 times by the existing
path-selective replacement and 2 times by the candidate. The original computed
publication implementation is retained; the differential is covered by
computed-publication.test.ts.
