@pyreon/state-tree 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-present Vit Bokisch
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,249 @@
1
+ # @pyreon/state-tree
2
+
3
+ Structured reactive state trees with signal-backed models, computed views, actions, snapshots, JSON patches, and middleware.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ bun add @pyreon/state-tree
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```ts
14
+ import { model, getSnapshot, onPatch } from "@pyreon/state-tree"
15
+ import { computed } from "@pyreon/reactivity"
16
+
17
+ const Counter = model({
18
+ state: { count: 0 },
19
+ views: (self) => ({
20
+ doubled: computed(() => self.count() * 2),
21
+ }),
22
+ actions: (self) => ({
23
+ inc: () => self.count.update((c) => c + 1),
24
+ reset: () => self.count.set(0),
25
+ }),
26
+ })
27
+
28
+ const counter = Counter.create({ count: 5 })
29
+ counter.count() // 5
30
+ counter.inc()
31
+ counter.doubled() // 12
32
+
33
+ getSnapshot(counter) // { count: 6 }
34
+ ```
35
+
36
+ Models are defined once, then instantiated with `.create()` or used as singletons with `.asHook(id)`.
37
+
38
+ ## API
39
+
40
+ ### `model(config)`
41
+
42
+ Define a reactive model. Returns a `ModelDefinition` with `.create()` and `.asHook()`.
43
+
44
+ | Parameter | Type | Description |
45
+ | --- | --- | --- |
46
+ | `config.state` | `StateShape` | Plain object — each key becomes a `Signal<T>` on the instance |
47
+ | `config.views` | `(self) => Record<string, Computed>` | Factory returning computed signals for derived state |
48
+ | `config.actions` | `(self) => Record<string, Function>` | Factory returning functions that mutate state |
49
+
50
+ **Returns:** `ModelDefinition<TState, TActions, TViews>`
51
+
52
+ The `self` parameter in views and actions is strongly typed for state signals and loosely typed for actions/views to avoid circular type issues.
53
+
54
+ ```ts
55
+ const Todo = model({
56
+ state: { text: "", done: false },
57
+ views: (self) => ({
58
+ summary: computed(() => `${self.done() ? "[x]" : "[ ]"} ${self.text()}`),
59
+ }),
60
+ actions: (self) => ({
61
+ toggle: () => self.done.update((d) => !d),
62
+ }),
63
+ })
64
+ ```
65
+
66
+ ### `ModelDefinition.create(initial?)`
67
+
68
+ Create an independent model instance, optionally overriding default state values.
69
+
70
+ | Parameter | Type | Description |
71
+ | --- | --- | --- |
72
+ | `initial` | `Partial<Snapshot<TState>>` | Partial snapshot to override defaults |
73
+
74
+ **Returns:** `ModelInstance<TState, TActions, TViews>`
75
+
76
+ ```ts
77
+ const todo = Todo.create({ text: "Buy milk" })
78
+ todo.text() // "Buy milk"
79
+ todo.done() // false (default)
80
+ ```
81
+
82
+ ### `ModelDefinition.asHook(id)`
83
+
84
+ Return a singleton hook function. Every call returns the same instance for the given ID.
85
+
86
+ | Parameter | Type | Description |
87
+ | --- | --- | --- |
88
+ | `id` | `string` | Unique identifier for the singleton |
89
+
90
+ **Returns:** `() => ModelInstance<TState, TActions, TViews>`
91
+
92
+ ```ts
93
+ const useCounter = Counter.asHook("app-counter")
94
+ const a = useCounter()
95
+ const b = useCounter()
96
+ // a === b (same instance)
97
+ ```
98
+
99
+ ### `getSnapshot(instance)`
100
+
101
+ Serialize a model instance to a plain JS object. Nested model instances are recursively serialized.
102
+
103
+ | Parameter | Type | Description |
104
+ | --- | --- | --- |
105
+ | `instance` | `object` | A model instance created via `.create()` or `.asHook()` |
106
+
107
+ **Returns:** `Snapshot<TState>`
108
+
109
+ ```ts
110
+ getSnapshot(counter) // { count: 6 }
111
+ ```
112
+
113
+ ### `applySnapshot(instance, snapshot)`
114
+
115
+ Restore state from a plain object. Writes are batched for a single reactive flush. Missing keys are left unchanged.
116
+
117
+ | Parameter | Type | Description |
118
+ | --- | --- | --- |
119
+ | `instance` | `object` | Target model instance |
120
+ | `snapshot` | `Partial<Snapshot<TState>>` | Partial or full snapshot to apply |
121
+
122
+ ```ts
123
+ applySnapshot(counter, { count: 0 })
124
+ counter.count() // 0
125
+ ```
126
+
127
+ ### `onPatch(instance, listener)`
128
+
129
+ Subscribe to state mutations as JSON patches. Returns an unsubscribe function.
130
+
131
+ | Parameter | Type | Description |
132
+ | --- | --- | --- |
133
+ | `instance` | `object` | Model instance to observe |
134
+ | `listener` | `PatchListener` | Callback receiving `Patch` objects |
135
+
136
+ **Returns:** `() => void` (unsubscribe)
137
+
138
+ ```ts
139
+ const unsub = onPatch(counter, (patch) => {
140
+ console.log(patch) // { op: "replace", path: "/count", value: 7 }
141
+ })
142
+ counter.inc()
143
+ unsub()
144
+ ```
145
+
146
+ ### `applyPatch(instance, patch)`
147
+
148
+ Apply a JSON patch (or array of patches) to a model instance. Only `"replace"` operations are supported. Multiple patches are batched.
149
+
150
+ | Parameter | Type | Description |
151
+ | --- | --- | --- |
152
+ | `instance` | `object` | Target model instance |
153
+ | `patch` | `Patch \| Patch[]` | Single patch or array of patches |
154
+
155
+ ```ts
156
+ applyPatch(counter, { op: "replace", path: "/count", value: 10 })
157
+
158
+ // Replay recorded patches (undo/redo, time-travel):
159
+ applyPatch(counter, [
160
+ { op: "replace", path: "/count", value: 1 },
161
+ { op: "replace", path: "/count", value: 2 },
162
+ ])
163
+ ```
164
+
165
+ ### `addMiddleware(instance, middleware)`
166
+
167
+ Intercept every action call. Middlewares run in registration order. Call `next(call)` to continue the chain.
168
+
169
+ | Parameter | Type | Description |
170
+ | --- | --- | --- |
171
+ | `instance` | `object` | Model instance |
172
+ | `middleware` | `MiddlewareFn` | `(call, next) => unknown` |
173
+
174
+ **Returns:** `() => void` (unsubscribe)
175
+
176
+ ```ts
177
+ const unsub = addMiddleware(counter, (call, next) => {
178
+ console.log(`> ${call.name}(${call.args})`)
179
+ const result = next(call)
180
+ console.log(`< ${call.name}`)
181
+ return result
182
+ })
183
+ ```
184
+
185
+ ### `resetHook(id)` / `resetAllHooks()`
186
+
187
+ Clear singleton instances created via `.asHook()`. Useful for testing and HMR.
188
+
189
+ | Parameter | Type | Description |
190
+ | --- | --- | --- |
191
+ | `id` | `string` | Hook ID to reset (for `resetHook`) |
192
+
193
+ ```ts
194
+ resetHook("app-counter") // Clear one hook
195
+ resetAllHooks() // Clear all hooks
196
+ ```
197
+
198
+ ## Patterns
199
+
200
+ ### Nested Models
201
+
202
+ Use `ModelDefinition` values in `state` to compose models. Snapshots and patches resolve nested paths automatically.
203
+
204
+ ```ts
205
+ const Profile = model({ state: { name: "", age: 0 } })
206
+
207
+ const App = model({
208
+ state: { title: "My App", profile: Profile },
209
+ })
210
+
211
+ const app = App.create({ title: "Hello", profile: { name: "Alice", age: 30 } })
212
+ getSnapshot(app) // { title: "Hello", profile: { name: "Alice", age: 30 } }
213
+ ```
214
+
215
+ ### Time-Travel Debugging
216
+
217
+ Record patches and replay them to implement undo/redo.
218
+
219
+ ```ts
220
+ const history: Patch[] = []
221
+ onPatch(counter, (p) => history.push(p))
222
+
223
+ counter.inc()
224
+ counter.inc()
225
+
226
+ applySnapshot(counter, { count: 0 })
227
+ applyPatch(counter, history) // replays to count: 2
228
+ ```
229
+
230
+ ## Types
231
+
232
+ | Type | Description |
233
+ | --- | --- |
234
+ | `ModelDefinition` | Returned by `model()` — has `.create()` and `.asHook()` |
235
+ | `ModelInstance` | The instance type: state signals + actions + views |
236
+ | `ModelSelf` | The `self` type inside views/actions factories |
237
+ | `StateShape` | `Record<string, unknown>` — the state config shape |
238
+ | `Snapshot` | Recursive plain-object serialization of state |
239
+ | `Patch` | `{ op: "replace", path: string, value: unknown }` |
240
+ | `PatchListener` | `(patch: Patch) => void` |
241
+ | `ActionCall` | `{ name: string, args: unknown[], path: string }` |
242
+ | `MiddlewareFn` | `(call: ActionCall, next: (call: ActionCall) => unknown) => unknown` |
243
+
244
+ ## Gotchas
245
+
246
+ - Only `"replace"` patches are supported — no `"add"` or `"remove"` operations.
247
+ - `applySnapshot` leaves missing keys unchanged; it does not delete extra state.
248
+ - `self` inside actions/views is loosely typed for non-state keys to prevent circular type resolution. Use explicit types if needed.
249
+ - Always call `resetAllHooks()` in test `afterEach` to prevent singleton leakage between tests.