@kitionstage/sdk 0.0.0-stage → 0.5.2-stage.13

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.
Files changed (259) hide show
  1. package/README.md +73 -2
  2. package/dist/LICENSE +177 -0
  3. package/dist/THIRD_PARTY_NOTICES +28 -0
  4. package/dist/lib/assets/kitEngine.worker-3iMvwtlI.js +12732 -0
  5. package/dist/lib/assets/loro_wasm_bg-Gulzks_0.wasm +0 -0
  6. package/dist/lib/chunks/batch-BWpAyHvP.js +789 -0
  7. package/dist/lib/chunks/canonical-BIWfVCL-.js +87 -0
  8. package/dist/lib/chunks/envelope-D6MGY-ZN.js +61 -0
  9. package/dist/lib/chunks/replica-D8w3I4sn.js +2472 -0
  10. package/dist/lib/chunks/runtime-BVJHE1Pg.js +997 -0
  11. package/dist/lib/chunks/session-BqXC9a1-.js +281 -0
  12. package/dist/lib/chunks/toolIds-BCeSGHpV.js +821 -0
  13. package/dist/lib/chunks/workspaceTree-Destqupf.js +23 -0
  14. package/dist/lib/convergence/index.js +1035 -0
  15. package/dist/lib/convergence/node.js +8 -0
  16. package/dist/lib/embed-server/callbacks.js +37 -0
  17. package/dist/lib/embed-server/cli.js +19 -0
  18. package/dist/lib/embed-server/index.js +272 -0
  19. package/dist/lib/extensions/index.js +439 -0
  20. package/dist/lib/extensions/panel.html +208 -0
  21. package/dist/lib/extensions/runtime.js +198 -0
  22. package/dist/lib/extensions/sandbox.html +35 -0
  23. package/dist/lib/kdm/index.js +437 -0
  24. package/dist/lib/kit-dev-host/checkUiIds.mjs +44 -0
  25. package/dist/lib/kit-dev-host/index.js +308 -0
  26. package/dist/lib/kit-dev-host/lineRow.mjs +47 -0
  27. package/dist/lib/kit-dev-host/modeSmoke.mjs +178 -0
  28. package/dist/lib/kit-editor/index.js +6481 -0
  29. package/dist/lib/kit-editor/styles.css +807 -0
  30. package/dist/lib/kit-editor/workspaceTree.js +1 -0
  31. package/dist/lib/kit-engine/index.js +7 -0
  32. package/dist/lib/kit-host/index.js +530 -0
  33. package/dist/lib/kit-ui-protocol/index.js +336 -0
  34. package/dist/lib/node-only/embed-server-callbacks.js +2 -0
  35. package/dist/lib/node-only/embed-server.js +2 -0
  36. package/dist/lib/sync/index.js +1008 -0
  37. package/dist/lib/sync/openToken.js +201 -0
  38. package/dist/lib/sync/replicaVersions.js +51 -0
  39. package/dist/standalone/chunks/batch-CAGYk6m4.js +789 -0
  40. package/dist/standalone/chunks/client-B9xkOcvf.js +772 -0
  41. package/dist/standalone/chunks/collab-CTQZ9h7J.js +1022 -0
  42. package/dist/standalone/chunks/comment-Ds9t8xSE.js +94 -0
  43. package/dist/standalone/chunks/comments-uVDS8Wxp.js +41 -0
  44. package/dist/standalone/chunks/document-B5MMuYyN.js +324 -0
  45. package/dist/standalone/chunks/envelope-GX4Cynkx.js +7612 -0
  46. package/dist/standalone/chunks/index-BEgEEnhU.js +287 -0
  47. package/dist/standalone/chunks/index-EEl8hGbP.js +1967 -0
  48. package/dist/standalone/chunks/kits-Cp51mDlw.js +9 -0
  49. package/dist/standalone/chunks/replica-Di2iCPiD.js +3281 -0
  50. package/dist/standalone/chunks/replicaVersions-C3rJxnk9.js +50 -0
  51. package/dist/standalone/chunks/touched-T9jKJjxn.js +78 -0
  52. package/dist/standalone/index.js +12 -0
  53. package/dist/standalone/script/index.js +339 -0
  54. package/dist/standalone/script/kits/board.js +5 -0
  55. package/dist/standalone/script/kits/cad.js +5 -0
  56. package/dist/standalone/script/kits/design.js +5 -0
  57. package/dist/standalone/script/kits/doc.js +5 -0
  58. package/dist/standalone/script/kits/film.js +5 -0
  59. package/dist/standalone/script/kits/html.js +5 -0
  60. package/dist/standalone/script/kits/index.js +38 -0
  61. package/dist/standalone/script/kits/layout.js +5 -0
  62. package/dist/standalone/script/kits/motion.js +5 -0
  63. package/dist/standalone/script/kits/note.js +5 -0
  64. package/dist/standalone/script/kits/pdf.js +5 -0
  65. package/dist/standalone/script/kits/photo.js +5 -0
  66. package/dist/standalone/script/kits/scene.js +5 -0
  67. package/dist/standalone/script/kits/sheet.js +5 -0
  68. package/dist/standalone/script/kits/slide.js +5 -0
  69. package/dist/standalone/script/kits/table.js +5 -0
  70. package/dist/standalone/script/kits/vector.js +5 -0
  71. package/dist/standalone/script/node.js +401 -0
  72. package/dist/standalone/script/proxy.js +254 -0
  73. package/dist/types/convergence/src/adapter.d.ts +131 -0
  74. package/dist/types/convergence/src/engine.d.ts +66 -0
  75. package/dist/types/convergence/src/index.d.ts +21 -0
  76. package/dist/types/convergence/src/net.d.ts +52 -0
  77. package/dist/types/convergence/src/node.d.ts +6 -0
  78. package/dist/types/convergence/src/report.d.ts +56 -0
  79. package/dist/types/convergence/src/rng.d.ts +12 -0
  80. package/dist/types/convergence/src/scenarios.d.ts +15 -0
  81. package/dist/types/convergence/src/state.d.ts +67 -0
  82. package/dist/types/embed/src/agent.d.ts +88 -0
  83. package/dist/types/embed/src/blobs.d.ts +2 -0
  84. package/dist/types/embed/src/collab.d.ts +250 -0
  85. package/dist/types/embed/src/comments.d.ts +30 -0
  86. package/dist/types/embed/src/errors.d.ts +24 -0
  87. package/dist/types/embed/src/handlers.d.ts +92 -0
  88. package/dist/types/embed/src/index.d.ts +20 -0
  89. package/dist/types/embed/src/mount.d.ts +39 -0
  90. package/dist/types/embed/src/replicaStore.d.ts +3 -0
  91. package/dist/types/embed/src/rooms.d.ts +40 -0
  92. package/dist/types/embed/src/schemas.d.ts +7 -0
  93. package/dist/types/embed/src/syncClients.d.ts +28 -0
  94. package/dist/types/embed/src/theme.d.ts +7 -0
  95. package/dist/types/embed/src/types.d.ts +596 -0
  96. package/dist/types/embed/src/ui.d.ts +33 -0
  97. package/dist/types/embed/src/version.d.ts +2 -0
  98. package/dist/types/embed-server/src/callbacks.d.ts +30 -0
  99. package/dist/types/embed-server/src/cli.d.ts +1 -0
  100. package/dist/types/embed-server/src/index.d.ts +19 -0
  101. package/dist/types/embed-server/src/page.d.ts +15 -0
  102. package/dist/types/embed-server/src/server.d.ts +39 -0
  103. package/dist/types/embed-server/src/session.d.ts +22 -0
  104. package/dist/types/extensions/src/gate.d.ts +17 -0
  105. package/dist/types/extensions/src/generated/runtime.d.ts +8 -0
  106. package/dist/types/extensions/src/host.d.ts +135 -0
  107. package/dist/types/extensions/src/index.d.ts +13 -0
  108. package/dist/types/extensions/src/manifest.d.ts +82 -0
  109. package/dist/types/extensions/src/protocol.d.ts +159 -0
  110. package/dist/types/extensions/src/rpc.d.ts +52 -0
  111. package/dist/types/extensions/src/runtime/document.d.ts +40 -0
  112. package/dist/types/extensions/src/runtime/index.d.ts +10 -0
  113. package/dist/types/extensions/src/runtime/panel.d.ts +19 -0
  114. package/dist/types/extensions/src/runtime/runtime.d.ts +54 -0
  115. package/dist/types/extensions/src/runtime/worker.d.ts +1 -0
  116. package/dist/types/extensions/src/sandbox.d.ts +41 -0
  117. package/dist/types/kdm/src/args.d.ts +12 -0
  118. package/dist/types/kdm/src/batch.d.ts +118 -0
  119. package/dist/types/kdm/src/canonical.d.ts +25 -0
  120. package/dist/types/kdm/src/comment.d.ts +114 -0
  121. package/dist/types/kdm/src/diff.d.ts +125 -0
  122. package/dist/types/kdm/src/envelope.d.ts +27 -0
  123. package/dist/types/kdm/src/errors.d.ts +28 -0
  124. package/dist/types/kdm/src/footprint.d.ts +21 -0
  125. package/dist/types/kdm/src/ids.d.ts +57 -0
  126. package/dist/types/kdm/src/index.d.ts +18 -0
  127. package/dist/types/kdm/src/marks.d.ts +32 -0
  128. package/dist/types/kdm/src/op.d.ts +124 -0
  129. package/dist/types/kdm/src/origin.d.ts +41 -0
  130. package/dist/types/kdm/src/overlay.d.ts +92 -0
  131. package/dist/types/kdm/src/projection.d.ts +29 -0
  132. package/dist/types/kdm/src/read.d.ts +90 -0
  133. package/dist/types/kdm/src/replica.d.ts +403 -0
  134. package/dist/types/kdm/src/schema.d.ts +185 -0
  135. package/dist/types/kdm/src/testing.d.ts +28 -0
  136. package/dist/types/kdm/src/toolIds.d.ts +61 -0
  137. package/dist/types/kdm/src/touched.d.ts +24 -0
  138. package/dist/types/kdm/src/tx.d.ts +215 -0
  139. package/dist/types/kdm/src/value.d.ts +23 -0
  140. package/dist/types/kit-dev-host/src/checkNoPaths.d.ts +19 -0
  141. package/dist/types/kit-dev-host/src/checkUiIds.d.mts +2 -0
  142. package/dist/types/kit-dev-host/src/index.d.ts +179 -0
  143. package/dist/types/kit-dev-host/src/lineRow.d.mts +14 -0
  144. package/dist/types/kit-dev-host/src/memoryFiles.d.ts +15 -0
  145. package/dist/types/kit-dev-host/src/modeSmoke.d.mts +8 -0
  146. package/dist/types/kit-editor/src/CommandDialog.d.ts +22 -0
  147. package/dist/types/kit-editor/src/CommentsPanel.d.ts +45 -0
  148. package/dist/types/kit-editor/src/CustomizeDialog.d.ts +32 -0
  149. package/dist/types/kit-editor/src/HostButtons.d.ts +11 -0
  150. package/dist/types/kit-editor/src/RenderFailure.d.ts +7 -0
  151. package/dist/types/kit-editor/src/TextSink.d.ts +6 -0
  152. package/dist/types/kit-editor/src/brand.d.ts +2 -0
  153. package/dist/types/kit-editor/src/catalogMenus.d.ts +27 -0
  154. package/dist/types/kit-editor/src/chart.d.ts +138 -0
  155. package/dist/types/kit-editor/src/conflicts.d.ts +12 -0
  156. package/dist/types/kit-editor/src/drawing.d.ts +83 -0
  157. package/dist/types/kit-editor/src/editor.d.ts +544 -0
  158. package/dist/types/kit-editor/src/engine/KitCanvas.d.ts +70 -0
  159. package/dist/types/kit-editor/src/engine/backdrop.d.ts +32 -0
  160. package/dist/types/kit-editor/src/engine/createKitFile.d.ts +12 -0
  161. package/dist/types/kit-editor/src/engine/decorations.d.ts +14 -0
  162. package/dist/types/kit-editor/src/engine/engineOverlays.d.ts +197 -0
  163. package/dist/types/kit-editor/src/engine/engineTools.d.ts +116 -0
  164. package/dist/types/kit-editor/src/engine/kitDraft.d.ts +70 -0
  165. package/dist/types/kit-editor/src/engine/kitEngine.d.ts +390 -0
  166. package/dist/types/kit-editor/src/engine/kitEngine.worker.d.ts +30 -0
  167. package/dist/types/kit-editor/src/engine/kitHost.d.ts +41 -0
  168. package/dist/types/kit-editor/src/engine/kitModel.d.ts +32 -0
  169. package/dist/types/kit-editor/src/engine/kitModelRunner.d.ts +99 -0
  170. package/dist/types/kit-editor/src/engine/kitModule.d.ts +185 -0
  171. package/dist/types/kit-editor/src/engine/kitShortcuts.d.ts +32 -0
  172. package/dist/types/kit-editor/src/engine/kitTools.d.ts +79 -0
  173. package/dist/types/kit-editor/src/engine/lazyFonts.d.ts +34 -0
  174. package/dist/types/kit-editor/src/engine/lentFiles.d.ts +29 -0
  175. package/dist/types/kit-editor/src/engine/rasterViewport.d.ts +178 -0
  176. package/dist/types/kit-editor/src/engine/readOnly.d.ts +78 -0
  177. package/dist/types/kit-editor/src/engine/refusal.d.ts +39 -0
  178. package/dist/types/kit-editor/src/engine/replica.d.ts +23 -0
  179. package/dist/types/kit-editor/src/engine/useKitDocument.d.ts +154 -0
  180. package/dist/types/kit-editor/src/engine/workerRelay.d.ts +62 -0
  181. package/dist/types/kit-editor/src/files.d.ts +74 -0
  182. package/dist/types/kit-editor/src/frame/EditorFrame.d.ts +74 -0
  183. package/dist/types/kit-editor/src/frame/FocusBar.d.ts +10 -0
  184. package/dist/types/kit-editor/src/frame/MenuNodes.d.ts +20 -0
  185. package/dist/types/kit-editor/src/frame/MenuRibbon.d.ts +8 -0
  186. package/dist/types/kit-editor/src/frame/ModeButton.d.ts +7 -0
  187. package/dist/types/kit-editor/src/frame/menus.d.ts +64 -0
  188. package/dist/types/kit-editor/src/frame/modes.d.ts +51 -0
  189. package/dist/types/kit-editor/src/frame/useFrameLayout.d.ts +34 -0
  190. package/dist/types/kit-editor/src/host.d.ts +127 -0
  191. package/dist/types/kit-editor/src/index.d.ts +85 -0
  192. package/dist/types/kit-editor/src/ink.d.ts +26 -0
  193. package/dist/types/kit-editor/src/lease.d.ts +53 -0
  194. package/dist/types/kit-editor/src/oneInFlight.d.ts +7 -0
  195. package/dist/types/kit-editor/src/phrases.d.ts +25 -0
  196. package/dist/types/kit-editor/src/presence.d.ts +79 -0
  197. package/dist/types/kit-editor/src/strings.d.ts +6 -0
  198. package/dist/types/kit-editor/src/toolIcons.d.ts +32 -0
  199. package/dist/types/kit-editor/src/uiCatalog.d.ts +59 -0
  200. package/dist/types/kit-editor/src/uiConfig.d.ts +53 -0
  201. package/dist/types/kit-editor/src/uiContext.d.ts +65 -0
  202. package/dist/types/kit-editor/src/uiStore.d.ts +20 -0
  203. package/dist/types/kit-editor/src/useCommentAnchors.d.ts +29 -0
  204. package/dist/types/kit-editor/src/useKitSession.d.ts +115 -0
  205. package/dist/types/kit-editor/src/workspaceTree.d.ts +5 -0
  206. package/dist/types/kit-engine/src/contract.d.ts +154 -0
  207. package/dist/types/kit-engine/src/index.d.ts +2 -0
  208. package/dist/types/kit-engine/src/session.d.ts +133 -0
  209. package/dist/types/kit-host/src/files.d.ts +163 -0
  210. package/dist/types/kit-host/src/index.d.ts +315 -0
  211. package/dist/types/kit-ui-protocol/src/index.d.ts +1145 -0
  212. package/dist/types/loro-crdt.d.ts +9 -0
  213. package/dist/types/script/kits/board.d.ts +534 -0
  214. package/dist/types/script/kits/cad.d.ts +2937 -0
  215. package/dist/types/script/kits/design.d.ts +3213 -0
  216. package/dist/types/script/kits/doc.d.ts +2575 -0
  217. package/dist/types/script/kits/film.d.ts +4067 -0
  218. package/dist/types/script/kits/html.d.ts +38 -0
  219. package/dist/types/script/kits/index.d.ts +20 -0
  220. package/dist/types/script/kits/layout.d.ts +3483 -0
  221. package/dist/types/script/kits/motion.d.ts +4826 -0
  222. package/dist/types/script/kits/note.d.ts +631 -0
  223. package/dist/types/script/kits/pdf.d.ts +829 -0
  224. package/dist/types/script/kits/photo.d.ts +7574 -0
  225. package/dist/types/script/kits/scene.d.ts +2962 -0
  226. package/dist/types/script/kits/sheet.d.ts +2419 -0
  227. package/dist/types/script/kits/slide.d.ts +1894 -0
  228. package/dist/types/script/kits/table.d.ts +654 -0
  229. package/dist/types/script/kits/vector.d.ts +5167 -0
  230. package/dist/types/script/src/agentRelay.d.ts +48 -0
  231. package/dist/types/script/src/capabilities.d.ts +21 -0
  232. package/dist/types/script/src/document.d.ts +87 -0
  233. package/dist/types/script/src/drafts.d.ts +141 -0
  234. package/dist/types/script/src/exchange.d.ts +30 -0
  235. package/dist/types/script/src/headless.d.ts +190 -0
  236. package/dist/types/script/src/index.d.ts +15 -0
  237. package/dist/types/script/src/kitModel.d.ts +17 -0
  238. package/dist/types/script/src/kits.d.ts +8 -0
  239. package/dist/types/script/src/node.d.ts +42 -0
  240. package/dist/types/script/src/port.d.ts +89 -0
  241. package/dist/types/script/src/proxy.d.ts +132 -0
  242. package/dist/types/script/src/room.d.ts +162 -0
  243. package/dist/types/script/src/sources.d.ts +73 -0
  244. package/dist/types/sync/src/backoff.d.ts +9 -0
  245. package/dist/types/sync/src/blobSection.d.ts +23 -0
  246. package/dist/types/sync/src/capabilities.d.ts +20 -0
  247. package/dist/types/sync/src/client.d.ts +253 -0
  248. package/dist/types/sync/src/framing.d.ts +35 -0
  249. package/dist/types/sync/src/hash.d.ts +2 -0
  250. package/dist/types/sync/src/index.d.ts +19 -0
  251. package/dist/types/sync/src/leases.d.ts +82 -0
  252. package/dist/types/sync/src/openToken.d.ts +104 -0
  253. package/dist/types/sync/src/protocol.d.ts +484 -0
  254. package/dist/types/sync/src/relay.d.ts +52 -0
  255. package/dist/types/sync/src/replicaVersions.d.ts +17 -0
  256. package/dist/types/sync/src/saveMachine.d.ts +83 -0
  257. package/dist/types/sync/src/saveRun.d.ts +52 -0
  258. package/dist/types/sync/src/transport.d.ts +19 -0
  259. package/package.json +229 -4
