@asaidimu/ui-store
v1.0.0
Published
Framework-agnostic reactive store core with actions, artifacts, persistence, validation and composition helpers.
Maintainers
Readme
@asaidimu/ui-store
Framework-agnostic reactive store core built on top of
@asaidimu/utils-store. It adds:
- Actions — named, bound state mutations with lifecycle tracking.
- Artifacts — lazily resolved async resources/services with dependency
tracking via
@asaidimu/utils-artifacts. - Transformers and validators — pluggable state-update pipelines.
- Readiness tracking —
ready,onReady()andisReady()for stores backed by asynchronous persistence. - Composition helpers —
mergeStoreDefinitions()for combining disjoint store definitions. - Disposal —
dispose()releases middleware, listeners and artifacts.
This package deliberately does not depend on React (or any other UI
framework). A framework adapter should depend on @asaidimu/ui-store and
layer its own reactive bindings on top of the returned CoreStore.
Installation
bun add @asaidimu/ui-store
# or: npm install @asaidimu/ui-storeQuick start
import { createCoreStore } from "@asaidimu/ui-store";
type CounterState = {
count: number;
step: number;
};
const counter = createCoreStore({
state: { count: 0, step: 1 } satisfies CounterState,
actions: {
increment: ({ state }) => ({ count: state.count + state.step }),
setStep: (_ctx, step: number) => ({ step }),
},
});
await counter.actions.increment();
await counter.actions.setStep(5);
await counter.actions.increment();
console.log(counter.getState()); // { count: 6, step: 5 }
// Always release resources when the store is no longer needed.
await counter.dispose();createCoreStore() returns a CoreStore:
| Member | Description |
| --------------- | ---------------------------------------------------------------- |
| store | The underlying ReactiveDataStore instance. |
| artifacts | The ArtifactContainer managing async resources. |
| actions | Boundary-safe action functions (the internal context is hidden). |
| getState() | Non-reactive state snapshot. |
| ready | Promise resolving when persistence is initialised. |
| onReady(cb) | Subscribe to readiness; returns an unsubscribe function. |
| isReady() | Synchronous readiness check. |
| observer | StoreObserver instance when metrics are enabled. |
| actionTracker | In-flight/completed action tracker when metrics are enabled. |
| dispose() | Releases middleware, listeners, observers and artifacts. |
Artifacts
Artifacts are async services or resources resolved through the store. They can be singletons or transients, depend on state, and be invalidated automatically when their dependencies change.
import { createCoreStore } from "@asaidimu/ui-store";
type AppState = { apiUrl: string };
const app = createCoreStore({
state: { apiUrl: "/api/v1" } satisfies AppState,
artifacts: {
api: {
factory: async ({ use }) => {
const baseUrl = await use(({ select }) =>
select((state: AppState) => state.apiUrl),
);
return {
get: (path: string) => fetch(`${baseUrl}${path}`),
};
},
},
},
actions: {
setApiUrl: (_ctx, apiUrl: string) => ({ apiUrl }),
},
});
const api = await app.artifacts.require("api");Changing apiUrl invalidates the api singleton; the next resolution builds
it against the new base URL.
Transformers and validators
transform middlewares run before state is committed and may return a patched
update. validate middlewares are blocking: returning false rejects the
update.
const store = createCoreStore({
state: { count: 0 },
actions: {
add: (_ctx, amount: number) => ({ count: amount }),
},
transform: {
clamp: (_ctx, update) => ({
count: Math.max(0, Number(update.count ?? 0)),
}),
},
validate: {
finite: (_ctx, update) =>
update.count === undefined || Number.isFinite(update.count),
},
});Transformer and validator functions receive an ActionContext with state,
store, resolve() and require().
Persistence
Pass a SimplePersistence implementation to createCoreStore to hydrate the
store and persist subsequent changes:
import { createCoreStore } from "@asaidimu/ui-store";
import { WebStoragePersistence } from "@asaidimu/utils-persistence";
const persistence = new WebStoragePersistence<{ theme: string }>({
app: "my-app",
version: "1.0.0",
storageKey: "settings",
});
const store = createCoreStore({ state: { theme: "light" } }, { persistence });
await store.ready;Use broadcastChannel to synchronise the store across browser tabs when the
underlying ReactiveDataStore supports it.
Composing definitions
mergeStoreDefinitions(base, supplied) combines two disjoint definitions into
one. Any key declared by both definitions throws immediately, so accidental
overwrites are caught at startup.
import { createCoreStore, mergeStoreDefinitions } from "@asaidimu/ui-store";
const base = {
state: { userId: "" },
actions: {
setUser: (_ctx: any, userId: string) => ({ userId }),
},
} as const;
const feature = {
state: { panelOpen: false },
actions: {
togglePanel: ({ state }: any) => ({ panelOpen: !state.panelOpen }),
},
} as const;
const store = createCoreStore(
mergeStoreDefinitions(base as any, feature as any),
);The merged type preserves each definition's state, actions and artifact registry.
Metrics, observation and disposal
const store = createCoreStore({ state: { count: 0 } }, { enableMetrics: true });
store.observer?.getEventHistory();
store.actionTracker?.getExecutions();
await store.dispose();dispose() is idempotent. It does not dispose a ReactiveDataStore
supplied through StoreOptions.store, because that store may be shared with
code outside this CoreStore.
Development
bunx vitest run src/ui-storeLicense
MIT
