trellis 3.2.0 → 3.2.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 (258) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +61 -171
  3. package/dist/browser/index.d.ts +18 -0
  4. package/dist/browser/index.d.ts.map +1 -0
  5. package/dist/browser/index.js +95 -0
  6. package/dist/{chunk-3ETIIPPB.js → chunk-2W3MHTMG.js} +190 -27
  7. package/dist/{chunk-MBNBTJCR.js → chunk-6GEZ6DN5.js} +2 -2
  8. package/dist/chunk-7ZFRVCUE.js +211 -0
  9. package/dist/chunk-CAG4FULI.js +121 -0
  10. package/dist/{chunk-GD5QJXSS.js → chunk-FWRS4CSC.js} +2 -2
  11. package/dist/{chunk-36VSSTL7.js → chunk-GU374KWZ.js} +1 -1
  12. package/dist/{chunk-3GDRZTAW.js → chunk-H6JB3PZ3.js} +1 -1
  13. package/dist/{chunk-ZHVI7BQN.js → chunk-IZX2PLIB.js} +191 -28
  14. package/dist/chunk-J2TXUFCZ.js +289 -0
  15. package/dist/{chunk-BJ7EZ7FP.js → chunk-JHHEXEDM.js} +17 -0
  16. package/dist/{chunk-X762XWVC.js → chunk-KIJITUZB.js} +1 -1
  17. package/dist/{chunk-7WQGTFVJ.js → chunk-L5N5PR2S.js} +130 -75
  18. package/dist/{chunk-BXSTJVE3.js → chunk-N6MYZT4O.js} +2 -1
  19. package/dist/{chunk-KKDRMIV6.js → chunk-QB5ISE47.js} +1 -1
  20. package/dist/{chunk-HO4TURXW.js → chunk-S3XLFZ27.js} +28 -11
  21. package/dist/{chunk-BQBUVMRN.js → chunk-S6GBJ2ZB.js} +25 -14
  22. package/dist/{chunk-IUWVEEOX.js → chunk-SGMDTWJJ.js} +4 -0
  23. package/dist/{chunk-FZVCXDYW.js → chunk-UQISRW6T.js} +65 -12
  24. package/dist/{chunk-B3ZIFA2O.js → chunk-VBYUTRXX.js} +1 -1
  25. package/dist/cli/deploy-cli.d.ts +18 -0
  26. package/dist/cli/deploy-cli.d.ts.map +1 -0
  27. package/dist/cli/index.d.ts +1 -1
  28. package/dist/cli/index.d.ts.map +1 -1
  29. package/dist/cli/index.js +153 -100
  30. package/dist/client/index.browser.d.ts +29 -0
  31. package/dist/client/index.browser.d.ts.map +1 -0
  32. package/dist/client/index.browser.js +64 -0
  33. package/dist/client/index.js +10 -10
  34. package/dist/client/sdk.browser.d.ts +104 -0
  35. package/dist/client/sdk.browser.d.ts.map +1 -0
  36. package/dist/{sdk-LZ7W3EEY.js → client/sdk.browser.js} +2 -2
  37. package/dist/client/sdk.js +1 -1
  38. package/dist/core/index.js +6 -6
  39. package/dist/db/index.js +18 -18
  40. package/dist/db/inspector.js +6 -6
  41. package/dist/db/trellis.css +1 -1
  42. package/dist/decisions/index.js +2 -2
  43. package/dist/deploy-LQ7GUGJ5.js +9 -0
  44. package/dist/{deploy-66EC752W.js → deploy-YNVG5E4E.js} +1 -1
  45. package/dist/deploy-cli-24BCHAXY.js +67 -0
  46. package/dist/deploy-cli-C35HTITO.js +67 -0
  47. package/dist/embeddings/auto-embed.d.ts.map +1 -1
  48. package/dist/embeddings/index.js +1 -1
  49. package/dist/embeddings/store.d.ts.map +1 -1
  50. package/dist/engine.d.ts +27 -7
  51. package/dist/engine.d.ts.map +1 -1
  52. package/dist/index.js +6 -6
  53. package/dist/mcp/server.d.ts.map +1 -1
  54. package/dist/react/index.js +2 -2
  55. package/dist/react/schema-hooks.js +7 -7
  56. package/dist/{remote-manager-SG545WNY.js → remote-manager-ODE3T2KR.js} +5 -5
  57. package/dist/scaffold/seed.d.ts.map +1 -1
  58. package/dist/scaffold/write.d.ts +1 -1
  59. package/dist/scaffold/write.d.ts.map +1 -1
  60. package/dist/schema/index.js +4 -3
  61. package/dist/server/deploy-meta.d.ts +25 -0
  62. package/dist/server/deploy-meta.d.ts.map +1 -0
  63. package/dist/server/deploy.d.ts +7 -2
  64. package/dist/server/deploy.d.ts.map +1 -1
  65. package/dist/server/index.d.ts +5 -2
  66. package/dist/server/index.d.ts.map +1 -1
  67. package/dist/server/index.js +52 -18
  68. package/dist/server/realtime.d.ts +4 -1
  69. package/dist/server/realtime.d.ts.map +1 -1
  70. package/dist/server/server.d.ts +1 -0
  71. package/dist/server/server.d.ts.map +1 -1
  72. package/dist/server/sprites.d.ts +18 -1
  73. package/dist/server/sprites.d.ts.map +1 -1
  74. package/dist/server/tenancy.d.ts +4 -0
  75. package/dist/server/tenancy.d.ts.map +1 -1
  76. package/dist/server/usage-meter.d.ts +53 -0
  77. package/dist/server/usage-meter.d.ts.map +1 -0
  78. package/dist/{server-IGBIIJSF.js → server-MB3OPSPI.js} +6 -1
  79. package/dist/{server-BOH7M4TT.js → server-ZVWGLLRF.js} +7 -2
  80. package/dist/sprites-KQGTGM6W.js +27 -0
  81. package/dist/{tenancy-S676GLID.js → tenancy-NBLLGCNJ.js} +1 -1
  82. package/dist/{tenancy-OP34NFFS.js → tenancy-POMWQP6M.js} +5 -3
  83. package/dist/vcs/index.js +3 -3
  84. package/dist/vcs/types.d.ts +2 -0
  85. package/dist/vcs/types.d.ts.map +1 -1
  86. package/package.json +17 -6
  87. package/dist/better-sqlite-backend-PII64VE6.js +0 -159
  88. package/dist/better-sqlite-backend-VUBVQ7SN.js +0 -209
  89. package/dist/better-sqlite-backend-Y3AQN65E.js +0 -159
  90. package/dist/better-sqlite-backend-Y3M7DXOX.js +0 -159
  91. package/dist/boot-middleware-FJDGVUM4.js +0 -9
  92. package/dist/boot-middleware-MLJUTLUM.js +0 -9
  93. package/dist/boot-middleware-ZZPDZNYR.js +0 -9
  94. package/dist/chunk-276LKLZR.js +0 -359
  95. package/dist/chunk-2CX5UCRV.js +0 -111
  96. package/dist/chunk-2ESYSVXG.js +0 -48
  97. package/dist/chunk-2I5JU73Y.js +0 -340
  98. package/dist/chunk-2UNSRRNB.js +0 -171
  99. package/dist/chunk-335UEHQR.js +0 -907
  100. package/dist/chunk-4CF2L46N.js +0 -29
  101. package/dist/chunk-5CINODKT.js +0 -41
  102. package/dist/chunk-5ESGWJ5L.js +0 -45
  103. package/dist/chunk-5FGLQGMF.js +0 -1676
  104. package/dist/chunk-5IQZFITY.js +0 -357
  105. package/dist/chunk-5JWFAQDW.js +0 -150
  106. package/dist/chunk-62UHTVU3.js +0 -141
  107. package/dist/chunk-66UJQT2I.js +0 -35
  108. package/dist/chunk-6RNNVOAS.js +0 -355
  109. package/dist/chunk-6X23PZ6H.js +0 -969
  110. package/dist/chunk-7C7LL6MB.js +0 -315
  111. package/dist/chunk-7F4HM3JG.js +0 -394
  112. package/dist/chunk-7KJ7T4D3.js +0 -910
  113. package/dist/chunk-7QQQNUB5.js +0 -92
  114. package/dist/chunk-7QWJBS72.js +0 -946
  115. package/dist/chunk-7R36OZK3.js +0 -957
  116. package/dist/chunk-7UPKCOHE.js +0 -946
  117. package/dist/chunk-A3BONW34.js +0 -35
  118. package/dist/chunk-AHMDVHBL.js +0 -141
  119. package/dist/chunk-AW6A4OZY.js +0 -171
  120. package/dist/chunk-BJ5EKCJ5.js +0 -458
  121. package/dist/chunk-BRGYDO7D.js +0 -223
  122. package/dist/chunk-C5KPSEDN.js +0 -359
  123. package/dist/chunk-CCTNYTUC.js +0 -940
  124. package/dist/chunk-CYQ2OVD2.js +0 -35
  125. package/dist/chunk-DDAK7YOE.js +0 -299
  126. package/dist/chunk-DRILKBY6.js +0 -965
  127. package/dist/chunk-DXE24HNN.js +0 -45
  128. package/dist/chunk-E7ICUNW7.js +0 -945
  129. package/dist/chunk-EAL2PUOE.js +0 -10022
  130. package/dist/chunk-ELT7MLZB.js +0 -109
  131. package/dist/chunk-EWEIRF6G.js +0 -171
  132. package/dist/chunk-F5VDGQJC.js +0 -120
  133. package/dist/chunk-FCPL3IEQ.js +0 -98
  134. package/dist/chunk-FDPKYSV7.js +0 -96
  135. package/dist/chunk-FES3TC24.js +0 -171
  136. package/dist/chunk-FOWKR5TW.js +0 -129
  137. package/dist/chunk-G3XIHPSQ.js +0 -361
  138. package/dist/chunk-GKJLYLVU.js +0 -359
  139. package/dist/chunk-GNXHXNVQ.js +0 -113
  140. package/dist/chunk-GSR6ILTM.js +0 -277
  141. package/dist/chunk-GWRIMRSX.js +0 -45
  142. package/dist/chunk-H72UW2HJ.js +0 -45
  143. package/dist/chunk-HGI74PXB.js +0 -7417
  144. package/dist/chunk-HGRA37LO.js +0 -145
  145. package/dist/chunk-HXSRQO3L.js +0 -145
  146. package/dist/chunk-IG2X2BVO.js +0 -373
  147. package/dist/chunk-IIJVDD54.js +0 -373
  148. package/dist/chunk-IX4BBOIT.js +0 -394
  149. package/dist/chunk-IXU4RMQM.js +0 -349
  150. package/dist/chunk-J6OUIION.js +0 -857
  151. package/dist/chunk-K46RNFDE.js +0 -171
  152. package/dist/chunk-KAGU2XMY.js +0 -359
  153. package/dist/chunk-KCVYJNVX.js +0 -394
  154. package/dist/chunk-KYLIQ3YI.js +0 -399
  155. package/dist/chunk-KZYJJIRN.js +0 -946
  156. package/dist/chunk-LFOX744K.js +0 -96
  157. package/dist/chunk-LHOVJEWR.js +0 -7403
  158. package/dist/chunk-LOPXTPF3.js +0 -120
  159. package/dist/chunk-LZR3VIFU.js +0 -907
  160. package/dist/chunk-MCKGQKYU.js +0 -15
  161. package/dist/chunk-MU6EOS6F.js +0 -0
  162. package/dist/chunk-MWRQ2TXT.js +0 -357
  163. package/dist/chunk-NO73OK2I.js +0 -102
  164. package/dist/chunk-NPE2YJHK.js +0 -394
  165. package/dist/chunk-NSDXU6QX.js +0 -2213
  166. package/dist/chunk-NXIRDSZ6.js +0 -145
  167. package/dist/chunk-NZWFNHCS.js +0 -407
  168. package/dist/chunk-OB4CMMX6.js +0 -260
  169. package/dist/chunk-OBKU74FU.js +0 -7411
  170. package/dist/chunk-OQNDWRDE.js +0 -145
  171. package/dist/chunk-OVWAJMB6.js +0 -394
  172. package/dist/chunk-PDHLBTTD.js +0 -45
  173. package/dist/chunk-PEQNRKLG.js +0 -210
  174. package/dist/chunk-QERIS7QY.js +0 -7403
  175. package/dist/chunk-QHA2DM3C.js +0 -373
  176. package/dist/chunk-QLM4HSYC.js +0 -45
  177. package/dist/chunk-S2OT3TQJ.js +0 -283
  178. package/dist/chunk-S5PHSN5K.js +0 -907
  179. package/dist/chunk-SIAA4J6H.js +0 -21
  180. package/dist/chunk-SQBNLUIA.js +0 -171
  181. package/dist/chunk-STLN6A6B.js +0 -355
  182. package/dist/chunk-U7HV7GU2.js +0 -17
  183. package/dist/chunk-UGZHOGRA.js +0 -39
  184. package/dist/chunk-UICF66FS.js +0 -359
  185. package/dist/chunk-UK3EQREE.js +0 -1078
  186. package/dist/chunk-UPKPURVY.js +0 -394
  187. package/dist/chunk-URC74VCN.js +0 -959
  188. package/dist/chunk-V3G7Q3QQ.js +0 -102
  189. package/dist/chunk-VUJ6SA55.js +0 -303
  190. package/dist/chunk-VUJQLIML.js +0 -141
  191. package/dist/chunk-VWKLKLYB.js +0 -267
  192. package/dist/chunk-VYC3RZMK.js +0 -277
  193. package/dist/chunk-WMERMSWI.js +0 -154
  194. package/dist/chunk-WMR777PO.js +0 -2213
  195. package/dist/chunk-X46IECAC.js +0 -517
  196. package/dist/chunk-XEN3OEYY.js +0 -2234
  197. package/dist/chunk-XZQ66K7A.js +0 -124
  198. package/dist/chunk-YY3GF7DH.js +0 -7411
  199. package/dist/chunk-ZE5R3H4C.js +0 -907
  200. package/dist/chunk-ZMN5LUB7.js +0 -7411
  201. package/dist/chunk-ZUV4MD5U.js +0 -94
  202. package/dist/config-KMY6RRK3.js +0 -19
  203. package/dist/config-VDMK2DUJ.js +0 -19
  204. package/dist/deploy-SO7AFK6L.js +0 -9
  205. package/dist/engine-7GXBM4IT.js +0 -7
  206. package/dist/engine-NSR6BIF7.js +0 -7
  207. package/dist/factory-2P64OC7M.js +0 -34
  208. package/dist/factory-YP4ZZK5K.js +0 -34
  209. package/dist/import-AJLYHFIA.js +0 -10
  210. package/dist/launch-explorer-AI6L2AWJ.js +0 -91
  211. package/dist/query-GJL3CVGN.js +0 -31
  212. package/dist/query-MBJSK3EB.js +0 -31
  213. package/dist/query-TJHEVSKL.js +0 -31
  214. package/dist/query-WUIKOHPE.js +0 -524
  215. package/dist/remote-manager-BLJZ6KF6.js +0 -224
  216. package/dist/remote-manager-BPYE46SI.js +0 -223
  217. package/dist/remote-manager-FMESEAFA.js +0 -224
  218. package/dist/remote-manager-K2WZ5RHY.js +0 -223
  219. package/dist/remote-manager-SG5PQKCH.js +0 -224
  220. package/dist/remote-manager-WGP6MIQZ.js +0 -224
  221. package/dist/sdk-3KBB3E6V.js +0 -16
  222. package/dist/sdk-4ZQO6UTU.js +0 -16
  223. package/dist/sdk-6JA6GV3G.js +0 -16
  224. package/dist/sdk-6VTP5UTZ.js +0 -16
  225. package/dist/sdk-7VS6TYCD.js +0 -16
  226. package/dist/sdk-HQ3FTLRT.js +0 -16
  227. package/dist/sdk-HZ7NU3XE.js +0 -15
  228. package/dist/sdk-KBQE2OXT.js +0 -16
  229. package/dist/sdk-MSCDZ7JU.js +0 -15
  230. package/dist/sdk-WNZOGO3S.js +0 -15
  231. package/dist/sdk-YLV33ZCW.js +0 -9
  232. package/dist/sdk-ZSUD2LLJ.js +0 -16
  233. package/dist/server-AFXFFBWA.js +0 -11
  234. package/dist/server-AGHC4VUL.js +0 -11
  235. package/dist/server-DBUY2KY5.js +0 -11
  236. package/dist/server-GWBQJPRG.js +0 -11
  237. package/dist/server-JZZFULVU.js +0 -11
  238. package/dist/server-L5XAF4M5.js +0 -11
  239. package/dist/server-NYFUHANA.js +0 -12
  240. package/dist/server-OABUB2LO.js +0 -12
  241. package/dist/server-P2CKZWWV.js +0 -12
  242. package/dist/sprites-XVSMQLSI.js +0 -15
  243. package/dist/sql-wasm-FORCZFHZ.js +0 -2148
  244. package/dist/sql-wasm-JZH76RLO.js +0 -2148
  245. package/dist/sqljs-backend-CJQOIQYE.js +0 -266
  246. package/dist/sqljs-backend-KWXBUDUO.js +0 -266
  247. package/dist/state-demo.bundle.js +0 -1033
  248. package/dist/tenancy-CBWYEVUB.js +0 -11
  249. package/dist/tenancy-FO6WVYFN.js +0 -13
  250. package/dist/tenancy-FWDBESMX.js +0 -14
  251. package/dist/tenancy-HGPIS5QA.js +0 -13
  252. package/dist/tenancy-HXFALA37.js +0 -14
  253. package/dist/tenancy-V7ARWNNV.js +0 -14
  254. package/dist/tenancy-ZDN4GXK5.js +0 -13
  255. package/dist/tenancy-ZT5VMY7B.js +0 -14
  256. package/dist/vm-config-YZRJ3KUB.js +0 -21
  257. /package/dist/{chunk-2BRTCEHB.js → chunk-PZ4XYZ4J.js} +0 -0
  258. /package/dist/{chunk-EO3J7GRP.js → chunk-WXSWA3MV.js} +0 -0