@@ -0,0 +1,3281 @@
1
+ import { K, s as _, e as h, c as I, g as X, i as ae, a as pe, h as nn, j as sn, k as on, f as P, L as Fe, o as Se, l as xe, V as se, w as We, d as An, b as Vn, U as En } from "./envelope-GX4Cynkx.js";
2
+ function Ue(o) {
3
+ return o === "person" || o === "extension" ? "person" : o === "agent" ? "agent" : null;
4
+ }
5
+ const zs = (o, e) => ({ kind: "person", principal: o, label: e }), Hs = (o, e) => ({ kind: "agent", principal: o, label: e }), Me = (o) => ({ kind: "system", principal: "kdm", label: o });
6
+ function Gs(o) {
7
+ return JSON.stringify([o.kind, o.principal, o.label ?? null]);
8
+ }
9
+ const at = ["person", "agent", "extension", "import", "system"];
10
+ function Qe(o) {
11
+ const e = o !== null && typeof o == "object" ? o : null;
12
+ if (!(e !== null && typeof e.kind == "string" && at.includes(e.kind) && typeof e.principal == "string" && (e.label === void 0 || typeof e.label == "string"))) throw new K("invalid-value", `an origin needs a kind (${at.join(", ")}), a string principal, and an optional string label`);
13
+ }
14
+ function he(o, e) {
15
+ return JSON.stringify([o.kind, o.principal, o.label ?? null, e]);
16
+ }
17
+ function Rn(o) {
18
+ const e = Nn(o);
19
+ if (e === null) return null;
20
+ const t = JSON.parse(o)[3];
21
+ return { origin: e, schemaVersion: typeof t == "number" && Number.isInteger(t) && t >= 0 ? t : null };
22
+ }
23
+ function Nn(o) {
24
+ let e;
25
+ try {
26
+ e = JSON.parse(o);
27
+ } catch {
28
+ return null;
29
+ }
30
+ return !Array.isArray(e) || typeof e[0] != "string" || !at.includes(e[0]) || typeof e[1] != "string" ? null : { kind: e[0], principal: e[1], label: typeof e[2] == "string" ? e[2] : void 0 };
31
+ }
32
+ const ct = (o) => o >= 56320 && o <= 57343;
33
+ function ve(o) {
34
+ let e = "", t = 0;
35
+ for (let n = 0; n < o.length; n += 1) {
36
+ const s = o.charCodeAt(n);
37
+ if (!(s < 55296 || s > 57343)) {
38
+ if (s <= 56319 && ct(o.charCodeAt(n + 1))) {
39
+ n += 1;
40
+ continue;
41
+ }
42
+ e += `${o.slice(t, n)}�`, t = n + 1;
43
+ }
44
+ }
45
+ return t === 0 ? o : e + o.slice(t);
46
+ }
47
+ const Tn = (o) => {
48
+ const e = Object.getPrototypeOf(o);
49
+ return e === Object.prototype || e === null;
50
+ };
51
+ function lt(o, e) {
52
+ const t = /* @__PURE__ */ new Set(), n = (s, i) => {
53
+ const r = (a) => {
54
+ throw e(`holds ${a}${i ? ` at ${i}` : ""}, which is not JSON`);
55
+ };
56
+ switch (typeof s) {
57
+ case "string":
58
+ return ve(s);
59
+ case "boolean":
60
+ return s;
61
+ case "number":
62
+ return Number.isFinite(s) ? s : r(String(s));
63
+ case "object":
64
+ break;
65
+ default:
66
+ return r(typeof s > "u" ? "undefined" : `a ${typeof s}`);
67
+ }
68
+ if (s === null) return null;
69
+ t.has(s) && r("a cycle"), t.add(s);
70
+ try {
71
+ if (Array.isArray(s)) {
72
+ Object.getPrototypeOf(s) !== Array.prototype && r("an array subclass");
73
+ const l = [];
74
+ for (let c = 0; c < s.length; c += 1)
75
+ c in s || r("a hole"), l.push(n(s[c], `${i}[${c}]`));
76
+ return l;
77
+ }
78
+ Tn(s) || r(`a ${s.constructor?.name ?? "non-plain object"}`), Object.getOwnPropertySymbols(s).length > 0 && r("a symbol key");
79
+ const a = {};
80
+ for (const l of Object.keys(s))
81
+ l === "__proto__" && r("a `__proto__` key"), _(a, ve(l), n(s[l], `${i}.${l}`));
82
+ return a;
83
+ } finally {
84
+ t.delete(s);
85
+ }
86
+ };
87
+ return o === void 0 ? null : n(o, "");
88
+ }
89
+ const Ee = 1, At = 2 ** 53, Cn = 2 ** 32 - 1, Dn = (o) => o.kind === "list" || o.kind === "tree" || (o.kind === "ref" || o.kind === "map") && o.owns === !0;
90
+ function Fn(o, e) {
91
+ const t = (i) => typeof i == "object" && i !== null && !Array.isArray(i), n = (i) => typeof i == "string" && i !== "" && e(i) ? i : null, s = [];
92
+ if (!t(o)) return s;
93
+ for (const i of Object.keys(o).sort(I)) {
94
+ const r = o[i], a = n(r);
95
+ if (a !== null)
96
+ s.push([a, i]);
97
+ else if (t(r))
98
+ for (const l of Object.keys(r).sort(I)) {
99
+ const c = n(r[l]);
100
+ c !== null && s.push([c, `${i}.${l}`]);
101
+ }
102
+ }
103
+ return s;
104
+ }
105
+ const Wn = 32;
106
+ function Bn(o) {
107
+ return o === "" ? null : o.length > Wn ? "a prefix has at most 32 characters" : /^[A-Za-z]/.test(o) ? /^[A-Za-z0-9_:/-]*$/.test(o) ? null : "a prefix holds ASCII letters, digits, `_`, `-`, `:`, and `/` only" : "a prefix starts with a letter";
108
+ }
109
+ const Xs = (o) => Object.values(o.types).some((e) => e.toolId !== void 0);
110
+ function Ys(o, e) {
111
+ if (o.readOnly) return !0;
112
+ const t = o.readOnlyWhen;
113
+ if (t === void 0) return !1;
114
+ const n = e(t.field);
115
+ return typeof n == "string" && t.values.includes(n);
116
+ }
117
+ const Pn = ["after", "before", "both", "none"], _n = ["string", "number", "integer", "boolean", "enum", "json", "blob", "ref", "text", "list", "tree", "map"], Jn = ["text", "list", "tree", "map"], Un = ["ref", "list", "tree"], qe = (o) => Jn.includes(o), D = (o) => Object.keys(o).sort(I), A = (o) => o !== null && typeof o == "object" && !Array.isArray(o), Vt = (o) => typeof o == "number" && Number.isInteger(o) && o >= 0 && o <= Cn;
118
+ function U(o, e, t) {
119
+ for (const n of Object.keys(e))
120
+ if (!t.includes(n)) throw h.schema(`${o}: unknown field \`${n}\``);
121
+ }
122
+ function rn(o, e) {
123
+ if (!A(e)) throw h.schema(`${o}: a field definition is an object`);
124
+ if (U(o, e, ["kind", "of", "values", "optional", "marks", "readOnly", "owns", "cascade", "position", "display", "sample", "minimum", "maximum", "multipleOf", "label", "members"]), typeof e.kind != "string" || !_n.includes(e.kind)) throw h.schema(`${o}: unknown kind \`${String(e.kind)}\``);
125
+ const t = { kind: e.kind };
126
+ if (e.label !== void 0 && e.label !== null) {
127
+ if (typeof e.label != "string") throw h.schema(`${o}: label is a string`);
128
+ t.label = e.label;
129
+ }
130
+ for (const n of ["minimum", "maximum", "multipleOf"]) {
131
+ const s = e[n];
132
+ if (s != null) {
133
+ if (!["number", "integer", "json"].includes(t.kind) || typeof s != "number" || !Number.isFinite(s) || n === "multipleOf" && s <= 0) throw h.schema(`${o}: invalid numeric limit ${n}`);
134
+ t[n] = s;
135
+ }
136
+ }
137
+ if (t.minimum !== void 0 && t.maximum !== void 0 && t.minimum > t.maximum) throw h.schema(`${o}: minimum exceeds maximum`);
138
+ if (e.members !== void 0) {
139
+ if (!A(e.members) || !["json", "map"].includes(t.kind) && Object.keys(e.members).length > 0) throw h.schema(`${o}: members requires json or map and an object`);
140
+ t.members = {};
141
+ for (const [n, s] of Object.entries(e.members)) {
142
+ if (n.split(".").some((c) => !/^[^.[\]]+(?:\[\])*$/.test(c))) throw h.schema(`${o}: invalid member path ${n}`);
143
+ if (!A(s)) throw h.schema(`${o}: member limits must be an object`);
144
+ U(o, s, ["minimum", "maximum", "multipleOf", "nullable"]);
145
+ const { nullable: i, ...r } = s;
146
+ if (i !== void 0 && typeof i != "boolean") throw h.schema(`${o}: nullable is a boolean`);
147
+ const a = rn(`${o}.${n}`, { kind: "number", ...r }), l = {};
148
+ i === !0 && (l.nullable = !0);
149
+ for (const c of ["minimum", "maximum", "multipleOf"]) a[c] !== void 0 && (l[c] = a[c]);
150
+ _(t.members, n, l);
151
+ }
152
+ }
153
+ if (e.of !== void 0 && e.of !== null) {
154
+ if (typeof e.of != "string") throw h.schema(`${o}: \`of\` is a type name`);
155
+ t.of = e.of;
156
+ }
157
+ if (e.values !== void 0) {
158
+ if (!Array.isArray(e.values) || !e.values.every((n) => typeof n == "string")) throw h.schema(`${o}: \`values\` is a list of strings`);
159
+ t.values = [...e.values];
160
+ }
161
+ if (e.optional !== void 0) {
162
+ if (typeof e.optional != "boolean") throw h.schema(`${o}: \`optional\` is a boolean`);
163
+ t.optional = e.optional;
164
+ }
165
+ if (e.marks !== void 0) {
166
+ if (!A(e.marks)) throw h.schema(`${o}: \`marks\` is an object of mark definitions`);
167
+ const n = {};
168
+ for (const s of D(e.marks)) {
169
+ const i = e.marks[s];
170
+ if (!A(i)) throw h.schema(`${o} mark \`${s}\`: a mark definition is an object`);
171
+ if (U(`${o} mark \`${s}\``, i, ["expand"]), typeof i.expand != "string" || !Pn.includes(i.expand)) throw h.schema(`${o} mark \`${s}\`: \`expand\` is after, before, both, or none`);
172
+ _(n, s, { expand: i.expand });
173
+ }
174
+ t.marks = n;
175
+ }
176
+ if (e.readOnly !== void 0) {
177
+ if (typeof e.readOnly != "boolean") throw h.schema(`${o}: \`readOnly\` is a boolean`);
178
+ e.readOnly && (t.readOnly = !0);
179
+ }
180
+ if (e.owns !== void 0) {
181
+ if (typeof e.owns != "boolean") throw h.schema(`${o}: \`owns\` is a boolean`);
182
+ e.owns && (t.owns = !0);
183
+ }
184
+ if (e.cascade !== void 0) {
185
+ if (typeof e.cascade != "boolean" || e.cascade && t.kind !== "tree") throw h.schema(`${o}: cascade requires a tree and a boolean`);
186
+ e.cascade && (t.cascade = !0);
187
+ }
188
+ if (e.position !== void 0) {
189
+ if (typeof e.position != "boolean") throw h.schema(`${o}: \`position\` is a boolean`);
190
+ e.position && (t.position = !0);
191
+ }
192
+ if (e.display !== void 0 && e.display !== null) {
193
+ const n = e.display, s = (i) => typeof i == "number" && Number.isFinite(i) && i > 0;
194
+ if (!A(n) || n.kind !== "time" || !s(n.perSecond) || n.fps !== void 0 && n.fps !== null && !s(n.fps))
195
+ throw h.schema(`${o}: \`display\` is { kind: "time", perSecond, fps? } with positive numbers`);
196
+ U(`${o} display`, n, ["kind", "perSecond", "fps"]), t.display = { kind: "time", perSecond: n.perSecond, ...s(n.fps) ? { fps: n.fps } : {} };
197
+ }
198
+ if (e.sample !== void 0 && e.sample !== null) {
199
+ if (typeof e.sample != "boolean") throw h.schema(`${o}: \`sample\` is a boolean`);
200
+ t.sample = e.sample;
201
+ }
202
+ return t;
203
+ }
204
+ function Kn(o) {
205
+ return o === "" ? "a mark key is not empty" : o.startsWith("$") ? "names starting with `$` are reserved" : o.includes(":") ? "a mark key holds no `:`" : o === "__proto__" ? "`__proto__` is not a mark key" : null;
206
+ }
207
+ const vt = (o) => o.kind === "text" && o.marks !== void 0 && Object.keys(o.marks).length > 0;
208
+ function qn(o) {
209
+ const e = /* @__PURE__ */ new Map();
210
+ for (const t of D(o.types)) {
211
+ const n = o.types[t].fields;
212
+ for (const s of D(n)) {
213
+ const i = n[s].marks ?? {};
214
+ for (const r of D(i)) e.set(r, i[r].expand);
215
+ }
216
+ }
217
+ return e;
218
+ }
219
+ function Ln(o) {
220
+ if (!A(o)) throw h.schema("a schema is a JSON object");
221
+ if (U("schema", o, ["kdm", "kit", "schemaVersion", "root", "types"]), !Vt(o.kdm)) throw h.schema("`kdm` is required and is a whole number");
222
+ if (typeof o.kit != "string") throw h.schema("`kit` is required and is a string");
223
+ if (!Vt(o.schemaVersion)) throw h.schema("`schemaVersion` is required and is a whole number");
224
+ if (typeof o.root != "string") throw h.schema("`root` is required and is a string");
225
+ if (!A(o.types)) throw h.schema("`types` is required and is an object");
226
+ const e = o.types, t = {};
227
+ for (const n of D(o.types)) {
228
+ const s = o.types[n];
229
+ if (!A(s)) throw h.schema(`type \`${n}\` is an object`);
230
+ if (U(`type \`${n}\``, s, ["fields", "projected", "projectedOps", "batchOps", "creation", "readOnly", "readOnlyWhen", "toolId", "pathName", "label", "derived", "text", "batchIndependent", "moveConsequences", "structuralConsequences"]), !A(s.fields)) throw h.schema(`type \`${n}\` needs \`fields\``);
231
+ const i = {};
232
+ for (const a of D(s.fields)) _(i, a, rn(`\`${n}.${a}\``, s.fields[a]));
233
+ const r = { fields: i };
234
+ if (s.projected !== void 0) {
235
+ if (typeof s.projected != "boolean") throw h.schema(`type \`${n}\`: projected is a boolean`);
236
+ s.projected && (r.projected = !0);
237
+ }
238
+ if (s.projectedOps !== void 0) {
239
+ if (!r.projected || !A(s.projectedOps)) throw h.schema(`type \`${n}\`: projectedOps requires projected:true`);
240
+ const a = {};
241
+ for (const [l, c] of Object.entries(s.projectedOps)) {
242
+ if (!l || !A(c) || typeof c.command != "string" || !c.command || Object.keys(c).some((f) => !["command", "params"].includes(f)) || c.params !== void 0 && (!A(c.params) || Object.entries(c.params).some(([f, u]) => !f || typeof u != "string" || u.split(".").some((p) => !p))))
243
+ throw h.schema(`type \`${n}\`: projectedOps needs an operation, command and parameter paths`);
244
+ _(a, l, { command: c.command, ...A(c.params) ? { params: { ...c.params } } : {} });
245
+ }
246
+ Object.keys(a).length && (r.projectedOps = a);
247
+ }
248
+ if (s.structuralConsequences !== void 0) {
249
+ const a = s.structuralConsequences;
250
+ if (!Array.isArray(a) || a.some(
251
+ (l) => !A(l) || Object.keys(l).some((c) => !["container", "on", "fields"].includes(c)) || typeof l.container != "string" || !Object.hasOwn(e, l.container) || !Array.isArray(l.on) || !l.on.length || l.on.some((c) => !["create", "delete", "move", "rename"].includes(c) && !(c === "set" && Object.values(e).some((f) => A(f) && f.projected === !0))) || !Array.isArray(l.fields) || !l.fields.length || l.fields.some((c) => typeof c != "string" || c.split(".").some((f) => !f) || !i[c.split(".")[0]] || c.includes(".") && !["json", "map"].includes(i[c.split(".")[0]].kind))
252
+ )) throw h.schema(`type \`${n}\`: structuralConsequences needs a declared container, structural actions and stored field paths`);
253
+ a.length && (r.structuralConsequences = a.map((l) => ({ container: l.container, on: [...l.on], fields: [...l.fields] })));
254
+ }
255
+ if (s.moveConsequences !== void 0) {
256
+ if (!Array.isArray(s.moveConsequences) || s.moveConsequences.some((a) => {
257
+ if (typeof a != "string" || a.split(".").some((c) => !c)) return !0;
258
+ const l = i[a.split(".")[0]];
259
+ return !l?.position || a.includes(".") && l.kind !== "json";
260
+ })) throw h.schema(`type \`${n}\`: moveConsequences must name position fields or their JSON members`);
261
+ s.moveConsequences.length && (r.moveConsequences = [...s.moveConsequences]);
262
+ }
263
+ if (s.creation !== void 0) {
264
+ if (!A(s.creation)) throw h.schema("creation is an object");
265
+ U("creation", s.creation, ["fields", "command", "fixtures"]);
266
+ for (const l of ["fields", "fixtures"]) if (s.creation[l] !== void 0 && !A(s.creation[l])) throw h.schema(`creation.${l} is an object`);
267
+ const a = s.creation.command;
268
+ if (a !== void 0) {
269
+ if (!A(a) || typeof a.command != "string" || !a.command) throw h.schema("creation command required");
270
+ if (U("creation command", a, ["command", "params"]), a.params !== void 0 && (!A(a.params) || Object.entries(a.params).some(([l, c]) => !l || typeof c != "string" || c.split(".").some((f) => !f)))) throw h.schema("invalid creation command paths");
271
+ }
272
+ r.creation = structuredClone(s.creation);
273
+ }
274
+ if (s.batchOps !== void 0) {
275
+ if (!A(s.batchOps)) throw h.schema(`type \`${n}\`: batchOps is a mapping`);
276
+ const a = {};
277
+ for (const [l, c] of Object.entries(s.batchOps)) {
278
+ if (!l || !A(c)) throw h.schema("invalid batchOps operation");
279
+ if (c.direct === !0)
280
+ U("direct batchOps", c, ["direct"]), a[l] = { direct: !0 };
281
+ else {
282
+ if (U("command batchOps", c, ["command", "params"]), typeof c.command != "string" || !c.command || c.params !== void 0 && (!A(c.params) || Object.entries(c.params).some(([f, u]) => !f || typeof u != "string" || u.split(".").some((p) => !p)))) throw h.schema("invalid batchOps command");
283
+ a[l] = { command: c.command, params: c.params };
284
+ }
285
+ }
286
+ r.batchOps = a;
287
+ }
288
+ if (s.batchIndependent !== void 0) {
289
+ if (typeof s.batchIndependent != "boolean") throw h.schema(`type \`${n}\`: \`batchIndependent\` is a boolean`);
290
+ s.batchIndependent && (r.batchIndependent = !0);
291
+ }
292
+ if (s.readOnly !== void 0) {
293
+ if (typeof s.readOnly != "boolean") throw h.schema(`type \`${n}\`: \`readOnly\` is a boolean`);
294
+ s.readOnly && (r.readOnly = !0);
295
+ }
296
+ if (s.readOnlyWhen !== void 0 && s.readOnlyWhen !== null) {
297
+ const a = s.readOnlyWhen;
298
+ if (!A(a)) throw h.schema(`type \`${n}\`: \`readOnlyWhen\` is { field, values }`);
299
+ if (U(`type \`${n}\` readOnlyWhen`, a, ["field", "values"]), typeof a.field != "string") throw h.schema(`type \`${n}\`: \`readOnlyWhen.field\` is a field name`);
300
+ if (!Array.isArray(a.values) || !a.values.every((l) => typeof l == "string")) throw h.schema(`type \`${n}\`: \`readOnlyWhen.values\` is a list of strings`);
301
+ r.readOnlyWhen = { field: a.field, values: [...a.values] };
302
+ }
303
+ if (s.toolId !== void 0 && s.toolId !== null) {
304
+ const a = s.toolId;
305
+ if (!A(a)) throw h.schema(`type \`${n}\`: \`toolId\` is { field, prefix?, parent? }`);
306
+ if (U(`type \`${n}\` toolId`, a, ["field", "prefix", "parent"]), typeof a.field != "string") throw h.schema(`type \`${n}\`: \`toolId.field\` is a field name`);
307
+ if (a.prefix !== void 0 && typeof a.prefix != "string") throw h.schema(`type \`${n}\`: \`toolId.prefix\` is a string`);
308
+ if (a.parent !== void 0 && a.parent !== null && typeof a.parent != "string") throw h.schema(`type \`${n}\`: \`toolId.parent\` is a type name`);
309
+ r.toolId = { field: a.field, prefix: typeof a.prefix == "string" ? a.prefix : "", ...typeof a.parent == "string" ? { parent: a.parent } : {} };
310
+ }
311
+ if (s.pathName !== void 0 && s.pathName !== null) {
312
+ const a = s.pathName, l = typeof a == "string" ? i[a.split(".")[0]]?.kind : void 0, c = l === "json" || (l === "string" || l === "enum") && typeof a == "string" && !a.includes(".");
313
+ if (typeof a != "string" || !c) throw h.schema(`type \`${n}\`: \`pathName\` \`${String(a)}\` names no string or enum field, nor a member of a json field`);
314
+ r.pathName = a;
315
+ }
316
+ for (const a of ["label", "text"]) if (s[a] !== void 0 && s[a] !== null) {
317
+ const l = s[a], c = typeof l == "string" ? i[l.split(".")[0]]?.kind : void 0, f = c === "json" || (c === "string" || c === "text" || c === "enum") && typeof l == "string" && !l.includes(".");
318
+ if (typeof l != "string" || !f) throw h.schema(`type \`${n}\`: \`${a}\` \`${String(l)}\` names no string, text or enum field, nor a member of a json field`);
319
+ r[a] = l;
320
+ }
321
+ if (s.derived !== void 0 && s.derived !== null) {
322
+ if (!A(s.derived)) throw h.schema(`type \`${n}\`: \`derived\` is an object of names`);
323
+ const a = {};
324
+ for (const l of D(s.derived)) {
325
+ if (!/^[A-Za-z0-9_]+$/.test(l)) throw h.schema(`type \`${n}\`: derived \`${l}\` is no name (ASCII letters, digits and \`_\`)`);
326
+ const c = s.derived[l];
327
+ if (!A(c)) throw h.schema(`type \`${n}\`: derived \`${l}\` is { description? }`);
328
+ if (U(`type \`${n}\` derived \`${l}\``, c, ["description", "premiseOnly", "onDemand"]), c.description !== void 0 && typeof c.description != "string") throw h.schema(`type \`${n}\`: derived \`${l}\`.description is a string`);
329
+ if (c.premiseOnly !== void 0 && typeof c.premiseOnly != "boolean") throw h.schema(`type \`${n}\`: derived \`${l}\`.premiseOnly is a boolean`);
330
+ if (c.onDemand !== void 0 && typeof c.onDemand != "boolean") throw h.schema(`type \`${n}\`: derived \`${l}\`.onDemand is a boolean`);
331
+ if (c.onDemand && !c.premiseOnly) throw h.schema(`type \`${n}\`: onDemand derived facts require premiseOnly`);
332
+ _(a, l, { ...typeof c.description == "string" ? { description: c.description } : {}, ...c.premiseOnly ? { premiseOnly: !0 } : {}, ...c.onDemand ? { onDemand: !0 } : {} });
333
+ }
334
+ Object.keys(a).length > 0 && (r.derived = a);
335
+ }
336
+ _(t, n, r);
337
+ }
338
+ return { kdm: o.kdm, kit: o.kit, schemaVersion: o.schemaVersion, root: o.root, types: t };
339
+ }
340
+ function zn(o) {
341
+ if (o.kdm !== Ee) throw h.schema(`kdm ${o.kdm} is not supported; this build reads ${Ee}`);
342
+ if (!Object.hasOwn(o.types, o.root)) throw h.schema(`root type \`${o.root}\` is not declared`);
343
+ if (o.types[o.root].projected) throw h.schema("the root type cannot be projected");
344
+ const e = /* @__PURE__ */ new Map();
345
+ for (const t of D(o.types)) {
346
+ if (t.startsWith("$")) throw h.schema(`type \`${t}\`: names starting with \`$\` are reserved`);
347
+ const n = o.types[t], s = n.readOnlyWhen;
348
+ if (s !== void 0) {
349
+ if (n.readOnly) throw h.schema(`type \`${t}\`: \`readOnly\` and \`readOnlyWhen\` exclude each other`);
350
+ if (!Object.hasOwn(n.fields, s.field)) throw h.schema(`type \`${t}\`: \`readOnlyWhen\` names undeclared field \`${s.field}\``);
351
+ const i = n.fields[s.field];
352
+ if (i.kind !== "enum") throw h.schema(`type \`${t}\`: \`readOnlyWhen\` names \`${s.field}\`, which is not an enum`);
353
+ if (s.values.length === 0) throw h.schema(`type \`${t}\`: \`readOnlyWhen\` needs \`values\``);
354
+ const r = s.values.find((a) => !(i.values ?? []).includes(a));
355
+ if (r !== void 0) throw h.schema(`type \`${t}\`: \`readOnlyWhen\` value \`${r}\` is not a value of \`${t}.${s.field}\``);
356
+ }
357
+ n.toolId !== void 0 && Hn(o, t, n.toolId);
358
+ for (const i of D(n.fields)) {
359
+ const r = n.fields[i];
360
+ if (i.startsWith("$") || i.startsWith("~")) throw h.schema(`\`${t}.${i}\`: names starting with \`$\` or \`~\` are reserved`);
361
+ const a = Un.includes(r.kind), l = r.kind === "map" && r.owns === !0;
362
+ if (r.of !== void 0 && !a && !l) throw h.schema(`\`${t}.${i}\`: only ref, list, and tree fields take \`of\``);
363
+ if (r.owns && (r.kind === "list" || r.kind === "tree"))
364
+ throw h.schema(`\`${t}.${i}\`: only ref fields take \`owns\` (list and tree fields always own their items)`);
365
+ if (r.owns && r.kind !== "ref" && r.kind !== "map") throw h.schema(`\`${t}.${i}\`: only ref and map fields take \`owns\``);
366
+ if (r.values?.length && r.kind !== "enum") throw h.schema(`\`${t}.${i}\`: only enum fields take \`values\``);
367
+ if (r.kind === "enum" && !r.values?.length) throw h.schema(`\`${t}.${i}\`: an enum needs \`values\``);
368
+ if (a || l && r.of !== void 0) {
369
+ if (r.of === void 0) throw h.schema(`\`${t}.${i}\` needs \`of\``);
370
+ if (!Object.hasOwn(o.types, r.of)) throw h.schema(`\`${t}.${i}\` refers to undeclared type \`${r.of}\``);
371
+ }
372
+ const c = r.marks ?? {}, f = D(c);
373
+ if (f.length > 0 && r.kind !== "text") throw h.schema(`\`${t}.${i}\`: only text fields take \`marks\``);
374
+ for (const u of f) {
375
+ const p = Kn(u);
376
+ if (p !== null) throw h.schema(`\`${t}.${i}\` mark \`${u}\`: ${p}`);
377
+ const y = c[u].expand, $ = e.get(u);
378
+ if ($ !== void 0 && $ !== y)
379
+ throw h.schema(`\`${t}.${i}\` mark \`${u}\` expands \`${y}\`, but it is declared elsewhere expanding \`${$}\`; a mark key has one expand in a schema`);
380
+ e.set(u, y);
381
+ }
382
+ }
383
+ }
384
+ }
385
+ function Hn(o, e, t) {
386
+ const n = (u) => h.schema(`type \`${e}\`: \`toolId\` ${u}`), s = o.types[e].fields;
387
+ if (!Object.hasOwn(s, t.field)) throw n(`names undeclared field \`${t.field}\``);
388
+ const i = s[t.field];
389
+ if (i.kind !== "integer" && i.kind !== "string") throw n(`names \`${t.field}\`, which is not an integer or a string`);
390
+ if (!i.readOnly) throw n(`names \`${t.field}\`, which is not \`readOnly\`: only the kit writes an object's tool id`);
391
+ const r = Bn(t.prefix);
392
+ if (r !== null) throw n(`prefix \`${t.prefix}\`: ${r}`);
393
+ const a = t.parent;
394
+ if (a === void 0) return;
395
+ if (!Object.hasOwn(o.types, a)) throw n(`names undeclared parent type \`${a}\``);
396
+ const l = o.types[a];
397
+ if (l.toolId === void 0) throw n(`names parent \`${a}\`, which declares no \`toolId\``);
398
+ if (!Object.values(l.fields).some((u) => (u.kind === "list" || u.kind === "tree" || u.kind === "ref" || u.kind === "map" && u.owns) && u.of === e))
399
+ throw n(`names parent \`${a}\`, which has no list, tree, or ref field of \`${e}\``);
400
+ const c = [];
401
+ let f = a;
402
+ for (; f !== void 0; ) {
403
+ if (f === e) throw n(`parent \`${a}\` leads back to \`${e}\`: parents form no cycle`);
404
+ if (c.includes(f)) break;
405
+ c.push(f), f = Object.hasOwn(o.types, f) ? o.types[f].toolId?.parent : void 0;
406
+ }
407
+ }
408
+ function Zs(o) {
409
+ let e = o;
410
+ if (typeof o == "string")
411
+ try {
412
+ e = JSON.parse(o);
413
+ } catch (n) {
414
+ throw h.schema(String(n));
415
+ }
416
+ const t = Ln(e);
417
+ return zn(t), t;
418
+ }
419
+ function Gn(o, e) {
420
+ if (!Object.hasOwn(o.types, e)) throw h.unknownType(e);
421
+ return o.types[e];
422
+ }
423
+ function je(o, e, t) {
424
+ const n = Gn(o, e);
425
+ if (!Object.hasOwn(n.fields, t)) throw h.unknownField(e, t, Object.keys(n.fields).sort());
426
+ return n.fields[t];
427
+ }
428
+ function Qs(o, e, t, n) {
429
+ ht(o, e, t, n);
430
+ }
431
+ function ht(o, e, t, n) {
432
+ const s = je(o, e, t);
433
+ if (qe(s.kind)) throw h.invalidValue(e, t, Zn(s.kind));
434
+ if (n == null) {
435
+ if (s.optional) return null;
436
+ throw h.invalidValue(e, t, "is required");
437
+ }
438
+ const i = lt(n, (a) => h.invalidValue(e, t, a));
439
+ if (dt(e, t, i, s), s.members !== void 0 && Object.keys(s.members).length > 0) {
440
+ for (const [a, l] of Object.entries(s.members)) for (const c of ke(i, a))
441
+ if (!(Array.isArray(c) || A(c) || c === null && l.nullable)) {
442
+ if (typeof c != "number") throw h.invalidValue(e, t, "bounded members require a number or an explicitly nullable null");
443
+ dt(e, t, c, l);
444
+ }
445
+ }
446
+ let r;
447
+ switch (s.kind) {
448
+ case "string":
449
+ case "ref":
450
+ r = typeof i == "string";
451
+ break;
452
+ case "number":
453
+ r = typeof i == "number";
454
+ break;
455
+ case "integer":
456
+ r = typeof i == "number" && Number.isInteger(i) && Math.abs(i) <= At;
457
+ break;
458
+ case "boolean":
459
+ r = typeof i == "boolean";
460
+ break;
461
+ case "enum":
462
+ r = typeof i == "string" && (s.values ?? []).includes(i);
463
+ break;
464
+ case "blob":
465
+ r = A(i) && typeof i.hash == "string" && typeof i.mime == "string" && typeof i.size == "number" && Number.isInteger(i.size) && i.size >= 0 && i.size <= At;
466
+ break;
467
+ default:
468
+ r = !0;
469
+ }
470
+ if (!r && s.kind === "enum") throw h.invalidValue(e, t, Yn(s.values ?? [], i));
471
+ if (!r) throw h.invalidValue(e, t, `expects ${/^[aeiou]/.test(s.kind) ? "an" : "a"} ${s.kind} value`);
472
+ return i;
473
+ }
474
+ function ke(o, e) {
475
+ if (e === "") return [o];
476
+ const t = e.search(/[.\[]/), n = t < 0 ? e : e.slice(0, t);
477
+ return n === "*" ? A(o) ? Object.values(o).flatMap((s) => ke(s, e.slice(n.length))) : [] : n !== "" ? A(o) && Object.hasOwn(o, n) ? ke(o[n], e.slice(n.length)) : [] : e.startsWith("[]") ? Array.isArray(o) ? o.flatMap((s) => ke(s, e.slice(2))) : [] : e.startsWith(".") ? ke(o, e.slice(1)) : [];
478
+ }
479
+ function dt(o, e, t, n) {
480
+ if (typeof t != "number") return;
481
+ const s = n.multipleOf !== void 0 ? t / n.multipleOf : 0;
482
+ if (n.minimum !== void 0 && t < n.minimum || n.maximum !== void 0 && t > n.maximum || !Number.isFinite(s) || Math.abs(s - Math.round(s)) > 1e-9) throw h.invalidValue(o, e, "is outside minimum/maximum or is not a multipleOf the declared step");
483
+ }
484
+ function Xn(o, e, t, n, s) {
485
+ const i = je(o, e, t);
486
+ if (i.of !== void 0 && (typeof s != "string" || s === "")) throw h.invalidValue(e, t, `map entry \`${n}\` expects the id of a \`${i.of}\``);
487
+ for (const [r, a] of Object.entries(i.members ?? {}))
488
+ for (const l of ke({ [n]: s }, r))
489
+ if (!(Array.isArray(l) || A(l) || l === null && a.nullable)) {
490
+ if (typeof l != "number") throw h.invalidValue(e, t, `map entry \`${n}\` requires a number`);
491
+ dt(e, t, l, a);
492
+ }
493
+ }
494
+ const Et = 20;
495
+ function Yn(o, e) {
496
+ const t = o.slice(0, Et).map((r) => `\`${r}\``), n = Math.max(0, o.length - Et), s = n > 0 ? `, and ${n} more (\`describe\` lists them all)` : "", i = typeof e == "string" ? `\`${e}\`` : typeof e == "number" ? "a number" : typeof e == "boolean" ? "a boolean" : Array.isArray(e) ? "an array" : e === null ? "null" : "an object";
497
+ return `takes one of ${t.join(", ")}${s}, not ${i}`;
498
+ }
499
+ function Zn(o) {
500
+ return `is a container, not a value: change it with ${{
501
+ text: "text.insert, text.delete, text.set, text.mark, text.unmark",
502
+ list: "list.insert, list.move, list.remove",
503
+ tree: "tree.insert, tree.move",
504
+ map: "map.set, map.delete"
505
+ }[o] ?? "its operations"}, or set the fields of the objects it holds`;
506
+ }
507
+ const Rt = 8, Ie = (o, e) => {
508
+ try {
509
+ return o();
510
+ } catch {
511
+ return e;
512
+ }
513
+ };
514
+ function Qn(o) {
515
+ return {
516
+ objectsOfType: (e) => o.objectsOfType(e),
517
+ register: (e, t) => Ie(() => o.get(e, t), null),
518
+ held: (e, t, n) => {
519
+ if (n === "list") return Ie(() => o.list(e, t), []);
520
+ if (n === "tree") return Ie(() => o.tree(e, t), []).map((s) => s.object).filter((s) => o.exists(s));
521
+ if (n === "ref") {
522
+ const s = Ie(() => o.get(e, t), null);
523
+ return typeof s == "string" ? [s] : [];
524
+ }
525
+ return [];
526
+ },
527
+ map: (e, t) => Object.fromEntries(Ie(() => o.mapEntries(e, t), [])),
528
+ exists: (e) => o.exists(e)
529
+ };
530
+ }
531
+ const re = (o) => typeof o == "object" && o !== null && !Array.isArray(o);
532
+ function es(o) {
533
+ const e = re(o) && re(o.objects) ? o.objects : {}, t = (s, i) => {
534
+ const r = Object.hasOwn(e, s) ? e[s] : void 0;
535
+ return re(r) && Object.hasOwn(r, i) ? r[i] : null;
536
+ }, n = (s, i) => {
537
+ for (const r of Array.isArray(s) ? s : [])
538
+ re(r) && (typeof r.object == "string" && i.push(r.object), n(r.children, i));
539
+ };
540
+ return {
541
+ objectsOfType: (s) => Object.keys(e).filter((i) => re(e[i]) && e[i].$type === s).sort(I),
542
+ register: t,
543
+ held: (s, i, r) => {
544
+ const a = t(s, i), l = [];
545
+ return r === "list" && Array.isArray(a) ? l.push(...a.filter((c) => typeof c == "string")) : r === "tree" ? n(a, l) : r === "ref" && typeof a == "string" && l.push(a), l.filter((c) => Object.hasOwn(e, c));
546
+ },
547
+ map: (s, i) => t(s, i),
548
+ exists: (s) => Object.hasOwn(e, s)
549
+ };
550
+ }
551
+ function ts(o, e, t) {
552
+ const n = t.map(([s, i]) => {
553
+ const r = i === void 0 ? void 0 : o.types[i]?.pathName;
554
+ if (r === void 0) return null;
555
+ const [a, ...l] = r.split(".");
556
+ let c = e.register(s, a);
557
+ for (const f of l) c = re(c) ? c[f] ?? null : null;
558
+ return { text: typeof c == "string" ? c : null };
559
+ });
560
+ return n.map((s, i) => {
561
+ if (s === null) return null;
562
+ const r = s.text, a = r !== null && r !== "" && !/[/.#@]/.test(r) && !/^\d+$/.test(r) ? r : null;
563
+ if (a === null) return `#${i + 1}`;
564
+ const l = n.slice(0, i).filter((c) => c !== null && c.text === a).length;
565
+ return l === 0 ? a : `${a}#${l + 1}`;
566
+ });
567
+ }
568
+ function ns(o) {
569
+ return typeof o == "number" && Number.isInteger(o) ? String(o) : typeof o == "string" && o !== "" ? o : null;
570
+ }
571
+ const ss = (o) => o.split(/[:/]/).pop() ?? o;
572
+ function Nt(o) {
573
+ const e = o.map((t) => `\`${t}\``);
574
+ return e.length <= 1 ? e.join("") : `${e.slice(0, -1).join(", ")} and ${e[e.length - 1]}`;
575
+ }
576
+ class Q {
577
+ constructor(e, t, n, s) {
578
+ this.active = e, this.own = t, this.named = n, this.owners = s;
579
+ }
580
+ static none() {
581
+ return new Q(!1, /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map());
582
+ }
583
+ /** The tool ids of a replica's current state. */
584
+ static ofReplica(e) {
585
+ return Q.build(e.schema, Qn(e));
586
+ }
587
+ /** The tool ids of a canonical state (`Replica.stateJson`) read with `schema`. */
588
+ static ofState(e, t) {
589
+ return Q.build(e, es(t));
590
+ }
591
+ static build(e, t) {
592
+ const n = D(e.types).flatMap((g) => {
593
+ const v = e.types[g].toolId;
594
+ return v ? [[g, v]] : [];
595
+ });
596
+ if (n.length === 0) return Q.none();
597
+ const s = /* @__PURE__ */ new Map();
598
+ for (const [g, v] of n)
599
+ for (const O of t.objectsOfType(g)) {
600
+ const S = ns(t.register(O, v.field));
601
+ S !== null && s.set(O, { type: g, tool: v, value: S });
602
+ }
603
+ const i = /* @__PURE__ */ new Map();
604
+ for (const [g, v] of n) {
605
+ const O = v.parent;
606
+ if (O === void 0 || !Object.hasOwn(e.types, O)) continue;
607
+ const S = e.types[O];
608
+ for (const x of D(S.fields)) {
609
+ const M = S.fields[x];
610
+ if (!(!(M.kind === "list" || M.kind === "tree" || M.kind === "ref") || M.of !== g))
611
+ for (const V of t.objectsOfType(O))
612
+ for (const E of t.held(V, x, M.kind)) {
613
+ const R = i.get(E) ?? [];
614
+ R.includes(V) || R.push(V), i.set(E, R);
615
+ }
616
+ }
617
+ }
618
+ const r = /* @__PURE__ */ new Map(), a = (g, v) => {
619
+ const O = r.get(g);
620
+ if (O !== void 0) return O;
621
+ const S = s.get(g);
622
+ let x = null;
623
+ if (S !== void 0) {
624
+ const M = `${S.tool.prefix}${S.value}`;
625
+ if (S.tool.parent === void 0) x = M;
626
+ else {
627
+ const V = i.get(g);
628
+ if (V !== void 0 && V.length === 1 && v <= 64) {
629
+ const E = a(V[0], v + 1);
630
+ E !== null && (x = `${E}/${M}`);
631
+ }
632
+ }
633
+ }
634
+ return r.set(g, x), x;
635
+ };
636
+ for (const g of [...s.keys()].sort(I)) a(g, 0);
637
+ const l = /* @__PURE__ */ new Map();
638
+ for (const [g, v] of r) {
639
+ const O = s.get(g);
640
+ if (v === null || O === void 0) continue;
641
+ const S = l.get(v) ?? [];
642
+ S.push({ id: g, type: O.type, value: O.value }), l.set(v, S);
643
+ }
644
+ const c = /* @__PURE__ */ new Map(), f = /* @__PURE__ */ new Map();
645
+ for (const g of [...l.keys()].sort(I)) {
646
+ const v = l.get(g).sort((O, S) => I(O.type, S.type) || I(O.id, S.id));
647
+ f.set(g, v), v.length === 1 && c.set(v[0].id, g);
648
+ }
649
+ const u = /* @__PURE__ */ new Map(), p = Object.values(e.types).some((g) => g.pathName !== void 0), y = /* @__PURE__ */ new Map();
650
+ if (p) for (const g of D(e.types)) for (const v of t.objectsOfType(g)) y.set(v, g);
651
+ for (const g of D(e.types)) {
652
+ const v = e.types[g].fields;
653
+ for (const O of D(v)) {
654
+ const S = v[O];
655
+ if (Dn(S))
656
+ for (const x of t.objectsOfType(g)) {
657
+ const M = S.kind === "map" ? Fn(t.map(x, O), (E) => t.exists(E)) : t.held(x, O, S.kind).map((E, R) => [E, S.kind === "ref" ? null : String(R)]), V = p && S.kind === "list" ? ts(e, t, M.map(([E]) => [E, y.get(E)])) : [];
658
+ M.forEach(([E, R], ee) => {
659
+ const d = u.get(E) ?? [];
660
+ d.some((m) => m.owner === x && m.field === O) || d.push({ owner: x, field: O, at: R, name: V[ee] ?? null }), u.set(E, d);
661
+ });
662
+ }
663
+ }
664
+ }
665
+ const $ = (g) => {
666
+ const v = c.get(g);
667
+ if (v !== void 0) return v;
668
+ const O = u.get(g);
669
+ return O !== void 0 && O.length === 1 && O[0].at !== null && /^\d+$/.test(O[0].at) ? O[0].at : null;
670
+ }, j = (g) => {
671
+ const v = g.indexOf("."), O = v < 0 ? g : g.slice(0, v), S = v < 0 ? null : g.slice(v + 1);
672
+ let x = $(O);
673
+ if (x === null) {
674
+ const M = O.split(":").map($);
675
+ if (M.some((V) => V === null)) return null;
676
+ x = M.join(":");
677
+ }
678
+ return S === null ? x : `${x}.${S}`;
679
+ }, b = [];
680
+ for (const g of u.values())
681
+ for (const v of g) {
682
+ const O = v.at === null ? null : j(v.at);
683
+ O !== null && b.push([v, O]);
684
+ }
685
+ for (const [g, v] of b) g.at = v;
686
+ return new Q(!0, c, f, u);
687
+ }
688
+ /**
689
+ * As the Rust `ToolIds::attributed`: for an object without a tool id of its own, the nearest
690
+ * object holding it that has one and the path from it (`body.paragraphs.0`); `null` for an object
691
+ * with a tool id, without tool ids in the schema, or when an object on the way has no single holder.
692
+ */
693
+ attributed(e) {
694
+ if (!this.active || this.own.has(e)) return null;
695
+ const t = [];
696
+ let n = e;
697
+ for (let s = 0; s < 64; s += 1) {
698
+ const i = this.owners.get(n);
699
+ if (i === void 0 || i.length !== 1) return null;
700
+ const [r] = i;
701
+ r.at !== null && t.push(r.at), t.push(r.field);
702
+ const a = this.own.get(r.owner);
703
+ if (a !== void 0) return { holder: a, path: t.reverse().join(".") };
704
+ n = r.owner;
705
+ }
706
+ return null;
707
+ }
708
+ /**
709
+ * As the Rust `ToolIds::named_path`: `attributed`'s path in the words of the kit's commands, the names
710
+ * of the objects on the way whose type declares a `pathName` joined by `/`, then the path below the
711
+ * last of them; `null` when no object on the way is named so.
712
+ */
713
+ namedPath(e) {
714
+ if (!this.active || this.own.has(e)) return null;
715
+ const t = [], n = [];
716
+ let s = e;
717
+ for (let i = 0; i < 64; i += 1) {
718
+ const r = this.owners.get(s);
719
+ if (r === void 0 || r.length !== 1) return null;
720
+ const [a] = r;
721
+ if (a.name !== null ? t.push(a.name) : t.length === 0 && (a.at !== null && n.push(a.at), n.push(a.field)), this.own.has(a.owner)) {
722
+ if (t.length === 0) return null;
723
+ const l = t.reverse().join("/");
724
+ return n.length === 0 ? l : `${l}.${n.reverse().join(".")}`;
725
+ }
726
+ s = a.owner;
727
+ }
728
+ return null;
729
+ }
730
+ /** The type of the object a tool id names, when it names one. */
731
+ typeOf(e) {
732
+ const t = this.named.get(e);
733
+ return t !== void 0 && t.length === 1 ? t[0].type : null;
734
+ }
735
+ /** Whether the schema declares tool ids. */
736
+ isActive() {
737
+ return this.active;
738
+ }
739
+ /** The object's tool id, when it has one of its own. */
740
+ toolId(e) {
741
+ return this.own.get(e) ?? null;
742
+ }
743
+ /** How the object is named at the tool interface: its tool id, else its object id. */
744
+ showJson(e) {
745
+ return typeof e == "string" ? this.show(e) : Array.isArray(e) ? e.map((t) => this.showJson(t)) : re(e) ? Object.fromEntries(Object.entries(e).map(([t, n]) => [
746
+ this.toolId(t) ?? t.split(":").map((s) => this.show(s)).join(":"),
747
+ this.showJson(n)
748
+ ])) : e;
749
+ }
750
+ show(e) {
751
+ return this.own.get(e) ?? e;
752
+ }
753
+ /** References in marks share the tool id space; inserted characters stay literal. */
754
+ showText(e) {
755
+ return Array.isArray(e) ? e.map((t) => re(t) && Object.hasOwn(t, "attributes") ? { ...t, attributes: this.showJson(t.attributes) } : t) : e;
756
+ }
757
+ /**
758
+ * The object `text` names: a tool id, else an object id for which `exists` holds; an `Unresolved`
759
+ * when it names none or several. Without declared tool ids, `text` as an object id.
760
+ */
761
+ resolve(e, t) {
762
+ if (!this.active) return e;
763
+ const n = this.named.get(e);
764
+ if (n !== void 0 && n.length === 1) return n[0].id;
765
+ if (n !== void 0 && n.length > 1) {
766
+ const s = n.map((r) => `the \`${r.type}\` \`${r.id}\``), i = `${s.slice(0, -1).join(", ")} and ${s[s.length - 1]}`;
767
+ return {
768
+ reason: "ambiguous",
769
+ message: `\`${e}\` names ${n.length} objects (${i}), so it names none of them: give one of their object ids, which they answer until the kit gives each an id of its own`
770
+ };
771
+ }
772
+ return t(e) ? e : { reason: "not-found", message: this.notFound(e) };
773
+ }
774
+ /** Why `text` names no object, with the ids it may have meant (KHP A44, A48). */
775
+ notFound(e) {
776
+ const t = ss(e), n = [...this.named.entries()].filter(([, i]) => i.some((r) => r.value === t)).map(([i]) => i);
777
+ if (n.length > 0) {
778
+ const i = n.slice(0, Rt), r = n.length > i.length ? `, and ${n.length - i.length} more` : "";
779
+ return `no object has the id \`${e}\`; these end in \`${t}\`: ${Nt(i)}${r} (an id is written whole, as query and load answer it)`;
780
+ }
781
+ const s = e.slice(0, e.length - t.length);
782
+ if (s !== "") {
783
+ const i = [...this.named.keys()].filter((r) => r.startsWith(s));
784
+ if (i.length > 0 && i.length <= Rt) return `no object has the id \`${e}\`; the ids starting \`${s}\` are ${Nt(i)}`;
785
+ if (i.length > 0) return `no object has the id \`${e}\`; ${i.length} ids start \`${s}\`: query or load answers them`;
786
+ }
787
+ return `no object has the id \`${e}\`: give an id that query or load answers, \`root\`, or the \`$name\` of an object created earlier in the batch`;
788
+ }
789
+ }
790
+ const eo = (o) => typeof o != "string";
791
+ function ge(o, e) {
792
+ const t = {};
793
+ for (const [n, s] of qn(e)) _(t, n, { expand: s });
794
+ o.configTextStyle(t);
795
+ }
796
+ const os = (o, e) => {
797
+ const t = o ? Object.keys(o).sort(I) : [], n = e ? Object.keys(e).sort(I) : [];
798
+ return t.length !== n.length ? !1 : t.every((s, i) => s === n[i] && JSON.stringify(X(o[s])) === JSON.stringify(X(e[s])));
799
+ };
800
+ function an(o, e, t) {
801
+ if (e === "") return;
802
+ const n = o[o.length - 1];
803
+ if (n && os(n.attributes, t)) {
804
+ n.insert += e;
805
+ return;
806
+ }
807
+ o.push(t && Object.keys(t).length > 0 ? { insert: e, attributes: t } : { insert: e });
808
+ }
809
+ function kt(o, e) {
810
+ const t = e.marks ?? {}, n = [];
811
+ for (const s of o.toDelta()) {
812
+ const i = s.insert;
813
+ if (typeof i != "string" || i === "") continue;
814
+ const r = s.attributes ?? {};
815
+ let a;
816
+ for (const l of Object.keys(r).sort(I)) {
817
+ if (!Object.hasOwn(t, l)) continue;
818
+ const c = r[l];
819
+ c != null && (a ??= {}, _(a, l, X(c)));
820
+ }
821
+ an(n, i, a);
822
+ }
823
+ return n;
824
+ }
825
+ const ue = "meta", Y = "objects", ce = "$type", Ot = "object", Re = "schemaVersion", cn = "schemaRaises", ln = "birth", hn = "root", Tt = (o) => typeof o == "number" && Number.isSafeInteger(o) && o >= 0;
826
+ function fe(o) {
827
+ const e = o.getMap(ue).get(Re);
828
+ if (!Tt(e)) return null;
829
+ let t = e;
830
+ for (const n of o.getMap(cn).keys()) {
831
+ const s = Number(n);
832
+ Tt(s) && String(s) === n && s > t && (t = s);
833
+ }
834
+ return t;
835
+ }
836
+ const is = { text: on, list: sn, tree: nn, map: pe };
837
+ function q(o, e) {
838
+ const t = o.getMap(Y).get(e);
839
+ if (!(t instanceof pe)) throw h.notFound(e);
840
+ return t;
841
+ }
842
+ function De(o, e) {
843
+ const t = o.get(ce);
844
+ if (typeof t != "string") throw h.notFound(e);
845
+ return t;
846
+ }
847
+ const Ne = (o, e) => De(q(o, e), e), dn = (o, e) => h.engine(`${o}.${e} holds the wrong container`), fn = (o, e, t) => h.invalidValue(o, e, `is not a ${t} field`);
848
+ function G(o, e, t, n) {
849
+ if (o === void 0) return null;
850
+ if (o instanceof is[e]) return o;
851
+ throw dn(t, n);
852
+ }
853
+ function B(o, e, t, n, s) {
854
+ const i = q(o, t), r = De(i, t);
855
+ if (je(e, r, n).kind !== s) throw fn(r, n, s);
856
+ return G(i.get(n), s, t, n);
857
+ }
858
+ function rs(o, e, t, n) {
859
+ const s = B(o, e, t, n, "text");
860
+ if (!s) return [];
861
+ const i = je(e, Ne(o, t), n);
862
+ if (vt(i)) return kt(s, i);
863
+ const r = [];
864
+ return an(r, s.toString(), void 0), r;
865
+ }
866
+ function $t(o, e, t, n) {
867
+ const s = q(o, t), i = De(s, t);
868
+ if (qe(je(e, i, n).kind)) throw h.invalidValue(i, n, "is a container; read it with its accessor");
869
+ return Ye(s.get(n));
870
+ }
871
+ const Ye = (o) => o === void 0 || ae(o) ? null : X(o);
872
+ function un(o) {
873
+ return o.keys().sort(I).map((e) => [e, Ye(o.get(e))]);
874
+ }
875
+ function et(o, e) {
876
+ if (Object.values(e.types).some((t) => t.projected))
877
+ for (const t of cs(o)) {
878
+ const n = De(q(o, t), t), s = e.types[n];
879
+ if (s) {
880
+ if (s.projected) throw h.invalidValue(n, "$type", "projected objects are computed by the kit, never stored");
881
+ for (const [i, r] of Object.entries(s.fields)) {
882
+ if (!r.of || !e.types[r.of]?.projected) continue;
883
+ const a = q(o, t).get(i), l = ae(a) ? a.toJSON() : a;
884
+ if (l != null && !(Array.isArray(l) && !l.length) && !(typeof l == "object" && !Object.keys(l).length))
885
+ throw h.invalidValue(n, i, "projected membership is computed by the kit, never stored");
886
+ }
887
+ }
888
+ }
889
+ }
890
+ function pn(o, e) {
891
+ const t = [];
892
+ for (const [n, s] of o.getMap(Y).entries())
893
+ s instanceof pe && s.get(ce) === e && t.push(n);
894
+ return t.sort(I);
895
+ }
896
+ function Ze(o) {
897
+ return o.forEach((e, t) => {
898
+ if (typeof e != "string") throw h.encoding(`list item ${t} is ${as(e)}, not an object id`);
899
+ }), o;
900
+ }
901
+ const as = (o) => ae(o) ? "a container" : JSON.stringify(o) ?? String(o);
902
+ function Le(o) {
903
+ const e = o.data.get(Ot);
904
+ return typeof e == "string" ? e : null;
905
+ }
906
+ function cs(o) {
907
+ return o.getMap(Y).keys().sort(I);
908
+ }
909
+ const ye = (o) => o !== null && typeof o == "object" && !Array.isArray(o), be = "__proto__", mn = (o) => ae(o) ? o.toJSON() : o;
910
+ function gn(o) {
911
+ const e = [];
912
+ for (const t of o ?? []) {
913
+ const n = t.meta?.[Ot];
914
+ typeof n == "string" && e.push({ children: gn(t.children), object: n });
915
+ }
916
+ return e;
917
+ }
918
+ function yn(o) {
919
+ const e = [];
920
+ for (const t of o ?? []) {
921
+ const n = Le(t);
922
+ n !== null && e.push({ children: yn(t.children()), object: n });
923
+ }
924
+ return e;
925
+ }
926
+ function ls(o) {
927
+ const e = {};
928
+ for (const t of o.keys()) _(e, t, mn(o.get(t)));
929
+ return e;
930
+ }
931
+ function bn(o, e, t) {
932
+ const n = q(o, t), s = De(n, t), i = { [ce]: s };
933
+ if (!Object.hasOwn(e.types, s)) return i;
934
+ const r = e.types[s].fields;
935
+ for (const a of D(r)) {
936
+ const l = r[a].kind;
937
+ let c;
938
+ if (l === "text" && vt(r[a])) {
939
+ const f = B(o, e, t, a, "text");
940
+ c = f ? kt(f, r[a]) : [];
941
+ } else if (l === "text") c = B(o, e, t, a, "text")?.toString() ?? "";
942
+ else if (l === "list") c = Ze(B(o, e, t, a, "list")?.toArray() ?? []);
943
+ else if (l === "tree") c = yn(B(o, e, t, a, "tree")?.roots());
944
+ else if (l === "map") {
945
+ const f = B(o, e, t, a, "map");
946
+ c = f ? ls(f) : {};
947
+ } else c = $t(o, e, t, a);
948
+ _(i, a, c);
949
+ }
950
+ return i;
951
+ }
952
+ const Ct = /* @__PURE__ */ new WeakMap();
953
+ function hs(o, e) {
954
+ let t = Ct.get(o);
955
+ t || Ct.set(o, t = /* @__PURE__ */ new Map());
956
+ let n = t.get(e);
957
+ return n || t.set(e, n = [ce, ...Object.keys(o.types[e].fields)].sort(I)), n;
958
+ }
959
+ const ds = (o) => o !== null && typeof o == "object" ? X(o) : o;
960
+ function Dt(o, e) {
961
+ const t = o.toJSON(), n = ye(t[Y]) ? t[Y] : {}, s = o.getMap(Y), i = Object.keys(n);
962
+ s.get(be) !== void 0 && i.push(be), i.sort(I);
963
+ const r = {};
964
+ for (const c of i) {
965
+ const f = n[c], u = ye(f) ? f[ce] : void 0, p = typeof u == "string" && Object.hasOwn(e.types, u);
966
+ if (c === be || p && Object.hasOwn(e.types[u].fields, be)) {
967
+ _(r, c, X(bn(o, e, c)));
968
+ continue;
969
+ }
970
+ if (!ye(f) || typeof u != "string") throw h.notFound(c);
971
+ if (!p) {
972
+ r[c] = { [ce]: u };
973
+ continue;
974
+ }
975
+ const y = {};
976
+ r[c] = y;
977
+ const $ = e.types[u].fields;
978
+ for (const j of hs(e, u)) {
979
+ if (j === ce) {
980
+ y[j] = u;
981
+ continue;
982
+ }
983
+ const b = f[j], g = () => dn(c, j);
984
+ switch ($[j].kind) {
985
+ case "text":
986
+ if (b !== void 0 && typeof b != "string") throw g();
987
+ if (vt($[j])) {
988
+ const v = b === void 0 ? null : G(q(o, c).get(j), "text", c, j);
989
+ y[j] = v ? kt(v, $[j]) : [];
990
+ } else y[j] = b ?? "";
991
+ break;
992
+ case "list":
993
+ if (b !== void 0 && !Array.isArray(b)) throw g();
994
+ y[j] = Array.isArray(b) ? Ze(b) : [];
995
+ break;
996
+ case "tree":
997
+ if (b !== void 0 && !Array.isArray(b)) throw g();
998
+ y[j] = gn(b);
999
+ break;
1000
+ case "map": {
1001
+ if (b !== void 0 && !ye(b)) throw g();
1002
+ const v = ye(b) ? { ...b } : {}, O = q(o, c).get(j), S = O instanceof pe ? O.get(be) : void 0;
1003
+ S !== void 0 && _(v, be, mn(S)), y[j] = X(v);
1004
+ break;
1005
+ }
1006
+ default:
1007
+ y[j] = b === void 0 ? null : ds(b);
1008
+ }
1009
+ }
1010
+ }
1011
+ const a = ye(t[ue]) ? { ...t[ue] } : {}, l = fe(o);
1012
+ return l !== null && (a[Re] = l), { meta: X(a), objects: r };
1013
+ }
1014
+ const ft = 80;
1015
+ function fs(o, e) {
1016
+ const t = Array.from(o), n = Array.from(e);
1017
+ if (o === e || t.length <= ft) return;
1018
+ let s = 0, i = 0;
1019
+ for (; s < Math.min(t.length, n.length) && t[s] === n[s]; ) s++;
1020
+ for (; i < Math.min(t.length, n.length) - s && t[t.length - 1 - i] === n[n.length - 1 - i]; ) i++;
1021
+ const r = t.length - s - i, a = n.length - s - i;
1022
+ return {
1023
+ offset: s,
1024
+ removed: t.slice(s, s + Math.min(r, 80)).join(""),
1025
+ inserted: n.slice(s, s + Math.min(a, 80)).join(""),
1026
+ removedLength: r,
1027
+ insertedLength: a,
1028
+ before: t.slice(Math.max(0, s - 20), s).join(""),
1029
+ after: t.slice(t.length - i, t.length - i + 20).join(""),
1030
+ complete: r <= 80 && a <= 80
1031
+ };
1032
+ }
1033
+ function wn(o, e, t) {
1034
+ let n = 0;
1035
+ const s = (a, l, c) => c.split(".").reduce((f, u) => W(f) ? f[u] : Array.isArray(f) ? f[Number(u)] : void 0, Te(a)[l]), i = { ...o, changed: o.changed.map((a) => ({ ...a, edits: a.edits?.map((l) => {
1036
+ const c = s(e, a.id, l.field), f = s(t, a.id, l.field), u = c == null ? "" : me(c), p = f == null ? "" : me(f), y = u === null || p === null ? void 0 : fs(u, p);
1037
+ if (!y) return l;
1038
+ const $ = new TextEncoder().encode(JSON.stringify(y)).length;
1039
+ return n + $ > 65536 ? { ...l, spansTruncated: !0 } : (n += $, { ...l, span: y });
1040
+ }) })) }, r = oe.get(o);
1041
+ return r && oe.set(i, r), i;
1042
+ }
1043
+ const us = 20, Ft = "…", ut = "$type", W = (o) => typeof o == "object" && o !== null && !Array.isArray(o);
1044
+ function Te(o) {
1045
+ const e = W(o) ? o.objects : void 0;
1046
+ return W(e) ? e : {};
1047
+ }
1048
+ const Z = (o) => W(o) && typeof o[ut] == "string" ? o[ut] : "";
1049
+ function Oe(o) {
1050
+ const e = W(o) ? { ...o } : {};
1051
+ return delete e[ut], e;
1052
+ }
1053
+ function Wt(o) {
1054
+ return o == null ? !1 : typeof o == "string" || Array.isArray(o) ? o.length > 0 : W(o) ? Object.keys(o).length > 0 : !0;
1055
+ }
1056
+ function me(o) {
1057
+ return typeof o == "string" ? o : Array.isArray(o) && o.length > 0 && o.every((e) => W(e) && typeof e.insert == "string") ? o.map((e) => e.insert).join("") : null;
1058
+ }
1059
+ const pt = (o, e) => JSON.stringify(o) === JSON.stringify(e), vn = (o, e) => P(o) === P(e), $e = (...o) => [...new Set(o.flatMap((e) => Object.keys(e)))].sort(I), ps = (o) => Array.isArray(o) && o.length > 0 && o.every((e) => W(e) && typeof e.object == "string" && Array.isArray(e.children)), ms = (o, e) => Array.isArray(o) && o.length > 0 && o.every((t) => typeof t == "string" && e(t)), Bt = (o) => o == null || Array.isArray(o) && o.length === 0;
1060
+ function tt(o, e, t) {
1061
+ const n = (s) => (s(o) || s(e)) && (s(o) || Bt(o)) && (s(e) || Bt(e));
1062
+ return n(ps) ? "tree" : n((s) => ms(s, t)) ? "list" : "value";
1063
+ }
1064
+ function jt(o) {
1065
+ return !W(o) || typeof o.hash != "string" || typeof o.mime != "string" ? null : typeof o.size == "number" && Number.isInteger(o.size) && o.size >= 0 ? o.size : null;
1066
+ }
1067
+ function gs(o, e) {
1068
+ const t = Array.from(o);
1069
+ if (t.length <= ft) return o;
1070
+ const n = Math.min(Math.max(e - us, 0), t.length);
1071
+ let s = ft, i = "";
1072
+ n > 0 && (i += Ft, s -= 1);
1073
+ const r = t.slice(n);
1074
+ return i += r.length <= s ? r.join("") : r.slice(0, s - 1).join("") + Ft, { excerpt: i, length: t.length };
1075
+ }
1076
+ function Ce(o, e) {
1077
+ const t = jt(o);
1078
+ if (t !== null) return { size: t };
1079
+ const n = me(o);
1080
+ return n === null ? o : gs(n, e);
1081
+ }
1082
+ function ze(o, e) {
1083
+ return jt(o) === null ? Ce(o, e) : o;
1084
+ }
1085
+ function ys(o, e) {
1086
+ const [t, n] = [Array.from(o), Array.from(e)];
1087
+ let s = 0;
1088
+ for (; s < t.length && s < n.length && t[s] === n[s]; ) s += 1;
1089
+ return s;
1090
+ }
1091
+ const nt = (o) => JSON.stringify(o);
1092
+ class Pt {
1093
+ at = /* @__PURE__ */ new Map();
1094
+ add(e, t, n, s) {
1095
+ if (s === "list") {
1096
+ const i = [e, t, e];
1097
+ n.filter((a) => typeof a == "string").forEach((a, l) => {
1098
+ this.at.has(a) || this.at.set(a, { group: i, index: l });
1099
+ });
1100
+ } else s === "tree" && this.addNodes(e, t, e, n);
1101
+ }
1102
+ addNodes(e, t, n, s) {
1103
+ const i = [e, t, n];
1104
+ (Array.isArray(s) ? s : []).forEach((r, a) => {
1105
+ !W(r) || typeof r.object != "string" || (this.at.has(r.object) || this.at.set(r.object, { group: i, index: a }), this.addNodes(e, t, r.object, r.children));
1106
+ });
1107
+ }
1108
+ position(e) {
1109
+ const t = this.at.get(e);
1110
+ return t ? { parent: t.group[2], field: t.group[1], index: t.index } : null;
1111
+ }
1112
+ }
1113
+ const oe = /* @__PURE__ */ new WeakMap();
1114
+ function to(o, e) {
1115
+ const t = oe.get(o), n = { ...o, deleted: o.deleted.map((s) => {
1116
+ const i = t?.get(s.id), r = e.types[s.type]?.fields, a = Object.fromEntries(Object.entries(i ?? {}).filter(([l]) => l.startsWith("~") || r && Object.hasOwn(r, l)));
1117
+ return Object.keys(a).length ? { ...s, $was: a } : { ...s };
1118
+ }) };
1119
+ return t && oe.set(n, t), n;
1120
+ }
1121
+ function bs(o) {
1122
+ const e = [], t = o.map(() => null);
1123
+ o.forEach((i, r) => {
1124
+ let a = 0, l = e.length;
1125
+ for (; a < l; ) {
1126
+ const c = a + l >> 1;
1127
+ o[e[c]] < i ? a = c + 1 : l = c;
1128
+ }
1129
+ a > 0 && (t[r] = e[a - 1]), a === e.length ? e.push(r) : e[a] = r;
1130
+ });
1131
+ const n = /* @__PURE__ */ new Set();
1132
+ let s = e.length > 0 ? e[e.length - 1] : null;
1133
+ for (; s !== null; )
1134
+ n.add(s), s = t[s];
1135
+ return n;
1136
+ }
1137
+ const ws = 16;
1138
+ function _t(o) {
1139
+ if (jt(o) !== null) return !0;
1140
+ if (!W(o)) return !1;
1141
+ const e = Object.keys(o).sort(I).join(",");
1142
+ return e === "excerpt,length" || e === "size";
1143
+ }
1144
+ const mt = (o, e) => P(o) === P(e);
1145
+ function gt(o, e, t, n) {
1146
+ if (W(e) && W(t) && !_t(e) && !_t(t)) {
1147
+ const s = [.../* @__PURE__ */ new Set([...Object.keys(e), ...Object.keys(t)])].sort(I);
1148
+ for (const i of s) {
1149
+ const [r, a] = [e[i] ?? null, t[i] ?? null];
1150
+ mt(r, a) || gt(`${o}.${i}`, r, a, n);
1151
+ }
1152
+ return;
1153
+ }
1154
+ if (Array.isArray(e) && Array.isArray(t) && e.length === t.length) {
1155
+ e.forEach((s, i) => {
1156
+ mt(s, t[i]) || gt(`${o}.${i}`, s, t[i], n);
1157
+ });
1158
+ return;
1159
+ }
1160
+ n.push({ field: o, before: ze(e, 0), after: Ce(t, 0) });
1161
+ }
1162
+ const Jt = (o) => o.reduce((e, t) => e + t.field.length + P(t.before).length + P(t.after).length, 0);
1163
+ function kn(o, e, t) {
1164
+ const n = [{ field: o, before: ze(e, 0), after: Ce(t, 0) }], s = [];
1165
+ return gt(o, e, t, s), s.length <= ws && Jt(s) < Jt(n) ? s : n;
1166
+ }
1167
+ function vs(o, e, t) {
1168
+ const n = e === null ? {} : e, s = t === null ? {} : t;
1169
+ if (!W(n) || !W(s)) return [{ field: o, before: e, after: t }];
1170
+ const i = [];
1171
+ for (const r of [.../* @__PURE__ */ new Set([...Object.keys(n), ...Object.keys(s)])].sort(I)) {
1172
+ const [a, l] = [n[r] ?? null, s[r] ?? null];
1173
+ mt(a, l) || i.push(...kn(`${o}.${r}`, a, l));
1174
+ }
1175
+ return i;
1176
+ }
1177
+ function ks(o, e) {
1178
+ for (const t of o.changed) {
1179
+ if (!t.edits) continue;
1180
+ const n = /* @__PURE__ */ new Map();
1181
+ for (const r of t.edits) {
1182
+ let a;
1183
+ try {
1184
+ a = je(e, t.type, r.field);
1185
+ } catch {
1186
+ continue;
1187
+ }
1188
+ const l = a.kind === "map" && !a.owns ? vs(r.field, r.before, r.after) : a.kind === "json" ? kn(r.field, r.before, r.after) : null;
1189
+ l && (l.length !== 1 || l[0].field !== r.field) && n.set(r.field, l);
1190
+ }
1191
+ if (n.size === 0) continue;
1192
+ const s = [];
1193
+ let i = [...t.fields];
1194
+ for (const r of t.edits) {
1195
+ const a = n.get(r.field);
1196
+ if (!a) {
1197
+ s.push(r);
1198
+ continue;
1199
+ }
1200
+ i = i.filter((l) => l !== r.field), i.push(...a.map((l) => l.field)), s.push(...a);
1201
+ }
1202
+ t.edits = s.sort((r, a) => I(r.field, a.field)), t.fields = [...new Set(i)].sort(I);
1203
+ }
1204
+ return o;
1205
+ }
1206
+ function yt(o, e, t, n, s) {
1207
+ const i = (b) => n(b) !== null, r = { created: [], changed: [], moved: [], deleted: [] }, a = [], [l, c] = [new Pt(), new Pt()], f = /* @__PURE__ */ new Set(), u = /* @__PURE__ */ new Set(), p = /* @__PURE__ */ new Map();
1208
+ oe.set(r, p);
1209
+ for (const b of o) {
1210
+ const g = Object.hasOwn(e, b) ? e[b] : void 0, v = Object.hasOwn(t, b) ? t[b] : void 0;
1211
+ if (g === void 0 && v !== void 0) {
1212
+ f.add(b);
1213
+ const O = Oe(v), S = $e(O).filter((M) => Wt(O[M])), x = {};
1214
+ for (const M of S) {
1215
+ const V = M.startsWith("~") ? "value" : tt(null, O[M], i);
1216
+ V === "value" ? x[M] = Ce(O[M], 0) : c.add(b, M, O[M], V);
1217
+ const E = me(O[M]);
1218
+ s && E && a.push({ id: b, field: M, before: "", after: E });
1219
+ }
1220
+ r.created.push({ id: b, type: Z(v), fields: S, values: x });
1221
+ } else if (g !== void 0 && v === void 0) {
1222
+ u.add(b);
1223
+ const O = Oe(g), S = {};
1224
+ for (const x of $e(O)) {
1225
+ const M = x.startsWith("~") ? "value" : tt(O[x], null, i);
1226
+ M === "value" && Wt(O[x]) && (S[x] = ze(O[x], 0)), l.add(b, x, O[x], M);
1227
+ }
1228
+ p.set(b, S), r.deleted.push({ id: b, type: Z(g), fields: [] });
1229
+ } else if (g !== void 0 && v !== void 0 && !pt(g, v)) {
1230
+ const [O, S] = [Oe(g), Oe(v)], x = [], M = [];
1231
+ Z(g) !== Z(v) && (x.push("$type"), M.push({ field: "$type", before: Z(g), after: Z(v) }));
1232
+ for (const V of $e(O, S)) {
1233
+ const E = O[V] ?? null, R = S[V] ?? null;
1234
+ if (pt(E, R)) continue;
1235
+ const ee = V.startsWith("~") ? "value" : tt(E, R, i);
1236
+ if (ee !== "tree" && x.push(V), ee !== "value") {
1237
+ l.add(b, V, E, ee), c.add(b, V, R, ee);
1238
+ continue;
1239
+ }
1240
+ const d = (N) => N === null ? "" : me(N), [m, k] = [d(E), d(R)];
1241
+ let w = 0;
1242
+ m !== null && k !== null && (w = ys(m, k), s && m !== k && a.push({ id: b, field: V, before: m, after: k })), M.push({ field: V, before: ze(E, w), after: Ce(R, w) });
1243
+ }
1244
+ x.length && r.changed.push({ id: b, type: Z(v) || Z(g), fields: x, edits: M });
1245
+ }
1246
+ }
1247
+ for (const b of r.created) {
1248
+ const g = c.position(b.id);
1249
+ g && (b.at = g);
1250
+ }
1251
+ for (const b of r.deleted) {
1252
+ const g = l.position(b.id);
1253
+ g && (b.at = g);
1254
+ }
1255
+ const y = /* @__PURE__ */ new Map();
1256
+ for (const [b, { group: g, index: v }] of c.at) {
1257
+ const O = l.at.get(b);
1258
+ if (O && nt(O.group) === nt(g)) {
1259
+ const S = nt(g);
1260
+ y.has(S) || y.set(S, []), y.get(S).push({ id: b, was: O.index, now: v });
1261
+ }
1262
+ }
1263
+ const $ = /* @__PURE__ */ new Set();
1264
+ for (const b of y.values()) {
1265
+ b.sort((g, v) => g.now - v.now);
1266
+ for (const g of bs(b.map((v) => v.was))) $.add(b[g].id);
1267
+ }
1268
+ const j = [.../* @__PURE__ */ new Set([...l.at.keys(), ...c.at.keys()])].sort(I);
1269
+ for (const b of j)
1270
+ f.has(b) || u.has(b) || $.has(b) || r.moved.push({ id: b, type: n(b) ?? "", from: l.position(b), to: c.position(b) });
1271
+ return s && (r.texts = a), r;
1272
+ }
1273
+ function no(o, e) {
1274
+ const [t, n] = [Te(o), Te(e)], s = (i) => Object.hasOwn(n, i) ? Z(n[i]) : Object.hasOwn(t, i) ? Z(t[i]) : null;
1275
+ return yt($e(t, n), t, n, s, !0);
1276
+ }
1277
+ function so(o, e, t, n) {
1278
+ o = wn(o, t, n);
1279
+ const s = Te(t), i = Te(n), r = Q.ofState(e, n), a = Q.ofState(e, t), l = {};
1280
+ let c = 0;
1281
+ for (const p of $e(s, i)) {
1282
+ if (!Object.hasOwn(s, p) || !Object.hasOwn(i, p)) continue;
1283
+ const y = Oe(s[p]), $ = Oe(i[p]);
1284
+ for (const j of $e(y, $)) {
1285
+ if (pt(y[j], $[j]) || me(y[j]) === null || me($[j]) === null) continue;
1286
+ const b = new TextEncoder().encode(JSON.stringify(y[j])).length;
1287
+ if (b > 1048576 || c + b > 4194304) continue;
1288
+ const g = r.attributed(p), v = g?.holder ?? r.show(p), O = g ? `${g.path}.${j}` : j;
1289
+ (l[v] ??= {})[O] = a.showText(y[j]), c += b;
1290
+ }
1291
+ }
1292
+ if (!Object.keys(l).length) return o;
1293
+ const f = { ...o, $text: l }, u = oe.get(o);
1294
+ return u && oe.set(f, u), f;
1295
+ }
1296
+ const oo = (o) => !o.created.length && !o.changed.length && !o.moved.length && !o.deleted.length;
1297
+ function Os(o, e, t, n) {
1298
+ if (!t.isActive() && !n.isActive()) return o;
1299
+ const s = oe.get(o) ?? /* @__PURE__ */ new Map(), i = (d, m) => {
1300
+ const k = d.toolId(m) === null ? d.attributed(m) : null;
1301
+ return k !== null ? `${k.holder}.${k.path}` : d.show(m);
1302
+ }, r = (d, m, k) => typeof m != "string" || m === "" ? m : d.toolId(m) === null && d.attributed(m) === null ? { unnamed: k ?? "object" } : i(d, m), a = (d, m) => Object.hasOwn(e.types, d) && Object.hasOwn(e.types[d].fields, m) ? e.types[d].fields[m].of ?? void 0 : void 0, l = (d, m) => {
1303
+ const k = d.toolId(m.parent) === null ? d.attributed(m.parent) : null;
1304
+ return k !== null ? { parent: k.holder, field: `${k.path}.${m.field}`, index: m.index } : { ...m, parent: d.show(m.parent) };
1305
+ }, c = new Map([...o.created, ...o.changed].map((d) => [d.id, d.type])), f = (d, m) => d !== void 0 && Object.hasOwn(e.types, d) && Object.hasOwn(e.types[d].fields, m) && e.types[d].fields[m].kind === "ref", u = (d, m) => f(c.get(d), m), p = (d, m) => ["json", "map"].includes(e.types[d]?.fields[m.split(".")[0]]?.kind ?? ""), y = (d) => d.sort((m, k) => I(m.id, k.id)), $ = o.created.map((d) => {
1306
+ const m = { ...d };
1307
+ return d.values && (m.values = Object.fromEntries(Object.entries(d.values).map(([k, w]) => [k, f(d.type, k) ? r(n, w, a(d.type, k)) : p(d.type, k) ? n.showJson(w) : w]))), d.at && (m.at = l(n, d.at)), m;
1308
+ }), j = o.changed.map((d) => {
1309
+ const m = { ...d };
1310
+ if (d.edits) {
1311
+ m.edits = d.edits.map(
1312
+ (w) => f(d.type, w.field) ? { ...w, before: r(t, w.before, a(d.type, w.field)), after: r(n, w.after, a(d.type, w.field)) } : p(d.type, w.field) ? { ...w, before: t.showJson(w.before), after: n.showJson(w.after) } : w
1313
+ );
1314
+ const k = new Set(m.edits.filter((w) => f(d.type, w.field) && typeof w.before == "string" && vn(w.before, w.after)).map((w) => w.field));
1315
+ k.size > 0 && (m.edits = m.edits.filter((w) => !k.has(w.field)), m.fields = m.fields.filter((w) => !k.has(w)));
1316
+ }
1317
+ return m;
1318
+ }).filter((d) => d.fields.length > 0), b = /* @__PURE__ */ new Map(), g = (d, m) => {
1319
+ const k = b.get(d) ?? { type: "", fields: [], edits: [], values: {} };
1320
+ return k.type = m.typeOf(d) ?? "", b.set(d, k), k;
1321
+ }, v = new Set(o.created.map((d) => n.show(d.id))), O = new Set(o.deleted.map((d) => t.show(d.id))), S = [];
1322
+ for (const d of j) {
1323
+ const m = n.attributed(d.id);
1324
+ if (m === null) {
1325
+ S.push(d);
1326
+ continue;
1327
+ }
1328
+ const { holder: k, path: w } = m, N = g(k, n);
1329
+ if (N.fields.push(...d.fields.map((J) => `${w}.${J}`)), v.has(k)) {
1330
+ for (const J of d.edits ?? []) N.values[`${w}.${J.field}`] = J.after;
1331
+ continue;
1332
+ }
1333
+ const te = n.namedPath(d.id);
1334
+ N.edits.push(...(d.edits ?? []).map((J) => ({ ...J, field: `${w}.${J.field}`, ...te === null ? {} : { named: `${te}.${J.field}` } })));
1335
+ }
1336
+ const x = [];
1337
+ for (const d of $) {
1338
+ const m = n.attributed(d.id);
1339
+ if (m === null) {
1340
+ x.push(d);
1341
+ continue;
1342
+ }
1343
+ const { holder: k, path: w } = m, N = g(k, n), te = d.values ?? {};
1344
+ if (v.has(k)) {
1345
+ N.fields.push(...d.fields.map((le) => `${w}.${le}`));
1346
+ for (const [le, In] of Object.entries(te)) N.values[`${w}.${le}`] = In;
1347
+ continue;
1348
+ }
1349
+ N.fields.push(w);
1350
+ const J = n.namedPath(d.id);
1351
+ N.edits.push({ field: w, before: null, after: te, ...J === null ? {} : { named: J } });
1352
+ }
1353
+ const M = [];
1354
+ for (const d of o.deleted) {
1355
+ const m = t.attributed(d.id);
1356
+ if (m === null) {
1357
+ M.push({ ...d });
1358
+ continue;
1359
+ }
1360
+ if (O.has(m.holder)) continue;
1361
+ const k = g(m.holder, t);
1362
+ k.fields.push(m.path);
1363
+ const w = t.namedPath(d.id);
1364
+ k.edits.push({ field: m.path, before: s.get(d.id) ?? {}, after: null, ...w === null ? {} : { named: w } });
1365
+ }
1366
+ const V = (d) => {
1367
+ const m = d.lastIndexOf(".");
1368
+ return m >= 0 && /^\d+$/.test(d.slice(m + 1)) ? d.slice(0, m) : d;
1369
+ }, E = [];
1370
+ for (const d of o.moved) {
1371
+ const [m, k] = [t.attributed(d.id), n.attributed(d.id)];
1372
+ if (m === null && k === null) {
1373
+ E.push(d);
1374
+ continue;
1375
+ }
1376
+ if (m !== null && k !== null && m.holder === k.holder) {
1377
+ if (!v.has(k.holder)) {
1378
+ const w = g(k.holder, n);
1379
+ w.fields.push(V(k.path)), w.edits.push({ field: V(k.path), before: m.path, after: k.path });
1380
+ }
1381
+ continue;
1382
+ }
1383
+ if (m !== null && !O.has(m.holder)) {
1384
+ const w = g(m.holder, t);
1385
+ w.fields.push(V(m.path)), w.edits.push({ field: V(m.path), before: m.path, after: null });
1386
+ }
1387
+ if (k !== null && !v.has(k.holder)) {
1388
+ const w = g(k.holder, n);
1389
+ w.fields.push(V(k.path)), w.edits.push({ field: V(k.path), before: null, after: k.path });
1390
+ }
1391
+ }
1392
+ for (const d of b.values()) $s(d);
1393
+ const R = {
1394
+ created: x.map((d) => ({ ...d, id: n.show(d.id) })),
1395
+ changed: S.map((d) => ({ ...d, id: n.show(d.id) })),
1396
+ moved: E.map((d) => ({ ...d, id: n.show(d.id), from: d.from ? l(t, d.from) : null, to: d.to ? l(n, d.to) : null })),
1397
+ deleted: M.map((d) => {
1398
+ const m = { ...d, id: t.show(d.id) };
1399
+ return d.at && (m.at = l(t, d.at)), m;
1400
+ })
1401
+ }, ee = (d) => [...new Set(d)].sort(I);
1402
+ for (const d of [...b.keys()].sort(I)) {
1403
+ const m = b.get(d), k = R.created.find((N) => N.id === d);
1404
+ if (k !== void 0) {
1405
+ k.fields = ee([...k.fields, ...m.fields]), k.values = { ...k.values ?? {}, ...m.values };
1406
+ continue;
1407
+ }
1408
+ if (m.fields.length === 0 && m.edits.length === 0) continue;
1409
+ let w = R.changed.find((N) => N.id === d);
1410
+ w === void 0 && (w = { id: d, type: m.type, fields: [], edits: [] }, R.changed.push(w)), w.fields = ee([...w.fields, ...m.fields]), w.edits = [...w.edits ?? [], ...m.edits].sort((N, te) => I(N.field, te.field));
1411
+ }
1412
+ return y(R.created), y(R.changed), y(R.deleted), y(R.moved), o.texts && (R.texts = o.texts.map((d) => {
1413
+ const m = u(d.id, d.field), k = (J, le) => m && le !== "" ? i(J, le) : le, w = n.attributed(d.id), [N, te] = w !== null ? [w.holder, `${w.path}.${d.field}`] : [i(n, d.id), d.field];
1414
+ return { ...d, id: N, field: te, before: k(t, d.before), after: k(n, d.after) };
1415
+ }).sort((d, m) => I(d.id, m.id) || I(d.field, m.field))), o.footprint !== void 0 && (R.footprint = o.footprint), oe.set(R, new Map([...s].map(([d, m]) => {
1416
+ const k = t.typeOf(d) ?? "";
1417
+ return [t.show(d), Object.fromEntries(Object.entries(m).map(([w, N]) => [
1418
+ w,
1419
+ f(k, w) ? r(t, N, a(k, w)) : p(k, w) ? t.showJson(N) : N
1420
+ ]))];
1421
+ }))), R;
1422
+ }
1423
+ function $s(o) {
1424
+ const e = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Map();
1425
+ for (const i of o.edits)
1426
+ i.before === null && W(i.after) && e.set(i.field, i.after), i.after === null && W(i.before) && t.set(i.field, i.before);
1427
+ const n = new Set([...e.keys()].filter((i) => t.has(i)));
1428
+ if (n.size === 0) return;
1429
+ const s = new Map(o.edits.filter((i) => n.has(i.field) && i.named !== void 0).map((i) => [i.field, i.named]));
1430
+ o.edits = o.edits.filter((i) => !n.has(i.field)), o.fields = o.fields.filter((i) => !n.has(i));
1431
+ for (const i of [...n].sort(I)) {
1432
+ const r = t.get(i), a = e.get(i);
1433
+ for (const l of [.../* @__PURE__ */ new Set([...Object.keys(r), ...Object.keys(a)])].sort(I)) {
1434
+ const c = Object.hasOwn(r, l) ? r[l] : null, f = Object.hasOwn(a, l) ? a[l] : null;
1435
+ if (!vn(c, f)) {
1436
+ o.fields.push(`${i}.${l}`);
1437
+ const u = s.get(i);
1438
+ o.edits.push({ field: `${i}.${l}`, before: c, after: f, ...u === void 0 ? {} : { named: `${u}.${l}` } });
1439
+ }
1440
+ }
1441
+ }
1442
+ }
1443
+ function On(o) {
1444
+ return Array.from(o, (e) => e.toString(16).padStart(2, "0")).join("");
1445
+ }
1446
+ function ie(o) {
1447
+ const e = On(o);
1448
+ return `${e.slice(0, 8)}-${e.slice(8, 12)}-${e.slice(12, 16)}-${e.slice(16, 20)}-${e.slice(20)}`;
1449
+ }
1450
+ const js = [
1451
+ /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i,
1452
+ /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i,
1453
+ /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i,
1454
+ /^([0-9a-f]{32})$/i
1455
+ ];
1456
+ function st(o) {
1457
+ if (typeof o != "string") throw h.encoding("a UUID is a string");
1458
+ for (const e of js) {
1459
+ const t = e.exec(o);
1460
+ if (!t) continue;
1461
+ const n = t.slice(1).join(""), s = new Uint8Array(16);
1462
+ for (let i = 0; i < 16; i += 1) s[i] = parseInt(n.slice(i * 2, i * 2 + 2), 16);
1463
+ return s;
1464
+ }
1465
+ throw h.encoding(`\`${o}\` is not a UUID`);
1466
+ }
1467
+ function $n(o = Date.now()) {
1468
+ const e = new Uint8Array(16);
1469
+ crypto.getRandomValues(e);
1470
+ let t = BigInt(o);
1471
+ for (let n = 5; n >= 0; n -= 1)
1472
+ e[n] = Number(t & 0xffn), t >>= 8n;
1473
+ return e[6] = e[6] & 15 | 112, e[8] = e[8] & 63 | 128, ie(e);
1474
+ }
1475
+ const Ss = () => $n(), io = () => $n(), Ut = (1n << 64n) - 1n;
1476
+ function Be(o) {
1477
+ if (typeof o != "bigint") throw h.encoding("an actor id is a bigint");
1478
+ if (o === Ut) throw h.encoding("actor id u64::MAX is reserved");
1479
+ if (o < 0n || o > Ut) throw h.encoding(`actor id ${o} is not an unsigned 64-bit integer`);
1480
+ return o;
1481
+ }
1482
+ function ro() {
1483
+ const o = new Uint8Array(8);
1484
+ return crypto.getRandomValues(o), BigInt(`0x${On(o)}`) >> 1n;
1485
+ }
1486
+ const St = /* @__PURE__ */ new WeakMap(), xt = Symbol("NodeRef");
1487
+ class jn {
1488
+ /** @internal */
1489
+ constructor(e, t) {
1490
+ if (e !== xt) throw new TypeError("NodeRef handles come from Tx.treeCreate and Replica.tree");
1491
+ St.set(this, t), Object.defineProperty(this, "id", { value: t.id, enumerable: !0, writable: !1, configurable: t.id === null });
1492
+ }
1493
+ equals(e) {
1494
+ return this.id !== null || e.id !== null ? this.id === e.id : this === e;
1495
+ }
1496
+ }
1497
+ const Sn = (o) => new jn(xt, { id: o }), xs = (o, e) => new jn(xt, { id: null, pending: { tx: o, index: e } }), Ms = (o) => St.get(o);
1498
+ function Is(o, e) {
1499
+ const t = St.get(o);
1500
+ !t || t.id !== null || (t.id = e, Object.defineProperty(o, "id", { value: e, enumerable: !0, writable: !1, configurable: !1 }));
1501
+ }
1502
+ function Mt(o) {
1503
+ return typeof o == "string" ? JSON.stringify(o) : o == null || typeof o == "number" || typeof o == "boolean" ? String(o) : typeof o == "bigint" ? `${o}n` : Array.isArray(o) ? "an array" : `a ${typeof o}`;
1504
+ }
1505
+ function T(o, e) {
1506
+ if (typeof e != "string") throw new K("invalid-value", `${o} must be a string, not ${Mt(e)}`);
1507
+ }
1508
+ function z(o, e) {
1509
+ if (typeof e != "number" || !Number.isSafeInteger(e) || e < 0)
1510
+ throw new K("out-of-range", `${o} ${Mt(e)} is out of range: it must be a whole number from 0`);
1511
+ }
1512
+ function Kt(o, e) {
1513
+ const t = e !== null && typeof e == "object" ? Object.getPrototypeOf(e) : void 0;
1514
+ if (t !== Object.prototype && t !== null || Object.getOwnPropertySymbols(e).length > 0)
1515
+ throw new K("invalid-value", `${o} must be a plain object, not ${Mt(e)}`);
1516
+ }
1517
+ const xn = "[A-Za-z0-9][A-Za-z0-9:_-]{0,127}", As = new RegExp(`^${xn}$`);
1518
+ function Vs(o, e) {
1519
+ if (!As.test(e)) throw h.invalidValue(o, "$id", `cannot be \`${e}\`: an object id matches \`${xn}\``);
1520
+ }
1521
+ const bt = (o) => `c:${o}`, ot = (o) => `p:${o}`, He = (o) => o.startsWith("p:") ? Number(o.slice(2)) : null, Ge = (o) => o.slice(2), Es = 4;
1522
+ class Rs {
1523
+ constructor(e, t) {
1524
+ this.committed = e, this.len = t, this.after = t > 0 ? [{ text: null, start: 0, length: t }] : [];
1525
+ }
1526
+ /** The pieces before the cursor, in order, and their total length (the cursor's position). */
1527
+ before = [];
1528
+ beforeLength = 0;
1529
+ /** The pieces after the cursor, last first: the piece right after the cursor is the last element. */
1530
+ after;
1531
+ /** The committed text, once read. */
1532
+ committedString = null;
1533
+ engineChecks = 0;
1534
+ /**
1535
+ * Whether `position` falls between the two halves of a surrogate pair. Every stored string is
1536
+ * well formed, so that is when the code unit at `position` is a low surrogate, in an inserted
1537
+ * string or in the committed text.
1538
+ */
1539
+ splits(e) {
1540
+ if (e <= 0 || e >= this.len) return !1;
1541
+ this.seek(e);
1542
+ const t = this.after[this.after.length - 1], n = t.start + e - this.beforeLength;
1543
+ return t.text !== null ? ct(t.text.charCodeAt(n)) : this.committedSplits(n);
1544
+ }
1545
+ /** Inserts `content` (well formed) at `index`. */
1546
+ insert(e, t) {
1547
+ t && (this.cut(e), this.before.push({ text: t, start: 0, length: t.length }), this.beforeLength += t.length, this.len += t.length);
1548
+ }
1549
+ /** Deletes `count` code units from `index`. */
1550
+ delete(e, t) {
1551
+ if (t !== 0) {
1552
+ this.cut(e);
1553
+ for (let n = t; n > 0; ) {
1554
+ const s = this.after.pop();
1555
+ if (s.length > n) {
1556
+ this.after.push({ text: s.text, start: s.start + n, length: s.length - n });
1557
+ break;
1558
+ }
1559
+ n -= s.length;
1560
+ }
1561
+ this.len -= t;
1562
+ }
1563
+ }
1564
+ /** The text with the pending edits applied. */
1565
+ text() {
1566
+ const e = this.before.some((s) => s.text === null) || this.after.some((s) => s.text === null) ? this.committedText() : "", t = (s) => (s.text ?? e).slice(s.start, s.start + s.length);
1567
+ let n = "";
1568
+ for (const s of this.before) n += t(s);
1569
+ for (let s = this.after.length - 1; s >= 0; s -= 1) n += t(this.after[s]);
1570
+ return n;
1571
+ }
1572
+ committedText() {
1573
+ return this.committedString ??= this.committed?.toString() ?? "", this.committedString;
1574
+ }
1575
+ /** Whether position `at` of the committed text falls inside a surrogate pair. */
1576
+ committedSplits(e) {
1577
+ const t = this.committed;
1578
+ if (!t || e <= 0 || e >= t.length) return !1;
1579
+ if (this.committedString === null && this.engineChecks < Es) {
1580
+ this.engineChecks += 1;
1581
+ const n = t.convertPos(e, "utf16", "unicode");
1582
+ return n === void 0 || t.convertPos(n, "unicode", "utf16") !== e;
1583
+ }
1584
+ return ct(this.committedText().charCodeAt(e));
1585
+ }
1586
+ /**
1587
+ * Moves the cursor to the start of the piece holding `position` (`position` < `len`), or to the
1588
+ * end when `position` is the length.
1589
+ */
1590
+ seek(e) {
1591
+ const { before: t, after: n } = this;
1592
+ for (; this.beforeLength > e; ) {
1593
+ const s = t.pop();
1594
+ this.beforeLength -= s.length, n.push(s);
1595
+ }
1596
+ for (; n.length > 0 && this.beforeLength + n[n.length - 1].length <= e; ) {
1597
+ const s = n.pop();
1598
+ this.beforeLength += s.length, t.push(s);
1599
+ }
1600
+ }
1601
+ /** Moves the cursor to `position`, splitting the piece there if `position` falls inside it. */
1602
+ cut(e) {
1603
+ this.seek(e);
1604
+ const t = e - this.beforeLength;
1605
+ if (t === 0) return;
1606
+ const n = this.after.pop();
1607
+ this.before.push({ text: n.text, start: n.start, length: t }), this.after.push({ text: n.text, start: n.start + t, length: n.length - t }), this.beforeLength = e;
1608
+ }
1609
+ }
1610
+ class Ns {
1611
+ constructor(e) {
1612
+ this.len = e;
1613
+ }
1614
+ edits = [];
1615
+ replay(e) {
1616
+ const t = [...e], n = () => h.engine("a staged list edit does not fit the list");
1617
+ for (const s of this.edits)
1618
+ if ("insert" in s) {
1619
+ if (s.insert > t.length) throw n();
1620
+ t.splice(s.insert, 0, s.item);
1621
+ } else if ("move" in s) {
1622
+ if (s.move >= t.length || s.to >= t.length) throw n();
1623
+ t.splice(s.to, 0, ...t.splice(s.move, 1));
1624
+ } else {
1625
+ if (s.remove >= t.length) throw n();
1626
+ t.splice(s.remove, 1);
1627
+ }
1628
+ return t;
1629
+ }
1630
+ }
1631
+ class Ts {
1632
+ constructor(e) {
1633
+ this.committed = e;
1634
+ }
1635
+ /** `null` as a value: the node is a root. */
1636
+ parents = /* @__PURE__ */ new Map();
1637
+ /** Nodes this transaction deleted (M10b). */
1638
+ deleted = /* @__PURE__ */ new Set();
1639
+ /** The node's parent (`null`: a root), or `undefined` if the tree has no such live node. */
1640
+ parent(e) {
1641
+ if (this.deleted.has(e)) return;
1642
+ if (this.parents.has(e)) return this.parents.get(e);
1643
+ if (He(e) !== null || !this.committed) return;
1644
+ const t = this.committed.getNodeByID(Ge(e));
1645
+ if (!t || t.isDeleted()) return;
1646
+ const n = t.parent();
1647
+ return n ? bt(n.id) : null;
1648
+ }
1649
+ contains(e) {
1650
+ return this.parent(e) !== void 0;
1651
+ }
1652
+ /** Whether making `parent` the parent of `node` makes `node` its own ancestor. A looping chain (a corrupt tree) counts as a cycle. */
1653
+ wouldCycle(e, t) {
1654
+ const n = /* @__PURE__ */ new Set();
1655
+ let s = t;
1656
+ for (; s != null; ) {
1657
+ if (s === e || n.has(s)) return !0;
1658
+ n.add(s), s = this.parent(s);
1659
+ }
1660
+ return !1;
1661
+ }
1662
+ }
1663
+ function Cs(o, e, t, n, s) {
1664
+ const i = new Array(n.length);
1665
+ for (const r of t) {
1666
+ r.op !== "raiseSchema" && s(r.id);
1667
+ try {
1668
+ Fs(o, e, r, i);
1669
+ } catch (a) {
1670
+ throw a instanceof K ? a : h.engine(a instanceof Error ? a.message : String(a));
1671
+ }
1672
+ }
1673
+ n.forEach((r, a) => {
1674
+ const l = i[a];
1675
+ l !== void 0 && Is(r, l);
1676
+ });
1677
+ }
1678
+ const qt = 1024;
1679
+ function Ds(o, e, t) {
1680
+ if (t.length <= qt) {
1681
+ o.insert(e, t);
1682
+ return;
1683
+ }
1684
+ const n = [];
1685
+ for (let i = 0; i < t.length; ) {
1686
+ n.push(i);
1687
+ let r = i + qt;
1688
+ const a = t.charCodeAt(r);
1689
+ r < t.length && a >= 56320 && a <= 57343 && (r += 1), i = r;
1690
+ }
1691
+ let s = t.length;
1692
+ for (let i = n.length - 1; i >= 0; i -= 1)
1693
+ o.insert(e, t.slice(n[i], s)), s = n[i];
1694
+ }
1695
+ function Fs(o, e, t, n) {
1696
+ switch (t.op) {
1697
+ case "create": {
1698
+ const s = o.getMap(Y).setContainer(t.id, new pe());
1699
+ s.set(ce, t.ty);
1700
+ for (const r of D(t.fields)) s.set(r, t.fields[r]);
1701
+ const i = e.types[t.ty].fields;
1702
+ for (const r of D(i)) {
1703
+ const a = i[r].kind;
1704
+ a === "text" ? s.setContainer(r, new on()) : a === "list" ? s.setContainer(r, new sn()) : a === "tree" ? s.setContainer(r, new nn()) : a === "map" && s.setContainer(r, new pe());
1705
+ }
1706
+ return;
1707
+ }
1708
+ case "set":
1709
+ return q(o, t.id).set(t.field, t.value);
1710
+ case "delete":
1711
+ return o.getMap(Y).delete(t.id);
1712
+ case "textInsert":
1713
+ return Ds(L(o, t.id, t.field, "text"), t.index, t.content);
1714
+ case "textDelete":
1715
+ return L(o, t.id, t.field, "text").delete(t.index, t.count);
1716
+ case "textMark":
1717
+ return L(o, t.id, t.field, "text").mark({ start: t.start, end: t.end }, t.key, t.value);
1718
+ case "textUnmark":
1719
+ return L(o, t.id, t.field, "text").unmark({ start: t.start, end: t.end }, t.key);
1720
+ case "listInsert":
1721
+ return L(o, t.id, t.field, "list").insert(t.index, t.item);
1722
+ case "listMove":
1723
+ return L(o, t.id, t.field, "list").move(t.from, t.to);
1724
+ case "listRemove":
1725
+ return L(o, t.id, t.field, "list").delete(t.index, 1);
1726
+ case "mapSet":
1727
+ return L(o, t.id, t.field, "map").set(t.key, t.value);
1728
+ case "mapDelete":
1729
+ return L(o, t.id, t.field, "map").delete(t.key);
1730
+ case "treeCreate": {
1731
+ const s = L(o, t.id, t.field, "tree").createNode(Pe(n, t.parent));
1732
+ s.data.set(Ot, t.object), n[t.node] = s.id;
1733
+ return;
1734
+ }
1735
+ case "treeMove": {
1736
+ const s = Pe(n, t.node);
1737
+ if (s === void 0) throw h.engine("a staged tree move has no node");
1738
+ return L(o, t.id, t.field, "tree").move(s, Pe(n, t.parent));
1739
+ }
1740
+ case "treeDelete": {
1741
+ const s = Pe(n, t.node);
1742
+ if (s === void 0) throw h.engine("a staged tree delete has no node");
1743
+ return L(o, t.id, t.field, "tree").delete(s);
1744
+ }
1745
+ case "raiseSchema": {
1746
+ const s = fe(o);
1747
+ if (s !== null && s >= t.version) return;
1748
+ o.getMap(ue).set(Re, t.version), o.getMap(cn).set(String(t.version), !0);
1749
+ return;
1750
+ }
1751
+ }
1752
+ }
1753
+ function L(o, e, t, n) {
1754
+ const s = G(q(o, e).get(t), n, e, t);
1755
+ if (!s) throw h.notFound(`${e}.${t}`);
1756
+ return s;
1757
+ }
1758
+ function Pe(o, e) {
1759
+ if (e === null) return;
1760
+ const t = He(e);
1761
+ if (t === null) return Ge(e);
1762
+ const n = o[t];
1763
+ if (n === void 0) throw h.engine(`tree node ${t} is used before it exists`);
1764
+ return n;
1765
+ }
1766
+ function C(o, e) {
1767
+ T("an object id", o), T("a field name", e);
1768
+ }
1769
+ const H = (o, e) => JSON.stringify([o, e]);
1770
+ let Ws = 1;
1771
+ class Xe {
1772
+ constructor(e, t) {
1773
+ this.doc = e, this.schema = t;
1774
+ }
1775
+ serial = Ws++;
1776
+ ops = [];
1777
+ /** Objects this transaction created: their type and the index of their `create` operation. */
1778
+ created = /* @__PURE__ */ new Map();
1779
+ deleted = /* @__PURE__ */ new Set();
1780
+ /** Register writes: the index of the latest `set` operation of each field. */
1781
+ registers = /* @__PURE__ */ new Map();
1782
+ texts = /* @__PURE__ */ new Map();
1783
+ lists = /* @__PURE__ */ new Map();
1784
+ trees = /* @__PURE__ */ new Map();
1785
+ /** Map writes by field: for each key written, the index of its latest `mapSet` operation, or `null` when the latest write deleted it. */
1786
+ maps = /* @__PURE__ */ new Map();
1787
+ /** The ids of `created` by type, in creation order (deleted ones included). */
1788
+ createdByType = /* @__PURE__ */ new Map();
1789
+ nodes = [];
1790
+ /** The largest schema version this transaction raised the document to. */
1791
+ raised = null;
1792
+ ended = !1;
1793
+ /** @internal Runs `build` on a new transaction; answers its result and its staged operations. */
1794
+ static stage(e, t, n) {
1795
+ const s = new Xe(e, t);
1796
+ let i;
1797
+ try {
1798
+ i = n(s);
1799
+ } finally {
1800
+ s.ended = !0;
1801
+ }
1802
+ if (typeof i?.then == "function")
1803
+ throw h.engine("a transaction runs synchronously; its function returned a promise");
1804
+ const { ops: r, nodes: a } = s, l = new Set(r.flatMap((c) => c.op === "create" ? [c.id] : []));
1805
+ return {
1806
+ result: i,
1807
+ staged: {
1808
+ empty: r.length === 0,
1809
+ raisesSchema: r.some((c) => c.op === "raiseSchema"),
1810
+ undoTouches: r.flatMap((c, f) => {
1811
+ if (c.op === "raiseSchema") return [];
1812
+ const u = [{ id: c.id, fields: "field" in c ? [c.field] : null }];
1813
+ let p;
1814
+ if (c.op === "listInsert") p = c.item;
1815
+ else if (c.op === "treeCreate") p = c.object;
1816
+ else if (c.op === "listMove" || c.op === "listRemove")
1817
+ p = s.undoListItem(c.id, c.field, c.op === "listMove" ? c.from : c.index, f);
1818
+ else if ((c.op === "treeMove" || c.op === "treeDelete") && He(c.node) === null) {
1819
+ const $ = B(e, t, c.id, c.field, "tree")?.getNodeByID(Ge(c.node));
1820
+ p = $ ? Le($) ?? void 0 : void 0;
1821
+ }
1822
+ return p && u.push({ id: p, fields: [] }), u;
1823
+ }),
1824
+ apply: (c, f, u) => Cs(c, f, r, a, u),
1825
+ // Writes to an object the same operations create are left out, as its creation's own
1826
+ // fields are: no undo reaches such a register before a later write replaces it (undoing
1827
+ // the creation removes the whole object), so the replica keeps no note of them.
1828
+ registerWrites: r.flatMap((c) => (c.op === "set" || c.op === "mapSet" || c.op === "mapDelete") && l.has(c.id) ? [] : c.op === "set" ? [{ id: c.id, field: null, key: c.field, value: c.value }] : c.op === "mapSet" ? [{ id: c.id, field: c.field, key: c.key, value: c.value }] : c.op === "mapDelete" ? [{ id: c.id, field: c.field, key: c.key, value: void 0 }] : [])
1829
+ }
1830
+ };
1831
+ }
1832
+ undoListItem(e, t, n, s) {
1833
+ for (let r = s - 1; r >= 0; r -= 1) {
1834
+ const a = this.ops[r];
1835
+ if (!(!("id" in a) || a.id !== e || !("field" in a) || a.field !== t))
1836
+ if (a.op === "listInsert") {
1837
+ if (n === a.index) return a.item;
1838
+ n > a.index && (n -= 1);
1839
+ } else a.op === "listRemove" ? n >= a.index && (n += 1) : a.op === "listMove" && (n === a.to ? n = a.from : a.from < a.to && n >= a.from && n < a.to ? n += 1 : a.to < a.from && n > a.to && n <= a.from && (n -= 1));
1840
+ }
1841
+ if (this.created.has(e)) return;
1842
+ const i = B(this.doc, this.schema, e, t, "list")?.get(n);
1843
+ return typeof i == "string" ? i : void 0;
1844
+ }
1845
+ /**
1846
+ * Raises the document's minimum schema version to `version` (rule M20): replicas whose schema is
1847
+ * older then refuse to load the document or import its changes (`newer-schema`). A migration
1848
+ * raises the version in the transaction that rewrites the document into the new form. Answers
1849
+ * whether the version rose: raising to a version the document already has, or a lower one,
1850
+ * changes nothing. Concurrent raises keep the largest.
1851
+ *
1852
+ * Only a `system` transaction raises the version, so it is never an undo step (`transact`
1853
+ * refuses others as `invalid-value`). `version` is at most the transaction's schema version: a
1854
+ * build cannot require a schema it does not read.
1855
+ */
1856
+ raiseSchemaVersion(e) {
1857
+ if (this.live(), !(typeof e == "number" && Number.isInteger(e) && e >= 0))
1858
+ throw h.invalidValue("$meta", "schemaVersion", "cannot be raised to a value that is not a non-negative integer");
1859
+ if (e > this.schema.schemaVersion)
1860
+ throw h.invalidValue("$meta", "schemaVersion", `cannot be raised to ${e}: this kit reads schema versions up to ${this.schema.schemaVersion}`);
1861
+ return e <= this.minSchemaVersion() ? !1 : (this.raised = e, this.ops.push({ op: "raiseSchema", version: e }), !0);
1862
+ }
1863
+ /** The document's minimum schema version (rule M20), including this transaction's raises. */
1864
+ minSchemaVersion() {
1865
+ return Math.max(fe(this.doc) ?? 0, this.raised ?? 0);
1866
+ }
1867
+ /**
1868
+ * Creates an object of type `ty` with its register fields; container fields start empty. Its id
1869
+ * is a new UUID v7, or `options.id`: an id the host chose, matching
1870
+ * `[A-Za-z0-9][A-Za-z0-9:_-]{0,127}` and naming no object of the document or of this
1871
+ * transaction (one it deleted included); otherwise `invalid-value`. Replicas that create one id
1872
+ * concurrently keep one of the objects.
1873
+ */
1874
+ create(e, t, n) {
1875
+ this.live(), T("a type name", e), Kt("the fields", t);
1876
+ let s;
1877
+ if (n !== void 0) {
1878
+ Kt("the options", n);
1879
+ const f = Object.keys(n).find((u) => u !== "id");
1880
+ if (f !== void 0) throw new K("invalid-value", `the options take only \`id\`, not \`${f}\``);
1881
+ s = n.id, s !== void 0 && T("an object id", s);
1882
+ }
1883
+ if (!Object.hasOwn(this.schema.types, e)) throw h.unknownType(e);
1884
+ const i = this.schema.types[e];
1885
+ if (i.projected) throw h.invalidValue(e, "$type", "projected objects are computed by the kit, never stored");
1886
+ const r = D(t), a = {};
1887
+ for (const f of r) {
1888
+ const u = ht(this.schema, e, f, t[f]);
1889
+ typeof u == "string" && this.checkOf(e, f, i.fields[f], u), _(a, f, u);
1890
+ }
1891
+ for (const f of D(i.fields)) {
1892
+ const u = i.fields[f];
1893
+ if (!qe(u.kind) && !u.optional && !Object.hasOwn(t, f)) throw h.invalidValue(e, f, "is required");
1894
+ }
1895
+ const l = s === void 0 ? Ss() : this.freeId(e, s);
1896
+ this.created.set(l, { ty: e, op: this.ops.length });
1897
+ const c = this.createdByType.get(e);
1898
+ return c ? c.push(l) : this.createdByType.set(e, [l]), this.ops.push({ op: "create", id: l, ty: e, fields: a }), l;
1899
+ }
1900
+ /** Sets one register field. Concurrent sets of one field resolve to one winner; sets of different fields both survive. */
1901
+ set(e, t, n) {
1902
+ this.live(), C(e, t);
1903
+ const { ty: s, def: i } = this.field(e, t), r = ht(this.schema, s, t, n);
1904
+ typeof r == "string" && this.checkOf(s, t, i, r), this.registers.set(H(e, t), this.ops.length), this.ops.push({ op: "set", id: e, field: t, value: r });
1905
+ }
1906
+ /** Deletes an object. References to it dangle; kits treat that as a validation state. */
1907
+ delete(e) {
1908
+ if (!this.exists(e)) throw h.notFound(e);
1909
+ this.deleted.add(e), this.ops.push({ op: "delete", id: e });
1910
+ }
1911
+ exists(e) {
1912
+ return this.live(), T("an object id", e), !this.deleted.has(e) && (this.created.has(e) || this.doc.getMap(Y).get(e) instanceof pe);
1913
+ }
1914
+ /** Whether this transaction already removed the object, including an ownership cascade. */
1915
+ wasDeleted(e) {
1916
+ return this.deleted.has(e);
1917
+ }
1918
+ /** The type of a live object, including one this transaction created; not-found for an object it deleted. */
1919
+ objectType(e) {
1920
+ return this.live(), T("an object id", e), this.typeOf(e);
1921
+ }
1922
+ get(e, t) {
1923
+ this.live(), C(e, t);
1924
+ const { ty: n, def: s } = this.field(e, t);
1925
+ if (qe(s.kind)) throw h.invalidValue(n, t, "is a container; read it with its accessor");
1926
+ const i = this.pendingRegister(e, t);
1927
+ return i !== void 0 ? i : $t(this.doc, this.schema, e, t);
1928
+ }
1929
+ /** Inserts `content` at `index`, counted in UTF-16 code units. */
1930
+ textInsert(e, t, n, s) {
1931
+ this.live(), C(e, t), z("index", n), T("the content", s), this.containerField(e, t, "text");
1932
+ const i = this.textState(e, t, !0);
1933
+ if (n > i.len) throw h.outOfRange(n, i.len);
1934
+ if (i.splits(n)) throw Ae(n);
1935
+ const r = ve(s);
1936
+ this.texts.set(H(e, t), i), i.insert(n, r), this.ops.push({ op: "textInsert", id: e, field: t, index: n, content: r });
1937
+ }
1938
+ /** Deletes `count` UTF-16 code units starting at `index`. */
1939
+ textDelete(e, t, n, s) {
1940
+ this.live(), C(e, t), z("index", n), z("count", s), this.containerField(e, t, "text");
1941
+ const i = this.textState(e, t, !0), r = n + s;
1942
+ if (r > i.len) throw h.outOfRange(r, i.len);
1943
+ if (i.splits(n)) throw Ae(n);
1944
+ if (i.splits(r)) throw Ae(r);
1945
+ this.texts.set(H(e, t), i), i.delete(n, s), this.ops.push({ op: "textDelete", id: e, field: t, index: n, count: s });
1946
+ }
1947
+ /** The length of a text field in UTF-16 code units, including this transaction's edits. */
1948
+ textLength(e, t) {
1949
+ return this.live(), C(e, t), this.containerField(e, t, "text"), this.textState(e, t, !1).len;
1950
+ }
1951
+ /** A text field including this transaction's edits. Reads the whole text. */
1952
+ text(e, t) {
1953
+ return this.live(), C(e, t), this.containerField(e, t, "text"), this.textState(e, t, !1).text();
1954
+ }
1955
+ /**
1956
+ * Sets mark `key` to `value` over the code units `start..end` of a text field (rule M19). The
1957
+ * field declares `key` in its schema `marks`; `value` is plain JSON and not `null` (remove a
1958
+ * mark with `textUnmark`). An empty range changes nothing. Concurrent marks of one key over
1959
+ * overlapping ranges resolve to one value per character; marks of different keys all apply.
1960
+ */
1961
+ textMark(e, t, n, s, i, r) {
1962
+ this.live(), C(e, t), z("index", n), z("index", s), T("a mark key", i);
1963
+ const a = this.markKey(e, t, i);
1964
+ if (r == null) throw h.invalidValue(a, t, `mark \`${i}\` takes a value; remove a mark with textUnmark`);
1965
+ const l = lt(r, (c) => h.invalidValue(a, t, `mark \`${i}\` ${c}`));
1966
+ this.markRange(e, t, n, s) && this.ops.push({ op: "textMark", id: e, field: t, start: n, end: s, key: i, value: l });
1967
+ }
1968
+ /** Removes mark `key` from the code units `start..end` of a text field. Characters without the mark are left as they are; an empty range changes nothing. */
1969
+ textUnmark(e, t, n, s, i) {
1970
+ this.live(), C(e, t), z("index", n), z("index", s), T("a mark key", i), this.markKey(e, t, i), this.markRange(e, t, n, s) && this.ops.push({ op: "textUnmark", id: e, field: t, start: n, end: s, key: i });
1971
+ }
1972
+ listInsert(e, t, n, s) {
1973
+ this.live(), C(e, t), z("index", n), T("a list item", s);
1974
+ const { ty: i, def: r } = this.containerField(e, t, "list");
1975
+ this.checkOf(i, t, r, s);
1976
+ const a = this.listState(e, t);
1977
+ if (n > a.len) throw h.outOfRange(n, a.len);
1978
+ a.len += 1, a.edits.push({ insert: n, item: s }), this.ops.push({ op: "listInsert", id: e, field: t, index: n, item: s });
1979
+ }
1980
+ /** Moves the item at `from` so that it ends at index `to`. */
1981
+ listMove(e, t, n, s) {
1982
+ this.live(), C(e, t), z("index", n), z("index", s), this.containerField(e, t, "list");
1983
+ const i = this.listState(e, t);
1984
+ if (n >= i.len || s >= i.len) throw h.outOfRange(Math.max(n, s), i.len);
1985
+ i.edits.push({ move: n, to: s }), this.ops.push({ op: "listMove", id: e, field: t, from: n, to: s });
1986
+ }
1987
+ listRemove(e, t, n) {
1988
+ this.live(), C(e, t), z("index", n), this.containerField(e, t, "list");
1989
+ const s = this.listState(e, t);
1990
+ if (n >= s.len) throw h.outOfRange(n, s.len);
1991
+ s.len -= 1, s.edits.push({ remove: n }), this.ops.push({ op: "listRemove", id: e, field: t, index: n });
1992
+ }
1993
+ /** The list's items including this transaction's edits. Reads the whole list: call it only when the items themselves are wanted. */
1994
+ listItems(e, t) {
1995
+ this.live(), C(e, t), this.containerField(e, t, "list");
1996
+ const n = G(this.stored(e, t, !1), "list", e, t), s = n ? Ze(n.toArray()) : [];
1997
+ return this.lists.get(H(e, t))?.replay(s) ?? s;
1998
+ }
1999
+ /** `listItems` under the name `Replica` uses. */
2000
+ list(e, t) {
2001
+ return this.listItems(e, t);
2002
+ }
2003
+ /** Sets `key` of a map field. Concurrent sets of one key resolve to one winner. */
2004
+ mapSet(e, t, n, s) {
2005
+ this.live(), C(e, t), T("a map key", n);
2006
+ const i = this.writableMap(e, t), r = lt(s, (l) => h.invalidValue(i, t, l));
2007
+ Xn(this.schema, i, t, n, r), typeof r == "string" && this.checkOf(i, t, this.schema.types[i].fields[t], r);
2008
+ const a = ve(n);
2009
+ this.mapWrites(e, t).set(a, this.ops.length), this.ops.push({ op: "mapSet", id: e, field: t, key: a, value: r });
2010
+ }
2011
+ mapDelete(e, t, n) {
2012
+ this.live(), C(e, t), T("a map key", n), this.writableMap(e, t);
2013
+ const s = ve(n);
2014
+ this.mapWrites(e, t).set(s, null), this.ops.push({ op: "mapDelete", id: e, field: t, key: s });
2015
+ }
2016
+ /**
2017
+ * One key of a map field including this transaction's writes, or `null`, as `Replica.mapGet`
2018
+ * reads it. Costs one lookup in the transaction's writes of the field and at most one in the
2019
+ * document, however large the transaction.
2020
+ */
2021
+ mapGet(e, t, n) {
2022
+ this.live(), C(e, t), T("a map key", n), this.containerField(e, t, "map");
2023
+ const s = ve(n), i = this.maps.get(H(e, t))?.get(s);
2024
+ if (i !== void 0) return this.pendingMapValue(i);
2025
+ const r = G(this.stored(e, t, !1), "map", e, t);
2026
+ return r ? Ye(r.get(s)) : null;
2027
+ }
2028
+ /**
2029
+ * A map field's keys and values including this transaction's writes, sorted by key (code point
2030
+ * order, as in the canonical state), each as `mapGet` reads it. Reads the whole map and sorts
2031
+ * the result on every call, O(n log n) in its keys: call it only when every entry is wanted.
2032
+ */
2033
+ mapEntries(e, t) {
2034
+ this.live(), C(e, t), this.containerField(e, t, "map");
2035
+ const n = G(this.stored(e, t, !1), "map", e, t), s = n ? un(n) : [], i = this.maps.get(H(e, t));
2036
+ if (!i) return s;
2037
+ const r = new Map(s);
2038
+ for (const [a, l] of i)
2039
+ l === null ? r.delete(a) : r.set(a, this.pendingMapValue(l));
2040
+ return [...r].sort((a, l) => I(a[0], l[0]));
2041
+ }
2042
+ /**
2043
+ * Ids of the live objects of type `ty`, including those this transaction created and without
2044
+ * those it deleted, sorted as `Replica.objectsOfType` sorts them. One pass over every object of
2045
+ * the document, O(objects) per call, plus this transaction's creations of `ty`; when it created
2046
+ * any, the whole result is sorted again, O(n log n) per call.
2047
+ */
2048
+ objectsOfType(e) {
2049
+ this.live(), T("a type name", e);
2050
+ const t = (i) => !this.deleted.has(i);
2051
+ let n = pn(this.doc, e);
2052
+ this.deleted.size > 0 && (n = n.filter(t));
2053
+ const s = this.createdByType.get(e);
2054
+ return s ? n.concat(s.filter(t)).sort(I) : n;
2055
+ }
2056
+ /** Adds a node naming `object` under `parent` (`null`: a root), last among its siblings. The handle resolves when the transaction commits. */
2057
+ treeCreate(e, t, n, s) {
2058
+ this.live(), C(e, t), T("a tree node object", s);
2059
+ const { ty: i, def: r } = this.containerField(e, t, "tree");
2060
+ this.checkOf(i, t, r, s);
2061
+ const a = n == null ? null : this.nodeKey(n), l = this.nodes.length, c = this.treeState(e, t);
2062
+ if (a !== null && !c.contains(a)) throw h.notFound(`parent node in ${e}.${t}`);
2063
+ c.parents.set(ot(l), a);
2064
+ const f = xs(this.serial, l);
2065
+ return this.nodes.push(f), this.ops.push({ op: "treeCreate", id: e, field: t, parent: a, object: s, node: l }), f;
2066
+ }
2067
+ /**
2068
+ * Moves `node` under `parent` (`null`: a root), last among its siblings. A move that would make a
2069
+ * node its own ancestor (counting this transaction's earlier moves) is a `cycle` error; concurrent
2070
+ * moves that would form a cycle are resolved by the engine.
2071
+ */
2072
+ treeMove(e, t, n, s) {
2073
+ this.live(), C(e, t), this.containerField(e, t, "tree");
2074
+ const i = this.nodeKey(n), r = s == null ? null : this.nodeKey(s), a = this.treeState(e, t);
2075
+ if (!a.contains(i) || r !== null && !a.contains(r)) throw h.notFound(`node in ${e}.${t}`);
2076
+ if (r !== null && a.wouldCycle(i, r)) throw h.cycle();
2077
+ a.parents.set(i, r), this.ops.push({ op: "treeMove", id: e, field: t, node: i, parent: r });
2078
+ }
2079
+ /**
2080
+ * Rule M10b: leaves every object of the tree named by one node. For each object that several of
2081
+ * the document's nodes name (a redo made a new node for it while another replica's concurrent
2082
+ * move kept the old one alive), the node kept is the least by engine id (peer, then counter)
2083
+ * among those with no ancestor naming the same object; every other node naming it has its
2084
+ * children moved, in order, to the end of the kept node's children, and is then deleted. The
2085
+ * choice depends on the state alone, so replicas that repair one state concurrently make the
2086
+ * same moves and deletes. Nodes this transaction created are not considered. Answers how many
2087
+ * nodes it deleted; 0 writes nothing. Run it in a kit's repair (engine contract E14, a `system`
2088
+ * transaction) for every tree field.
2089
+ */
2090
+ treeDedupe(e, t) {
2091
+ this.live(), C(e, t), this.containerField(e, t, "tree");
2092
+ let n = 0;
2093
+ for (let s = this.treeDuplicate(e, t); s; s = this.treeDuplicate(e, t)) {
2094
+ const [i, r] = s;
2095
+ for (const c of this.tree(e, t))
2096
+ c.parent?.id === r.id && this.treeMove(e, t, c.node, i);
2097
+ const a = this.nodeKey(r), l = this.treeState(e, t);
2098
+ l.parents.delete(a), l.deleted.add(a), this.ops.push({ op: "treeDelete", id: e, field: t, node: a }), n += 1;
2099
+ }
2100
+ return n;
2101
+ }
2102
+ /** The first object in pre-order that several of the document's nodes name (M10b): the node to keep and the first other one in pre-order. */
2103
+ treeDuplicate(e, t) {
2104
+ const n = this.tree(e, t).filter((p) => p.node.id !== null), s = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map();
2105
+ let r = null;
2106
+ for (const p of n) {
2107
+ s.set(p.node.id, p.parent?.id ?? null);
2108
+ const y = i.get(p.object) ?? [];
2109
+ y.push(p.node), i.set(p.object, y), y.length === 2 && r === null && (r = p.object);
2110
+ }
2111
+ const a = r === null ? void 0 : i.get(r);
2112
+ if (!a) return null;
2113
+ const l = new Set(a.map((p) => p.id)), c = (p) => {
2114
+ for (let y = s.get(p.id) ?? null; y !== null; y = s.get(y) ?? null)
2115
+ if (l.has(y)) return !1;
2116
+ return !0;
2117
+ }, f = a.filter(c).sort((p, y) => Bs(p.id, y.id))[0], u = f && a.find((p) => p.id !== f.id);
2118
+ return f && u ? [f, u] : null;
2119
+ }
2120
+ /**
2121
+ * The tree's nodes in pre-order as this transaction sees it: the document's nodes plus the nodes
2122
+ * it created, each node it created or moved last among its new siblings, as they will be once it
2123
+ * applies. A node that names no object is skipped with its subtree, as in `Replica.tree`. Reads
2124
+ * the whole tree: O(nodes + this transaction's operations).
2125
+ */
2126
+ tree(e, t) {
2127
+ this.live(), C(e, t), this.containerField(e, t, "tree");
2128
+ const n = G(this.stored(e, t, !1), "tree", e, t), s = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map(), a = (p, y) => {
2129
+ const $ = s.get(p);
2130
+ $ ? $.push(y) : s.set(p, [y]), i.set(y, p);
2131
+ }, l = (p, y) => {
2132
+ for (const $ of p ?? []) {
2133
+ const j = bt($.id);
2134
+ a(y, j), r.set(j, Le($)), l($.children(), j);
2135
+ }
2136
+ };
2137
+ n && l(n.roots(), null);
2138
+ for (const p of this.ops)
2139
+ if (p.op === "treeCreate" && p.id === e && p.field === t) {
2140
+ const y = ot(p.node);
2141
+ a(p.parent, y), r.set(y, p.object);
2142
+ } else if (p.op === "treeMove" && p.id === e && p.field === t) {
2143
+ const y = i.get(p.node);
2144
+ y !== void 0 && s.set(y, (s.get(y) ?? []).filter(($) => $ !== p.node)), a(p.parent, p.node);
2145
+ } else if (p.op === "treeDelete" && p.id === e && p.field === t) {
2146
+ const y = i.get(p.node);
2147
+ y !== void 0 && s.set(y, (s.get(y) ?? []).filter(($) => $ !== p.node)), i.delete(p.node);
2148
+ }
2149
+ const c = (p) => {
2150
+ const y = He(p);
2151
+ if (y === null) return Sn(Ge(p));
2152
+ const $ = this.nodes[y];
2153
+ if (!$) throw h.engine(`tree node ${y} was not staged`);
2154
+ return $;
2155
+ }, f = [], u = (p, y) => {
2156
+ for (const $ of s.get(p) ?? []) {
2157
+ const j = r.get($);
2158
+ if (j == null) continue;
2159
+ const b = c($);
2160
+ f.push({ node: b, object: j, parent: y }), u($, b);
2161
+ }
2162
+ };
2163
+ return u(null, null), f;
2164
+ }
2165
+ /** Checks an id the host chose for a new object of type `ty`. */
2166
+ freeId(e, t) {
2167
+ if (Vs(e, t), this.created.has(t) || this.deleted.has(t) || this.doc.getMap(Y).get(t) !== void 0)
2168
+ throw h.invalidValue(e, "$id", `cannot be \`${t}\`: that object id is taken`);
2169
+ return t;
2170
+ }
2171
+ live() {
2172
+ if (this.ended) throw h.engine("the transaction has ended");
2173
+ }
2174
+ /** The type of a live object, declared by the schema. */
2175
+ typeOf(e) {
2176
+ if (this.deleted.has(e)) throw h.notFound(e);
2177
+ const t = this.created.get(e);
2178
+ if (t) return t.ty;
2179
+ const n = Ne(this.doc, e);
2180
+ if (!Object.hasOwn(this.schema.types, n)) throw h.unknownType(n);
2181
+ return n;
2182
+ }
2183
+ /** The object's type and the definition of `field`. */
2184
+ field(e, t) {
2185
+ const n = this.typeOf(e), s = this.schema.types[n].fields;
2186
+ if (!Object.hasOwn(s, t)) throw h.unknownField(n, t, Object.keys(s).sort());
2187
+ return { ty: n, def: s[t] };
2188
+ }
2189
+ containerField(e, t, n) {
2190
+ const s = this.field(e, t);
2191
+ if (s.def.kind !== n) throw fn(s.ty, t, n);
2192
+ return s;
2193
+ }
2194
+ /** Refuses a target that exists but is not of the field's `of` type. A missing target is accepted: a dangling reference is a validation state. */
2195
+ checkOf(e, t, n, s) {
2196
+ const i = n?.of;
2197
+ if (i === void 0) return;
2198
+ let r = null;
2199
+ if (!this.deleted.has(s) && (r = this.created.get(s)?.ty ?? null, r === null))
2200
+ try {
2201
+ r = Ne(this.doc, s);
2202
+ } catch {
2203
+ r = null;
2204
+ }
2205
+ if (r !== null && r !== i) throw h.invalidValue(e, t, `expects an object of type \`${i}\`, and \`${s}\` is a \`${r}\``);
2206
+ }
2207
+ /**
2208
+ * The document's container for a field, or `null` when it starts empty: the object was created
2209
+ * by this transaction, or (for reads) it predates the field. Writes to a field the stored object
2210
+ * lacks are `not-found`.
2211
+ */
2212
+ stored(e, t, n) {
2213
+ if (this.created.has(e)) return;
2214
+ const s = q(this.doc, e).get(t);
2215
+ if (s === void 0 && n) throw h.notFound(`${e}.${t}`);
2216
+ return s;
2217
+ }
2218
+ /** The pending writes of a map field, made on first use. */
2219
+ mapWrites(e, t) {
2220
+ const n = H(e, t);
2221
+ let s = this.maps.get(n);
2222
+ return s || this.maps.set(n, s = /* @__PURE__ */ new Map()), s;
2223
+ }
2224
+ /** The value of the `mapSet` operation at `index` (`null`: a deletion), as the engine will store it. */
2225
+ pendingMapValue(e) {
2226
+ if (e === null) return null;
2227
+ const t = this.ops[e];
2228
+ return t.op === "mapSet" ? X(t.value) : null;
2229
+ }
2230
+ pendingRegister(e, t) {
2231
+ const n = this.registers.get(H(e, t));
2232
+ if (n !== void 0) {
2233
+ const r = this.ops[n];
2234
+ if (r.op === "set") return X(r.value);
2235
+ }
2236
+ const s = this.created.get(e);
2237
+ if (!s) return;
2238
+ const i = this.ops[s.op];
2239
+ return i.op === "create" ? X(i.fields[t] ?? null) : void 0;
2240
+ }
2241
+ /** The text's state: this transaction's, or a fresh one over the document's text (not recorded until an edit succeeds). */
2242
+ textState(e, t, n) {
2243
+ const s = this.texts.get(H(e, t));
2244
+ if (s) return s;
2245
+ const i = G(this.stored(e, t, n), "text", e, t);
2246
+ return new Rs(i, i?.length ?? 0);
2247
+ }
2248
+ /** Checks that `field` is a text field declaring mark `key`; answers the object's type. */
2249
+ markKey(e, t, n) {
2250
+ const { ty: s, def: i } = this.containerField(e, t, "text");
2251
+ if (!i.marks || !Object.hasOwn(i.marks, n)) throw h.invalidValue(s, t, `declares no mark \`${n}\``);
2252
+ return s;
2253
+ }
2254
+ /** Checks a mark's range against the text including this transaction's edits; answers whether it holds any character. */
2255
+ markRange(e, t, n, s) {
2256
+ const i = this.textState(e, t, !0);
2257
+ if (s > i.len) throw h.outOfRange(s, i.len);
2258
+ if (n > s) throw h.outOfRange(n, s);
2259
+ if (i.splits(n)) throw Ae(n);
2260
+ if (i.splits(s)) throw Ae(s);
2261
+ return n < s;
2262
+ }
2263
+ listState(e, t) {
2264
+ const n = H(e, t);
2265
+ let s = this.lists.get(n);
2266
+ if (!s) {
2267
+ const i = G(this.stored(e, t, !0), "list", e, t);
2268
+ s = new Ns(i?.length ?? 0), this.lists.set(n, s);
2269
+ }
2270
+ return s;
2271
+ }
2272
+ /** Checks a map field for writing; answers the object's type. */
2273
+ writableMap(e, t) {
2274
+ const { ty: n } = this.containerField(e, t, "map");
2275
+ return G(this.stored(e, t, !0), "map", e, t), n;
2276
+ }
2277
+ treeState(e, t) {
2278
+ const n = H(e, t);
2279
+ let s = this.trees.get(n);
2280
+ return s || (s = new Ts(G(this.stored(e, t, !0), "tree", e, t)), this.trees.set(n, s)), s;
2281
+ }
2282
+ /** A handle as this transaction sees it. A handle of another transaction that never applied (it failed) names no node. */
2283
+ nodeKey(e) {
2284
+ const t = Ms(e);
2285
+ if (!t) throw h.notFound("a tree node the KDM did not make");
2286
+ if (t.id !== null) return bt(t.id);
2287
+ if (t.pending?.tx === this.serial) return ot(t.pending.index);
2288
+ throw h.notFound("a tree node from a transaction that did not commit");
2289
+ }
2290
+ }
2291
+ function Bs(o, e) {
2292
+ const t = (a) => {
2293
+ const l = a.indexOf("@");
2294
+ return [BigInt(a.slice(l + 1)), Number(a.slice(0, l))];
2295
+ }, [n, s] = t(o), [i, r] = t(e);
2296
+ return n !== i ? n < i ? -1 : 1 : s - r;
2297
+ }
2298
+ const Ae = (o) => new K("out-of-range", `index ${o} splits a character`), Ve = "kdm-rollback", Ke = "system", Ps = "import", Lt = (o) => h.engine(`applying a validated transaction failed: ${o instanceof Error ? o.message : String(o)}`), F = (o) => o instanceof Error ? o.message : String(o), _s = "the changes depend on history before this shallow replica's root; rebase it on a newer snapshot", Js = "the version is not in this replica's history (another document's, or the document was replaced since)", Us = "a shallow replica forks only at its current version; read earlier versions from the server", Ks = "the snapshot is older than this shallow replica's root; rebase it on a newer one", zt = (o) => F(o).includes("not included in the shallow history") ? h.historyMissing(_s) : h.encoding(F(o));
2299
+ function it(o, e) {
2300
+ const t = /* @__PURE__ */ new Set(), n = [], s = o.subscribe((i) => {
2301
+ for (const r of i.events)
2302
+ if (r.path[0] === Y) {
2303
+ if (r.path.length >= 2) {
2304
+ if (t.add(String(r.path[1])), r.diff.type === "map")
2305
+ for (const [a, l] of Object.entries(r.diff.updated)) ae(l) || n.push(wt(r.target, a));
2306
+ } else if (r.diff.type === "map") for (const a of Object.keys(r.diff.updated)) t.add(a);
2307
+ }
2308
+ });
2309
+ try {
2310
+ return { value: e(), changed: t, registers: n };
2311
+ } finally {
2312
+ s();
2313
+ }
2314
+ }
2315
+ const wt = (o, e) => `${o}\0${e}`, Ht = (o) => {
2316
+ const e = o.indexOf("\0");
2317
+ return [o.slice(0, e), o.slice(e + 1)];
2318
+ }, _e = (o) => new Set([...o].sort(I));
2319
+ function ne(o, e) {
2320
+ T("an object id", o), T("a field name", e);
2321
+ }
2322
+ function Gt(o) {
2323
+ if (typeof o != "function") throw new K("invalid-value", "a transaction needs a function");
2324
+ }
2325
+ function Xt(o) {
2326
+ if (!o.isShallow()) return !0;
2327
+ const e = se.fromEngine(o.shallowSinceVV()), t = o.fork();
2328
+ try {
2329
+ t.checkout(o.shallowSinceFrontiers());
2330
+ const n = t.getMap(ln).get(hn);
2331
+ return n instanceof Uint8Array && se.decode(n).equals(e);
2332
+ } catch {
2333
+ return !1;
2334
+ } finally {
2335
+ t.free();
2336
+ }
2337
+ }
2338
+ class de {
2339
+ constructor(e, t, n, s) {
2340
+ this.doc = e, this.schema = n, this.actor = s, et(e, n), this.docIdBytes = t.slice(), e.setPeerId(s), this.undoManagers = en(e, this.runs);
2341
+ }
2342
+ docIdBytes;
2343
+ undoManagers;
2344
+ changed = /* @__PURE__ */ new Set();
2345
+ /** Set while a transaction's function runs: nothing else may change the document then. */
2346
+ busy = !1;
2347
+ /** Set between `beginUndoGroup` and `endUndoGroup`. */
2348
+ grouping = !1;
2349
+ /** The open undo group's run, which its undo steps carry (rule M12b). */
2350
+ runs = { current: null, next: 1, replaying: !1, popped: null, pending: [], groups: /* @__PURE__ */ new Map() };
2351
+ /**
2352
+ * Set when a shallow replica refused an import (`newer-schema`) after the engine applied it: the
2353
+ * engine cannot rebuild a shallow document at an earlier version, so the replica refuses every
2354
+ * later change and export with the same error (standard 2.0 rule M16a).
2355
+ */
2356
+ closedBy = null;
2357
+ /**
2358
+ * For each replica whose changes an import could not apply yet, the counter just past the last
2359
+ * of them. They are applied (and no longer pending) once `version` reaches it.
2360
+ */
2361
+ pending = /* @__PURE__ */ new Map();
2362
+ /**
2363
+ * Registers an import changed: the candidates for another replica's later write, which an undo
2364
+ * or redo must keep (M12). Pruned at each undo and redo.
2365
+ */
2366
+ importedRegisters = /* @__PURE__ */ new Set();
2367
+ /**
2368
+ * Registers an undo or redo put back to another replica's value, with that value: still that
2369
+ * replica's write for the next undo or redo, though this replica wrote it last.
2370
+ */
2371
+ keptRegisters = /* @__PURE__ */ new Map();
2372
+ /**
2373
+ * The value this replica last wrote to each register (`undefined`: deleted it). Another
2374
+ * replica's later write of the same value is not a change an undo must keep (a script's own undo
2375
+ * that puts back this replica's value, for instance).
2376
+ */
2377
+ ownRegisters = /* @__PURE__ */ new Map();
2378
+ /**
2379
+ * The undo scope of this replica's last write to each register (`null`: a `system` or `import`
2380
+ * transaction), with the value written. An undo in one scope keeps the value another scope wrote
2381
+ * later, as it keeps another replica's (M12a). Pruned at each undo and redo.
2382
+ */
2383
+ localWrites = /* @__PURE__ */ new Map();
2384
+ /** A new, empty document. Only one replica creates a document; others `load` it. */
2385
+ static create(e, t, n) {
2386
+ return de.createWith(e, t, n, Me("create"), () => {
2387
+ }).replica;
2388
+ }
2389
+ /**
2390
+ * A new document whose initial content `build` writes in the creating commit, before undo
2391
+ * history starts: file imports and other bulk builds. Undo bookkeeping grows faster than
2392
+ * linearly with a transaction's size, so bulk content must not go through `transact`.
2393
+ * `build` is staged like a transaction; if it throws, no document is made.
2394
+ */
2395
+ static createWith(e, t, n, s, i) {
2396
+ Qe(s), Gt(i);
2397
+ const r = st(t);
2398
+ Be(n);
2399
+ const a = new Fe();
2400
+ a.setPeerId(n), ge(a, e);
2401
+ const l = a.getMap(ue);
2402
+ l.set("docId", ie(r)), l.set("kit", e.kit), l.set(Re, e.schemaVersion), l.set("kdm", Ee);
2403
+ const { result: c, staged: f } = Xe.stage(a, e, i);
2404
+ try {
2405
+ f.apply(a, e, () => {
2406
+ });
2407
+ } catch (u) {
2408
+ throw Lt(u);
2409
+ }
2410
+ return a.commit({ origin: Yt(s.kind), message: he(s, e.schemaVersion) }), { replica: new de(a, r, e, n), result: c };
2411
+ }
2412
+ /**
2413
+ * Opens a snapshot (or a full change export) as a new writable replica of `actor`. Refuses
2414
+ * (`schema`) a document of another kit or of another KDM version, and (`newer-schema`) one whose
2415
+ * minimum schema version (rule M20) is newer than `schema`'s; bytes that are not a KDM snapshot
2416
+ * are `encoding` errors.
2417
+ *
2418
+ * A snapshot holds the changes its replica applied, not those still pending on it (see
2419
+ * `hasPendingChanges`): the loaded replica has none pending, and fetches those changes again
2420
+ * when it syncs.
2421
+ */
2422
+ static load(e, t, n) {
2423
+ Be(n);
2424
+ const { docId: s, engine: i } = Se(t), r = new Fe();
2425
+ ge(r, e);
2426
+ let a;
2427
+ try {
2428
+ a = r.import(i);
2429
+ } catch (b) {
2430
+ throw h.encoding(F(b));
2431
+ }
2432
+ const l = r.getMap(ue), c = (b) => {
2433
+ const g = l.get(b);
2434
+ return g === void 0 || ae(g) ? null : g;
2435
+ }, f = c("kit");
2436
+ if (f === null) throw h.encoding("not a snapshot: meta.kit is missing (load a snapshot or a full export, not changes only)");
2437
+ if (f !== e.kit) throw h.schema(`the document belongs to ${P(f)}, not \`${e.kit}\``);
2438
+ const u = c("kdm");
2439
+ if (u !== Ee) throw h.schema(`the document uses kdm ${P(u)}; this build reads ${Ee}`);
2440
+ const p = fe(r);
2441
+ if (p === null)
2442
+ throw h.schema(`the document has schema version ${P(c(Re))}; this kit reads schema versions up to ${e.schemaVersion}`);
2443
+ if (p > e.schemaVersion) throw h.newerSchema(p, e.schemaVersion);
2444
+ const y = c("docId");
2445
+ let $ = null;
2446
+ try {
2447
+ $ = typeof y == "string" ? st(y) : null;
2448
+ } catch {
2449
+ $ = null;
2450
+ }
2451
+ if (!$ || !xe($, s)) throw h.encoding(`the bytes are labelled as document ${ie(s)}, but hold another`);
2452
+ const j = new de(r, s, e, n);
2453
+ return j.notePending(a), j;
2454
+ }
2455
+ /** The document's durable identity, as a lowercase hyphenated UUID. */
2456
+ get docId() {
2457
+ return ie(this.docIdBytes);
2458
+ }
2459
+ version() {
2460
+ return se.fromEngine(this.doc.oplogVersion());
2461
+ }
2462
+ /**
2463
+ * The document's minimum schema version (rule M20): the version it was created with, or the
2464
+ * largest one a transaction raised it to (`Tx.raiseSchemaVersion`). Never more than this
2465
+ * replica's schema version: loads and imports refuse such documents.
2466
+ */
2467
+ minSchemaVersion() {
2468
+ return fe(this.doc) ?? 0;
2469
+ }
2470
+ /**
2471
+ * The newest schema version any change of this replica was written under (rule M5a: every
2472
+ * commit records its author's schema version), or `null` when no change records one (they all
2473
+ * predate the rule). A version above this replica's schema means someone edits the document
2474
+ * with a newer kit: objects of types this schema lacks read as their `$type` only and refuse
2475
+ * edits here (`unknown-type`), and a host asks the person to update the kit. A shallow replica
2476
+ * (rule M16a) sees only the changes after its root.
2477
+ */
2478
+ authorSchemaVersion() {
2479
+ let e = null;
2480
+ for (const t of this.doc.getAllChanges().values())
2481
+ for (const n of t) {
2482
+ const s = n.message ? Rn(n.message)?.schemaVersion ?? null : null;
2483
+ s !== null && (e === null || s > e) && (e = s);
2484
+ }
2485
+ return e;
2486
+ }
2487
+ /**
2488
+ * Runs `f` as one transaction: one commit, one undo step, one origin. Operations are staged while
2489
+ * `f` runs and applied only if it returns: if `f` throws, the document, its version, and its
2490
+ * exports are unchanged and the error propagates. `f` must be synchronous.
2491
+ */
2492
+ transact(e, t) {
2493
+ this.idle(), this.checkOpen(), Qe(e), Gt(t), this.busy = !0;
2494
+ let n;
2495
+ try {
2496
+ n = Xe.stage(this.doc, this.schema, t);
2497
+ } finally {
2498
+ this.busy = !1;
2499
+ }
2500
+ const { result: s, staged: i } = n;
2501
+ if (i.empty) return s;
2502
+ if (i.raisesSchema && e.kind !== Ke)
2503
+ throw h.invalidValue("$meta", "schemaVersion", `is raised only in a \`system\` transaction, not \`${e.kind}\``);
2504
+ const r = this.doc.frontiers(), a = /* @__PURE__ */ new Set();
2505
+ try {
2506
+ i.apply(this.doc, this.schema, (c) => a.add(c));
2507
+ } catch (c) {
2508
+ if (this.doc.commit({ origin: Ve }), !rt(this.doc.frontiers(), r)) {
2509
+ try {
2510
+ this.doc.revertTo(r);
2511
+ } catch (f) {
2512
+ throw h.engine(F(f));
2513
+ }
2514
+ this.doc.commit({ origin: Ve, message: he(Me("rollback"), this.schema.schemaVersion) });
2515
+ }
2516
+ throw Lt(c);
2517
+ }
2518
+ this.runs.pending = i.undoTouches;
2519
+ const l = Ue(e.kind);
2520
+ if (this.runs.current !== null && l !== null) {
2521
+ const c = `${l}:${this.runs.current}`;
2522
+ this.runs.groups.set(c, Mn(this.runs.groups.get(c) ?? [], i.undoTouches));
2523
+ }
2524
+ this.doc.commit({ origin: Yt(e.kind), message: he(e, this.schema.schemaVersion) });
2525
+ for (const c of a) this.changed.add(c);
2526
+ return this.noteOwnWrites(i.registerWrites, Ue(e.kind)), s;
2527
+ }
2528
+ exists(e) {
2529
+ T("an object id", e);
2530
+ try {
2531
+ return q(this.doc, e), !0;
2532
+ } catch {
2533
+ return !1;
2534
+ }
2535
+ }
2536
+ objectType(e) {
2537
+ return T("an object id", e), Ne(this.doc, e);
2538
+ }
2539
+ get(e, t) {
2540
+ return ne(e, t), $t(this.doc, this.schema, e, t);
2541
+ }
2542
+ text(e, t) {
2543
+ return ne(e, t), B(this.doc, this.schema, e, t, "text")?.toString() ?? "";
2544
+ }
2545
+ /**
2546
+ * A text field as runs of characters with equal marks (rule M19), in order: adjacent runs differ
2547
+ * in their marks, no run is empty, and only the field's declared marks appear. A field that
2548
+ * declares no marks reads as one unmarked run (none when empty). Positions are counted in UTF-16
2549
+ * code units (`insert.length`).
2550
+ */
2551
+ textDelta(e, t) {
2552
+ return ne(e, t), rs(this.doc, this.schema, e, t);
2553
+ }
2554
+ /** The length of a text field in UTF-16 code units. */
2555
+ textLength(e, t) {
2556
+ return ne(e, t), B(this.doc, this.schema, e, t, "text")?.length ?? 0;
2557
+ }
2558
+ list(e, t) {
2559
+ ne(e, t);
2560
+ const n = B(this.doc, this.schema, e, t, "list");
2561
+ return n ? Ze(n.toArray()) : [];
2562
+ }
2563
+ /** One key of a map field, or `null`. */
2564
+ mapGet(e, t, n) {
2565
+ ne(e, t), T("a map key", n);
2566
+ const s = B(this.doc, this.schema, e, t, "map");
2567
+ return s ? Ye(s.get(n)) : null;
2568
+ }
2569
+ /**
2570
+ * A map field's keys and values, sorted by key (code point order, as in the canonical state),
2571
+ * each as `mapGet` reads it. Reads the whole map.
2572
+ */
2573
+ mapEntries(e, t) {
2574
+ ne(e, t);
2575
+ const n = B(this.doc, this.schema, e, t, "map");
2576
+ return n ? un(n) : [];
2577
+ }
2578
+ /**
2579
+ * The tree's nodes in pre-order (each parent before its children, siblings in order). A node
2580
+ * that names no object is skipped with its subtree, as in `stateJson`.
2581
+ */
2582
+ tree(e, t) {
2583
+ ne(e, t);
2584
+ const n = [], s = B(this.doc, this.schema, e, t, "tree"), i = (r, a) => {
2585
+ for (const l of r ?? []) {
2586
+ const c = Le(l);
2587
+ if (c === null) continue;
2588
+ const f = Sn(l.id);
2589
+ n.push({ node: f, object: c, parent: a }), i(l.children(), f);
2590
+ }
2591
+ };
2592
+ return s && i(s.roots(), null), n;
2593
+ }
2594
+ /**
2595
+ * Ids of the objects of type `ty`, sorted. One pass over the objects, so it suits large
2596
+ * documents; it costs O(objects) per call.
2597
+ */
2598
+ objectsOfType(e) {
2599
+ return T("a type name", e), pn(this.doc, e);
2600
+ }
2601
+ /**
2602
+ * The changes this replica has that a replica at `since` lacks, labelled with this document's id.
2603
+ *
2604
+ * With `Version.empty()` (every change) the bytes always `load` as this document. A shallow
2605
+ * replica (rule M16a) has no changes before its root, so for a `since` that does not reach its
2606
+ * root (the empty version above all) it answers its snapshot: its state at the root with every
2607
+ * change after it, which loads as a shallow replica with the same root and imports into any
2608
+ * replica that has the root, as these changes would. On a full replica, and for a `since` at or
2609
+ * after the root, the bytes are the changes alone.
2610
+ */
2611
+ exportChanges(e = se.empty()) {
2612
+ if (this.checkOpen(), !(e instanceof se)) throw new K("invalid-value", "a version must be a `Version`");
2613
+ if (!this.reaches(e)) return this.snapshot();
2614
+ let t;
2615
+ try {
2616
+ t = this.doc.export({ mode: "update", from: e.toEngine() });
2617
+ } catch (n) {
2618
+ throw h.encoding(F(n));
2619
+ }
2620
+ return We(this.docIdBytes, t);
2621
+ }
2622
+ /**
2623
+ * Applies changes from another replica or from storage, in any order, any number of times.
2624
+ * Answers the objects whose state changed. Bytes that are not a KDM export are `encoding`
2625
+ * errors; changes of another document are `wrong-document` errors and change nothing.
2626
+ *
2627
+ * Changes that raise the document's minimum schema version (rule M20) above this replica's
2628
+ * schema are `newer-schema` errors and change nothing: the state, the version, the exports, and
2629
+ * the changes still pending are as before the import. The engine cannot check changes without
2630
+ * applying them, so the replica is rebuilt from its history before the import; that clears its
2631
+ * undo and redo history, and `subscribeText` listeners stop receiving changes. A build that
2632
+ * meets this error is too old for the document: the host stops syncing and asks for an update.
2633
+ * A shallow replica cannot be rebuilt so: it keeps the changes and refuses every later change
2634
+ * and export with this error, and the host reopens the document from what it stored.
2635
+ *
2636
+ * On a shallow replica, changes that depend on history before its root (made by a replica that
2637
+ * had not seen the root yet) are `history-missing` errors and change nothing; see `rebase`.
2638
+ */
2639
+ importChanges(e) {
2640
+ this.idle(), this.checkOpen();
2641
+ const { docId: t, engine: n } = Se(e);
2642
+ if (!xe(t, this.docIdBytes)) throw h.wrongDocument(this.docId, ie(t));
2643
+ const s = this.doc.oplogFrontiers();
2644
+ let i = null;
2645
+ const { value: r, changed: a, registers: l } = it(this.doc, () => {
2646
+ try {
2647
+ return this.doc.import(n);
2648
+ } catch (u) {
2649
+ return i = u, null;
2650
+ }
2651
+ });
2652
+ try {
2653
+ et(this.doc, this.schema);
2654
+ } catch (u) {
2655
+ throw this.doc.isShallow() ? this.closedBy = u : this.restore(s), u;
2656
+ }
2657
+ const c = fe(this.doc);
2658
+ if (c !== null && c > this.schema.schemaVersion) {
2659
+ const u = h.newerSchema(c, this.schema.schemaVersion);
2660
+ throw this.doc.isShallow() ? (this.closedBy = u, u) : (this.restore(s), u);
2661
+ }
2662
+ if (r === null) throw zt(i);
2663
+ if (["person", "agent"].some((u) => this.undoManagers[u].canUndo() || this.undoManagers[u].canRedo())) for (const u of l) this.importedRegisters.add(u);
2664
+ this.notePending(r);
2665
+ for (const u of a) this.changed.add(u);
2666
+ return this.reopenUndoGroup(), _e(a);
2667
+ }
2668
+ /**
2669
+ * Whether this replica holds imported changes it could not apply yet, because they depend on
2670
+ * changes it has not received. Importing changes out of order is legitimate (they are applied as
2671
+ * soon as what they depend on arrives); a replica that stays in this state is missing changes,
2672
+ * which a sync from `version` fetches. Pending changes are not in `version`, the state, or the
2673
+ * exports.
2674
+ */
2675
+ hasPendingChanges() {
2676
+ const e = this.doc.oplogVersion();
2677
+ for (const [t, n] of this.pending) if ((e.get(t) ?? 0) < n) return !0;
2678
+ return !1;
2679
+ }
2680
+ /** The objects changed since the last call, by local transactions, imports, undo, and redo. */
2681
+ takeChanged() {
2682
+ const e = _e(this.changed);
2683
+ return this.changed = /* @__PURE__ */ new Set(), e;
2684
+ }
2685
+ /** A compacted copy of the whole document, for fast loading and new replicas. */
2686
+ snapshot() {
2687
+ this.checkOpen();
2688
+ let e;
2689
+ try {
2690
+ e = this.doc.export({ mode: "snapshot" });
2691
+ } catch (t) {
2692
+ throw h.encoding(F(t));
2693
+ }
2694
+ return We(this.docIdBytes, e);
2695
+ }
2696
+ /**
2697
+ * A **shallow snapshot** (standard 2.0 rule M16a): the document's current state with only the
2698
+ * history after `at`, for a device that holds a large document without its whole history. `load`
2699
+ * opens it as a shallow replica, which edits, exports, imports, and merges like a full one;
2700
+ * history before its root stays with whoever holds it (the sync server).
2701
+ *
2702
+ * The root is the latest version at or before `at` that every later change descends from (the
2703
+ * engine moves it back past changes made concurrently with `at`, so they stay in the retained
2704
+ * history); `Version.empty()` keeps the whole history. `at` must be a version this replica has
2705
+ * (`invalid-value` otherwise); on a shallow replica, an `at` before its own root is its root.
2706
+ */
2707
+ shallowSnapshot(e) {
2708
+ if (this.checkOpen(), !(e instanceof se)) throw new K("invalid-value", "a version must be a `Version`");
2709
+ if (!this.version().includes(e)) throw h.invalidValue("$shallow", "version", "names changes this replica does not have");
2710
+ const t = this.reaches(e) ? this.doc.vvToFrontiers(e.toEngine()) : this.doc.shallowSinceFrontiers();
2711
+ let n;
2712
+ try {
2713
+ n = this.doc.export({ mode: "shallow-snapshot", frontiers: t });
2714
+ } catch (s) {
2715
+ throw h.encoding(F(s));
2716
+ }
2717
+ return We(this.docIdBytes, n);
2718
+ }
2719
+ /** Whether this replica holds only part of the document's history: it was loaded from a `shallowSnapshot` (or a snapshot of a shallow replica). */
2720
+ isShallow() {
2721
+ return this.doc.isShallow();
2722
+ }
2723
+ /**
2724
+ * The version a shallow replica's retained history starts at (its root): it has every change
2725
+ * after it, and none of the history it summarizes. `null` for a full replica.
2726
+ */
2727
+ shallowRoot() {
2728
+ return this.doc.isShallow() ? se.fromEngine(this.doc.shallowSinceVV()) : null;
2729
+ }
2730
+ /**
2731
+ * Whether this replica carries the **document's whole history** (sync protocol S20): it is full,
2732
+ * or it is shallow and its root is the document's birth, so no replica of the document can hold
2733
+ * changes before it. A copy made by `copyAsNewDocument` is born at its root, and every replica
2734
+ * loaded from it, its snapshots and its drafts keep that root; a shallow snapshot taken later
2735
+ * (`shallowSnapshot` after more changes) does not.
2736
+ *
2737
+ * The birth is the version the copy recorded in the change that made it, read from this
2738
+ * replica's state **at its root**: a change after the root, which any client may make, never
2739
+ * counts, and a value written in such a change could only name a version before the root it is
2740
+ * part of. A server that trusts no client decides from the bytes alone. Shallow documents that
2741
+ * record no birth (copies made before it was recorded) do not carry it. As the Rust
2742
+ * `Replica::carries_whole_history`.
2743
+ */
2744
+ carriesWholeHistory() {
2745
+ return this.checkOpen(), Xt(this.doc);
2746
+ }
2747
+ /**
2748
+ * `carriesWholeHistory` of the document `bytes` (a snapshot or a full export) hold, read without
2749
+ * a schema, as a sync server reads a room's first state (rule S20). Bytes that are not a KDM
2750
+ * export, or that do not decode, are `encoding` errors. As the Rust
2751
+ * `Replica::snapshot_carries_whole_history`.
2752
+ */
2753
+ static snapshotCarriesWholeHistory(e) {
2754
+ const { engine: t } = Se(e), n = new Fe();
2755
+ try {
2756
+ if (An(t, !0).mode !== "shallow-snapshot") return !0;
2757
+ n.import(t);
2758
+ } catch (s) {
2759
+ throw n.free(), h.encoding(F(s));
2760
+ }
2761
+ try {
2762
+ return Xt(n);
2763
+ } finally {
2764
+ n.free();
2765
+ }
2766
+ }
2767
+ /** Whether `version` is at or after this replica's shallow root: always, on a full replica. */
2768
+ reaches(e) {
2769
+ const t = this.shallowRoot();
2770
+ return t === null || e.includes(t);
2771
+ }
2772
+ /**
2773
+ * Replaces this replica's document with `snapshot` (a full or shallow snapshot of the same
2774
+ * document, as a server answers it) plus every change this replica has that `snapshot` lacks,
2775
+ * and answers the objects whose state changed. For a shallow replica whose import failed with
2776
+ * `history-missing`: a newer snapshot from the server holds the changes it could not take,
2777
+ * rooted early enough for them, and this replica's own changes (pushed or not) are kept on top.
2778
+ * The state is what importing every change of both would give.
2779
+ *
2780
+ * Refuses (`wrong-document`) a snapshot of another document, what `load` refuses, and
2781
+ * (`history-missing`) a shallow snapshot whose root is after changes of this replica it lacks; a
2782
+ * refused rebase changes nothing. Clears the undo and redo history, like any load, and
2783
+ * `subscribeText` listeners stop receiving changes.
2784
+ */
2785
+ rebase(e) {
2786
+ this.idle(), this.checkOpen();
2787
+ const { docId: t } = Se(e);
2788
+ if (!xe(t, this.docIdBytes)) throw h.wrongDocument(this.docId, ie(t));
2789
+ const n = de.load(this.schema, e, this.actor);
2790
+ if (!n.version().includes(this.version()) && (n.importChanges(this.exportChanges(n.version())), !n.version().includes(this.version())))
2791
+ throw h.historyMissing(Ks);
2792
+ const s = (l) => l.objects ?? {}, i = s(this.stateJson()), r = s(n.stateJson()), a = /* @__PURE__ */ new Set();
2793
+ for (const l of /* @__PURE__ */ new Set([...Object.keys(i), ...Object.keys(r)]))
2794
+ (P(i[l] ?? null) !== P(r[l] ?? null) || l in i != l in r) && a.add(l);
2795
+ tn(this.undoManagers), this.doc = n.doc, this.undoManagers = n.undoManagers, this.importedRegisters.clear(), this.keptRegisters.clear(), this.ownRegisters.clear(), this.localWrites.clear();
2796
+ for (const [l, c] of n.pending) this.pending.set(l, Math.max(c, this.pending.get(l) ?? 0));
2797
+ this.prunePending(), this.reopenUndoGroup();
2798
+ for (const l of a) this.changed.add(l);
2799
+ return _e(a);
2800
+ }
2801
+ /**
2802
+ * Undoes the person's last transaction on this replica (the `person` scope, M12a). Changes from
2803
+ * other replicas and from other scopes (an agent's) are kept, including later changes to the
2804
+ * same object and to the same field: a register another replica or scope wrote after the undone
2805
+ * transaction keeps that value (M12). The objects it changes are reported by `takeChanged`.
2806
+ */
2807
+ undo() {
2808
+ return this.undoIn("person");
2809
+ }
2810
+ /** Redoes the person's last undone transaction, keeping other replicas' and scopes' later changes and reporting what it changes like `undo`. */
2811
+ redo() {
2812
+ return this.redoIn("person");
2813
+ }
2814
+ /** Undoes the last transaction of `scope` on this replica, like `undo` for the person. */
2815
+ undoIn(e) {
2816
+ const t = () => this.undoManagers[we(e)];
2817
+ return this.history(e, () => this.replayRun(() => t().topUndoValue(), () => t().undo()));
2818
+ }
2819
+ /** Redoes the last undone transaction of `scope`, like `redo` for the person. */
2820
+ redoIn(e) {
2821
+ const t = () => this.undoManagers[we(e)];
2822
+ return this.history(e, () => this.replayRun(() => t().topRedoValue(), () => t().redo()));
2823
+ }
2824
+ /**
2825
+ * One undo (or redo) of a run (rule M12b): the top step, and every step under it of the same undo
2826
+ * group, which an import split. Each undo or redo step it makes carries the run on.
2827
+ */
2828
+ replayRun(e, t) {
2829
+ this.runs.replaying = !0;
2830
+ try {
2831
+ const n = Zt(e()), s = t();
2832
+ let i = s;
2833
+ for (; i && n !== null && Zt(e()) === n; ) i = t();
2834
+ return s;
2835
+ } finally {
2836
+ this.runs.replaying = !1, this.runs.popped = null;
2837
+ }
2838
+ }
2839
+ /** Whether `undo` has a transaction of the person to undo. */
2840
+ canUndo() {
2841
+ return this.canUndoIn("person");
2842
+ }
2843
+ /** Whether `redo` has an undone transaction of the person to redo. */
2844
+ canRedo() {
2845
+ return this.canRedoIn("person");
2846
+ }
2847
+ /** Whether `undoIn(scope)` has a transaction to undo. */
2848
+ canUndoIn(e) {
2849
+ return this.idle(), this.undoManagers[we(e)].canUndo();
2850
+ }
2851
+ /** Whether `redoIn(scope)` has an undone transaction to redo. */
2852
+ canRedoIn(e) {
2853
+ return this.idle(), this.undoManagers[we(e)].canRedo();
2854
+ }
2855
+ /** The original objects and fields of the next undo step, including its whole group. */
2856
+ undoTouchesIn(e) {
2857
+ return this.idle(), this.historyTouches(e, this.undoManagers[we(e)].topUndoValue());
2858
+ }
2859
+ /** The original objects and fields of the next redo step. Reading leaves both histories intact. */
2860
+ redoTouchesIn(e) {
2861
+ return this.idle(), this.historyTouches(e, this.undoManagers[we(e)].topRedoValue());
2862
+ }
2863
+ historyTouches(e, t) {
2864
+ const n = It(t);
2865
+ return structuredClone(n?.run != null ? this.runs.groups.get(`${e}:${n.run}`) ?? n.touches : n?.touches ?? []);
2866
+ }
2867
+ /**
2868
+ * Starts an undo group: the transactions until `endUndoGroup` undo and redo as one step. Groups
2869
+ * do not nest (`invalid-value`). An undo or a redo ends the open group first, so undo while
2870
+ * grouping reverts the group as one step. It stays one undo step when other replicas' changes
2871
+ * arrive while it is open, also when they touch what the group changed (rule M12b): one undo
2872
+ * takes back all of it and keeps their changes. A group spans
2873
+ * both undo scopes (M12a): the person's transactions in it are one person step, and an agent's
2874
+ * are one agent step.
2875
+ */
2876
+ beginUndoGroup() {
2877
+ if (this.idle(), this.grouping) throw h.invalidValue("$undo", "group", "is already open");
2878
+ try {
2879
+ this.undoManagers.person.groupStart();
2880
+ } catch (e) {
2881
+ throw h.engine(F(e));
2882
+ }
2883
+ try {
2884
+ this.undoManagers.agent.groupStart();
2885
+ } catch (e) {
2886
+ throw this.undoManagers.person.groupEnd(), h.engine(F(e));
2887
+ }
2888
+ this.grouping = !0, this.runs.current = this.runs.next, this.runs.next += 1;
2889
+ }
2890
+ /** Ends the open undo group; does nothing when none is open. */
2891
+ endUndoGroup() {
2892
+ this.idle(), this.closeUndoGroup();
2893
+ }
2894
+ /** Drops the person's redo stack, keeping the undo stack. */
2895
+ clearRedo() {
2896
+ this.idle(), this.undoManagers.person.clearRedo();
2897
+ }
2898
+ /** Follows one text field: `listener` gets each change with whether this replica made it. */
2899
+ subscribeText(e, t, n) {
2900
+ ne(e, t);
2901
+ const s = B(this.doc, this.schema, e, t, "text");
2902
+ if (!s) throw h.notFound(`${e}.${t}`);
2903
+ return s.subscribe((i) => {
2904
+ for (const r of i.events)
2905
+ r.diff.type === "text" && n(r.diff.diff, i.by === "local");
2906
+ });
2907
+ }
2908
+ /**
2909
+ * A draft of this document (standard 2.0 A12): a new writable replica of `actor` holding every
2910
+ * change this one has, with no undo history. Edits made on it stay there until `mergeChanges`
2911
+ * takes them into another replica of the document.
2912
+ */
2913
+ fork(e) {
2914
+ return this.forkAt(this.version(), e);
2915
+ }
2916
+ /** A draft of this document as it was at `version` (see `fork`); `version` must be one this replica has reached. */
2917
+ forkAt(e, t) {
2918
+ if (this.idle(), this.checkOpen(), Be(t), !(e instanceof se)) throw new K("invalid-value", "a version must be a `Version`");
2919
+ if (!this.version().includes(e)) throw h.invalidValue("$draft", "version", "names changes this replica does not have");
2920
+ if (this.doc.isShallow() && !e.equals(this.version())) throw h.historyMissing(Us);
2921
+ let n;
2922
+ try {
2923
+ n = this.doc.isShallow() ? this.doc.fork() : this.doc.forkAt(this.doc.vvToFrontiers(e.toEngine()));
2924
+ } catch (s) {
2925
+ throw h.engine(F(s));
2926
+ }
2927
+ return ge(n, this.schema), new de(n, this.docIdBytes, this.schema, t);
2928
+ }
2929
+ /**
2930
+ * A copy of this document as a **new document** (data model, "A copy is a new document"): the
2931
+ * same objects, ids and content under the new permanent `docId`, as a writable replica of
2932
+ * `actor`. For a template instantiated twice, a copied file, or the same bytes stored twice: each
2933
+ * copy is its own document, with its own co-editing room. Unlike `fork` (a draft of the same
2934
+ * document, merged back), a copy never merges with its source or another copy: `importChanges`,
2935
+ * `mergeChanges` and `rebase` refuse each other's bytes (`wrong-document`).
2936
+ *
2937
+ * Answers a replica, as `fork` does, so a host edits it or stores its `snapshot`. The copy is a
2938
+ * shallow replica (rule M16a) rooted at its own first change: it holds the current state and no
2939
+ * history, so no deleted content, no earlier version and not the source's `docId` travel with
2940
+ * it; it forks only at its current version, and `changesSince` a version before the copy is
2941
+ * `history-missing`. Its undo and redo histories are empty. Object ids, tree node ids and every
2942
+ * value are kept; a blob is its content-addressed reference, so it resolves wherever the
2943
+ * source's blobs do (a host whose blob store is per document copies the referenced blobs too).
2944
+ *
2945
+ * There is no option to keep the history: the copy would share the source's change ids with
2946
+ * another document's, every earlier version of it would name the source's `docId`, and deleted
2947
+ * content would travel. Refuses (`invalid-value`) a `docId` equal to this document's. The
2948
+ * changes still pending on this replica are not in the copy. The Rust crate's
2949
+ * `Replica::copy_as_new_document` does the same.
2950
+ */
2951
+ copyAsNewDocument(e, t) {
2952
+ this.idle(), this.checkOpen();
2953
+ const n = st(e);
2954
+ if (Be(t), xe(n, this.docIdBytes)) throw h.invalidValue("$copy", "docId", "is this document's; a copy needs a new one");
2955
+ let s;
2956
+ try {
2957
+ const r = new Fe();
2958
+ ge(r, this.schema), r.import(this.doc.export({ mode: "shallow-snapshot", frontiers: this.doc.oplogFrontiers() })), r.setPeerId(t);
2959
+ const a = new Map(r.oplogVersion().toJSON()), l = t.toString();
2960
+ a.set(l, (a.get(l) ?? 0) + 1), r.getMap(ue).set("docId", ie(n)), r.getMap(ln).set(hn, Vn.parseJSON(a).encode()), r.commit({ origin: Ke, message: he(Me("new-document"), this.schema.schemaVersion) }), s = r.export({ mode: "shallow-snapshot", frontiers: r.oplogFrontiers() });
2961
+ } catch (r) {
2962
+ throw h.encoding(F(r));
2963
+ }
2964
+ const i = de.load(this.schema, We(n, s), t);
2965
+ if (!i.carriesWholeHistory()) throw h.engine("the copy is not rooted at the birth it records");
2966
+ return i;
2967
+ }
2968
+ /**
2969
+ * The canonical state this replica would have after importing `changes`, without changing it:
2970
+ * the "after" of a draft's comparison (`diffStates`). Refuses what `mergeChanges` refuses.
2971
+ */
2972
+ mergedState(e) {
2973
+ return this.idle(), this.checkOpen(), Dt(this.mergedDoc(e), this.schema);
2974
+ }
2975
+ /**
2976
+ * Takes another replica's changes (a draft's, made on a `fork`) into this one as one transaction
2977
+ * of its own, with `origin`: one undo step of the person (unless `origin` is `system` or `import`; M12a). The result
2978
+ * is the state a CRDT import would give, so edits made here (or imported) since the draft was
2979
+ * forked are kept; only the operations that turn this state into the merged one are written,
2980
+ * under this replica's actor. Answers the objects that changed.
2981
+ *
2982
+ * The draft's changes themselves are not imported: merging the same changes twice writes their
2983
+ * effect twice, so a host merges a draft once. Refuses (`invalid-value`) changes that depend on
2984
+ * changes this replica lacks, changes of another document (`wrong-document`), and changes that
2985
+ * raise the minimum schema version beyond this replica's (`newer-schema`); a refused merge
2986
+ * changes nothing.
2987
+ */
2988
+ mergeChanges(e, t) {
2989
+ this.idle(), this.checkOpen(), Qe(t);
2990
+ const n = Ue(t.kind), s = this.mergedDoc(e), i = this.doc.oplogFrontiers(), r = s.oplogFrontiers();
2991
+ if (rt(i, r)) return /* @__PURE__ */ new Set();
2992
+ let a;
2993
+ try {
2994
+ a = s.diff(i, r);
2995
+ } catch (u) {
2996
+ throw h.engine(F(u));
2997
+ }
2998
+ let l = null;
2999
+ const { changed: c, registers: f } = it(this.doc, () => {
3000
+ try {
3001
+ this.doc.applyDiff(a);
3002
+ } catch (u) {
3003
+ l = u;
3004
+ return;
3005
+ }
3006
+ this.doc.commit({ origin: n === null ? t.kind : "person", message: he(t, this.schema.schemaVersion) });
3007
+ });
3008
+ if (l !== null)
3009
+ throw this.doc.commit({ origin: Ve }), rt(this.doc.oplogFrontiers(), i) || (this.doc.revertTo(i), this.doc.commit({ origin: Ve, message: he(Me("rollback"), this.schema.schemaVersion) })), h.engine(F(l));
3010
+ for (const u of f) {
3011
+ const p = this.registerValue(u);
3012
+ p.container || (this.ownRegisters.set(u, p.value), this.localWrites.set(u, { by: n === null ? null : "person", value: p.value }));
3013
+ }
3014
+ for (const u of c) this.changed.add(u);
3015
+ return _e(c);
3016
+ }
3017
+ /** A copy of this document with `changes` imported, checked as `mergeChanges` checks them. */
3018
+ mergedDoc(e) {
3019
+ const { docId: t, engine: n } = Se(e);
3020
+ if (!xe(t, this.docIdBytes)) throw h.wrongDocument(this.docId, ie(t));
3021
+ const s = this.doc.fork();
3022
+ ge(s, this.schema);
3023
+ let i;
3024
+ try {
3025
+ i = s.import(n);
3026
+ } catch (a) {
3027
+ throw zt(a);
3028
+ }
3029
+ if (i.pending && i.pending.size > 0) throw h.invalidValue("$draft", "changes", "depend on changes this replica does not have");
3030
+ et(s, this.schema);
3031
+ const r = fe(s);
3032
+ if (r !== null && r > this.schema.schemaVersion) throw h.newerSchema(r, this.schema.schemaVersion);
3033
+ return s;
3034
+ }
3035
+ /**
3036
+ * What changed since `since` (a version this replica reached), as a write's receipt: a
3037
+ * `StateDiff` without `texts`, values cut to excerpts, objects named by their tool ids where the
3038
+ * schema declares them (OM9). Only the objects the changes since then touched are read, here and
3039
+ * in a fork at `since`; the answer equals `diffStates` of the two whole states. A version this
3040
+ * replica's history does not hold is a `history-missing` error. As the Rust `changes_since`.
3041
+ */
3042
+ changesSince(e, t = {}) {
3043
+ if (this.idle(), this.checkOpen(), !(e instanceof se)) throw new K("invalid-value", "a version must be a `Version`");
3044
+ if (!this.version().includes(e)) throw h.historyMissing(Js);
3045
+ if (e.equals(this.version())) return yt([], {}, {}, () => null, !1);
3046
+ const n = this.forkAt(e, this.actor), i = [...this.forkAt(e, this.actor).importChanges(this.exportChanges(e))].sort(I), r = (p, y) => {
3047
+ try {
3048
+ return Ne(p, y);
3049
+ } catch {
3050
+ return null;
3051
+ }
3052
+ }, a = (p) => {
3053
+ const y = {};
3054
+ for (const $ of i) r(p, $) !== null && (y[$] = bn(p, this.schema, $));
3055
+ return y;
3056
+ }, l = (p) => r(this.doc, p) ?? r(n.doc, p), c = { objects: a(n.doc) }, f = { objects: a(this.doc) };
3057
+ let u = ks(yt(i, c.objects, f.objects, l, !1), this.schema);
3058
+ return t.textSpans && (u = wn(u, c, f)), Os(u, this.schema, Q.ofReplica(n), Q.ofReplica(this));
3059
+ }
3060
+ /** The whole document in canonical form; see `stateText`. */
3061
+ stateJson() {
3062
+ return Dt(this.doc, this.schema);
3063
+ }
3064
+ /** The canonical state as text; equal to the Rust `state_json().to_string()` for the same changes. */
3065
+ stateText() {
3066
+ return P(this.stateJson());
3067
+ }
3068
+ /**
3069
+ * Replaces the document with its history up to `frontiers`, dropping every change applied since.
3070
+ * Changes still pending stay recorded in `pending`: they are missing again, and a sync fetches
3071
+ * them.
3072
+ */
3073
+ restore(e) {
3074
+ let t;
3075
+ try {
3076
+ t = this.doc.forkAt(e);
3077
+ } catch (n) {
3078
+ throw h.engine(F(n));
3079
+ }
3080
+ ge(t, this.schema), t.setPeerId(this.actor), tn(this.undoManagers), this.doc = t, this.undoManagers = en(t, this.runs), this.importedRegisters.clear(), this.keptRegisters.clear(), this.ownRegisters.clear(), this.localWrites.clear(), this.reopenUndoGroup();
3081
+ }
3082
+ /** Records the changes an import left pending, and forgets those applied since. */
3083
+ notePending(e) {
3084
+ for (const [t, { end: n }] of e.pending ?? []) this.pending.set(t, Math.max(n, this.pending.get(t) ?? 0));
3085
+ this.prunePending();
3086
+ }
3087
+ /** Forgets the pending changes applied since they were recorded. */
3088
+ prunePending() {
3089
+ if (this.pending.size === 0) return;
3090
+ const e = this.doc.oplogVersion();
3091
+ for (const [t, n] of this.pending) (e.get(t) ?? 0) >= n && this.pending.delete(t);
3092
+ }
3093
+ /** Throws the error that closed this shallow replica, if one did (see `importChanges`). */
3094
+ checkOpen() {
3095
+ if (this.closedBy) throw this.closedBy;
3096
+ }
3097
+ idle() {
3098
+ if (this.busy) throw h.engine("the document cannot change while a transaction runs; transactions do not nest");
3099
+ }
3100
+ closeUndoGroup() {
3101
+ this.grouping && (this.undoManagers.person.groupEnd(), this.undoManagers.agent.groupEnd(), this.grouping = !1, this.runs.current = null);
3102
+ }
3103
+ /**
3104
+ * After an import, makes sure the open group is still open in the engine: the engine ends it
3105
+ * when the import changes what the group changed, and then the group goes on as a new one.
3106
+ * Starting a group the engine still has open changes nothing; if the engine can start none, no
3107
+ * group is open any more.
3108
+ */
3109
+ reopenUndoGroup() {
3110
+ if (!this.grouping) return;
3111
+ const e = (t) => {
3112
+ try {
3113
+ return t.groupStart(), !0;
3114
+ } catch (n) {
3115
+ return F(n).includes("already an active undo group");
3116
+ }
3117
+ };
3118
+ e(this.undoManagers.person) && e(this.undoManagers.agent) || (this.undoManagers.person.groupEnd(), this.undoManagers.agent.groupEnd(), this.grouping = !1);
3119
+ }
3120
+ history(e, t) {
3121
+ this.idle(), this.checkOpen(), this.closeUndoGroup();
3122
+ const n = this.othersRegisters().map(([c, f]) => [c, f, void 0]);
3123
+ for (const [c, f, u] of this.otherScopesRegisters(e)) n.push([c, f, u]);
3124
+ const { value: s, changed: i, registers: r } = it(this.doc, () => {
3125
+ try {
3126
+ return t();
3127
+ } catch (c) {
3128
+ throw h.engine(F(c));
3129
+ }
3130
+ });
3131
+ for (const c of i) this.changed.add(c);
3132
+ for (const c of r) {
3133
+ const f = this.registerValue(c);
3134
+ f.container || (this.ownRegisters.set(c, f.value), this.localWrites.set(c, { by: e, value: f.value }));
3135
+ }
3136
+ const a = new Set(r);
3137
+ let l = !1;
3138
+ for (const [c, f, u] of n) {
3139
+ if (!a.has(c)) continue;
3140
+ const p = this.registerValue(c);
3141
+ if (p.container || Je(p.value, f)) continue;
3142
+ const [y, $] = Ht(c), j = this.doc.getContainerById(y);
3143
+ f === void 0 ? j.delete($) : j.set($, f), u !== void 0 ? this.localWrites.set(c, { by: u, value: f }) : (this.localWrites.delete(c), this.keptRegisters.set(c, f)), l = !0;
3144
+ }
3145
+ return l && this.doc.commit({ origin: Ke, message: he(Me("keep-later-changes"), this.schema.schemaVersion) }), s;
3146
+ }
3147
+ /**
3148
+ * The registers whose current value this replica wrote in another scope than `scope` (or in a
3149
+ * `system` or `import` transaction), with that value and its scope. Forgets the writes whose value
3150
+ * was changed since by anyone.
3151
+ */
3152
+ otherScopesRegisters(e) {
3153
+ const t = [], n = String(this.actor);
3154
+ for (const [s, i] of this.localWrites) {
3155
+ const r = this.registerValue(s);
3156
+ r.container || !Je(r.value, i.value) || r.lastEditor !== n ? this.localWrites.delete(s) : i.by !== e && t.push([s, r.value, i.by]);
3157
+ }
3158
+ return t;
3159
+ }
3160
+ /** A register's value now (`undefined`: absent), and whether it holds a container instead. */
3161
+ registerValue(e) {
3162
+ const [t, n] = Ht(e), s = this.doc.getContainerById(t);
3163
+ if (!s) return { value: void 0, container: !1, lastEditor: void 0 };
3164
+ const i = s.get(n);
3165
+ return { value: i, container: ae(i), lastEditor: s.getLastEditor(n) };
3166
+ }
3167
+ /**
3168
+ * The registers whose current value another replica wrote, with that value (`undefined`:
3169
+ * deleted there): an import changed them and another peer wrote them last, or an earlier undo or
3170
+ * redo kept them for another replica and nothing changed them since. Prunes both candidate sets
3171
+ * of registers that are this replica's own again.
3172
+ */
3173
+ othersRegisters() {
3174
+ const e = [], t = String(this.actor);
3175
+ for (const [n, s] of this.keptRegisters) {
3176
+ const i = this.registerValue(n);
3177
+ !i.container && Je(i.value, s) ? e.push([n, s]) : this.keptRegisters.delete(n);
3178
+ }
3179
+ for (const n of this.importedRegisters) {
3180
+ if (this.keptRegisters.has(n)) continue;
3181
+ const s = this.registerValue(n);
3182
+ s.container || s.lastEditor === void 0 || s.lastEditor === t ? this.importedRegisters.delete(n) : this.ownRegisters.has(n) && Je(this.ownRegisters.get(n), s.value) || e.push([n, s.value]);
3183
+ }
3184
+ return e;
3185
+ }
3186
+ /** Records the registers a local transaction of `scope` wrote, with their values. */
3187
+ noteOwnWrites(e, t) {
3188
+ for (const { id: n, field: s, key: i, value: r } of e) {
3189
+ let a;
3190
+ try {
3191
+ const l = q(this.doc, n);
3192
+ if (s === null) a = l.id;
3193
+ else {
3194
+ const c = l.get(s);
3195
+ if (!ae(c) || c.kind() !== "Map") continue;
3196
+ a = c.id;
3197
+ }
3198
+ } catch {
3199
+ continue;
3200
+ }
3201
+ this.ownRegisters.set(wt(a, i), r), this.localWrites.set(wt(a, i), { by: t, value: r });
3202
+ }
3203
+ }
3204
+ }
3205
+ const Je = (o, e) => o === e || o !== void 0 && e !== void 0 && P(o) === P(e), qs = "undo", Yt = (o) => Ue(o) ?? o, It = (o) => o && typeof o == "object" && "touches" in o ? o : null, Zt = (o) => It(o)?.run ?? null;
3206
+ function Mn(o, e) {
3207
+ const t = /* @__PURE__ */ new Map();
3208
+ for (const n of [...o, ...e]) {
3209
+ const s = t.get(n.id);
3210
+ t.set(n.id, s === null || n.fields === null ? null : /* @__PURE__ */ new Set([...s ?? [], ...n.fields]));
3211
+ }
3212
+ return [...t].sort(([n], [s]) => n < s ? -1 : n > s ? 1 : 0).map(([n, s]) => ({ id: n, fields: s === null ? null : [...s].sort() }));
3213
+ }
3214
+ const Qt = (o, e, t) => new En(o, {
3215
+ mergeInterval: 0,
3216
+ excludeOriginPrefixes: [Ve, Ke, Ps, e === "person" ? "agent" : "person", qs],
3217
+ onPush: () => {
3218
+ if (t.replaying) return { value: t.popped, cursors: [] };
3219
+ const n = t.current === null ? Mn([], t.pending) : t.groups.get(`${e}:${t.current}`) ?? t.pending;
3220
+ return { value: { run: t.current, touches: n }, cursors: [] };
3221
+ },
3222
+ onPop: (n, s) => {
3223
+ t.popped = It(s?.value);
3224
+ }
3225
+ }), en = (o, e) => ({ person: Qt(o, "person", e), agent: Qt(o, "agent", e) }), tn = (o) => {
3226
+ o.person.free(), o.agent.free();
3227
+ };
3228
+ function we(o) {
3229
+ if (o !== "person" && o !== "agent") throw new K("invalid-value", 'an undo scope is "person" or "agent"');
3230
+ return o;
3231
+ }
3232
+ const rt = (o, e) => {
3233
+ const t = (n) => n.map((s) => `${s.counter}@${s.peer}`).sort().join(",");
3234
+ return t(o) === t(e);
3235
+ };
3236
+ export {
3237
+ st as A,
3238
+ $n as B,
3239
+ to as C,
3240
+ ks as D,
3241
+ ft as E,
3242
+ so as F,
3243
+ wn as G,
3244
+ D as H,
3245
+ Qe as I,
3246
+ Dn as J,
3247
+ Ee as K,
3248
+ ws as L,
3249
+ Fn as M,
3250
+ jn as N,
3251
+ Y as O,
3252
+ eo as P,
3253
+ de as R,
3254
+ ce as T,
3255
+ Q as a,
3256
+ Xe as b,
3257
+ Hs as c,
3258
+ Qs as d,
3259
+ Rn as e,
3260
+ Nn as f,
3261
+ oo as g,
3262
+ no as h,
3263
+ Os as i,
3264
+ he as j,
3265
+ Gs as k,
3266
+ je as l,
3267
+ vt as m,
3268
+ io as n,
3269
+ Xs as o,
3270
+ Zs as p,
3271
+ qe as q,
3272
+ ro as r,
3273
+ Ss as s,
3274
+ Ys as t,
3275
+ zs as u,
3276
+ Me as v,
3277
+ fs as w,
3278
+ Gn as x,
3279
+ Ue as y,
3280
+ ie as z
3281
+ };