KSync Class
TheKSync class is the main interface for creating and managing real-time synchronized data stores. It provides methods for event handling, storage management, and synchronization.
Constructor
new KSync(options?)
Creates a new KSync instance.
options(optional): Configuration objectstorage: Storage adapter for persisting eventssyncClient: Client for synchronizing with remote peersmode: Synchronization mode (‘event-sourcing’ | ‘crdt’)
Properties
events
- Type:
Map<string, any> - Description: Read-only map of all events in the store
- Example:
state
- Type:
any - Description: Current materialized state of the store
- Example:
version
- Type:
number - Description: Current version/sequence number of the store
- Example:
Core Methods
emit(eventType, data)
Emits a new event to the store.
eventType(string): Type of the eventdata(any): Event payload data
Promise<void>
on(eventType, handler)
Registers an event listener.
eventType(string): Event type to listen for, or ’*’ for all eventshandler(function): Event handler function
() => void (unsubscribe function)
off(eventType, handler)
Removes an event listener.
eventType(string): Event typehandler(function): Handler function to remove
materialize(materializer)
Sets up a materializer function to compute derived state.
materializer(function): Function that takes events and returns computed state
query(queryFn)
Queries the current state.
queryFn(function): Function that receives current state and returns filtered data
Synchronization Methods
sync()
Manually triggers synchronization with remote peers.
Promise<void>
connect()
Connects to the sync server (if using WebSocket sync).
Promise<void>
disconnect()
Disconnects from the sync server.
Promise<void>
CRDT Methods
When using CRDT mode, additional methods are available:createLWWRegister(key, initialValue)
Creates a Last-Write-Wins register.
createGSet(key, initialItems?)
Creates a Grow-only Set.
createGCounter(key, initialValue?)
Creates a Grow-only Counter.
getCRDT(key)
Retrieves an existing CRDT by key.
Storage Methods
persist()
Manually triggers persistence to storage.
Promise<void>
load()
Loads events from storage.
Promise<void>
clear()
Clears all events and resets the store.
Promise<void>
Event Lifecycle
Event Object Structure
Every event in kSync has the following structure:Event Flow
- Emit:
emit()creates a new event - Validate: Event is validated and assigned an ID/version
- Store: Event is added to the event store
- Materialize: State is recomputed using the materializer
- Notify: Event listeners are triggered
- Persist: Event is saved to storage (if configured)
- Sync: Event is sent to remote peers (if connected)

