accordsync-core 0.3.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.
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .pytest_cache/
7
+ .mypy_cache/
8
+ .ruff_cache/
9
+ /interop/node/node_modules/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.5
2
+ Name: accordsync-core
3
+ Version: 0.3.0
4
+ Summary: Accord's merge core: hybrid logical clocks, operations, lww, counter, set and conflict.
5
+ Project-URL: Homepage, https://accord.benhattab.pro
6
+ Project-URL: Source, https://github.com/crossben/accordsync-python
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: crdt,local-first,offline-first,sync
10
+ Requires-Python: >=3.11
11
+ Description-Content-Type: text/markdown
12
+
13
+ # accordsync-core
14
+
15
+ **Accord's merge core for Python: hybrid logical clocks, operations and the four merge strategies.**
16
+
17
+ Pure Python, no I/O, no dependencies. Most programs use the client
18
+ [`accordsync`](https://pypi.org/project/accordsync/) or the server
19
+ [`accordsync-server`](https://pypi.org/project/accordsync-server/), which depend on it. Python 3.11+.
20
+
21
+ ```sh
22
+ pip install accordsync-core
23
+ ```
24
+
25
+ | Strategy | Merges by |
26
+ | --- | --- |
27
+ | `lww()` | Highest hybrid logical clock wins. |
28
+ | `counter()` | Sum of every increment; none is ever lost. |
29
+ | `set_()` | Add-wins set: a remove only removes what its writer had seen. |
30
+ | `conflict()` | Concurrent values are all kept and the field is flagged; a resolution supersedes exactly the values its writer saw. |
31
+
32
+ `set_()` has a trailing underscore so it does not shadow Python's `set`.
33
+
34
+ ```python
35
+ import time
36
+
37
+ from accordsync_core import LocalWriter, conflict, counter, define_schema
38
+
39
+ schema = define_schema({"dossier": {"visits": counter(), "status": conflict()}})
40
+
41
+
42
+ def now() -> int:
43
+ return time.time_ns() // 1_000_000
44
+
45
+
46
+ a = LocalWriter(schema, "phone-a", now)
47
+ b = LocalWriter(schema, "phone-b", now)
48
+
49
+ # Each device writes offline...
50
+ from_a = [a.inc("dossier:1", "visits", 1), a.assign("dossier:1", "status", "approved")]
51
+ from_b = [b.inc("dossier:1", "visits", 2), b.assign("dossier:1", "status", "rejected")]
52
+
53
+ # ...then they exchange ops, in any order, as often as the network repeats them.
54
+ for op in from_b + from_b:
55
+ a.receive(op)
56
+ for op in reversed(from_a):
57
+ b.receive(op)
58
+
59
+ assert a.replica.snapshot() == b.replica.snapshot()
60
+ print(a.replica.read("dossier:1"))
61
+ # {'visits': 3, 'status': {'conflicted': [{'value': 'approved', 'opId': 'phone-a:2'},
62
+ # {'value': 'rejected', 'opId': 'phone-b:2'}]}}
63
+ ```
64
+
65
+ It merges byte for byte like [`@accordsync/core`](https://www.npmjs.com/package/@accordsync/core):
66
+ the test suite runs the shared golden vectors in every delivery order, and random scenarios
67
+ generated by the TypeScript core must produce identical snapshots here.
68
+
69
+ Docs: [accord.benhattab.pro/docs/schema](https://accord.benhattab.pro/docs/schema/) ·
70
+ Source: [crossben/accordsync-python](https://github.com/crossben/accordsync-python) · Licence: Apache-2.0
@@ -0,0 +1,58 @@
1
+ # accordsync-core
2
+
3
+ **Accord's merge core for Python: hybrid logical clocks, operations and the four merge strategies.**
4
+
5
+ Pure Python, no I/O, no dependencies. Most programs use the client
6
+ [`accordsync`](https://pypi.org/project/accordsync/) or the server
7
+ [`accordsync-server`](https://pypi.org/project/accordsync-server/), which depend on it. Python 3.11+.
8
+
9
+ ```sh
10
+ pip install accordsync-core
11
+ ```
12
+
13
+ | Strategy | Merges by |
14
+ | --- | --- |
15
+ | `lww()` | Highest hybrid logical clock wins. |
16
+ | `counter()` | Sum of every increment; none is ever lost. |
17
+ | `set_()` | Add-wins set: a remove only removes what its writer had seen. |
18
+ | `conflict()` | Concurrent values are all kept and the field is flagged; a resolution supersedes exactly the values its writer saw. |
19
+
20
+ `set_()` has a trailing underscore so it does not shadow Python's `set`.
21
+
22
+ ```python
23
+ import time
24
+
25
+ from accordsync_core import LocalWriter, conflict, counter, define_schema
26
+
27
+ schema = define_schema({"dossier": {"visits": counter(), "status": conflict()}})
28
+
29
+
30
+ def now() -> int:
31
+ return time.time_ns() // 1_000_000
32
+
33
+
34
+ a = LocalWriter(schema, "phone-a", now)
35
+ b = LocalWriter(schema, "phone-b", now)
36
+
37
+ # Each device writes offline...
38
+ from_a = [a.inc("dossier:1", "visits", 1), a.assign("dossier:1", "status", "approved")]
39
+ from_b = [b.inc("dossier:1", "visits", 2), b.assign("dossier:1", "status", "rejected")]
40
+
41
+ # ...then they exchange ops, in any order, as often as the network repeats them.
42
+ for op in from_b + from_b:
43
+ a.receive(op)
44
+ for op in reversed(from_a):
45
+ b.receive(op)
46
+
47
+ assert a.replica.snapshot() == b.replica.snapshot()
48
+ print(a.replica.read("dossier:1"))
49
+ # {'visits': 3, 'status': {'conflicted': [{'value': 'approved', 'opId': 'phone-a:2'},
50
+ # {'value': 'rejected', 'opId': 'phone-b:2'}]}}
51
+ ```
52
+
53
+ It merges byte for byte like [`@accordsync/core`](https://www.npmjs.com/package/@accordsync/core):
54
+ the test suite runs the shared golden vectors in every delivery order, and random scenarios
55
+ generated by the TypeScript core must produce identical snapshots here.
56
+
57
+ Docs: [accord.benhattab.pro/docs/schema](https://accord.benhattab.pro/docs/schema/) ·
58
+ Source: [crossben/accordsync-python](https://github.com/crossben/accordsync-python) · Licence: Apache-2.0
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "accordsync-core"
3
+ version = "0.3.0"
4
+ description = "Accord's merge core: hybrid logical clocks, operations, lww, counter, set and conflict."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ keywords = ["offline-first", "sync", "crdt", "local-first"]
10
+ dependencies = [
11
+ ]
12
+
13
+ [project.urls]
14
+ Homepage = "https://accord.benhattab.pro"
15
+ Source = "https://github.com/crossben/accordsync-python"
16
+
17
+ [build-system]
18
+ requires = ["hatchling>=1.26"]
19
+ build-backend = "hatchling.build"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/accordsync_core"]
23
+
24
+ [tool.ruff]
25
+ extend = "../../pyproject.toml"
26
+ src = ["src", "tests"]
27
+
28
+ [tool.ruff.lint.per-file-ignores]
29
+ # Seeded generators are the point of the law and vector tests; the awkward characters are on purpose.
30
+ "tests/**" = ["S311", "RUF001"]
@@ -0,0 +1,90 @@
1
+ """Accord's merge core: hybrid logical clocks, operations and the four merge strategies."""
2
+
3
+ from .canonical import canonical_json
4
+ from .errors import AccordError, ClockSkewError
5
+ from .hlc import MAX_COUNTER, MAX_SAFE_INTEGER, Hlc, assert_node, compare_hlc
6
+ from .op import (
7
+ AddOp,
8
+ AssignOp,
9
+ IncOp,
10
+ JsonValue,
11
+ Op,
12
+ OpId,
13
+ OpKind,
14
+ ParsedOpId,
15
+ RemoveOp,
16
+ SetElement,
17
+ compare_op_ids,
18
+ parse_op_id,
19
+ record_type,
20
+ )
21
+ from .replica import ApplyResult, FieldRef, RecordSnapshot, Replica
22
+ from .schema import (
23
+ KINDS,
24
+ RecordFields,
25
+ Schema,
26
+ Strategy,
27
+ StrategyName,
28
+ conflict,
29
+ counter,
30
+ define_schema,
31
+ fields_of,
32
+ lww,
33
+ set_,
34
+ strategy_for,
35
+ )
36
+ from .strategies import ABSENT, FieldSnapshot
37
+ from .wire import WireOp, decode_op, encode_op
38
+ from .writer import DEFAULT_MAX_SKEW_MS, LocalWriter
39
+
40
+ PROTOCOL_VERSION = 1
41
+ """The Accord sync protocol this package speaks (docs/protocol.md in the Accord repository).
42
+ A breaking change to the wire format bumps it."""
43
+
44
+ __all__ = [
45
+ "ABSENT",
46
+ "DEFAULT_MAX_SKEW_MS",
47
+ "KINDS",
48
+ "MAX_COUNTER",
49
+ "MAX_SAFE_INTEGER",
50
+ "PROTOCOL_VERSION",
51
+ "AccordError",
52
+ "AddOp",
53
+ "ApplyResult",
54
+ "AssignOp",
55
+ "ClockSkewError",
56
+ "FieldRef",
57
+ "FieldSnapshot",
58
+ "Hlc",
59
+ "IncOp",
60
+ "JsonValue",
61
+ "LocalWriter",
62
+ "Op",
63
+ "OpId",
64
+ "OpKind",
65
+ "ParsedOpId",
66
+ "RecordFields",
67
+ "RecordSnapshot",
68
+ "RemoveOp",
69
+ "Replica",
70
+ "Schema",
71
+ "SetElement",
72
+ "Strategy",
73
+ "StrategyName",
74
+ "WireOp",
75
+ "assert_node",
76
+ "canonical_json",
77
+ "compare_hlc",
78
+ "compare_op_ids",
79
+ "conflict",
80
+ "counter",
81
+ "decode_op",
82
+ "define_schema",
83
+ "encode_op",
84
+ "fields_of",
85
+ "lww",
86
+ "parse_op_id",
87
+ "record_type",
88
+ "set_",
89
+ "strategy_for",
90
+ ]
@@ -0,0 +1,15 @@
1
+ """String helpers that make Python strings behave like JavaScript's UTF-16 strings."""
2
+
3
+
4
+ def utf16_key(s: str) -> bytes:
5
+ """Sort key giving JavaScript's `a < b` order: by UTF-16 code unit, not by code point.
6
+
7
+ The two differ for characters above U+FFFF (surrogate pairs, 0xD800...) against U+E000-U+FFFF.
8
+ `surrogatepass` keeps lone surrogates, which JSON may carry and JavaScript strings may hold.
9
+ """
10
+ return s.encode("utf-16-be", "surrogatepass")
11
+
12
+
13
+ def utf16_len(s: str) -> int:
14
+ """`s.length` in JavaScript: the number of UTF-16 code units."""
15
+ return len(utf16_key(s)) // 2
@@ -0,0 +1,122 @@
1
+ """Canonical JSON, byte for byte what the TypeScript core's `canonicalJson` prints.
2
+
3
+ That is `JSON.stringify` of objects built from code-unit-sorted keys, so this reproduces
4
+ JavaScript rather than Python's `json` module:
5
+ - keys that are array indices ("0".."4294967294", no leading zeros) come first in numeric order,
6
+ because JavaScript objects always order them that way; the others follow by UTF-16 code unit;
7
+ - numbers print as JavaScript prints them: `1` not `1.0`, `0` for `-0.0`, `1e-7`, `1e+21`;
8
+ - strings escape exactly like `JSON.stringify` (lone surrogates as `\\udXXX`, the rest raw).
9
+ """
10
+
11
+ import math
12
+ import re
13
+ from collections.abc import Iterable, Mapping
14
+ from decimal import Decimal
15
+
16
+ from ._text import utf16_key
17
+
18
+ MAX_ARRAY_INDEX = 4294967294
19
+ _ARRAY_INDEX = re.compile(r"0|[1-9][0-9]*")
20
+ _SHORT_ESCAPES = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r"}
21
+ _SHORT_ESCAPES["\t"] = "\\t"
22
+
23
+
24
+ def canonical_json(value: object) -> str:
25
+ out: list[str] = []
26
+ _write(out, value)
27
+ return "".join(out)
28
+
29
+
30
+ def _write(out: list[str], value: object) -> None:
31
+ # `bool` first: it is a subclass of `int`.
32
+ if value is None:
33
+ out.append("null")
34
+ elif type(value) is bool:
35
+ out.append("true" if value else "false")
36
+ elif isinstance(value, int | float):
37
+ out.append(js_number(value))
38
+ elif isinstance(value, str):
39
+ out.append(js_string(value))
40
+ elif isinstance(value, list | tuple):
41
+ out.append("[")
42
+ for i, v in enumerate(value):
43
+ if i:
44
+ out.append(",")
45
+ _write(out, v)
46
+ out.append("]")
47
+ elif isinstance(value, Mapping):
48
+ out.append("{")
49
+ for i, k in enumerate(js_key_order(value.keys())):
50
+ if i:
51
+ out.append(",")
52
+ out.append(js_string(k))
53
+ out.append(":")
54
+ _write(out, value[k])
55
+ out.append("}")
56
+ else:
57
+ raise TypeError(f"canonical_json: not a JSON value: {type(value).__name__}")
58
+
59
+
60
+ def js_key_order(keys: Iterable[object]) -> list[str]:
61
+ """The order JavaScript gives the keys of an object built from code-unit-sorted entries."""
62
+ indices: list[str] = []
63
+ others: list[str] = []
64
+ for k in keys:
65
+ if not isinstance(k, str):
66
+ raise TypeError(f"canonical_json: object keys must be strings, got {k!r}")
67
+ if _ARRAY_INDEX.fullmatch(k) and int(k) <= MAX_ARRAY_INDEX:
68
+ indices.append(k)
69
+ else:
70
+ others.append(k)
71
+ indices.sort(key=int)
72
+ others.sort(key=utf16_key)
73
+ return indices + others
74
+
75
+
76
+ def js_number(n: int | float) -> str:
77
+ """A number as JavaScript's `String(n)` / `JSON.stringify` prints it."""
78
+ if isinstance(n, int):
79
+ # JavaScript numbers are doubles: an integer past 2^53 prints as the double it rounds to.
80
+ if abs(n) <= 2**53:
81
+ return str(n)
82
+ n = float(n)
83
+ if not math.isfinite(n):
84
+ return "null"
85
+ if n == 0:
86
+ return "0" # also -0.0
87
+ sign = "-" if n < 0 else ""
88
+ # repr gives the shortest digits that round-trip, as JavaScript does; only the layout differs.
89
+ # The value is 0.DIGITS x 10^point (the k digits and n of ECMAScript's Number::toString).
90
+ t = Decimal(repr(abs(n))).normalize().as_tuple()
91
+ digits = "".join(map(str, t.digits))
92
+ point = len(digits) + int(t.exponent)
93
+ k = len(digits)
94
+ if k <= point <= 21:
95
+ return sign + digits + "0" * (point - k)
96
+ if 0 < point <= 21:
97
+ return sign + digits[:point] + "." + digits[point:]
98
+ if -6 < point <= 0:
99
+ return sign + "0." + "0" * -point + digits
100
+ e = point - 1
101
+ e_str = f"e+{e}" if e >= 0 else f"e-{-e}"
102
+ if k == 1:
103
+ return sign + digits + e_str
104
+ return sign + digits[0] + "." + digits[1:] + e_str
105
+
106
+
107
+ def js_string(s: str) -> str:
108
+ """A string as `JSON.stringify` prints it."""
109
+ # Re-pair surrogates first: a high and a low surrogate side by side are one character to
110
+ # JavaScript, printed raw; only lone surrogates are escaped.
111
+ s = s.encode("utf-16-be", "surrogatepass").decode("utf-16-be", "surrogatepass")
112
+ out = ['"']
113
+ for ch in s:
114
+ c = ord(ch)
115
+ if ch in _SHORT_ESCAPES:
116
+ out.append(_SHORT_ESCAPES[ch])
117
+ elif c < 0x20 or 0xD800 <= c <= 0xDFFF:
118
+ out.append(f"\\u{c:04x}")
119
+ else:
120
+ out.append(ch)
121
+ out.append('"')
122
+ return "".join(out)
@@ -0,0 +1,9 @@
1
+ """Errors raised by the core."""
2
+
3
+
4
+ class AccordError(ValueError):
5
+ """Invalid input: a malformed op, a write that does not fit the schema, a bad snapshot."""
6
+
7
+
8
+ class ClockSkewError(AccordError):
9
+ """A remote clock too far ahead of this device's physical time."""