@@ -1,1033 +0,0 @@
1
- // src/vcs/ops.ts
2
- async function hashVcsOp(op) {
3
- const content = JSON.stringify({
4
- kind: op.kind,
5
- timestamp: op.timestamp,
6
- agentId: op.agentId,
7
- previousHash: op.previousHash,
8
- vcs: op.vcs
9
- });
10
- const msgUint8 = new TextEncoder().encode(content);
11
- const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8);
12
- const hashArray = Array.from(new Uint8Array(hashBuffer));
13
- const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
14
- return `trellis:op:${hashHex}`;
15
- }
16
- async function verifyVcsOpHash(op) {
17
- return op.hash === await hashVcsOp(op);
18
- }
19
- async function createVcsOp(kind, params) {
20
- const opBase = {
21
- kind,
22
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
23
- agentId: params.agentId,
24
- previousHash: params.previousHash,
25
- vcs: params.vcs
26
- };
27
- return {
28
- ...opBase,
29
- hash: await hashVcsOp(opBase)
30
- };
31
- }
32
- function isVcsOpKind(kind) {
33
- return kind.startsWith("vcs:");
34
- }
35
-
36
- // demo/state-demo/issue-projector.ts
37
- function projectIssues(ops) {
38
- const byId = /* @__PURE__ */ new Map();
39
- for (const op of ops) {
40
- const id = op.vcs?.issueId;
41
- if (!id) continue;
42
- if (op.kind === "vcs:issueCreate") {
43
- byId.set(id, {
44
- id,
45
- title: op.vcs?.issueTitle ?? id,
46
- status: op.vcs?.issueStatus === "closed" ? "closed" : "open",
47
- priority: op.vcs?.issuePriority,
48
- agentId: op.agentId
49
- });
50
- continue;
51
- }
52
- const issue = byId.get(id);
53
- if (!issue) continue;
54
- if (op.kind === "vcs:issueClose") {
55
- issue.status = "closed";
56
- } else if (op.kind === "vcs:issueReopen") {
57
- issue.status = "open";
58
- } else if (op.kind === "vcs:issueUpdate" && op.vcs?.issueStatus === "closed") {
59
- issue.status = "closed";
60
- } else if (op.kind === "vcs:issueUpdate" && op.vcs?.issueTitle) {
61
- issue.title = op.vcs.issueTitle;
62
- }
63
- }
64
- return [...byId.values()];
65
- }
66
-
67
- // demo/state-demo/demo-session.ts
68
- var DemoSession = class {
69
- agentId;
70
- ops = [];
71
- issueSeq = 0;
72
- onChange;
73
- onAfterWrite;
74
- constructor(opts = {}) {
75
- this.agentId = opts.agentId ?? "agent:demo";
76
- this.onChange = opts.onChange;
77
- this.onAfterWrite = opts.onAfterWrite;
78
- }
79
- getAgentId() {
80
- return this.agentId;
81
- }
82
- getOps() {
83
- return [...this.ops];
84
- }
85
- getIssues() {
86
- const owned = /* @__PURE__ */ new Set();
87
- for (const op of this.ops) {
88
- if (op.kind === "vcs:issueCreate" && op.agentId === this.agentId && op.vcs?.issueId) {
89
- owned.add(op.vcs.issueId);
90
- }
91
- }
92
- return projectIssues(this.ops).filter((i) => owned.has(i.id));
93
- }
94
- /** Merge remote ops (dedupe by hash, sort by time). */
95
- integrate(remote) {
96
- const seen = new Set(this.ops.map((o) => o.hash));
97
- let changed = false;
98
- for (const op of remote) {
99
- if (seen.has(op.hash)) continue;
100
- this.ops.push(op);
101
- seen.add(op.hash);
102
- changed = true;
103
- }
104
- if (changed) {
105
- this.ops.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
106
- this.emit();
107
- }
108
- }
109
- nextIssueId() {
110
- this.issueSeq += 1;
111
- const slug = this.agentId.replace(/^agent:/, "") || "peer";
112
- return `TRL-${slug}-${this.issueSeq}`;
113
- }
114
- async addIssue(title, priority = "medium") {
115
- const issueId = this.nextIssueId();
116
- const op = await createVcsOp("vcs:issueCreate", {
117
- agentId: this.agentId,
118
- previousHash: this.lastHash(),
119
- vcs: {
120
- issueId,
121
- issueTitle: title.trim() || "Untitled",
122
- issueStatus: "queue",
123
- issuePriority: priority
124
- }
125
- });
126
- this.ops.push(op);
127
- const advance = await createVcsOp("vcs:branchAdvance", {
128
- agentId: this.agentId,
129
- previousHash: op.hash,
130
- vcs: { branchName: "main", headHash: op.hash }
131
- });
132
- this.ops.push(advance);
133
- this.emit();
134
- return op;
135
- }
136
- async setIssueClosed(id, closed) {
137
- const issue = this.getIssues().find((i) => i.id === id);
138
- if (!issue) return null;
139
- if (closed && issue.status === "closed") return null;
140
- if (!closed && issue.status === "open") return null;
141
- const kind = closed ? "vcs:issueClose" : "vcs:issueReopen";
142
- const op = await createVcsOp(kind, {
143
- agentId: this.agentId,
144
- previousHash: this.lastHash(),
145
- vcs: {
146
- issueId: id,
147
- issueStatus: closed ? "closed" : "queue"
148
- }
149
- });
150
- this.ops.push(op);
151
- this.emit();
152
- return op;
153
- }
154
- lastHash() {
155
- return this.ops[this.ops.length - 1]?.hash;
156
- }
157
- emit() {
158
- this.onChange?.({ ops: this.getOps(), issues: this.getIssues() });
159
- void this.onAfterWrite?.();
160
- }
161
- };
162
- function mergeOps(...logs) {
163
- const seen = /* @__PURE__ */ new Set();
164
- const merged = [];
165
- for (const log of logs) {
166
- for (const op of log) {
167
- if (seen.has(op.hash)) continue;
168
- seen.add(op.hash);
169
- merged.push(op);
170
- }
171
- }
172
- return merged.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
173
- }
174
-
175
- // src/sync/types.ts
176
- var PROTOCOL_VERSION = 1;
177
- var MIN_SUPPORTED_VERSION = 1;
178
- var MAX_SUPPORTED_VERSION = 1;
179
-
180
- // src/sync/room-core.ts
181
- var DEFAULT_SNAPSHOT_MAX_OPS = 500;
182
- var SyncRoomCore = class {
183
- roomPeer;
184
- peers = /* @__PURE__ */ new Map();
185
- ops = [];
186
- constructor(roomId = "room", roomName = roomId) {
187
- this.roomPeer = {
188
- id: roomId,
189
- name: roomName
190
- };
191
- }
192
- connectPeer(peerId, peerName = peerId) {
193
- this.peers.set(peerId, {
194
- id: peerId,
195
- name: peerName,
196
- lastSeen: (/* @__PURE__ */ new Date()).toISOString()
197
- });
198
- }
199
- disconnectPeer(peerId) {
200
- this.peers.delete(peerId);
201
- }
202
- getRoomPeer() {
203
- return { ...this.roomPeer };
204
- }
205
- peersFor(peerId) {
206
- return [
207
- this.getRoomPeer(),
208
- ...[...this.peers.values()].filter((peer) => peer.id !== peerId).map((peer) => ({ ...peer }))
209
- ];
210
- }
211
- getOps() {
212
- return [...this.ops];
213
- }
214
- getOpCount() {
215
- return this.ops.length;
216
- }
217
- /** Build a tail snapshot for late-joiner catch-up. */
218
- buildSnapshot(maxOps = DEFAULT_SNAPSHOT_MAX_OPS) {
219
- const opCount = this.ops.length;
220
- const headHash = this.ops.at(-1)?.hash;
221
- if (opCount <= maxOps) {
222
- return {
223
- headHash,
224
- opCount,
225
- truncated: false,
226
- ops: [...this.ops]
227
- };
228
- }
229
- return {
230
- headHash,
231
- opCount,
232
- truncated: true,
233
- ops: this.ops.slice(-maxOps)
234
- };
235
- }
236
- /** Deliver a snapshot message to a connected peer. */
237
- snapshotDeliveries(peerId, maxOps = DEFAULT_SNAPSHOT_MAX_OPS) {
238
- const snap = this.buildSnapshot(maxOps);
239
- return [
240
- {
241
- peerId,
242
- message: {
243
- version: PROTOCOL_VERSION,
244
- type: "snapshot",
245
- peerId: this.roomPeer.id,
246
- headHash: snap.headHash,
247
- opCount: snap.opCount,
248
- truncated: snap.truncated,
249
- ops: snap.ops
250
- }
251
- }
252
- ];
253
- }
254
- async receive(fromPeerId, message) {
255
- const peer = this.peers.get(fromPeerId);
256
- if (peer) {
257
- peer.lastSeen = (/* @__PURE__ */ new Date()).toISOString();
258
- }
259
- if (typeof message.version !== "number" || message.version < MIN_SUPPORTED_VERSION || message.version > MAX_SUPPORTED_VERSION) {
260
- return [
261
- {
262
- peerId: fromPeerId,
263
- message: {
264
- version: PROTOCOL_VERSION,
265
- type: "nack",
266
- peerId: this.roomPeer.id,
267
- refs: [],
268
- reason: "protocol-version",
269
- details: `Unsupported protocol version ${message.version}; supported range is ${MIN_SUPPORTED_VERSION}-${MAX_SUPPORTED_VERSION}.`
270
- }
271
- }
272
- ];
273
- }
274
- switch (message.type) {
275
- case "have":
276
- return this.handleHave(fromPeerId, message);
277
- case "want":
278
- return this.handleWant(fromPeerId, message);
279
- case "sync-snapshot":
280
- return this.snapshotDeliveries(
281
- fromPeerId,
282
- message.maxOps ?? DEFAULT_SNAPSHOT_MAX_OPS
283
- );
284
- case "ops":
285
- return this.handleOps(fromPeerId, message.ops);
286
- case "ack":
287
- case "nack":
288
- case "snapshot":
289
- return [];
290
- }
291
- }
292
- async handleHave(peerId, message) {
293
- const deliveries = this.roomOpsDeliveries(peerId, message.heads.main);
294
- const roomHashes = new Set(this.ops.map((op) => op.hash));
295
- const peerHead = message.heads.main;
296
- if (message.opCount > this.ops.length || peerHead && !roomHashes.has(peerHead)) {
297
- deliveries.push({
298
- peerId,
299
- message: {
300
- version: PROTOCOL_VERSION,
301
- type: "want",
302
- peerId: this.roomPeer.id,
303
- wantHashes: []
304
- }
305
- });
306
- } else if (!deliveries.some(
307
- (d) => d.message.type === "want" || d.message.type === "ops"
308
- )) {
309
- deliveries.push({
310
- peerId,
311
- message: {
312
- version: PROTOCOL_VERSION,
313
- type: "want",
314
- peerId: this.roomPeer.id,
315
- wantHashes: []
316
- }
317
- });
318
- }
319
- return deliveries;
320
- }
321
- async handleWant(peerId, message) {
322
- if (message.wantHashes.length > 0) {
323
- const wanted = new Set(message.wantHashes);
324
- return this.opsDelivery(
325
- peerId,
326
- this.ops.filter((op) => wanted.has(op.hash))
327
- );
328
- }
329
- if (message.maxOps !== void 0 && message.maxOps > 0 && !message.afterHash) {
330
- return this.snapshotDeliveries(peerId, message.maxOps);
331
- }
332
- return this.roomOpsDeliveries(peerId, message.afterHash);
333
- }
334
- async handleOps(peerId, ops) {
335
- const result = await this.appendOps(ops);
336
- const accepted = ops.filter(
337
- (op) => this.ops.some((roomOp) => roomOp.hash === op.hash)
338
- );
339
- const deliveries = [];
340
- if (accepted.length > 0) {
341
- deliveries.push({
342
- peerId,
343
- message: {
344
- version: PROTOCOL_VERSION,
345
- type: "ack",
346
- peerId: this.roomPeer.id,
347
- integrated: accepted.map((op) => op.hash)
348
- }
349
- });
350
- }
351
- if (result.acceptedOps.length > 0) {
352
- deliveries.push(...this.broadcastOps(peerId, result.acceptedOps));
353
- }
354
- return deliveries;
355
- }
356
- async appendOps(incomingOps) {
357
- const known = new Set(this.ops.map((op) => op.hash));
358
- const pendingByHash = /* @__PURE__ */ new Map();
359
- const rejected = [];
360
- const acceptedOps = [];
361
- let skipped = 0;
362
- let applied = 0;
363
- for (const op of incomingOps) {
364
- if (known.has(op.hash) || pendingByHash.has(op.hash)) {
365
- skipped++;
366
- continue;
367
- }
368
- if (!isVcsOpKind(op.kind)) {
369
- rejected.push({
370
- op,
371
- reason: "invalid-kind",
372
- message: `Rejected non-VCS op kind '${op.kind}'.`
373
- });
374
- continue;
375
- }
376
- if (!await verifyVcsOpHash(op)) {
377
- rejected.push({
378
- op,
379
- reason: "hash-mismatch",
380
- message: `Rejected op with mismatched hash '${op.hash}'.`
381
- });
382
- continue;
383
- }
384
- pendingByHash.set(op.hash, op);
385
- }
386
- let pending = [...pendingByHash.values()];
387
- while (pending.length > 0) {
388
- const nextPending = [];
389
- let progressed = false;
390
- for (const op of pending) {
391
- if (op.previousHash && !known.has(op.previousHash)) {
392
- nextPending.push(op);
393
- continue;
394
- }
395
- this.ops.push(op);
396
- known.add(op.hash);
397
- acceptedOps.push(op);
398
- applied++;
399
- progressed = true;
400
- }
401
- if (!progressed) {
402
- for (const op of nextPending) {
403
- rejected.push({
404
- op,
405
- reason: "missing-dependency",
406
- message: `Missing previousHash '${op.previousHash}' for op '${op.hash}'.`
407
- });
408
- }
409
- break;
410
- }
411
- pending = nextPending;
412
- }
413
- return { applied, skipped, rejected, acceptedOps };
414
- }
415
- roomOpsDeliveries(peerId, afterHash) {
416
- let ops = this.ops;
417
- if (afterHash) {
418
- const index = this.ops.findIndex((op) => op.hash === afterHash);
419
- ops = index >= 0 ? this.ops.slice(index + 1) : this.ops;
420
- }
421
- return this.opsDelivery(peerId, ops);
422
- }
423
- opsDelivery(peerId, ops) {
424
- if (ops.length === 0) return [];
425
- return [
426
- {
427
- peerId,
428
- message: {
429
- version: PROTOCOL_VERSION,
430
- type: "ops",
431
- peerId: this.roomPeer.id,
432
- ops
433
- }
434
- }
435
- ];
436
- }
437
- broadcastOps(fromPeerId, ops) {
438
- const deliveries = [];
439
- for (const peerId of this.peers.keys()) {
440
- if (peerId === fromPeerId) continue;
441
- deliveries.push(...this.opsDelivery(peerId, ops));
442
- }
443
- return deliveries;
444
- }
445
- };
446
-
447
- // src/sync/memory-room.ts
448
- var MemorySyncRoom = class {
449
- core;
450
- transports = /* @__PURE__ */ new Map();
451
- constructor(roomId = "room", roomName = roomId) {
452
- this.core = new SyncRoomCore(roomId, roomName);
453
- }
454
- connectPeer(peerId, peerName = peerId) {
455
- this.core.connectPeer(peerId, peerName);
456
- const transport = new MemoryRoomTransport(this, peerId, peerName);
457
- this.transports.set(peerId, transport);
458
- return transport;
459
- }
460
- disconnectPeer(peerId) {
461
- this.core.disconnectPeer(peerId);
462
- this.transports.delete(peerId);
463
- }
464
- getRoomPeer() {
465
- return this.core.getRoomPeer();
466
- }
467
- peersFor(peerId) {
468
- return this.core.peersFor(peerId);
469
- }
470
- getOps() {
471
- return this.core.getOps();
472
- }
473
- getOpCount() {
474
- return this.core.getOpCount();
475
- }
476
- async receive(fromPeerId, message) {
477
- const deliveries = await this.core.receive(fromPeerId, message);
478
- for (const delivery of deliveries) {
479
- await this.deliver(delivery.peerId, delivery.message);
480
- }
481
- }
482
- async deliver(peerId, message) {
483
- const transport = this.transports.get(peerId);
484
- if (!transport) {
485
- throw new Error(`Peer not connected to room: ${peerId}`);
486
- }
487
- await transport.deliver(message);
488
- }
489
- };
490
- var MemoryRoomTransport = class {
491
- room;
492
- peerId;
493
- peerName;
494
- handlers = [];
495
- constructor(room, peerId, peerName = peerId) {
496
- this.room = room;
497
- this.peerId = peerId;
498
- this.peerName = peerName;
499
- }
500
- async send(peerId, message) {
501
- if (peerId !== this.room.getRoomPeer().id) {
502
- throw new Error(`Peer not connected through room: ${peerId}`);
503
- }
504
- await this.room.receive(this.peerId, message);
505
- }
506
- onMessage(handler) {
507
- this.handlers.push(handler);
508
- }
509
- peers() {
510
- return this.room.peersFor(this.peerId);
511
- }
512
- getPeerId() {
513
- return this.peerId;
514
- }
515
- getPeerName() {
516
- return this.peerName;
517
- }
518
- async deliver(message) {
519
- for (const handler of this.handlers) {
520
- await handler(message);
521
- }
522
- }
523
- };
524
-
525
- // src/sync/reconciler.ts
526
- function findForkPoint(opsA, opsB) {
527
- const hashesB = new Set(opsB.map((o) => o.hash));
528
- let forkPoint = null;
529
- for (const op of opsA) {
530
- if (hashesB.has(op.hash)) {
531
- forkPoint = op.hash;
532
- }
533
- }
534
- return forkPoint;
535
- }
536
- function reconcile(opsA, opsB) {
537
- const forkPoint = findForkPoint(opsA, opsB);
538
- const hashesA = new Set(opsA.map((o) => o.hash));
539
- const hashesB = new Set(opsB.map((o) => o.hash));
540
- const shared = [];
541
- const uniqueToA = [];
542
- const uniqueToB = [];
543
- for (const op of opsA) {
544
- if (hashesB.has(op.hash)) {
545
- shared.push(op);
546
- } else {
547
- uniqueToA.push(op);
548
- }
549
- }
550
- for (const op of opsB) {
551
- if (!hashesA.has(op.hash)) {
552
- uniqueToB.push(op);
553
- }
554
- }
555
- if (uniqueToA.length === 0) {
556
- return {
557
- merged: [...shared, ...uniqueToB],
558
- uniqueToA: [],
559
- uniqueToB,
560
- forkPoint,
561
- clean: true,
562
- conflicts: []
563
- };
564
- }
565
- if (uniqueToB.length === 0) {
566
- return {
567
- merged: [...shared, ...uniqueToA],
568
- uniqueToA,
569
- uniqueToB: [],
570
- forkPoint,
571
- clean: true,
572
- conflicts: []
573
- };
574
- }
575
- const conflicts = detectConflicts(uniqueToA, uniqueToB);
576
- const interleaved = interleaveByTimestamp(uniqueToA, uniqueToB);
577
- return {
578
- merged: [...shared, ...interleaved],
579
- uniqueToA,
580
- uniqueToB,
581
- forkPoint,
582
- clean: conflicts.length === 0,
583
- conflicts
584
- };
585
- }
586
- var FILE_MUTATION_KINDS = /* @__PURE__ */ new Set([
587
- "vcs:fileAdd",
588
- "vcs:fileModify",
589
- "vcs:fileDelete",
590
- "vcs:fileRename"
591
- ]);
592
- function detectConflicts(uniqueA, uniqueB) {
593
- const conflicts = [];
594
- const aMutations = /* @__PURE__ */ new Map();
595
- for (const op of uniqueA) {
596
- if (!FILE_MUTATION_KINDS.has(op.kind) || !op.vcs?.filePath) continue;
597
- const path = op.vcs.filePath;
598
- if (!aMutations.has(path)) aMutations.set(path, []);
599
- aMutations.get(path).push(op);
600
- }
601
- for (const op of uniqueB) {
602
- if (!FILE_MUTATION_KINDS.has(op.kind) || !op.vcs?.filePath) continue;
603
- const path = op.vcs.filePath;
604
- const aOps = aMutations.get(path);
605
- if (!aOps) continue;
606
- for (const aOp of aOps) {
607
- if (aOp.kind === "vcs:fileModify" && op.kind === "vcs:fileModify") {
608
- conflicts.push({
609
- opA: aOp,
610
- opB: op,
611
- filePath: path,
612
- reason: `Both sides modified ${path}`
613
- });
614
- } else if (aOp.kind === "vcs:fileDelete" && op.kind === "vcs:fileModify" || aOp.kind === "vcs:fileModify" && op.kind === "vcs:fileDelete") {
615
- conflicts.push({
616
- opA: aOp,
617
- opB: op,
618
- filePath: path,
619
- reason: `Delete/modify conflict on ${path}`
620
- });
621
- } else if (aOp.kind === "vcs:fileAdd" && op.kind === "vcs:fileAdd") {
622
- if (aOp.vcs?.contentHash !== op.vcs?.contentHash) {
623
- conflicts.push({
624
- opA: aOp,
625
- opB: op,
626
- filePath: path,
627
- reason: `Both sides added ${path} with different content`
628
- });
629
- }
630
- }
631
- }
632
- }
633
- return conflicts;
634
- }
635
- function interleaveByTimestamp(a, b) {
636
- const result = [];
637
- let ai = 0;
638
- let bi = 0;
639
- while (ai < a.length && bi < b.length) {
640
- const tA = new Date(a[ai].timestamp).getTime();
641
- const tB = new Date(b[bi].timestamp).getTime();
642
- if (tA <= tB) {
643
- result.push(a[ai++]);
644
- } else {
645
- result.push(b[bi++]);
646
- }
647
- }
648
- while (ai < a.length) result.push(a[ai++]);
649
- while (bi < b.length) result.push(b[bi++]);
650
- return result;
651
- }
652
-
653
- // src/sync/sync-engine.ts
654
- var SyncEngine = class {
655
- localPeerId;
656
- state;
657
- transport;
658
- getLocalOps;
659
- onOpsReceived;
660
- onNackReceived;
661
- branchPolicy;
662
- constructor(opts) {
663
- this.localPeerId = opts.localPeerId;
664
- this.transport = opts.transport;
665
- this.getLocalOps = opts.getLocalOps;
666
- this.onOpsReceived = opts.onOpsReceived;
667
- this.onNackReceived = opts.onNackReceived;
668
- this.branchPolicy = opts.branchPolicy ?? { linear: true };
669
- this.state = {
670
- localPeerId: opts.localPeerId,
671
- peerHeads: /* @__PURE__ */ new Map(),
672
- pendingAcks: /* @__PURE__ */ new Set(),
673
- lastSync: /* @__PURE__ */ new Map()
674
- };
675
- this.transport.onMessage((msg) => this.handleMessage(msg));
676
- }
677
- // -------------------------------------------------------------------------
678
- // Public API
679
- // -------------------------------------------------------------------------
680
- /**
681
- * Initiate a sync with a specific peer.
682
- * Sends a 'have' message advertising our heads.
683
- */
684
- async pushTo(peerId) {
685
- const ops = this.getLocalOps();
686
- const heads = {};
687
- if (ops.length > 0) {
688
- heads["main"] = ops[ops.length - 1].hash;
689
- }
690
- await this.transport.send(peerId, {
691
- version: PROTOCOL_VERSION,
692
- type: "have",
693
- peerId: this.localPeerId,
694
- heads,
695
- opCount: ops.length
696
- });
697
- }
698
- /**
699
- * Request ops from a peer.
700
- */
701
- async pullFrom(peerId) {
702
- const ops = this.getLocalOps();
703
- const lastHash = ops.length > 0 ? ops[ops.length - 1].hash : void 0;
704
- await this.transport.send(peerId, {
705
- version: PROTOCOL_VERSION,
706
- type: "want",
707
- peerId: this.localPeerId,
708
- wantHashes: [],
709
- afterHash: lastHash
710
- });
711
- }
712
- /**
713
- * Request the peer's complete op set and rely on hash dedupe during ingest.
714
- */
715
- async pullAllFrom(peerId) {
716
- await this.transport.send(peerId, {
717
- version: PROTOCOL_VERSION,
718
- type: "want",
719
- peerId: this.localPeerId,
720
- wantHashes: []
721
- });
722
- }
723
- /**
724
- * Request a truncated tail snapshot from a room peer (late-joiner catch-up).
725
- * The room replies with a `snapshot` message handled like `ops`.
726
- */
727
- async requestSnapshot(peerId, maxOps = DEFAULT_SNAPSHOT_MAX_OPS) {
728
- await this.transport.send(peerId, {
729
- version: PROTOCOL_VERSION,
730
- type: "sync-snapshot",
731
- peerId: this.localPeerId,
732
- maxOps
733
- });
734
- }
735
- /**
736
- * Send all our ops to a peer (full push).
737
- */
738
- async sendOps(peerId, ops) {
739
- const opsToSend = ops ?? this.getLocalOps();
740
- await this.sendOpsMessage(peerId, opsToSend);
741
- }
742
- /**
743
- * Internal: send an `ops` message and track outbound hashes in
744
- * `pendingAcks` until the receiver acks or nacks them. All three sites
745
- * that emit `ops` (sendOps, handleHave, handleWant) route through here so
746
- * pendingAcks reflects every outbound op uniformly.
747
- */
748
- async sendOpsMessage(peerId, ops) {
749
- if (ops.length === 0) return;
750
- for (const op of ops) {
751
- this.state.pendingAcks.add(op.hash);
752
- }
753
- await this.transport.send(peerId, {
754
- version: PROTOCOL_VERSION,
755
- type: "ops",
756
- peerId: this.localPeerId,
757
- ops
758
- });
759
- }
760
- /**
761
- * Reconcile our ops with a remote peer's ops.
762
- */
763
- reconcileWith(remoteOps) {
764
- const localOps = this.getLocalOps();
765
- return reconcile(localOps, remoteOps);
766
- }
767
- /**
768
- * Get current sync state.
769
- */
770
- getState() {
771
- return this.state;
772
- }
773
- /**
774
- * Get branch policy.
775
- */
776
- getBranchPolicy() {
777
- return this.branchPolicy;
778
- }
779
- /**
780
- * Set branch policy.
781
- */
782
- setBranchPolicy(policy) {
783
- this.branchPolicy = policy;
784
- }
785
- /**
786
- * List known peers.
787
- */
788
- listPeers() {
789
- return this.transport.peers();
790
- }
791
- // -------------------------------------------------------------------------
792
- // Message handling
793
- // -------------------------------------------------------------------------
794
- async handleMessage(msg) {
795
- if (typeof msg.version !== "number" || msg.version < MIN_SUPPORTED_VERSION || msg.version > MAX_SUPPORTED_VERSION) {
796
- await this.transport.send(msg.peerId, {
797
- version: PROTOCOL_VERSION,
798
- type: "nack",
799
- peerId: this.localPeerId,
800
- refs: [],
801
- reason: "protocol-version",
802
- details: `Unsupported protocol version ${msg.version}; supported range is ${MIN_SUPPORTED_VERSION}-${MAX_SUPPORTED_VERSION}.`
803
- });
804
- return;
805
- }
806
- switch (msg.type) {
807
- case "have":
808
- await this.handleHave(msg);
809
- break;
810
- case "want":
811
- await this.handleWant(msg);
812
- break;
813
- case "ops":
814
- await this.handleOps(msg);
815
- break;
816
- case "ack":
817
- this.handleAck(msg);
818
- break;
819
- case "nack":
820
- await this.handleNack(msg);
821
- break;
822
- case "snapshot":
823
- await this.handleSnapshot(msg);
824
- break;
825
- case "sync-snapshot":
826
- break;
827
- }
828
- }
829
- async handleSnapshot(msg) {
830
- if (msg.ops.length === 0) return;
831
- await this.handleOps({
832
- version: msg.version,
833
- type: "ops",
834
- peerId: msg.peerId,
835
- ops: msg.ops
836
- });
837
- }
838
- async handleHave(msg) {
839
- this.state.peerHeads.set(msg.peerId, msg.heads);
840
- const localOps = this.getLocalOps();
841
- const localHashes = new Set(localOps.map((o) => o.hash));
842
- for (const [, hash] of Object.entries(msg.heads)) {
843
- if (!localHashes.has(hash)) {
844
- const afterHash = msg.opCount > localOps.length ? void 0 : localOps.length > 0 ? localOps[localOps.length - 1].hash : void 0;
845
- await this.transport.send(msg.peerId, {
846
- version: PROTOCOL_VERSION,
847
- type: "want",
848
- peerId: this.localPeerId,
849
- wantHashes: [],
850
- afterHash
851
- });
852
- return;
853
- }
854
- }
855
- if (msg.opCount > localOps.length) {
856
- await this.transport.send(msg.peerId, {
857
- version: PROTOCOL_VERSION,
858
- type: "want",
859
- peerId: this.localPeerId,
860
- wantHashes: []
861
- });
862
- return;
863
- }
864
- const peerOpCount = msg.opCount;
865
- if (localOps.length > peerOpCount) {
866
- await this.sendOpsMessage(msg.peerId, localOps.slice(peerOpCount));
867
- }
868
- }
869
- async handleWant(msg) {
870
- const localOps = this.getLocalOps();
871
- let opsToSend;
872
- if (msg.afterHash) {
873
- const idx = localOps.findIndex((o) => o.hash === msg.afterHash);
874
- opsToSend = idx >= 0 ? localOps.slice(idx + 1) : localOps;
875
- } else if (msg.wantHashes.length > 0) {
876
- const wanted = new Set(msg.wantHashes);
877
- opsToSend = localOps.filter((o) => wanted.has(o.hash));
878
- } else {
879
- opsToSend = localOps;
880
- }
881
- await this.sendOpsMessage(msg.peerId, opsToSend);
882
- }
883
- async handleOps(msg) {
884
- if (msg.ops.length === 0) return;
885
- let result;
886
- if (this.branchPolicy.linear) {
887
- const localOps = this.getLocalOps();
888
- const localHashes = new Set(localOps.map((o) => o.hash));
889
- const newOps = msg.ops.filter((o) => !localHashes.has(o.hash));
890
- if (newOps.length > 0) {
891
- result = await this.onOpsReceived(newOps) ?? void 0;
892
- }
893
- } else {
894
- const reconciled = this.reconcileWith(msg.ops);
895
- if (reconciled.uniqueToB.length > 0) {
896
- result = await this.onOpsReceived(reconciled.uniqueToB) ?? void 0;
897
- }
898
- }
899
- const rejections = result?.rejections ?? [];
900
- if (rejections.length > 0) {
901
- const byReason = /* @__PURE__ */ new Map();
902
- for (const r of rejections) {
903
- const entry = byReason.get(r.reason) ?? {
904
- refs: [],
905
- details: r.details
906
- };
907
- entry.refs.push(r.hash);
908
- byReason.set(r.reason, entry);
909
- }
910
- for (const [reason, entry] of byReason) {
911
- await this.transport.send(msg.peerId, {
912
- version: PROTOCOL_VERSION,
913
- type: "nack",
914
- peerId: this.localPeerId,
915
- refs: entry.refs,
916
- reason,
917
- details: entry.details
918
- });
919
- }
920
- }
921
- const rejectedSet = new Set(rejections.map((r) => r.hash));
922
- const ackHashes = msg.ops.map((o) => o.hash).filter((h) => !rejectedSet.has(h));
923
- if (ackHashes.length > 0) {
924
- await this.transport.send(msg.peerId, {
925
- version: PROTOCOL_VERSION,
926
- type: "ack",
927
- peerId: this.localPeerId,
928
- integrated: ackHashes
929
- });
930
- }
931
- this.state.lastSync.set(msg.peerId, (/* @__PURE__ */ new Date()).toISOString());
932
- }
933
- handleAck(msg) {
934
- for (const hash of msg.integrated) {
935
- this.state.pendingAcks.delete(hash);
936
- }
937
- this.state.lastSync.set(msg.peerId, (/* @__PURE__ */ new Date()).toISOString());
938
- }
939
- async handleNack(msg) {
940
- for (const ref of msg.refs) {
941
- this.state.pendingAcks.delete(ref);
942
- }
943
- this.state.lastSync.set(msg.peerId, (/* @__PURE__ */ new Date()).toISOString());
944
- if (this.onNackReceived) {
945
- await this.onNackReceived(msg);
946
- }
947
- }
948
- };
949
-
950
- // demo/state-demo/multiplayer-room.ts
951
- var MultiplayerRoom = class {
952
- alice;
953
- bob;
954
- room = new MemorySyncRoom("docs-state-demo", "Docs state");
955
- engineAlice;
956
- engineBob;
957
- roomPeerId;
958
- onChange;
959
- pushDebounceMs;
960
- pushTimer;
961
- flushing = false;
962
- constructor(opts = {}) {
963
- this.onChange = opts.onChange;
964
- this.pushDebounceMs = opts.pushDebounceMs ?? 80;
965
- this.roomPeerId = this.room.getRoomPeer().id;
966
- const scheduleSync = () => this.scheduleSync();
967
- this.alice = new DemoSession({
968
- agentId: "agent:alice",
969
- onChange: () => this.emit(),
970
- onAfterWrite: scheduleSync
971
- });
972
- this.bob = new DemoSession({
973
- agentId: "agent:bob",
974
- onChange: () => this.emit(),
975
- onAfterWrite: scheduleSync
976
- });
977
- this.engineAlice = new SyncEngine({
978
- localPeerId: "alice",
979
- transport: this.room.connectPeer("alice", "Alice"),
980
- getLocalOps: () => this.alice.getOps(),
981
- onOpsReceived: (ops) => {
982
- this.alice.integrate(ops);
983
- },
984
- branchPolicy: { linear: false }
985
- });
986
- this.engineBob = new SyncEngine({
987
- localPeerId: "bob",
988
- transport: this.room.connectPeer("bob", "Bob"),
989
- getLocalOps: () => this.bob.getOps(),
990
- onOpsReceived: (ops) => {
991
- this.bob.integrate(ops);
992
- },
993
- branchPolicy: { linear: false }
994
- });
995
- }
996
- getMergedOps() {
997
- return mergeOps(this.alice.getOps(), this.bob.getOps());
998
- }
999
- emit() {
1000
- this.onChange?.({
1001
- alice: { ops: this.alice.getOps(), issues: this.alice.getIssues() },
1002
- bob: { ops: this.bob.getOps(), issues: this.bob.getIssues() },
1003
- mergedOps: this.getMergedOps()
1004
- });
1005
- }
1006
- scheduleSync() {
1007
- if (this.pushTimer !== void 0) clearTimeout(this.pushTimer);
1008
- this.pushTimer = setTimeout(() => {
1009
- this.pushTimer = void 0;
1010
- void this.flushSync();
1011
- }, this.pushDebounceMs);
1012
- }
1013
- /** Push/pull both peers through the room relay. */
1014
- async flushSync() {
1015
- if (this.flushing) return;
1016
- this.flushing = true;
1017
- try {
1018
- await this.engineAlice.pushTo(this.roomPeerId);
1019
- await this.engineBob.pullAllFrom(this.roomPeerId);
1020
- await this.engineBob.pushTo(this.roomPeerId);
1021
- await this.engineAlice.pullAllFrom(this.roomPeerId);
1022
- this.emit();
1023
- } finally {
1024
- this.flushing = false;
1025
- }
1026
- }
1027
- };
1028
- export {
1029
- DemoSession,
1030
- MultiplayerRoom,
1031
- mergeOps,
1032
- projectIssues
1033
- };