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

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,1022 @@
1
+ import { o as fe } from "./envelope-GX4Cynkx.js";
2
+ import { R as re, r as we } from "./replica-Di2iCPiD.js";
3
+ import { b as ae, e as le, d as G, E as pe, R as me, l as ve, a as O, s as F, t as R, c as C, K as Q, L as ye, f as ee } from "./index-EEl8hGbP.js";
4
+ import { S as T, a as ge, l as be, D as Se } from "./client-B9xkOcvf.js";
5
+ import { LORO_REPLICA_VERSIONS as ke } from "./replicaVersions-C3rJxnk9.js";
6
+ import { commentSchema as Ee } from "./comments-uVDS8Wxp.js";
7
+ function Re(s) {
8
+ const e = s ?? {};
9
+ for (const t of [e.code, e.reason, e.data?.reason]) if (t === "conflict" || t === "corrupted") return t;
10
+ return "failed";
11
+ }
12
+ async function Ce(s) {
13
+ const { client: e, docId: t, trigger: n } = s;
14
+ let i;
15
+ try {
16
+ i = await e.saveBegin(t, n);
17
+ } catch (d) {
18
+ if (d instanceof T && d.reason === "conflict") return { status: "busy" };
19
+ throw d;
20
+ }
21
+ if (i.save.status !== "force-save") return { status: "clean" };
22
+ const { seq: o, authors: r, receipt: l } = i;
23
+ let c;
24
+ try {
25
+ c = await s.write({ seq: o, authors: r, trigger: n, receipt: l });
26
+ } catch (d) {
27
+ const p = (s.classify ?? Re)(d);
28
+ return await e.saveEnd(t, o, { error: p }).catch(() => {
29
+ }), { status: "failed", error: p, cause: d };
30
+ }
31
+ await e.saveEnd(t, o, { version: c });
32
+ let a = !1;
33
+ if (s.checkpoint)
34
+ try {
35
+ await s.checkpoint({ seq: o, version: c }), a = !0;
36
+ } catch {
37
+ a = !1;
38
+ }
39
+ return { status: "saved", version: c, seq: o, authors: r, checkpointed: a };
40
+ }
41
+ const Ae = "application/octet-stream";
42
+ function L(s) {
43
+ return s instanceof Uint8Array ? s : new Uint8Array(s);
44
+ }
45
+ function U(s) {
46
+ return s.slice().buffer;
47
+ }
48
+ function Oe(s) {
49
+ const { docId: e, replica: t, sync: n, versions: i } = s;
50
+ let o = s.lastSent ?? new Uint8Array(), r = o;
51
+ const l = /* @__PURE__ */ new Set(), c = [];
52
+ let a = !1, d = !1, p = !1, S = !1, k = Promise.resolve();
53
+ const y = (h) => (k = k.then(() => S ? void 0 : h()).catch((v) => s.onError?.(v)), k);
54
+ async function u(h) {
55
+ const v = h.filter((m) => !l.has(m.hash));
56
+ if (!v.length) return;
57
+ const { missing: E } = await n.blobs.has(e, v.map((m) => m.hash)), b = new Set(E);
58
+ for (const m of v) b.has(m.hash) && await n.blobs.put(e, m.data, Ae);
59
+ for (const m of v) l.add(m.hash);
60
+ }
61
+ async function f() {
62
+ if (!a || d) return;
63
+ const h = L(await t.version()), v = r;
64
+ let E = v, b = await t.exportChanges(U(E));
65
+ const m = i.snapshotRoot(L(b.changes));
66
+ if (m && (E = i.merge(E, m), b = await t.exportChanges(U(E)), i.snapshotRoot(L(b.changes)))) {
67
+ s.onError?.(new Error("the replica answers a snapshot, not changes; changes/push takes change sets only"));
68
+ return;
69
+ }
70
+ const A = L(b.changes);
71
+ if (i.isEmpty(A)) return;
72
+ try {
73
+ await u(G(L(b.blobs)));
74
+ } catch {
75
+ return;
76
+ }
77
+ const N = i.merge(E, h);
78
+ r = i.merge(r, N), n.push(e, A).then(
79
+ () => {
80
+ i.includes(o, v) && (o = i.merge(o, N), s.onSent?.(o));
81
+ },
82
+ ($) => {
83
+ r = o, s.onError?.($);
84
+ }
85
+ );
86
+ }
87
+ async function g(h) {
88
+ const v = ae(h).filter((m) => !l.has(m));
89
+ let E = new Uint8Array();
90
+ if (v.length) {
91
+ let m;
92
+ try {
93
+ const { missing: A } = await n.blobs.has(e, v), N = new Set(A);
94
+ m = [];
95
+ for (const $ of v) N.has($) || m.push({ hash: $, data: (await n.blobs.get(e, $)).data });
96
+ } catch {
97
+ return c.push(h), !1;
98
+ }
99
+ for (const A of m) l.add(A.hash);
100
+ E = le(m);
101
+ }
102
+ await t.importChanges(U(h), U(E));
103
+ const b = i.endOf(h);
104
+ return b && (o = i.merge(o, b), r = i.merge(r, b)), !0;
105
+ }
106
+ async function H() {
107
+ for (; c.length; ) {
108
+ const h = c.shift();
109
+ if (!await g(h)) return;
110
+ }
111
+ }
112
+ async function q(h) {
113
+ h === void 0 || c.length || !s.onSeen || s.onSeen({ seq: h, version: L(await t.version()) });
114
+ }
115
+ async function I() {
116
+ const h = await n.join(e, s.since ?? null, {});
117
+ a = !0, d = h.role === "viewer", s.onJoined?.({ presence: h.presence, role: h.role });
118
+ for (const v of h.changes) await g(v);
119
+ await q(h.seq);
120
+ }
121
+ const K = [
122
+ n.onChanges(e, (h) => void y(async () => {
123
+ await g(h.changes) && await q(h.seq);
124
+ })),
125
+ t.onChanged(() => void y(f)),
126
+ n.onAccess?.(e, (h) => {
127
+ d = h === null || h === "viewer", h === null && (a = !1, p = !0), s.onAccess?.(h);
128
+ }) ?? (() => {
129
+ }),
130
+ n.onState((h) => {
131
+ h === "online" && y(async () => {
132
+ p || (a || await I(), await H(), await f());
133
+ });
134
+ })
135
+ ];
136
+ return n.state === "online" && y(async () => {
137
+ await I(), await f();
138
+ }), {
139
+ stop: () => {
140
+ if (!S) {
141
+ S = !0;
142
+ for (const h of K) h();
143
+ a && n.leave(e);
144
+ }
145
+ },
146
+ idle: () => k
147
+ };
148
+ }
149
+ const X = "ko1.", Le = "kition-open", _e = 3600, De = 60;
150
+ class w extends Error {
151
+ constructor(e) {
152
+ super(`open token refused: ${e}`), this.code = e;
153
+ }
154
+ }
155
+ const te = ["edit", "comment", "download", "share", "export"];
156
+ function Y(s) {
157
+ if (!/^[A-Za-z0-9_-]*$/.test(s) || s.length % 4 === 1) throw new w("malformed");
158
+ let e;
159
+ try {
160
+ const t = atob(s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - s.length % 4) % 4));
161
+ e = Uint8Array.from(t, (n) => n.charCodeAt(0));
162
+ } catch {
163
+ throw new w("malformed");
164
+ }
165
+ if (Ie(e) !== s) throw new w("malformed");
166
+ return e;
167
+ }
168
+ function Te(s) {
169
+ let e = 0;
170
+ const t = () => {
171
+ for (; e < s.length && `
172
+ \r`.includes(s[e]); ) e += 1;
173
+ }, n = () => {
174
+ if (s[e] !== '"') return null;
175
+ const o = e;
176
+ for (e += 1; e < s.length && s[e] !== '"'; ) e += s[e] === "\\" ? 2 : 1;
177
+ if (e >= s.length) return null;
178
+ e += 1;
179
+ try {
180
+ return JSON.parse(s.slice(o, e));
181
+ } catch {
182
+ return null;
183
+ }
184
+ }, i = (o) => {
185
+ if (o > 8) return !1;
186
+ t();
187
+ const r = s[e];
188
+ if (r === "{") {
189
+ e += 1;
190
+ const c = /* @__PURE__ */ new Set();
191
+ if (t(), s[e] === "}")
192
+ return e += 1, !0;
193
+ for (; ; ) {
194
+ t();
195
+ const a = n();
196
+ if (a === null || c.has(a) || (c.add(a), t(), s[e] !== ":") || (e += 1, !i(o + 1))) return !1;
197
+ if (t(), s[e] === ",") {
198
+ e += 1;
199
+ continue;
200
+ }
201
+ return s[e] !== "}" ? !1 : (e += 1, !0);
202
+ }
203
+ }
204
+ if (r === "[") {
205
+ if (e += 1, t(), s[e] === "]")
206
+ return e += 1, !0;
207
+ for (; ; ) {
208
+ if (!i(o + 1)) return !1;
209
+ if (t(), s[e] === ",") {
210
+ e += 1;
211
+ continue;
212
+ }
213
+ return s[e] !== "]" ? !1 : (e += 1, !0);
214
+ }
215
+ }
216
+ if (r === '"') return n() !== null;
217
+ const l = /^(?:-?(?:0|[1-9][0-9]*)(?![.eE0-9])|true|false|null)/.exec(s.slice(e));
218
+ return l ? (e += l[0].length, !0) : !1;
219
+ };
220
+ return i(0) ? (t(), e === s.length) : !1;
221
+ }
222
+ function Ie(s) {
223
+ let e = "";
224
+ for (const t of s) e += String.fromCharCode(t);
225
+ return btoa(e).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
226
+ }
227
+ function ce(s) {
228
+ if (typeof s != "string" || !s.startsWith(X)) throw new w("malformed");
229
+ const e = s.slice(X.length).split(".");
230
+ if (e.length !== 2 || !e[0] || !e[1]) throw new w("malformed");
231
+ return [e[0], e[1]];
232
+ }
233
+ const $e = (s) => typeof s == "boolean", P = (s) => typeof s == "string", se = (s) => typeof s == "number" && Number.isSafeInteger(s) && s >= 0;
234
+ function he(s) {
235
+ let e;
236
+ try {
237
+ const a = new TextDecoder("utf-8", { fatal: !0 }).decode(Y(s));
238
+ if (!Te(a)) throw new w("malformed");
239
+ e = JSON.parse(a);
240
+ } catch {
241
+ throw new w("malformed");
242
+ }
243
+ if (!e || typeof e != "object" || Array.isArray(e)) throw new w("malformed");
244
+ const t = e.perms, n = !!t && typeof t == "object" && !Array.isArray(t) && Object.keys(t).every((a) => te.includes(a)) && te.every((a) => $e(t[a])), i = e.watermark ?? null, o = i === null || typeof i == "object" && !Array.isArray(i) && Object.keys(i).length === 1 && P(i.text), r = e.name === void 0 ? "" : e.name;
245
+ if (!(typeof e.v == "number" && P(e.typ) && ["kid", "iss", "aud", "tenant", "sub", "file", "version", "doc_key"].every((a) => P(e[a])) && P(r) && n && o && se(e.iat) && se(e.exp) && (e.jti === void 0 || e.jti === null || P(e.jti)))) throw new w("malformed");
246
+ const c = { ...e, name: r, watermark: i };
247
+ return e.jti === null && delete c.jti, c;
248
+ }
249
+ function Pe(s) {
250
+ return /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])$/.test(s);
251
+ }
252
+ const de = /[\u0000-\u001f\u007f-\u009f]/, ue = (s) => new TextEncoder().encode(s).length, _ = (s, e) => s.length > 0 && ue(s) <= e && !de.test(s), V = (s, e) => s.length >= 1 && s.length <= 128 && new RegExp(`^[A-Za-z0-9._${e}-]+$`).test(s);
253
+ function Me(s) {
254
+ if (!(Pe(s.tenant) && _(s.kid, 128) && V(s.iss, "") && _(s.aud, 256) && _(s.sub, 128) && ue(s.name) <= 128 && !de.test(s.name) && V(s.file, ":") && _(s.version, 128) && V(s.doc_key, "") && (!s.perms.edit || s.perms.comment) && (s.watermark === null || _(s.watermark.text, 256)) && (s.jti === void 0 || _(s.jti, 128)))) throw new w("claims");
255
+ }
256
+ function xe(s, e) {
257
+ if (s.exp <= s.iat || s.exp - s.iat > _e) throw new w("expired");
258
+ if (s.iat > e + De) throw new w("not-yet-valid");
259
+ if (e >= s.exp) throw new w("expired");
260
+ }
261
+ function qe(s) {
262
+ const e = /* @__PURE__ */ new Set();
263
+ for (const t of s) {
264
+ const n = `${t.tenant}\0${t.kid}`;
265
+ if (e.has(n)) throw new w("duplicate-key");
266
+ e.add(n);
267
+ }
268
+ }
269
+ async function Ke(s, e, t, n = Math.floor(Date.now() / 1e3)) {
270
+ qe(e);
271
+ const [i, o] = ce(s), r = he(i);
272
+ if (r.v !== 1 || r.typ !== Le) throw new w("version");
273
+ const l = e.find((p) => p.kid === r.kid && p.tenant === r.tenant);
274
+ if (!l) throw new w("unknown-key");
275
+ const c = Y(l.publicKey), a = Y(o);
276
+ if (c.length !== 32 || a.length !== 64) throw new w("malformed");
277
+ let d = !1;
278
+ try {
279
+ const p = await crypto.subtle.importKey("raw", c, { name: "Ed25519" }, !1, ["verify"]);
280
+ d = await crypto.subtle.verify({ name: "Ed25519" }, p, a, new TextEncoder().encode(i));
281
+ } catch {
282
+ d = !1;
283
+ }
284
+ if (!d) throw new w("signature");
285
+ if (l.iss !== r.iss) throw new w("issuer");
286
+ if (r.aud !== t) throw new w("audience");
287
+ return Me(r), xe(r, n), r;
288
+ }
289
+ function Ne(s) {
290
+ return he(ce(s)[0]);
291
+ }
292
+ function Ue(s) {
293
+ return typeof s == "string" && s.startsWith(X);
294
+ }
295
+ const x = /* @__PURE__ */ new Map(), ne = /* @__PURE__ */ new WeakMap();
296
+ let Be = 0;
297
+ function je(s) {
298
+ let e = ne.get(s);
299
+ return e === void 0 && ne.set(s, e = Be += 1), e;
300
+ }
301
+ function We(s) {
302
+ const e = new WebSocket(s);
303
+ return e.binaryType = "arraybuffer", e;
304
+ }
305
+ function Z(s, e, t = We, n, i = "") {
306
+ const o = n ? `owner ${je(n)} ${i} ${s}` : `url ${s}`;
307
+ let r = x.get(o);
308
+ if (!r) {
309
+ const a = new ge({ createTransport: t, client: { name: "@kition/embed", version: pe } });
310
+ r = { client: a, users: 0 }, x.set(o, r), a.connect(s, e).catch(() => {
311
+ });
312
+ }
313
+ r.users += 1;
314
+ const l = r;
315
+ let c = !1;
316
+ return {
317
+ client: l.client,
318
+ release: () => {
319
+ c || (c = !0, l.users -= 1, !(l.users > 0 || x.get(o) !== l) && (x.delete(o), l.client.close()));
320
+ }
321
+ };
322
+ }
323
+ function Je(s) {
324
+ return x.has(`url ${s}`) ? Z(s, () => Promise.reject(new Error("unused"))) : null;
325
+ }
326
+ function D(s, e) {
327
+ return s.state === "online" ? Promise.resolve() : new Promise((t, n) => {
328
+ const i = () => {
329
+ r(), e?.removeEventListener("abort", o);
330
+ }, o = () => {
331
+ i(), n(new Error("the editor was closed"));
332
+ }, r = s.onState((l) => {
333
+ l === "online" && (i(), t());
334
+ });
335
+ e?.aborted ? o() : e?.addEventListener("abort", o);
336
+ });
337
+ }
338
+ const He = 15e3, Fe = "application/octet-stream", Ve = 2e4, ze = 3e4, Ge = 2e3, Xe = 3e4, Ye = 3e4, Ze = 200;
339
+ function Qe(s) {
340
+ return s instanceof T && (s.message === "disconnected" || s.reason === "not-found" || s.reason === "unavailable");
341
+ }
342
+ const et = 250, tt = 20, B = /* @__PURE__ */ new Map(), st = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i, j = (s, e) => s.replace(/-/g, "").toLowerCase() === e.replace(/-/g, "").toLowerCase();
343
+ function W(s) {
344
+ const e = s.replace(/-/g, "").toLowerCase();
345
+ return `${e.slice(0, 8)}-${e.slice(8, 12)}-${e.slice(12, 16)}-${e.slice(16, 20)}-${e.slice(20)}`;
346
+ }
347
+ function M(s) {
348
+ return s instanceof Error ? s : new Error(String(s));
349
+ }
350
+ function ie(s, e) {
351
+ let t = !0;
352
+ try {
353
+ t = re.snapshotCarriesWholeHistory(s);
354
+ } catch {
355
+ return;
356
+ }
357
+ if (!t) throw new Error(`${e} cannot be co-edited: its replica is a shallow one truncated after the document's birth, so it does not carry the document's whole history (sync protocol S20); open it from a full replica or a copy made as a new document`);
358
+ }
359
+ function z(s) {
360
+ try {
361
+ return C(fe(new Uint8Array(s)).docId);
362
+ } catch {
363
+ return null;
364
+ }
365
+ }
366
+ async function nt(s, e, t, n) {
367
+ const i = ae(t);
368
+ if (!i.length) return new Uint8Array();
369
+ const { missing: o } = await s.blobs.has(e, i), r = new Set(o), l = [];
370
+ for (const c of i) {
371
+ if (r.has(c)) continue;
372
+ const a = await n?.read(c).catch(() => null);
373
+ l.push({ hash: c, data: a ? new Uint8Array(R(a)) : (await s.blobs.get(e, c)).data });
374
+ }
375
+ return le(l);
376
+ }
377
+ async function oe(s, e, t) {
378
+ if (!t.length) return;
379
+ const { missing: n } = await s.blobs.has(e, t.map((o) => o.hash)), i = new Set(n);
380
+ for (const o of t) i.has(o.hash) && await s.blobs.put(e, o.data, Fe);
381
+ }
382
+ function it(s) {
383
+ return {
384
+ version: () => s.replica.version(),
385
+ exportChanges: (e) => s.replica.exportChanges(e),
386
+ importChanges: (e, t) => s.replica.importChanges(e, t),
387
+ onChanged: (e) => s.replica.onChanged(e)
388
+ };
389
+ }
390
+ function J(s, e) {
391
+ return { scope: s.scope, holder: { principalId: s.principalId, name: s.name, self: e } };
392
+ }
393
+ class ot {
394
+ constructor(e) {
395
+ this.host = e, this.records = new me(e.storage.state ?? ve()), this.versions = e.versions ?? ke, this.state = { status: "offline", docId: null, role: null };
396
+ }
397
+ /** The page's client this session co-edits through, from `connect` on (the first step of `prepare`). */
398
+ client;
399
+ release = () => {
400
+ };
401
+ records;
402
+ versions;
403
+ stopState = () => {
404
+ };
405
+ user = null;
406
+ /** The agent working for the person in this editor (an open agent port), shown in presence (A20). */
407
+ agent = null;
408
+ joinedDoc = null;
409
+ /** The room `adoptRoom` joined to catch its snapshot up, until a relay takes the membership over. */
410
+ adoptJoined = null;
411
+ /** The file generation (`doc_key`) of the room joined: the token may name a later one since (1.3). */
412
+ joinedDocKey = null;
413
+ move = null;
414
+ record = null;
415
+ relay = null;
416
+ stopPresence = null;
417
+ /** The kit's leases on the room's scopes, while attached (Kit UI protocol capability `lease`). */
418
+ leases = null;
419
+ stopLeases = null;
420
+ /** The latest `attach`, which `shareLink` waits for. */
421
+ attached = Promise.resolve();
422
+ /** Counts `attach` calls: a start that an `attach` or `detach` replaced stops where it is. */
423
+ generation = 0;
424
+ closed = !1;
425
+ /** The `openDocuments` key this session holds. */
426
+ claimed = null;
427
+ /** Renews the seed claim of a managed room while the kit opens (RM5). */
428
+ claimRenewal = null;
429
+ /** A managed editor found no room and no claim in time: it opens read-only (section 2.2, step 4). */
430
+ unavailable = !1;
431
+ /** This session's connection is its own identity provider's: its token is an open token (KitCollab 1.4). */
432
+ managed = !1;
433
+ /** The open token's claims, read (and with `openKeys` verified) when the session connected. */
434
+ claims = null;
435
+ /** The kit this session relays, while attached, and the mode it opened in. */
436
+ connection = null;
437
+ mode = "view";
438
+ /** What starts the kit's next save (D3): the person's Save unless the session asks for one itself. */
439
+ trigger = null;
440
+ autosave = null;
441
+ stopSave = null;
442
+ stopResolved = null;
443
+ saveWaiters = /* @__PURE__ */ new Set();
444
+ /** The room's changes this replica holds: every one up to `seenSeq`, and the ones it pushed after it. */
445
+ seenSeq = 0;
446
+ pushedSeqs = /* @__PURE__ */ new Set();
447
+ /** A saved version the kit is still to hear it holds (`document/held`), once the replica holds its `savedSeq`. */
448
+ heldPending = null;
449
+ heldSent = null;
450
+ state;
451
+ /**
452
+ * Takes the page's client for the server. The identity provider is always asked for the token
453
+ * first (managed-collab.md RM8, I8): an open token gets a connection of its own identity
454
+ * provider for its file, never one another editor opened; a sync token joins the one editors
455
+ * with sync tokens share for the server, or opens it with that token. A token that cannot be
456
+ * had now is asked again by the client, which keeps retrying; it never joins a shared
457
+ * connection, which could be another person's.
458
+ */
459
+ async connect() {
460
+ const { collaboration: e, identity: t, createTransport: n } = this.host, i = await Promise.resolve().then(() => t.token()).catch(() => null);
461
+ if (this.managed = Ue(i), e.open && !this.managed) throw new O("read-only", i === null ? "no open token for this file" : "the identity provider answered a token that is not an open token");
462
+ this.managed && (this.claims = await this.readClaims(i));
463
+ let o = i === null;
464
+ const r = () => o ? t.token() : (o = !0, i), l = this.managed ? Z(e.server, r, n, t, this.claims?.file ?? this.host.file.id) : (i !== null ? Je(e.server) : null) ?? Z(e.server, r, n, i === null ? t : void 0, this.host.file.id);
465
+ this.client = l.client, this.release = l.release, this.state = { ...this.state, status: this.client.state }, this.stopState = this.client.onState((c) => this.setState({ status: c }));
466
+ }
467
+ /** The open token's claims, verified against `collaboration.openKeys` when the page gives them (OT2). */
468
+ async readClaims(e) {
469
+ const { openKeys: t, openAudience: n } = this.host.collaboration;
470
+ if (t?.length && !n) throw new Error("collaboration.openKeys needs collaboration.openAudience, the server id open tokens name");
471
+ if (!t?.length || !n)
472
+ try {
473
+ return Ne(e);
474
+ } catch {
475
+ return null;
476
+ }
477
+ try {
478
+ return await Ke(e, t, n);
479
+ } catch (i) {
480
+ throw new O("read-only", `the open token does not verify (${i.code ?? "malformed"})`);
481
+ }
482
+ }
483
+ /**
484
+ * In a managed room: what the kit opens with from the token, with the
485
+ * permissions as the sync server read them when it said (it verified the token), and the watermark.
486
+ */
487
+ get openDocument() {
488
+ if (!this.managed) return null;
489
+ const e = this.client.open?.perms ?? this.claims?.perms;
490
+ return e ? { permissions: { download: e.download, export: e.export, share: e.share }, watermark: this.claims?.watermark ? { text: this.claims.watermark.text } : null } : null;
491
+ }
492
+ /** What the room lets this person do, once known: `view` for a viewer, `comment` for a commenter. */
493
+ get roleMode() {
494
+ if (this.unavailable) return "view";
495
+ const e = this.record?.role ?? (this.managed ? this.client.open?.role : void 0);
496
+ return e === "viewer" ? "view" : e === "commenter" ? "comment" : null;
497
+ }
498
+ /** Before the kit opens: resolves the given room, and makes its replica the one the kit opens. */
499
+ async prepare() {
500
+ await this.connect();
501
+ const { room: e } = this.host.collaboration;
502
+ if (this.user = await this.host.identity.user?.() ?? null, !e?.trim()) {
503
+ this.managed && await this.prepareManaged();
504
+ return;
505
+ }
506
+ const { kit: t, signal: n } = this.host;
507
+ let i, o = null, r;
508
+ if (st.test(e.trim()))
509
+ i = W(e.trim());
510
+ else {
511
+ r = e.trim(), await D(this.client, n);
512
+ const l = await this.client.openRoom(r);
513
+ if (l.kit !== t.id) throw new Error(`the room holds a ${l.kit} document, not ${t.id}`);
514
+ i = l.docId, o = l.role;
515
+ }
516
+ await this.adoptRoom(i, o, r);
517
+ }
518
+ /**
519
+ * Before the kit opens, for a managed room (an open token, KitCollab 1.4; managed-collab.md
520
+ * section 2.2): finds the room of the token's file generation, and when it has none, takes the
521
+ * seed claim (an editor) so exactly one session seeds it, from the file's checkpoint when the
522
+ * host keeps one for this version (CK2), else from the kit once it opens (`attach`). An editor
523
+ * that finds another seeding waits for it.
524
+ */
525
+ async prepareManaged() {
526
+ const { signal: e } = this.host;
527
+ await D(this.client, e);
528
+ const t = this.client.open;
529
+ if (!t) throw new Error("the sync server does not take open tokens (KitCollab 1.4)");
530
+ if (t.file !== this.host.file.id) throw new O("read-only", `the open token is for another file (${t.file}), not ${this.host.file.id}`);
531
+ const n = t.role === "editor", i = Date.now() + ze;
532
+ for (; ; ) {
533
+ const o = await this.client.resolveRoom(n);
534
+ if (this.state = { ...this.state, save: o.save ?? null }, o.docId) return this.adoptRoom(o.docId, t.role);
535
+ if (o.claimed) {
536
+ this.renewClaim();
537
+ const r = await this.seedFromCheckpoint();
538
+ return r ? this.adoptRoom(r, t.role) : void 0;
539
+ }
540
+ if (!n) return;
541
+ if (Date.now() >= i) {
542
+ this.unavailable = !0, this.host.emit("error", new O("read-only", "another editor is still preparing this document for co-editing; it is open read-only until then"));
543
+ return;
544
+ }
545
+ await this.roomOrPoll(e);
546
+ }
547
+ }
548
+ /** Resolves when the file generation's room appears or after a poll interval. */
549
+ roomOrPoll(e) {
550
+ return new Promise((t, n) => {
551
+ const i = () => {
552
+ clearTimeout(r), l(), e.removeEventListener("abort", o);
553
+ }, o = () => {
554
+ i(), n(new Error("the editor was closed"));
555
+ }, r = setTimeout(() => {
556
+ i(), t();
557
+ }, Ge), l = this.client.onRoomResolved(() => {
558
+ i(), t();
559
+ });
560
+ e.aborted ? o() : e.addEventListener("abort", o);
561
+ });
562
+ }
563
+ renewClaim() {
564
+ this.stopClaim(), this.claimRenewal = setInterval(() => void this.client.resolveRoom(!0).catch(() => {
565
+ }), Ve);
566
+ }
567
+ stopClaim() {
568
+ this.claimRenewal && clearInterval(this.claimRenewal), this.claimRenewal = null;
569
+ }
570
+ /**
571
+ * Seeds the managed room from the file's checkpoint (the replica the host keeps with the file)
572
+ * when it is the replica of the file as it is now (CK2): the room keeps the document's id after
573
+ * Kition Server lost it. Answers the room's id, or `null` when there is no such checkpoint.
574
+ */
575
+ async seedFromCheckpoint() {
576
+ const { kit: e, file: t, storage: n, replicas: i } = this.host, o = await F(n, t.id), r = await i.read(t.id).catch(() => null);
577
+ if (!o || !r || r.fileStamp !== o) return null;
578
+ const l = z(R(r.snapshot));
579
+ if (!l) return null;
580
+ const c = W(l);
581
+ ie(new Uint8Array(R(r.snapshot)), t.name), await oe(this.client, c, G(new Uint8Array(R(r.blobs))));
582
+ try {
583
+ return await this.client.createRoom(c, new Uint8Array(R(r.snapshot)), t.name, e.id), c;
584
+ } catch (a) {
585
+ if (a instanceof T && a.boundDocId) return a.boundDocId;
586
+ throw a;
587
+ } finally {
588
+ this.stopClaim();
589
+ }
590
+ }
591
+ /**
592
+ * Makes `docId`'s room the one the kit opens: its state becomes the stored replica unless the
593
+ * one stored already is the room's document for the file as it is now (its stamp).
594
+ */
595
+ async adoptRoom(e, t, n) {
596
+ const { kit: i, file: o, storage: r, replicas: l, signal: c } = this.host;
597
+ this.claim(e);
598
+ let a = await this.records.read(e);
599
+ const d = await F(r, o.id);
600
+ if (!d) throw new Error(`${o.name} is not in the storage`);
601
+ const p = await l.read(o.id).catch(() => null), S = p ? z(R(p.snapshot)) : null, k = !!(p && p.fileStamp === d && S && j(S, e));
602
+ if (k && !(a && a.fileId === o.id))
603
+ a = { docId: e, fileId: o.id, kit: i.id, role: t ?? a?.role ?? "editor", shareLink: n ?? a?.shareLink }, await this.records.write(a);
604
+ else if (k)
605
+ a && (t && a.role !== t || n && a.shareLink !== n) && (a = { ...a, role: t ?? a.role, shareLink: n ?? a.shareLink }, await this.records.write(a));
606
+ else {
607
+ await D(this.client, c);
608
+ const y = await this.roomState(e), u = await nt(this.client, e, y.snapshot, r.blob);
609
+ await l.write(o.id, { snapshot: R(y.snapshot), blobs: R(u), fileStamp: d });
610
+ const f = this.versions.endOf(y.snapshot);
611
+ a = {
612
+ docId: e,
613
+ fileId: o.id,
614
+ kit: i.id,
615
+ role: t ?? a?.role ?? "editor",
616
+ shareLink: n ?? a?.shareLink,
617
+ lastSent: f ? C(f) : void 0,
618
+ seen: f ? { seq: y.seq, version: C(f) } : void 0
619
+ }, await this.records.write(a);
620
+ }
621
+ this.record = a, this.setState({ docId: e, role: a.role });
622
+ }
623
+ /**
624
+ * The room's state to store as the file's replica, and the `seq` it holds every change up to.
625
+ * `snapshot/get` answers the room's last snapshot (its creation, or a compaction's), which can
626
+ * be older than the file: in a managed room the file is the room's state at its last save
627
+ * (`savedSeq`; a generation's file changes only through the room's saves, managed-collab.md
628
+ * 1.3). Such a snapshot is brought up to the save: the room is joined from the snapshot's `seq`
629
+ * (the relay joins it again, from the `seq` this answers, once the kit has opened) and the
630
+ * changes up to `savedSeq` are imported into a copy of the snapshot, read with a schema of the
631
+ * comment types alone, which reads any of the kit's documents. A catch-up that cannot be cut at
632
+ * `savedSeq` (one the server answered from a compacted snapshot) is taken whole: the room's
633
+ * latest state, which holds the file too.
634
+ */
635
+ async roomState(e) {
636
+ const { snapshot: t, seq: n } = await this.client.snapshot(e), i = this.managed ? (await this.client.resolveRoom()).save : null;
637
+ if (!i || i.savedSeq <= n) return { snapshot: t, seq: n };
638
+ let o;
639
+ try {
640
+ o = re.load(Ee(this.host.kit.id), t, we());
641
+ } catch (a) {
642
+ throw new Error(`the room's snapshot of ${this.host.file.name} does not load (${M(a).message}); it is older than the file, so it is not stored as its replica`);
643
+ }
644
+ this.adoptJoined && this.adoptJoined !== e && this.client.leave(this.adoptJoined);
645
+ const r = await this.client.join(e, n, {});
646
+ this.adoptJoined = e;
647
+ const l = !r.snapshot && r.changes.length === r.seq - n, c = l ? r.changes.slice(0, i.savedSeq - n) : r.changes;
648
+ for (const a of c) o.importChanges(a);
649
+ return { snapshot: o.exportChanges(), seq: l ? i.savedSeq : r.seq };
650
+ }
651
+ /** Once the kit has opened (again): relays its replica. Failures are reported as `error` events. */
652
+ attach(e, t) {
653
+ this.detach();
654
+ const n = this.generation;
655
+ return this.attached = this.start(e, t, () => this.closed || n !== this.generation).catch((i) => {
656
+ this.closed || this.host.emit("error", M(i));
657
+ }), this.attached;
658
+ }
659
+ /** Stops relaying (the kit is about to close or reopen). */
660
+ detach() {
661
+ this.generation += 1, this.stopSave?.(), this.stopSave = null, this.autosave && clearInterval(this.autosave), this.autosave = null, this.connection = null, this.stopResolved?.(), this.stopResolved = null, this.stopLeases?.(), this.stopLeases = null, this.leases?.dispose(), this.leases = null, this.relay?.stop(), this.relay = null, this.stopPresence?.(), this.stopPresence = null;
662
+ }
663
+ /** `host/leaseAcquire`: holds `scope` in the room; `{ lease: null }` before the room is joined or while offline. */
664
+ async acquireLease({ scope: e, ttl: t }) {
665
+ const n = this.leases;
666
+ if (!n) return { lease: null };
667
+ try {
668
+ const i = await n.acquire(e, t);
669
+ return { lease: i ? J(i, !0) : null };
670
+ } catch (i) {
671
+ const o = be(i);
672
+ throw o ? new Q(-32e3, `${o.name} is editing it`, { reason: ye, lease: J(o, !1) }) : i instanceof T && i.reason === "forbidden" ? new Q(-32e3, "the document is read-only", { reason: "read-only" }) : i;
673
+ }
674
+ }
675
+ async releaseLease({ scope: e }) {
676
+ await this.leases?.release(e);
677
+ }
678
+ listLeases() {
679
+ const e = this.leases;
680
+ return e ? e.list().map((t) => J(t, e.mine(t))) : [];
681
+ }
682
+ /**
683
+ * Once the kit has opened: holds the document its replica names for this session, refusing it
684
+ * (`EmbedError` `document-open`) when another editor on the page co-edits it. A kit without a
685
+ * replica id is left for `attach` to report.
686
+ */
687
+ async claimOpened(e) {
688
+ if (!e.capabilities.includes("replica")) return;
689
+ await e.replica.version();
690
+ const t = await e.replica.info();
691
+ t && this.claim(t);
692
+ }
693
+ claim(e) {
694
+ const t = `${this.host.collaboration.server} ${W(e)}`;
695
+ if (this.claimed === t) return;
696
+ const n = B.get(t);
697
+ if (n && n !== this) throw new O("document-open", `document ${W(e)} is already open in another editor on this page`);
698
+ this.unclaim(), B.set(t, this), this.claimed = t;
699
+ }
700
+ unclaim() {
701
+ this.claimed && B.get(this.claimed) === this && B.delete(this.claimed), this.claimed = null;
702
+ }
703
+ close() {
704
+ this.closed || (this.closed = !0, this.stopClaim(), this.unclaim(), this.detach(), this.adoptJoined && this.client.leave(this.adoptJoined), this.adoptJoined = null, this.stopState(), this.release(), this.setState({ status: "off" }));
705
+ }
706
+ /** A link to the room granting `role`: the room's own link for its owner, a new one otherwise. */
707
+ async shareLink(e = "editor") {
708
+ await this.attached;
709
+ const t = this.record;
710
+ if (!t) throw new Error("the document has no room yet");
711
+ if (e === "editor" && t.role === "owner" && t.shareLink) return t.shareLink;
712
+ await D(this.client, this.host.signal);
713
+ try {
714
+ return (await this.client.createLink(t.docId, e)).shareLink;
715
+ } catch (n) {
716
+ throw n instanceof T && n.reason === "forbidden" ? new O("read-only", "this room cannot be shared by this person: their role, or a room that grants access by sync token only") : n;
717
+ }
718
+ }
719
+ async start(e, t, n) {
720
+ const { kit: i, file: o } = this.host;
721
+ if (!e.capabilities.includes("replica")) throw new Error(`${i.id} cannot be co-edited: it keeps no replica`);
722
+ const r = it(e);
723
+ await r.version();
724
+ const l = await e.replica.info();
725
+ if (!l) throw new Error(`${o.name} has no replica id to co-edit with`);
726
+ if (this.record && !j(this.record.docId, l)) throw new Error(`${o.name} did not open as the room's document`);
727
+ this.claim(l);
728
+ const c = this.managed;
729
+ let a = this.record ?? (c ? null : await this.records.read(l));
730
+ if (!a) {
731
+ if (c && t !== "edit") {
732
+ this.waitForRoom();
733
+ return;
734
+ }
735
+ if (t !== "edit") throw new Error(`${o.name} is open read-only and has no room to join`);
736
+ a = await this.createRoom(e, l);
737
+ }
738
+ if (n()) return;
739
+ this.record = a, this.setState({ docId: l, role: a.role });
740
+ const d = await this.resumeSeq(a, r);
741
+ if (n()) return;
742
+ this.stopPresence = this.client.onPresence(l, (u) => this.host.emit("presence", u));
743
+ const p = new Se(this.client.leases, l);
744
+ this.leases = p;
745
+ let S = [];
746
+ this.stopLeases = p.onChanged((u) => {
747
+ const f = u.map((h) => J(h, p.mine(h)));
748
+ e.leasesChanged(f);
749
+ const g = (h) => `${h.scope}\0${h.holder.principalId}`, H = new Set(S.map(g)), q = new Set(f.map(g)), I = f.filter((h) => !H.has(g(h))), K = S.filter((h) => !q.has(g(h)));
750
+ S = f, (I.length || K.length) && this.host.emit("leases", { leases: f, held: I, released: K });
751
+ }), c && this.followSaves(l, e, t), this.seenSeq = d ?? 0, this.pushedSeqs.clear();
752
+ const k = this.client, y = Object.create(k);
753
+ y.push = async (u, f) => {
754
+ const g = await k.push(u, f);
755
+ return this.pushedSeqs.add(g.seq), this.offerHeld(), g;
756
+ }, this.adoptJoined = null, this.relay = Oe({
757
+ docId: l,
758
+ replica: r,
759
+ sync: y,
760
+ versions: this.versions,
761
+ lastSent: ee(a.lastSent),
762
+ since: d,
763
+ onSent: (u) => void this.records.update(l, { lastSent: C(u) }),
764
+ onSeen: ({ seq: u, version: f }) => {
765
+ this.seenSeq = Math.max(this.seenSeq, u), this.offerHeld(), this.records.update(l, { seen: { seq: u, version: C(f) } });
766
+ },
767
+ onJoined: ({ presence: u, role: f }) => {
768
+ this.host.emit("presence", u), this.joinedDoc = l, this.joinedDocKey = this.client.open?.docKey ?? null, this.takeRole(l, f), this.sendPresence(), !this.reopenFor(f, t) && c && t === "edit" && this.state.save?.status === "must-save" && this.saveNow("command");
769
+ },
770
+ // A role changed while joined (`room/access`), or while the connection was down (the re-join
771
+ // after reconnecting answered another): the kit opens again as the new role allows.
772
+ onAccess: (u) => {
773
+ u && (this.takeRole(l, u), this.reopenFor(u, t));
774
+ },
775
+ onError: (u) => this.host.emit("error", M(u))
776
+ });
777
+ }
778
+ /** Records `role` as this person's role in `docId`'s room. */
779
+ takeRole(e, t) {
780
+ this.record && this.record.role !== t && (this.record = { ...this.record, role: t }, this.records.update(e, { role: t })), this.setState({ role: t });
781
+ }
782
+ /** Opens the kit again read-only when `role` allows less than the kit was opened with (`mode`). */
783
+ reopenFor(e, t) {
784
+ if (e === "viewer" && t !== "view") this.host.reopenReadOnly("view");
785
+ else if (e === "commenter" && t === "edit") this.host.reopenReadOnly("comment");
786
+ else return !1;
787
+ return !0;
788
+ }
789
+ /**
790
+ * A managed viewer whose file had no room: when an editor makes it, the room's document becomes
791
+ * the stored replica and the kit opens it again, live.
792
+ */
793
+ waitForRoom() {
794
+ if (this.stopResolved) return;
795
+ const e = this.client.open?.role ?? "viewer", t = (n) => {
796
+ this.stopResolved?.(), this.stopResolved = null, this.adoptRoom(n, e).then(() => {
797
+ this.closed || this.host.reopen?.();
798
+ }).catch((i) => {
799
+ this.closed || this.host.emit("error", M(i));
800
+ });
801
+ };
802
+ this.stopResolved = this.client.onRoomResolved(t), this.client.resolveRoom().then((n) => {
803
+ n.docId && this.stopResolved && t(n.docId);
804
+ }, () => {
805
+ });
806
+ }
807
+ /**
808
+ * In a managed room: follows its save state (D3), moves this editor's file version along with
809
+ * every session's saves, autosaves an editor's unsaved changes (SV2), and saves first when the
810
+ * room waits for one (`must-save`, SV4).
811
+ */
812
+ followSaves(e, t, n) {
813
+ if (this.connection = t, this.mode = n, this.stopSave?.(), this.stopSave = this.client.onSave(e, (o) => this.saveChanged(o)), this.client.resolveRoom().then(
814
+ (o) => {
815
+ o.save && this.connection === t && !this.state.save && this.setState({ save: o.save });
816
+ },
817
+ () => {
818
+ }
819
+ ), n !== "edit") return;
820
+ const i = this.host.collaboration.autosaveMs ?? Xe;
821
+ this.autosave && clearInterval(this.autosave), this.autosave = setInterval(() => {
822
+ const o = this.state.save;
823
+ o?.dirty && o.status === "editing" && this.saveNow("timer");
824
+ }, i);
825
+ }
826
+ /** Whether this replica holds every change of the room up to `seq`. */
827
+ holds(e) {
828
+ for (let t = this.seenSeq + 1; t <= e; t += 1) if (!this.pushedSeqs.has(t)) return !1;
829
+ return !0;
830
+ }
831
+ /**
832
+ * Tells the kit a saved version holds nothing it lacks (`document/held`), once its replica holds
833
+ * the room's changes up to the save's `seq`: a co-editor's save is no file "changed on disk".
834
+ */
835
+ offerHeld() {
836
+ const e = this.heldPending, t = this.connection;
837
+ !e || !t || !this.holds(e.seq) || (this.heldPending = null, this.heldSent !== e.version && (this.heldSent = e.version, t.fileHeld(e.version)));
838
+ }
839
+ saveChanged(e) {
840
+ if (this.setState({ save: e }), e.status !== "force-save" && e.version && !e.reason && (this.heldPending = { version: e.version, seq: e.savedSeq }, this.offerHeld()), e.status !== "force-save") {
841
+ e.version && this.host.onVersion?.(e.version);
842
+ for (const t of [...this.saveWaiters]) t();
843
+ }
844
+ e.status === "must-save" && this.mode === "edit" && this.saveNow("command");
845
+ }
846
+ /**
847
+ * Has the kit save, as started by `trigger` (its own Save is the person's). Failures are
848
+ * reported, never thrown. A room waiting for a save (`must-save`) whose kit has not caught up
849
+ * with the room's changes yet (nothing to save) is asked again a few times.
850
+ */
851
+ async saveNow(e, t = 0) {
852
+ const n = this.connection;
853
+ if (!n || this.mode !== "edit" || this.trigger) return;
854
+ this.trigger = e;
855
+ let i = !0;
856
+ try {
857
+ i = (await n.save()).saved;
858
+ } catch (o) {
859
+ this.closed || this.host.emit("error", M(o));
860
+ } finally {
861
+ this.trigger = null;
862
+ }
863
+ !i && this.state.save?.status === "must-save" && t < tt && !this.closed && (await new Promise((o) => setTimeout(o, et)), this.connection === n && await this.saveNow(e, t + 1));
864
+ }
865
+ /**
866
+ * The save coordinator the editor's handlers run every save of a managed room through
867
+ * (managed-collab.md section 3); `null` before the room is joined or outside a managed room.
868
+ */
869
+ /** Whether this session co-edits a managed room (an open token's, KitCollab 1.4). */
870
+ isManaged() {
871
+ return this.managed;
872
+ }
873
+ /**
874
+ * Whether the file moved to a later co-editing generation since this session joined its room
875
+ * (managed-collab.md 1.3): the host changed the file outside the room, and the token now names
876
+ * the next `doc_key`. The room joined can save no more.
877
+ */
878
+ generationMoved() {
879
+ const e = this.client?.open?.docKey;
880
+ return this.managed && !!(this.joinedDocKey && e && e !== this.joinedDocKey);
881
+ }
882
+ /** Whether the token's file generation has a room already (someone opened the new version live). */
883
+ async nextGenerationHasRoom() {
884
+ return !!(await this.client.resolveRoom(!1)).docId;
885
+ }
886
+ /**
887
+ * After the person's copy became the file's content (SV5): waits for the host to start the
888
+ * generation that write makes (its token names a new `doc_key`), then prepares that generation's
889
+ * room and opens the kit on it, live.
890
+ */
891
+ moveToNextGeneration(e) {
892
+ return this.move ??= this.runMove(e).finally(() => {
893
+ this.move = null;
894
+ }), this.move;
895
+ }
896
+ /** The move to the next generation under way (SV5): saves wait for it, then go through the new room. */
897
+ moving() {
898
+ return this.move;
899
+ }
900
+ async runMove(e) {
901
+ const t = Date.now() + He;
902
+ for (; Date.now() < t && !this.closed && this.client.open?.docKey === e; ) await new Promise((n) => setTimeout(n, 100));
903
+ this.closed || (this.detach(), this.unclaim(), this.record = null, this.joinedDoc = null, this.joinedDocKey = null, this.setState({ docId: null, role: null, save: null }), await this.prepareManaged(), this.host.reopen?.());
904
+ }
905
+ /** The `doc_key` the token names now. */
906
+ currentDocKey() {
907
+ return this.client?.open?.docKey ?? null;
908
+ }
909
+ coordinator() {
910
+ const e = this.joinedDoc, t = this.client?.open?.docKey;
911
+ return !this.managed || !e || !t ? null : async (n) => {
912
+ const i = this.trigger ?? "user", o = Date.now() + Ye;
913
+ for (; ; ) {
914
+ let r;
915
+ try {
916
+ r = await Ce({
917
+ client: this.client,
918
+ docId: e,
919
+ trigger: i,
920
+ write: ({ seq: c, authors: a, receipt: d }) => n({ trigger: i, seq: c, authors: a, receipt: d, docKey: t, docId: e }),
921
+ checkpoint: ({ version: c }) => this.checkpoint(c)
922
+ });
923
+ } catch (c) {
924
+ if (!Qe(c) || Date.now() >= o) throw c;
925
+ await this.rejoined(o - Date.now());
926
+ continue;
927
+ }
928
+ if (r.status === "saved") return r.version;
929
+ if (r.status === "failed") throw r.cause;
930
+ const l = this.state.save?.version ?? null;
931
+ if (r.status === "clean") {
932
+ if (l) return l;
933
+ throw new Error("the room has nothing to save and no version yet");
934
+ }
935
+ if (Date.now() >= o) throw new Error("another editor is still saving this document");
936
+ await this.saveEnded(o - Date.now());
937
+ }
938
+ };
939
+ }
940
+ /** Waits until the client is online again, then a moment for its rooms to be joined again. */
941
+ async rejoined(e) {
942
+ const t = D(this.client, this.host.signal);
943
+ await Promise.race([t, new Promise((n) => setTimeout(n, e))]), await new Promise((n) => setTimeout(n, Math.min(Ze, Math.max(0, e))));
944
+ }
945
+ saveEnded(e) {
946
+ return new Promise((t) => {
947
+ const n = () => {
948
+ clearTimeout(i), this.saveWaiters.delete(n), t();
949
+ }, i = setTimeout(n, e);
950
+ this.saveWaiters.add(n);
951
+ });
952
+ }
953
+ /** CK1: after a saved version, the room's state becomes the file's checkpoint for it. */
954
+ async checkpoint(e) {
955
+ const t = this.connection;
956
+ if (!t) return;
957
+ const n = await t.replica.exportChanges(new ArrayBuffer(0));
958
+ await this.host.replicas.write(this.host.file.id, { snapshot: n.changes, blobs: n.blobs, fileStamp: e });
959
+ }
960
+ /** Makes the document's room from its whole history, its blobs uploaded first. */
961
+ async createRoom(e, t) {
962
+ const { kit: n, file: i, signal: o } = this.host;
963
+ await D(this.client, o);
964
+ const { saved: r } = this.managed ? { saved: !1 } : await e.save(), l = new Uint8Array(await e.replica.version()), c = await e.replica.exportChanges(new ArrayBuffer(0));
965
+ ie(new Uint8Array(c.changes), i.name), r || await this.keepReplica(t, c), await oe(this.client, t, G(new Uint8Array(c.blobs)));
966
+ let a;
967
+ try {
968
+ const { shareLink: d } = await this.client.createRoom(t, new Uint8Array(c.changes), i.name, n.id);
969
+ a = d ? { docId: t, fileId: i.id, kit: n.id, role: "owner", shareLink: d, lastSent: C(l) } : { docId: t, fileId: i.id, kit: n.id, role: "editor", lastSent: C(l) };
970
+ } catch (d) {
971
+ if (!(d instanceof T) || d.reason !== "conflict") throw d;
972
+ if (d.boundDocId && !j(d.boundDocId, t)) throw new Error(`${i.name} was opened for co-editing by another editor first; open it again`);
973
+ a = { docId: t, fileId: i.id, kit: n.id, role: "editor" };
974
+ } finally {
975
+ this.stopClaim();
976
+ }
977
+ return await this.records.write(a), a;
978
+ }
979
+ /** Stores `exported` as the file's replica unless the one stored is already this document's, for the file as it is. */
980
+ async keepReplica(e, t) {
981
+ const { file: n, storage: i, replicas: o } = this.host, r = await F(i, n.id);
982
+ if (!r) return;
983
+ const l = await o.read(n.id).catch(() => null), c = l ? z(R(l.snapshot)) : null;
984
+ l && l.fileStamp === r && c && j(c, e) || await o.write(n.id, { snapshot: t.changes, blobs: t.blobs, fileStamp: r });
985
+ }
986
+ /**
987
+ * The server `seq` to join from: the one an earlier session saw, if the replica still holds the
988
+ * version it had then; otherwise from the room's snapshot.
989
+ */
990
+ async resumeSeq(e, t) {
991
+ if (!e.seen) return null;
992
+ try {
993
+ const n = new Uint8Array(await t.version());
994
+ return this.versions.includes(n, ee(e.seen.version)) ? e.seen.seq : null;
995
+ } catch {
996
+ return null;
997
+ }
998
+ }
999
+ /** An agent started (a name) or stopped (`null`) working for the person here (`KitAgent 1.4` A20). */
1000
+ setAgent(e) {
1001
+ this.agent = e, this.sendPresence();
1002
+ }
1003
+ sendPresence() {
1004
+ this.joinedDoc && this.client.setPresence(this.joinedDoc, { kit: this.host.kit.id, user: this.user, ...this.agent ? { agent: { name: this.agent.name, origin: "agent" } } : {} });
1005
+ }
1006
+ setState(e) {
1007
+ const t = { ...this.state, ...e };
1008
+ t.status === this.state.status && t.docId === this.state.docId && t.role === this.state.role && t.save === this.state.save || (this.state = t, this.host.emit("collab", t));
1009
+ }
1010
+ }
1011
+ async function ut(s) {
1012
+ const e = new ot(s);
1013
+ try {
1014
+ return await e.prepare(), e;
1015
+ } catch (t) {
1016
+ throw e.close(), t;
1017
+ }
1018
+ }
1019
+ export {
1020
+ ot as CollabSession,
1021
+ ut as openCollabSession
1022
+ };