state-sync-log 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +277 -0
- package/dist/state-sync-log.esm.js +1339 -0
- package/dist/state-sync-log.esm.mjs +1339 -0
- package/dist/state-sync-log.umd.js +1343 -0
- package/dist/types/ClientId.d.ts +1 -0
- package/dist/types/SortedTxEntry.d.ts +44 -0
- package/dist/types/StateCalculator.d.ts +141 -0
- package/dist/types/TxRecord.d.ts +14 -0
- package/dist/types/checkpointUtils.d.ts +15 -0
- package/dist/types/checkpoints.d.ts +62 -0
- package/dist/types/clientState.d.ts +19 -0
- package/dist/types/createStateSyncLog.d.ts +97 -0
- package/dist/types/draft.d.ts +69 -0
- package/dist/types/error.d.ts +4 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/json.d.ts +23 -0
- package/dist/types/operations.d.ts +64 -0
- package/dist/types/reconcile.d.ts +7 -0
- package/dist/types/txLog.d.ts +32 -0
- package/dist/types/txTimestamp.d.ts +27 -0
- package/dist/types/utils.d.ts +23 -0
- package/package.json +94 -0
- package/src/ClientId.ts +1 -0
- package/src/SortedTxEntry.ts +83 -0
- package/src/StateCalculator.ts +407 -0
- package/src/TxRecord.ts +15 -0
- package/src/checkpointUtils.ts +44 -0
- package/src/checkpoints.ts +208 -0
- package/src/clientState.ts +37 -0
- package/src/createStateSyncLog.ts +330 -0
- package/src/draft.ts +288 -0
- package/src/error.ts +12 -0
- package/src/index.ts +8 -0
- package/src/json.ts +25 -0
- package/src/operations.ts +157 -0
- package/src/reconcile.ts +124 -0
- package/src/txLog.ts +208 -0
- package/src/txTimestamp.ts +56 -0
- package/src/utils.ts +55 -0
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2019 Javier González Garcés
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="./logo.png" height="220" />
|
|
3
|
+
</p>
|
|
4
|
+
<p align="center">
|
|
5
|
+
<i>State synchronization log for collaborative applications. <b>Validate every change before it happens.</b></i>
|
|
6
|
+
</p>
|
|
7
|
+
|
|
8
|
+
<p align="center">
|
|
9
|
+
<a aria-label="NPM version" href="https://www.npmjs.com/package/state-sync-log">
|
|
10
|
+
<img src="https://img.shields.io/npm/v/state-sync-log.svg?style=for-the-badge&logo=npm&labelColor=333" />
|
|
11
|
+
</a>
|
|
12
|
+
<a aria-label="License" href="./LICENSE">
|
|
13
|
+
<img src="https://img.shields.io/npm/l/state-sync-log.svg?style=for-the-badge&labelColor=333" />
|
|
14
|
+
</a>
|
|
15
|
+
<a aria-label="Types" href="./packages/state-sync-log/tsconfig.json">
|
|
16
|
+
<img src="https://img.shields.io/npm/types/state-sync-log.svg?style=for-the-badge&logo=typescript&labelColor=333" />
|
|
17
|
+
</a>
|
|
18
|
+
<br />
|
|
19
|
+
<a aria-label="CI" href="https://github.com/xaviergonz/state-sync-log/actions/workflows/main.yml">
|
|
20
|
+
<img src="https://img.shields.io/github/actions/workflow/status/xaviergonz/state-sync-log/main.yml?branch=master&label=CI&logo=github&style=for-the-badge&labelColor=333" />
|
|
21
|
+
</a>
|
|
22
|
+
<a aria-label="Codecov" href="https://codecov.io/gh/xaviergonz/state-sync-log">
|
|
23
|
+
<img src="https://img.shields.io/codecov/c/github/xaviergonz/state-sync-log?token=6MLRFUBK8V&label=codecov&logo=codecov&style=for-the-badge&labelColor=333" />
|
|
24
|
+
</a>
|
|
25
|
+
</p>
|
|
26
|
+
|
|
27
|
+
## The Problem with Standard CRDTs
|
|
28
|
+
|
|
29
|
+
Tools like Yjs and Automerge are amazing for text editing because **they never reject a change**—they just merge everything.
|
|
30
|
+
|
|
31
|
+
But for **business applications**, most often than not we have rules where "merging everything" can result in a bug. For example, if you have a "WIP Limit" of 3 tasks in a Kanban board and users drag two tasks in at once, you end up with 4 tasks.
|
|
32
|
+
|
|
33
|
+
## The Solution: state-sync-log
|
|
34
|
+
|
|
35
|
+
`state-sync-log` is a **Validated Replicated State Machine**. It uses the same robust technology as Yjs in its core (networking, offline support), but it fundamentally changes the rules:
|
|
36
|
+
|
|
37
|
+
**Every transaction is validated against your business logic before it is applied.**
|
|
38
|
+
|
|
39
|
+
If a peer sends an invalid transaction your clients **reject it strictly and deterministically**, even when the change itself was made while offline.
|
|
40
|
+
|
|
41
|
+
### Comparison
|
|
42
|
+
|
|
43
|
+
| Feature | state-sync-log | Standard CRDTs (Yjs, Automerge) |
|
|
44
|
+
| :--- | :---: | :---: |
|
|
45
|
+
| **Conflict Strategy** | 🫸 **Reject Invalid Changes** | 🔀 **Merge Everything** |
|
|
46
|
+
| **Data Model** | Plain JSON | Specialized Types (Y.Map, Y.Array) |
|
|
47
|
+
| **Validation** | ✅ First-class citizen | ❌ Not possible (by design) |
|
|
48
|
+
| **Best For** | Business logic, Forms, Games, CRUD, Complex editors | Text editing, Drawing, Notes |
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## Example: Kanban Board with WIP Limits
|
|
53
|
+
|
|
54
|
+
Imagine a Kanban board where you strictly enforce a limit of **3 tasks** in the "Doing" column.
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { createStateSyncLog } from "state-sync-log"
|
|
58
|
+
import * as Y from "yjs"
|
|
59
|
+
|
|
60
|
+
type Task = { id: string; title: string; status: "todo" | "doing" | "done" }
|
|
61
|
+
type State = { tasks: Task[] }
|
|
62
|
+
|
|
63
|
+
// 1. Define your business rules
|
|
64
|
+
const validate = (state: State) => {
|
|
65
|
+
// RULE: Cannot have more than 3 tasks in 'doing'
|
|
66
|
+
const doingCount = state.tasks.filter(t => t.status === "doing").length
|
|
67
|
+
if (doingCount > 3) return false
|
|
68
|
+
|
|
69
|
+
// RULE: Tasks must always have a title
|
|
70
|
+
if (state.tasks.some(t => t.title.trim() === "")) return false
|
|
71
|
+
|
|
72
|
+
return true
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 2. Initialize the log
|
|
76
|
+
const log = createStateSyncLog<State>({
|
|
77
|
+
yDoc: new Y.Doc(),
|
|
78
|
+
validate,
|
|
79
|
+
// ... other options
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
// 3. Try to move a 4th task to "doing"
|
|
83
|
+
// If another user already filled the slot, this operation
|
|
84
|
+
// will be REJECTED on all clients (including this one).
|
|
85
|
+
log.emit([
|
|
86
|
+
{ kind: "set", path: ["tasks", 3], key: "status", value: "doing" }
|
|
87
|
+
])
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Features
|
|
91
|
+
|
|
92
|
+
- 🛡️ **Bulletproof Validation**: Define a single `(state) => boolean` function. If it returns false, the transaction never happened.
|
|
93
|
+
- ⏭️ **Replayable History**: Since it's an event log, you can replay history to see exactly *how* a state was reached (up to the nearest checkpoint).
|
|
94
|
+
- 🏎️ **Optimistic UI**: Changes apply instantly locally. If they are later rejected (due to a conflict with a remote peer), the state automatically rolls back.
|
|
95
|
+
- 📦 **Plain JSON**: Work with standard JS objects and arrays. No need to learn `ymap.get('foo')` syntax.
|
|
96
|
+
- 🔌 **Network Agnostic**: Works with any Yjs provider (WebSockets, WebRTC, IndexedDB).
|
|
97
|
+
- 💾 **Storage Efficient**: Built-in compaction and retention policies keep your data small and fast.
|
|
98
|
+
|
|
99
|
+
## Contents
|
|
100
|
+
|
|
101
|
+
- [Installation](#installation)
|
|
102
|
+
- [API Reference](#api-reference)
|
|
103
|
+
- [Operations](#operations)
|
|
104
|
+
- [Gotchas & Limitations](#gotchas--limitations)
|
|
105
|
+
- [Contributing](#contributing)
|
|
106
|
+
- [License](#license)
|
|
107
|
+
|
|
108
|
+
## Installation
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
npm install state-sync-log
|
|
112
|
+
# or
|
|
113
|
+
pnpm add state-sync-log
|
|
114
|
+
# or
|
|
115
|
+
yarn add state-sync-log
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## Storage Efficiency
|
|
119
|
+
|
|
120
|
+
Since this is an append-only log, you might worry about it growing forever. We solved that.
|
|
121
|
+
|
|
122
|
+
### 🗜️ Automatic Compaction & Retention
|
|
123
|
+
|
|
124
|
+
`state-sync-log` can periodically be asked to compact the log into a **snapshot checkpoint**.
|
|
125
|
+
|
|
126
|
+
- **Checkpoints:** New peers just load the latest snapshot + recent ops. Fast load times!
|
|
127
|
+
- **Retention Window:** Old transaction history is automatically pruned after a set time (recommended: 2 weeks).
|
|
128
|
+
- **Result:** You get a full audit trail for recent history, without unboundedly growing storage.
|
|
129
|
+
|
|
130
|
+
## Integration with MobX, Signals, etc
|
|
131
|
+
|
|
132
|
+
You don't have to replace your existing state manager. `state-sync-log` is designed to drive them.
|
|
133
|
+
|
|
134
|
+
Using `applyOps`, you can surgically apply updates to **MobX**, **Preact Signals**, or any mutable store:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import { applyOps } from "state-sync-log"
|
|
138
|
+
import { observable } from "mobx"
|
|
139
|
+
|
|
140
|
+
// 1. Create your mutable MobX store (init with current state)
|
|
141
|
+
const store = observable(log.getState())
|
|
142
|
+
|
|
143
|
+
// 2. Sync it!
|
|
144
|
+
// 2. Sync it!
|
|
145
|
+
log.subscribe((newState, getAppliedOps) => {
|
|
146
|
+
// getAppliedOps is a lazy getter (computing reconciliation diffs only when requested)
|
|
147
|
+
const appliedOps = getAppliedOps()
|
|
148
|
+
|
|
149
|
+
// Apply ONLY the changes (efficient!)
|
|
150
|
+
applyOps(appliedOps, store)
|
|
151
|
+
})
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
By default, `applyOps` deep clones values before inserting them to prevent aliasing. For better performance, you can disable cloning if you guarantee op values won't be mutated:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
// Calculate ops first
|
|
158
|
+
const appliedOps = getAppliedOps()
|
|
159
|
+
applyOps(appliedOps, store, { cloneValues: false })
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## API Reference
|
|
163
|
+
|
|
164
|
+
### `createStateSyncLog(options)`
|
|
165
|
+
|
|
166
|
+
Initializes the synchronization log.
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import { createStateSyncLog } from "state-sync-log"
|
|
170
|
+
|
|
171
|
+
const log = createStateSyncLog<State>({
|
|
172
|
+
yDoc: new Y.Doc(),
|
|
173
|
+
validate: (state) => state.inventory >= 0
|
|
174
|
+
})
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
**Options:**
|
|
178
|
+
|
|
179
|
+
| Option | Type | Description |
|
|
180
|
+
| --- | --- | --- |
|
|
181
|
+
| `yDoc` | `Y.Doc` | **Required.** The Yjs document instance. |
|
|
182
|
+
| `validate` | `(state: State) => boolean` | **Required.** The gatekeeper function. If it returns `false`, the transaction is dropped. |
|
|
183
|
+
| `clientId` | `string` | Optional unique ID. Auto-generated if omitted. |
|
|
184
|
+
| `retentionWindowMs` | `number` | Time to keep transaction history before pruning (recommended: 2 weeks). Helps keep storage small. |
|
|
185
|
+
|
|
186
|
+
### `StateSyncLogController`
|
|
187
|
+
|
|
188
|
+
The object returned by `createStateSyncLog`.
|
|
189
|
+
|
|
190
|
+
#### `getState(): State`
|
|
191
|
+
|
|
192
|
+
Returns the current, validated state. Uses structural sharing for efficient immutable updates.
|
|
193
|
+
|
|
194
|
+
#### `emit(ops: Op[]): void`
|
|
195
|
+
|
|
196
|
+
Propose a change. The change applies optimistically but may be reverted if it conflicts with a remote change that renders it invalid.
|
|
197
|
+
|
|
198
|
+
#### `subscribe(callback): UnsubscribeFn`
|
|
199
|
+
|
|
200
|
+
Listen for state changes. The callback receives the new state and a lazy getter function for the operations applied.
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
log.subscribe((newState, getAppliedOps) => {
|
|
204
|
+
const appliedOps = getAppliedOps()
|
|
205
|
+
render(newState)
|
|
206
|
+
})
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
#### `reconcileState(targetState: State): void`
|
|
210
|
+
|
|
211
|
+
Automatically calculates the operations needed to turn the current state into `targetState` and emits them. Great for "Reset to Default" features.
|
|
212
|
+
|
|
213
|
+
#### `compact(): void`
|
|
214
|
+
|
|
215
|
+
Manually triggers a checkpoint. This compresses the history into a single snapshot to save memory and load time.
|
|
216
|
+
|
|
217
|
+
#### `dispose(): void`
|
|
218
|
+
|
|
219
|
+
Stop listening and cleanup.
|
|
220
|
+
|
|
221
|
+
## Operations
|
|
222
|
+
|
|
223
|
+
These are the atomic building blocks of your transactions.
|
|
224
|
+
|
|
225
|
+
### `set` (Objects)
|
|
226
|
+
|
|
227
|
+
Sets a property on an object.
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
{ kind: "set", path: ["users", "u1"], key: "name", value: "Alice" }
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
### `delete` (Objects)
|
|
234
|
+
|
|
235
|
+
Removes a property (equivalent of setting a property to `undefined`).
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
{ kind: "delete", path: ["users", "u1"], key: "avatarUrl" }
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
### `splice` (Arrays)
|
|
242
|
+
|
|
243
|
+
Insert, remove, or replace items in an array.
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
// Remove 1 item at index 0, insert "New Item"
|
|
247
|
+
{ kind: "splice", path: ["todoList"], index: 0, deleteCount: 1, inserts: ["New Item"] }
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
### `addToSet` (Arrays)
|
|
251
|
+
|
|
252
|
+
Adds an item only if it doesn't exist (like a Set).
|
|
253
|
+
|
|
254
|
+
```ts
|
|
255
|
+
{ kind: "addToSet", path: ["tags"], value: "urgent" }
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
### `deleteFromSet` (Arrays)
|
|
259
|
+
|
|
260
|
+
Removes an item if it exists.
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
{ kind: "deleteFromSet", path: ["tags"], value: "deprecated" }
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
## Gotchas & Limitations
|
|
267
|
+
|
|
268
|
+
1. **Validation must be deterministic:** Your `validate` function must return the same result for the same state input (deterministic). Don't check `Date.now()` or make API calls inside it.
|
|
269
|
+
2. **Not for Text:** Do not use this for collaborative text editing (Google Docs style). Use standard Y.Text for that; you can mix standard Yjs and `state-sync-log` in the same application!
|
|
270
|
+
|
|
271
|
+
## Contributing
|
|
272
|
+
|
|
273
|
+
See [CONTRIBUTING.md](./CONTRIBUTING.md).
|
|
274
|
+
|
|
275
|
+
## License
|
|
276
|
+
|
|
277
|
+
MIT. See [LICENSE](./LICENSE).
|