@litforge/state
v0.1.22
Published
Core state management library for LitForge projects. Provides a flexible event-sourcing system with persistence, snapshots, and Redux DevTools integration.
Downloads
551
Readme
@litforge/state
Core state management library for LitForge projects. Provides a flexible event-sourcing system with persistence, snapshots, and Redux DevTools integration.
Overview
@litforge/state is a framework-agnostic state management library that uses an event-sourcing pattern. It tracks all state changes as events, supports snapshots for performance, and provides persistence mechanisms for browser and Node.js environments.
Key Features
- Event Sourcing: All state changes are tracked as immutable events
- Persistence: Built-in support for browser (IndexedDB/localStorage) and Node.js (file system)
- Snapshots: Create state snapshots for efficient replay
- Redux DevTools: Full integration with Redux DevTools extension
- TypeScript: Fully typed with TypeScript support
- Framework Agnostic: Works with any framework or vanilla JavaScript
Installation
npm install @litforge/state
# or
pnpm add @litforge/state
# or
yarn add @litforge/stateBasic Usage
Creating a State System
import { createStateSystem, BrowserPersistor } from '@litforge/state';
const stateSystem = createStateSystem({
persistor: new BrowserPersistor(), // Optional: defaults to BrowserPersistor
});
// Load persisted state
await stateSystem.loadFromPersistor();Pushing Events
// Push an event
const event = stateSystem.push({
type: 'USER_LOGIN',
payload: { userId: '123', username: 'john' },
meta: { source: 'login-form' }
});Creating Snapshots
const currentState = { user: { id: '123' }, todos: [] };
const snapshot = stateSystem.snapshot(currentState);Subscribing to Events
const unsubscribe = stateSystem.subscribe((event) => {
console.log('New event:', event);
});
// Later, unsubscribe
unsubscribe();Replaying Events
await stateSystem.replay(
targetIndex,
(event, index) => {
// Apply event to your state
applyEventToState(event);
},
(snapshot) => {
// Restore from snapshot (optional)
restoreState(snapshot.state);
}
);Export/Import
// Export state
const json = stateSystem.export();
// Import state
await stateSystem.import(json);Singleton Pattern
For convenience, you can use the singleton pattern:
import { initStateSystem, getStateSystem } from '@litforge/state';
// Initialize (typically in your app setup)
await initStateSystem({
connectDevtools: true,
getState: () => yourCurrentState,
restoreState: (state) => { /* restore state */ },
name: 'MyApp'
});
// Get the instance anywhere
const stateSystem = getStateSystem();Persistors
BrowserPersistor
Uses IndexedDB with localStorage fallback:
import { BrowserPersistor } from '@litforge/state';
const persistor = new BrowserPersistor();NodeFilePersistor
For Node.js environments:
import { NodeFilePersistor } from '@litforge/state';
const persistor = new NodeFilePersistor('./state_store.json');Custom Persistor
Implement the Persistor interface:
import type { Persistor, Persisted } from '@litforge/state';
class MyCustomPersistor implements Persistor {
async save(data: Persisted): Promise<void> {
// Your save logic
}
async load(): Promise<Persisted | null> {
// Your load logic
}
}Redux DevTools Integration
import { connectReduxDevtools } from '@litforge/state';
const cleanup = connectReduxDevtools(
stateSystem,
() => yourCurrentState,
{
restoreState: (state) => { /* restore */ },
name: 'MyApp'
}
);Types
import type {
Event,
Snapshot,
Persistor,
Subscriber,
Persisted
} from '@litforge/state';API Reference
ActionLog
Main class for managing events and snapshots.
push(event): Add a new eventsnapshot(state): Create a state snapshotgetEvents(from, to): Get events in a rangesubscribe(fn): Subscribe to new eventsreplay(index, applyEvent, restoreSnapshot): Replay eventsexport(): Export state as JSONimport(json): Import state from JSONloadFromPersistor(): Load persisted state
License
Part of the LitForge component library.
