statepatch 0.1.0__tar.gz → 0.2.0__tar.gz
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.
- {statepatch-0.1.0 → statepatch-0.2.0}/PKG-INFO +1 -1
- {statepatch-0.1.0 → statepatch-0.2.0}/pyproject.toml +1 -1
- statepatch-0.2.0/src/statepatch/__init__.py +22 -0
- statepatch-0.1.0/src/statepatch/__init__.py → statepatch-0.2.0/src/statepatch/_core.py +24 -97
- statepatch-0.2.0/src/statepatch/_wire.py +94 -0
- {statepatch-0.1.0 → statepatch-0.2.0}/tests/test_observable.py +32 -4
- {statepatch-0.1.0 → statepatch-0.2.0}/.gitignore +0 -0
- {statepatch-0.1.0 → statepatch-0.2.0}/README.md +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: statepatch
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Immer-style ops over a plain JSON tree: observables that emit every mutation as an op
|
|
5
5
|
Project-URL: Repository, https://github.com/assistant-ui/harness-sdk
|
|
6
6
|
License-Expression: MIT
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Immer-style ops over a plain JSON tree.
|
|
2
|
+
|
|
3
|
+
An ``Observable`` wraps one value: ``.value`` reads a plain snapshot, every
|
|
4
|
+
mutation applies to the tree and emits the matching ``Op`` to subscribers.
|
|
5
|
+
Observables compose: an observable stored inside another mounts its op
|
|
6
|
+
stream at that path; removing it detaches it, live and reusable.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from ._core import Observable, Proxy, append, observable
|
|
10
|
+
from ._wire import Listener, Op, Path, Segment, plain
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"observable",
|
|
14
|
+
"Observable",
|
|
15
|
+
"Proxy",
|
|
16
|
+
"plain",
|
|
17
|
+
"append",
|
|
18
|
+
"Op",
|
|
19
|
+
"Path",
|
|
20
|
+
"Segment",
|
|
21
|
+
"Listener",
|
|
22
|
+
]
|
|
@@ -1,96 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
from typing import Any, Callable, Iterator
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
mutation applies to the tree and emits the matching ``Op`` to subscribers.
|
|
5
|
-
Observables compose: an observable stored inside another mounts its op
|
|
6
|
-
stream at that path; removing it detaches it, live and reusable.
|
|
7
|
-
"""
|
|
8
|
-
|
|
9
|
-
import math
|
|
10
|
-
from datetime import datetime
|
|
11
|
-
from typing import Any, Callable, Iterator, NamedTuple
|
|
12
|
-
|
|
13
|
-
Segment = str | int
|
|
14
|
-
Path = tuple[Segment, ...]
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
class Op(NamedTuple):
|
|
18
|
-
kind: str # "replace" | "add" | "remove"
|
|
19
|
-
path: Path
|
|
20
|
-
value: Any = None
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
Listener = Callable[[Op], None]
|
|
24
|
-
|
|
25
|
-
_MAX_SAFE_INT = 2**53 - 1
|
|
26
|
-
_MISSING: Any = object()
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def _snapshot(node: Any) -> Any:
|
|
30
|
-
if isinstance(node, Observable):
|
|
31
|
-
return _snapshot(node._state)
|
|
32
|
-
if isinstance(node, dict):
|
|
33
|
-
return {key: _snapshot(item) for key, item in node.items()}
|
|
34
|
-
if isinstance(node, list):
|
|
35
|
-
return [_snapshot(item) for item in node]
|
|
36
|
-
return node
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
def plain(value: Any) -> Any:
|
|
40
|
-
"""Resolve a proxy or observable to a plain snapshot; pass anything else through."""
|
|
41
|
-
if isinstance(value, Proxy):
|
|
42
|
-
_owner, _rel, node = value._target()
|
|
43
|
-
return _snapshot(node)
|
|
44
|
-
if isinstance(value, Observable):
|
|
45
|
-
return _snapshot(value._state)
|
|
46
|
-
return value
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
def _adopt(value: Any, base: Path) -> tuple[Any, list[tuple[Path, "Observable"]]]:
|
|
50
|
-
"""Validated deep copy keeping ``Observable`` nodes in place; returns the
|
|
51
|
-
stored tree and the mount points found inside it (paths rooted at ``base``)."""
|
|
52
|
-
mounts: list[tuple[Path, Observable]] = []
|
|
53
|
-
|
|
54
|
-
def walk(value: Any, path: Path) -> Any:
|
|
55
|
-
if isinstance(value, Observable):
|
|
56
|
-
mounts.append((path, value))
|
|
57
|
-
return value
|
|
58
|
-
if isinstance(value, Proxy):
|
|
59
|
-
value = plain(value)
|
|
60
|
-
if isinstance(value, bool) or value is None or isinstance(value, str):
|
|
61
|
-
return value
|
|
62
|
-
if isinstance(value, float):
|
|
63
|
-
if math.isnan(value) or math.isinf(value):
|
|
64
|
-
raise ValueError(f"{value!r} is not wire-encodable; floats must be finite")
|
|
65
|
-
return value
|
|
66
|
-
if isinstance(value, int):
|
|
67
|
-
if abs(value) > _MAX_SAFE_INT:
|
|
68
|
-
raise ValueError(
|
|
69
|
-
f"integer {value} exceeds the JS safe range (|n| <= 2**53-1); send it as a string"
|
|
70
|
-
)
|
|
71
|
-
return value
|
|
72
|
-
if isinstance(value, datetime):
|
|
73
|
-
if value.tzinfo is None or value.tzinfo.utcoffset(value) is None:
|
|
74
|
-
raise ValueError("naive datetime is not wire-encodable; attach a timezone")
|
|
75
|
-
return value
|
|
76
|
-
if isinstance(value, (list, tuple)):
|
|
77
|
-
return [walk(item, path + (i,)) for i, item in enumerate(value)]
|
|
78
|
-
if isinstance(value, dict):
|
|
79
|
-
out: dict[str, Any] = {}
|
|
80
|
-
for key, item in value.items():
|
|
81
|
-
if not isinstance(key, str):
|
|
82
|
-
raise TypeError(f"object keys must be strings, got {type(key).__name__}")
|
|
83
|
-
out[key] = walk(item, path + (key,))
|
|
84
|
-
return out
|
|
85
|
-
raise TypeError(f"{type(value).__name__} is not wire-encodable")
|
|
86
|
-
|
|
87
|
-
return walk(value, base), mounts
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
def _index(container: Any, key: Any) -> Any:
|
|
91
|
-
if isinstance(container, list) and isinstance(key, int) and key < 0:
|
|
92
|
-
return key + len(container)
|
|
93
|
-
return key
|
|
3
|
+
from ._wire import _MISSING, Listener, Op, Path, Segment, _adopt, _index, _snapshot, plain
|
|
94
4
|
|
|
95
5
|
|
|
96
6
|
class Observable:
|
|
@@ -220,6 +130,8 @@ class Observable:
|
|
|
220
130
|
return node._target(())
|
|
221
131
|
return self, path, node
|
|
222
132
|
|
|
133
|
+
# container delegators
|
|
134
|
+
|
|
223
135
|
def __getitem__(self, key: Any) -> Any:
|
|
224
136
|
return Proxy(self, ())[key]
|
|
225
137
|
|
|
@@ -320,11 +232,7 @@ class Proxy:
|
|
|
320
232
|
else container[key]
|
|
321
233
|
)
|
|
322
234
|
path = rel + (key,)
|
|
323
|
-
if isinstance(old, str) and
|
|
324
|
-
if value == old:
|
|
325
|
-
return
|
|
326
|
-
container[key] = value
|
|
327
|
-
owner._emit(Op("add", path + (len(old),), value[len(old) :]))
|
|
235
|
+
if isinstance(old, str) and value == old:
|
|
328
236
|
return
|
|
329
237
|
stored, mounts = _adopt(value, path)
|
|
330
238
|
owner._admit(mounts, path)
|
|
@@ -522,3 +430,22 @@ class Proxy:
|
|
|
522
430
|
def __repr__(self) -> str:
|
|
523
431
|
_owner, _rel, node = self._target()
|
|
524
432
|
return repr(_snapshot(node))
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def append(parent: Any, key: Segment, suffix: str) -> None:
|
|
436
|
+
"""Append ``suffix`` to the string at ``parent[key]``, recording an end-offset text-insert ``add`` op."""
|
|
437
|
+
if isinstance(parent, Observable):
|
|
438
|
+
parent = Proxy(parent, ())
|
|
439
|
+
if not isinstance(parent, Proxy):
|
|
440
|
+
raise TypeError(f"append expects a proxy or observable, got {type(parent).__name__}")
|
|
441
|
+
if not isinstance(suffix, str):
|
|
442
|
+
raise TypeError(f"append suffix must be a string, got {type(suffix).__name__}")
|
|
443
|
+
owner, rel, container = parent._target()
|
|
444
|
+
key = _index(container, key)
|
|
445
|
+
old = container[key]
|
|
446
|
+
if not isinstance(old, str):
|
|
447
|
+
raise TypeError(f"cannot append to a non-string at path {list(rel + (key,))!r}")
|
|
448
|
+
if suffix == "":
|
|
449
|
+
return
|
|
450
|
+
container[key] = old + suffix
|
|
451
|
+
owner._emit(Op("add", rel + (key, len(old)), suffix))
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from typing import TYPE_CHECKING, Any, Callable, NamedTuple
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from ._core import Observable
|
|
7
|
+
|
|
8
|
+
Segment = str | int
|
|
9
|
+
Path = tuple[Segment, ...]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Op(NamedTuple):
|
|
13
|
+
kind: str # "replace" | "add" | "remove"
|
|
14
|
+
path: Path
|
|
15
|
+
value: Any = None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
Listener = Callable[[Op], None]
|
|
19
|
+
|
|
20
|
+
_MAX_SAFE_INT = 2**53 - 1
|
|
21
|
+
_MISSING: Any = object()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _snapshot(node: Any) -> Any:
|
|
25
|
+
from ._core import Observable
|
|
26
|
+
|
|
27
|
+
if isinstance(node, Observable):
|
|
28
|
+
return _snapshot(node._state)
|
|
29
|
+
if isinstance(node, dict):
|
|
30
|
+
return {key: _snapshot(item) for key, item in node.items()}
|
|
31
|
+
if isinstance(node, list):
|
|
32
|
+
return [_snapshot(item) for item in node]
|
|
33
|
+
return node
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def plain(value: Any) -> Any:
|
|
37
|
+
"""Resolve a proxy or observable to a plain snapshot; pass anything else through."""
|
|
38
|
+
from ._core import Observable, Proxy
|
|
39
|
+
|
|
40
|
+
if isinstance(value, Proxy):
|
|
41
|
+
_owner, _rel, node = value._target()
|
|
42
|
+
return _snapshot(node)
|
|
43
|
+
if isinstance(value, Observable):
|
|
44
|
+
return _snapshot(value._state)
|
|
45
|
+
return value
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _adopt(value: Any, base: Path) -> tuple[Any, list[tuple[Path, "Observable"]]]:
|
|
49
|
+
"""Validated deep copy keeping ``Observable`` nodes in place; returns the
|
|
50
|
+
stored tree and the mount points found inside it (paths rooted at ``base``)."""
|
|
51
|
+
from ._core import Observable, Proxy
|
|
52
|
+
|
|
53
|
+
mounts: list[tuple[Path, Observable]] = []
|
|
54
|
+
|
|
55
|
+
def walk(value: Any, path: Path) -> Any:
|
|
56
|
+
if isinstance(value, Observable):
|
|
57
|
+
mounts.append((path, value))
|
|
58
|
+
return value
|
|
59
|
+
if isinstance(value, Proxy):
|
|
60
|
+
value = plain(value)
|
|
61
|
+
if isinstance(value, bool) or value is None or isinstance(value, str):
|
|
62
|
+
return value
|
|
63
|
+
if isinstance(value, float):
|
|
64
|
+
if math.isnan(value) or math.isinf(value):
|
|
65
|
+
raise ValueError(f"{value!r} is not wire-encodable; floats must be finite")
|
|
66
|
+
return value
|
|
67
|
+
if isinstance(value, int):
|
|
68
|
+
if abs(value) > _MAX_SAFE_INT:
|
|
69
|
+
raise ValueError(
|
|
70
|
+
f"integer {value} exceeds the JS safe range (|n| <= 2**53-1); send it as a string"
|
|
71
|
+
)
|
|
72
|
+
return value
|
|
73
|
+
if isinstance(value, datetime):
|
|
74
|
+
if value.tzinfo is None or value.tzinfo.utcoffset(value) is None:
|
|
75
|
+
raise ValueError("naive datetime is not wire-encodable; attach a timezone")
|
|
76
|
+
return value
|
|
77
|
+
if isinstance(value, (list, tuple)):
|
|
78
|
+
return [walk(item, path + (i,)) for i, item in enumerate(value)]
|
|
79
|
+
if isinstance(value, dict):
|
|
80
|
+
out: dict[str, Any] = {}
|
|
81
|
+
for key, item in value.items():
|
|
82
|
+
if not isinstance(key, str):
|
|
83
|
+
raise TypeError(f"object keys must be strings, got {type(key).__name__}")
|
|
84
|
+
out[key] = walk(item, path + (key,))
|
|
85
|
+
return out
|
|
86
|
+
raise TypeError(f"{type(value).__name__} is not wire-encodable")
|
|
87
|
+
|
|
88
|
+
return walk(value, base), mounts
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _index(container: Any, key: Any) -> Any:
|
|
92
|
+
if isinstance(container, list) and isinstance(key, int) and key < 0:
|
|
93
|
+
return key + len(container)
|
|
94
|
+
return key
|
|
@@ -4,7 +4,7 @@ mounted observables forward their op streams at the mount path."""
|
|
|
4
4
|
from datetime import datetime, timezone
|
|
5
5
|
|
|
6
6
|
import pytest
|
|
7
|
-
from statepatch import Op, observable
|
|
7
|
+
from statepatch import Op, append, observable
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
def collect(obs):
|
|
@@ -27,18 +27,46 @@ def test_dict_and_list_mutations_emit_wire_shaped_ops():
|
|
|
27
27
|
state["status"] = "streaming"
|
|
28
28
|
state["messages"].append({"id": "m1", "content": ""})
|
|
29
29
|
state["messages"][0]["content"] = "hel"
|
|
30
|
-
state["messages"][0]["content"] = "hello" #
|
|
30
|
+
state["messages"][0]["content"] = "hello" # assign is always a replace
|
|
31
31
|
state["messages"].pop(0)
|
|
32
32
|
assert ops == [
|
|
33
33
|
Op("replace", ("status",), "streaming"),
|
|
34
34
|
Op("add", ("messages", 0), {"id": "m1", "content": ""}),
|
|
35
|
-
Op("
|
|
36
|
-
Op("
|
|
35
|
+
Op("replace", ("messages", 0, "content"), "hel"),
|
|
36
|
+
Op("replace", ("messages", 0, "content"), "hello"),
|
|
37
37
|
Op("remove", ("messages", 0)),
|
|
38
38
|
]
|
|
39
39
|
assert state.value == {"status": "streaming", "messages": []}
|
|
40
40
|
|
|
41
41
|
|
|
42
|
+
def test_append_emits_an_end_offset_string_add():
|
|
43
|
+
state = observable({"text": "he", "parts": ["ab"]})
|
|
44
|
+
ops = collect(state)
|
|
45
|
+
append(state, "text", "llo")
|
|
46
|
+
append(state["parts"], 0, "c")
|
|
47
|
+
append(state, "text", "") # empty suffix is a no-op
|
|
48
|
+
assert state.value == {"text": "hello", "parts": ["abc"]}
|
|
49
|
+
assert ops == [
|
|
50
|
+
Op("add", ("text", 2), "llo"),
|
|
51
|
+
Op("add", ("parts", 0, 2), "c"),
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_append_fails_fast_on_bad_targets():
|
|
56
|
+
state = observable({"n": 1, "text": "hi"})
|
|
57
|
+
ops = collect(state)
|
|
58
|
+
with pytest.raises(TypeError, match="non-string"):
|
|
59
|
+
append(state, "n", "x")
|
|
60
|
+
with pytest.raises(TypeError, match="suffix must be a string"):
|
|
61
|
+
append(state, "text", 1)
|
|
62
|
+
with pytest.raises(KeyError):
|
|
63
|
+
append(state, "missing", "x")
|
|
64
|
+
with pytest.raises(TypeError, match="proxy or observable"):
|
|
65
|
+
append({"text": "hi"}, "text", "x")
|
|
66
|
+
assert state.value == {"n": 1, "text": "hi"}
|
|
67
|
+
assert ops == []
|
|
68
|
+
|
|
69
|
+
|
|
42
70
|
def test_values_are_dealised_on_write():
|
|
43
71
|
state = observable({})
|
|
44
72
|
held = {"a": [1]}
|
|
File without changes
|
|
File without changes
|