markloom 0.4.0 → 0.5.1

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 (51) hide show
  1. package/README.md +29 -16
  2. package/ai.md +160 -0
  3. package/collab.md +70 -0
  4. package/dist/ai/index.cjs +4 -3
  5. package/dist/ai/index.d.cts +4 -2
  6. package/dist/ai/index.d.ts +4 -2
  7. package/dist/ai/index.js +3 -2
  8. package/dist/chunk-4JSJAHTB.js +255 -0
  9. package/dist/{chunk-VVFIQLVR.cjs → chunk-4TMHVNL6.cjs} +71 -79
  10. package/dist/chunk-ALZ3A5CS.cjs +255 -0
  11. package/dist/{chunk-QXJHFQLJ.js → chunk-FCH7LZFI.js} +23 -15
  12. package/dist/chunk-GQ2HHRGI.cjs +16 -0
  13. package/dist/chunk-JS527FDV.cjs +294 -0
  14. package/dist/chunk-LA5SBCGQ.js +16 -0
  15. package/dist/{chunk-ITVAR2UM.js → chunk-LEYAQNJA.js} +5 -3
  16. package/dist/{chunk-J3QWW6CN.js → chunk-MFYF2A6U.js} +5 -13
  17. package/dist/chunk-RLTHVQNQ.js +294 -0
  18. package/dist/{chunk-VSTOMEU2.cjs → chunk-VXM7Q6P5.cjs} +813 -478
  19. package/dist/{chunk-LNSKDJMF.cjs → chunk-YIFOGP2D.cjs} +46 -38
  20. package/dist/{chunk-HA6XHJUD.cjs → chunk-YXQDCW4Y.cjs} +22 -20
  21. package/dist/{chunk-VMUJM52A.js → chunk-ZMTLSFLO.js} +350 -15
  22. package/dist/client-6KiH4kGK.d.ts +144 -0
  23. package/dist/client-ZRZj2nkq.d.cts +144 -0
  24. package/dist/collab/index.cjs +25 -0
  25. package/dist/collab/index.d.cts +11 -0
  26. package/dist/collab/index.d.ts +11 -0
  27. package/dist/collab/index.js +25 -0
  28. package/dist/comments-DlExS6f-.d.cts +43 -0
  29. package/dist/comments-PhnR7Gkn.d.ts +43 -0
  30. package/dist/{controller-B_wG2Wh-.d.ts → controller-BNuuUM3E.d.ts} +26 -2
  31. package/dist/{controller-Cd1Dprrk.d.cts → controller-DQITsFhy.d.cts} +26 -2
  32. package/dist/index.cjs +21 -243
  33. package/dist/index.d.cts +5 -7
  34. package/dist/index.d.ts +5 -7
  35. package/dist/index.js +22 -244
  36. package/dist/react/index.cjs +8 -5
  37. package/dist/react/index.d.cts +4 -2
  38. package/dist/react/index.d.ts +4 -2
  39. package/dist/react/index.js +7 -4
  40. package/dist/rebase-batch-8rL_aXEE.d.ts +38 -0
  41. package/dist/rebase-batch-bYnBJpRO.d.cts +38 -0
  42. package/dist/step-BrvHIK7O.d.cts +65 -0
  43. package/dist/step-BrvHIK7O.d.ts +65 -0
  44. package/dist/view/index.cjs +11 -8
  45. package/dist/view/index.d.cts +5 -3
  46. package/dist/view/index.d.ts +5 -3
  47. package/dist/view/index.js +7 -4
  48. package/dist/view/theme.css +72 -0
  49. package/package.json +10 -3
  50. package/dist/comments-USjT1wYN.d.cts +0 -105
  51. package/dist/comments-USjT1wYN.d.ts +0 -105
package/README.md CHANGED
@@ -16,7 +16,6 @@ import 'markloom/view/theme.css'
16
16
 
17
17
  const ed = new Editor(root, doc, {
18
18
  onChange: d => save(d), // or persist with docToMd(d)
19
- // optional: ai: { stream: yourStreamFn }
20
19
  })
21
20
  ```
22
21
 
@@ -46,19 +45,9 @@ This is not “we support export to `.md`.” The model is built so MD and the e
46
45
  - IME handled as a first-class path (composition aligned to the model, not “hope the browser is fine”).
47
46
  - Slash menu, bubble format bar, drag handle, gaps around atoms — product surface without forking the kernel.
48
47
 
49
- ### 4. AI write as a document transaction (not a floating card)
48
+ ### 4. AI write as a document transaction
50
49
 
51
- When you enable AI, generation is still the same tree and history:
52
-
53
- | Step | What happens |
54
- |------|----------------|
55
- | `/ai` or format bar | In-doc prompt shell |
56
- | Enter / stream | **Real top-level blocks** enter the body (faded = uncommitted) |
57
- | Live preview | MD soft-close + `mdToDoc` each frame → rich structure while streaming |
58
- | Accept | Strip draft marks, remove shell — **no second insert** |
59
- | Discard | **`undo` the whole transaction** (one past entry) |
60
-
61
- AI is strong because the rest of the model is strong — ids, Steps, MD, history — not because of a chat overlay.
50
+ One options field: `/ai`, format bar, real draft blocks, accept / undo — same tree and history. Example below; full transports in [ai.md](./ai.md).
62
51
 
63
52
  ### 5. Use the piece you need
64
53
 
@@ -66,6 +55,7 @@ AI is strong because the rest of the model is strong — ids, Steps, MD, history
66
55
  markloom tree, Steps, history, MD, appendText / diffById
67
56
  markloom/view editor + view/theme.css
68
57
  markloom/ai AI controller + stream helper + ai/theme.css
58
+ markloom/collab realtime OT client (pair with worker/)
69
59
  markloom/react optional React wrapper (peer react, optional)
70
60
  ```
71
61
 
@@ -79,25 +69,48 @@ const next = apply(doc, appendText(doc, blockId, token))
79
69
  await save(docToMd(next))
80
70
  ```
81
71
 
82
- **Editor + AI** (product):
72
+ **Editor + AI** (one example; [proxy / provider / custom → ai.md](./ai.md)):
73
+
74
+ ```bash
75
+ npm i markloom ai @ai-sdk/openai
76
+ ```
83
77
 
84
78
  ```ts
79
+ import { docToMd } from 'markloom'
85
80
  import { Editor } from 'markloom/view'
81
+ import { streamText } from 'ai'
82
+ import { createOpenAI } from '@ai-sdk/openai'
86
83
  import 'markloom/view/theme.css'
87
84
  import 'markloom/ai/theme.css'
88
85
 
86
+ const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY! })
87
+
89
88
  new Editor(el, doc, {
90
89
  onChange: d => save(docToMd(d)),
91
90
  ai: {
92
91
  stream: async (input, onToken) => {
93
- // your model or proxy
92
+ const result = streamText({
93
+ model: openai('gpt-4o-mini'),
94
+ prompt: input.context,
95
+ abortSignal: input.signal,
96
+ })
97
+ for await (const t of result.textStream) onToken(t)
94
98
  },
95
99
  },
96
100
  })
97
101
  ```
98
102
 
103
+ **Realtime collab** (one field; [worker + protocol → collab.md](./collab.md)):
104
+
105
+ ```ts
106
+ new Editor(el, doc, {
107
+ collab: { url: 'ws://127.0.0.1:8787', room: 'demo', name: 'Alice' },
108
+ })
109
+ ```
110
+
99
111
  ## Why this stack
100
112
 
113
+
101
114
  | Problem | Typical approach | markloom |
102
115
  |---------|------------------|----------|
103
116
  | MD round-trip ruins formatting | Best-effort export | Isomorphic projection + clean-block spans |
@@ -117,7 +130,7 @@ Preact, `@floating-ui/dom`, unified/mdast GFM (`mdast-util-*`, `micromark-extens
117
130
 
118
131
  ## Limits (honest)
119
132
 
120
- - Collaboration wire protocol (Yjs/OT network) not shipped; `map` / `rebase` foundations are in the kernel.
133
+ - Collaboration: client + Cloudflare Worker shipped (`collab: { url, room }` — see [collab.md](./collab.md)). TP2 / auth / multi-caret chrome still thin.
121
134
  - Tables are **atoms** (full grid model inside; not free nesting in the prose grammar).
122
135
 
123
136
  ## License
package/ai.md ADDED
@@ -0,0 +1,160 @@
1
+ # AI
2
+
3
+ Configure **how tokens arrive**. Slash `/ai`, format-bar continue/rewrite, draft blocks, live MD→structure, accept / undo discard are built in.
4
+
5
+ ```ts
6
+ import { Editor } from 'markloom/view'
7
+ import 'markloom/view/theme.css'
8
+ import 'markloom/ai/theme.css'
9
+ ```
10
+
11
+ Pick **one** transport: `provider` | `endpoint` | `stream`.
12
+
13
+ ---
14
+
15
+ ## Built-in OpenAI-compatible
16
+
17
+ Any host with `POST …/v1/chat/completions` + SSE (OpenAI, xAI, 智谱, …). Needs CORS; prefer a proxy in production.
18
+
19
+ ```ts
20
+ new Editor(el, doc, {
21
+ ai: {
22
+ provider: {
23
+ host: 'https://api.x.ai',
24
+ apiKey: import.meta.env.VITE_AI_KEY,
25
+ model: 'grok-3',
26
+ },
27
+ },
28
+ })
29
+ ```
30
+
31
+ ---
32
+
33
+ ## Same-origin proxy (production)
34
+
35
+ Keys stay on the server. Body from the editor: `{ action, context, docPreview, system, provider? }`. Respond with **SSE** — OpenAI `choices[0].delta.content` or `{ content: "…" }` per `data:` line.
36
+
37
+ ```ts
38
+ new Editor(el, doc, {
39
+ ai: { endpoint: '/api/ai/stream' },
40
+ })
41
+ ```
42
+
43
+ ```ts
44
+ // server: POST /api/ai/stream
45
+ export async function POST(req: Request) {
46
+ const body = await req.json()
47
+ const upstream = await fetch('https://api.x.ai/v1/chat/completions', {
48
+ method: 'POST',
49
+ headers: {
50
+ 'content-type': 'application/json',
51
+ authorization: `Bearer ${process.env.XAI_API_KEY}`,
52
+ },
53
+ body: JSON.stringify({
54
+ model: 'grok-3',
55
+ stream: true,
56
+ messages: [
57
+ { role: 'system', content: body.system },
58
+ {
59
+ role: 'user',
60
+ content: body.action === 'rewrite'
61
+ ? `Rewrite:\n\n${body.context}`
62
+ : `Continue after:\n\n${body.context}`,
63
+ },
64
+ ],
65
+ }),
66
+ })
67
+ return new Response(upstream.body, {
68
+ headers: {
69
+ 'content-type': 'text/event-stream',
70
+ 'cache-control': 'no-cache',
71
+ },
72
+ })
73
+ }
74
+ ```
75
+
76
+ ---
77
+
78
+ ## Vercel AI SDK
79
+
80
+ ```bash
81
+ npm i ai @ai-sdk/openai
82
+ # or @ai-sdk/xai, @ai-sdk/anthropic, …
83
+ ```
84
+
85
+ ```ts
86
+ import { streamText } from 'ai'
87
+ import { createOpenAI } from '@ai-sdk/openai'
88
+
89
+ const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY! })
90
+
91
+ new Editor(el, doc, {
92
+ ai: {
93
+ stream: async (input, onToken) => {
94
+ const result = streamText({
95
+ model: openai('gpt-4o-mini'),
96
+ system:
97
+ input.action === 'rewrite'
98
+ ? 'Rewrite clearly. Output body only, no preface.'
99
+ : 'Continue in the same voice. Output body only, no preface.',
100
+ prompt:
101
+ input.action === 'rewrite'
102
+ ? input.context
103
+ : [input.docPreview, input.context].filter(Boolean).join('\n\n'),
104
+ abortSignal: input.signal,
105
+ })
106
+ for await (const delta of result.textStream)
107
+ onToken(delta)
108
+ },
109
+ },
110
+ })
111
+ ```
112
+
113
+ Same `stream` shape works with any SDK provider, agents, or RAG — call `onToken` with text chunks.
114
+
115
+ ---
116
+
117
+ ## Custom backend / agent
118
+
119
+ ```ts
120
+ new Editor(el, doc, {
121
+ ai: {
122
+ stream: async ({ action, context, docPreview, signal }, onToken) => {
123
+ const res = await fetch('/my-agent', {
124
+ method: 'POST',
125
+ headers: { 'content-type': 'application/json' },
126
+ body: JSON.stringify({ action, context, docPreview }),
127
+ signal,
128
+ })
129
+ const reader = res.body!.getReader()
130
+ const dec = new TextDecoder()
131
+ while (true) {
132
+ const { done, value } = await reader.read()
133
+ if (done) break
134
+ onToken(dec.decode(value, { stream: true }))
135
+ }
136
+ },
137
+ },
138
+ })
139
+ ```
140
+
141
+ ---
142
+
143
+ ## Optional knobs
144
+
145
+ ```ts
146
+ ai: {
147
+ provider: { host, apiKey, model }, // or endpoint / stream
148
+ continueSystem: '…',
149
+ rewriteSystem: '…',
150
+ onError: msg => toast.error(msg), // default: window.alert
151
+ onBusy: busy => setSpinner(busy),
152
+ }
153
+ ```
154
+
155
+ Programmatic: `ed.ai?.openAtFocus('continue' | 'rewrite')`, `ed.ai?.stop()`.
156
+
157
+ | You write | Library does |
158
+ |-----------|----------------|
159
+ | `provider` **or** `endpoint` **or** `stream` | Slash, bubble, drafts, MD preview, accept/undo |
160
+ | styles (`view` + `ai` theme) | AI chrome |
package/collab.md ADDED
@@ -0,0 +1,70 @@
1
+ # Collaboration
2
+
3
+ Real-time multiplayer via **centralized OT** (markloom `rebase` / `makeBias`) and a **Cloudflare Worker** Durable Object room (same WebSocket pattern as the chat repo: `acceptWebSocket` + fan-out).
4
+
5
+ ## Client (copy-paste)
6
+
7
+ ```bash
8
+ npm i markloom
9
+ # run the worker (below) or point url at a deployed room host
10
+ ```
11
+
12
+ ```ts
13
+ import { Editor } from 'markloom/view'
14
+ import 'markloom/view/theme.css'
15
+
16
+ new Editor(el, doc, {
17
+ collab: {
18
+ url: 'ws://127.0.0.1:8787', // or wss://your-worker.workers.dev
19
+ room: 'demo-room',
20
+ name: 'Alice',
21
+ },
22
+ })
23
+ ```
24
+
25
+ That is enough: local edits upload as Steps; remote Steps apply through OT. No extension list.
26
+
27
+ **Presence (built-in, Feishu-style):** top-right avatar stack (self + peers) and colored remote carets with name labels. Colors auto-assign by `siteId` unless you set `color`. No extra config.
28
+
29
+ Optional: `color`, `name`, `seed` (empty room init; default = constructor `doc`).
30
+
31
+ Programmatic: `ed.collab` → `CollabClient` (`peersList`, `close()`).
32
+
33
+ ## Worker
34
+
35
+ ```bash
36
+ cd worker
37
+ bun install # or npm i
38
+ bun run dev # wrangler dev → ws://127.0.0.1:8787
39
+ ```
40
+
41
+ - `GET /room/:id` + WebSocket upgrade → one Durable Object per room name
42
+ - Snapshot persisted in DO storage; op log in memory (stale base → `resync`)
43
+
44
+ Deploy: `bun run deploy` (Cloudflare account + `wrangler login`).
45
+
46
+ ## Protocol (summary)
47
+
48
+ | Direction | Types |
49
+ |-----------|--------|
50
+ | C→S | `join`, `op`, `presence`, `ping` |
51
+ | S→C | `welcome`, `op`, `presence`, `peer-join` / `peer-leave`, `resync`, `error` |
52
+
53
+ See `src/collab/protocol.ts`.
54
+
55
+ ## Limits (honest)
56
+
57
+ - **TP2** (reordered remote undo chains) not proven; server serializes commits so common concurrent typing is covered by TP1 + central order.
58
+ - Local **undo** interleaved with remote may need a later resync.
59
+ - No auth: room id is the capability.
60
+ - Presence is on the wire; rich multi-caret chrome is optional product UI.
61
+
62
+ ## Lab
63
+
64
+ ```bash
65
+ # terminal 1
66
+ cd worker && bun run dev
67
+ # terminal 2
68
+ cd .. && bun run lab
69
+ # open two windows: http://localhost:5181/?room=demo
70
+ ```
package/dist/ai/index.cjs CHANGED
@@ -6,8 +6,9 @@
6
6
 
7
7
 
8
8
 
9
- var _chunkLNSKDJMFcjs = require('../chunk-LNSKDJMF.cjs');
10
- require('../chunk-VVFIQLVR.cjs');
9
+ var _chunkYIFOGP2Dcjs = require('../chunk-YIFOGP2D.cjs');
10
+ require('../chunk-4TMHVNL6.cjs');
11
+ require('../chunk-GQ2HHRGI.cjs');
11
12
 
12
13
 
13
14
 
@@ -16,4 +17,4 @@ require('../chunk-VVFIQLVR.cjs');
16
17
 
17
18
 
18
19
 
19
- exports.MarkloomAi = _chunkLNSKDJMFcjs.MarkloomAi; exports.aiInstructionFromQuery = _chunkLNSKDJMFcjs.aiInstructionFromQuery; exports.blockPlainText = _chunkLNSKDJMFcjs.blockPlainText; exports.createAiStream = _chunkLNSKDJMFcjs.createAiStream; exports.focusBlockId = _chunkLNSKDJMFcjs.focusBlockId; exports.precedingPlainText = _chunkLNSKDJMFcjs.precedingPlainText; exports.startAiWrite = _chunkLNSKDJMFcjs.startAiWrite;
20
+ exports.MarkloomAi = _chunkYIFOGP2Dcjs.MarkloomAi; exports.aiInstructionFromQuery = _chunkYIFOGP2Dcjs.aiInstructionFromQuery; exports.blockPlainText = _chunkYIFOGP2Dcjs.blockPlainText; exports.createAiStream = _chunkYIFOGP2Dcjs.createAiStream; exports.focusBlockId = _chunkYIFOGP2Dcjs.focusBlockId; exports.precedingPlainText = _chunkYIFOGP2Dcjs.precedingPlainText; exports.startAiWrite = _chunkYIFOGP2Dcjs.startAiWrite;
@@ -1,6 +1,8 @@
1
- export { A as AiConfig, a as AiPromptMode, b as AiProvider, c as AiStreamFn, d as AiStreamInput, e as AiWriteMode, f as AiWriteSession, M as MarkloomAi, g as MarkloomAiOpts, h as blockPlainText, i as createAiStream, j as focusBlockId, s as startAiWrite } from '../controller-Cd1Dprrk.cjs';
2
- import { E as ElementNode } from '../comments-USjT1wYN.cjs';
1
+ export { A as AiConfig, a as AiPromptMode, b as AiProvider, c as AiStreamFn, d as AiStreamInput, e as AiWriteMode, f as AiWriteSession, M as MarkloomAi, g as MarkloomAiOpts, h as blockPlainText, i as createAiStream, j as focusBlockId, s as startAiWrite } from '../controller-DQITsFhy.cjs';
2
+ import { E as ElementNode } from '../step-BrvHIK7O.cjs';
3
3
  import 'preact';
4
+ import '../comments-DlExS6f-.cjs';
5
+ import '../client-ZRZj2nkq.cjs';
4
6
 
5
7
  /** 顶层块 [0, blockIdx) 纯文本拼接(作 /ai 上下文) */
6
8
  declare function precedingPlainText(doc: ElementNode, blockIdx: number): string;
@@ -1,6 +1,8 @@
1
- export { A as AiConfig, a as AiPromptMode, b as AiProvider, c as AiStreamFn, d as AiStreamInput, e as AiWriteMode, f as AiWriteSession, M as MarkloomAi, g as MarkloomAiOpts, h as blockPlainText, i as createAiStream, j as focusBlockId, s as startAiWrite } from '../controller-B_wG2Wh-.js';
2
- import { E as ElementNode } from '../comments-USjT1wYN.js';
1
+ export { A as AiConfig, a as AiPromptMode, b as AiProvider, c as AiStreamFn, d as AiStreamInput, e as AiWriteMode, f as AiWriteSession, M as MarkloomAi, g as MarkloomAiOpts, h as blockPlainText, i as createAiStream, j as focusBlockId, s as startAiWrite } from '../controller-BNuuUM3E.js';
2
+ import { E as ElementNode } from '../step-BrvHIK7O.js';
3
3
  import 'preact';
4
+ import '../comments-PhnR7Gkn.js';
5
+ import '../client-6KiH4kGK.js';
4
6
 
5
7
  /** 顶层块 [0, blockIdx) 纯文本拼接(作 /ai 上下文) */
6
8
  declare function precedingPlainText(doc: ElementNode, blockIdx: number): string;
package/dist/ai/index.js CHANGED
@@ -6,8 +6,9 @@ import {
6
6
  focusBlockId,
7
7
  precedingPlainText,
8
8
  startAiWrite
9
- } from "../chunk-QXJHFQLJ.js";
10
- import "../chunk-J3QWW6CN.js";
9
+ } from "../chunk-FCH7LZFI.js";
10
+ import "../chunk-MFYF2A6U.js";
11
+ import "../chunk-LA5SBCGQ.js";
11
12
  export {
12
13
  MarkloomAi,
13
14
  aiInstructionFromQuery,
@@ -0,0 +1,255 @@
1
+ import {
2
+ transformRemoteAgainstPending
3
+ } from "./chunk-RLTHVQNQ.js";
4
+
5
+ // src/collab/colors.ts
6
+ var COLLAB_COLORS = [
7
+ "#3370ff",
8
+ "#f54a45",
9
+ "#ff8800",
10
+ "#00b578",
11
+ "#7b61ff",
12
+ "#e13edb",
13
+ "#14c0ff",
14
+ "#8f959e",
15
+ "#d83931",
16
+ "#2ea121"
17
+ ];
18
+ function collabColor(siteId, explicit) {
19
+ if (explicit)
20
+ return explicit;
21
+ const i = Math.abs((siteId || 1) - 1) % COLLAB_COLORS.length;
22
+ return COLLAB_COLORS[i];
23
+ }
24
+ function collabInitial(name, siteId) {
25
+ const n = (name || "").trim();
26
+ if (n) {
27
+ const ch = n[0];
28
+ return /[a-z]/i.test(ch) ? ch.toUpperCase() : ch;
29
+ }
30
+ return String(siteId ?? "?");
31
+ }
32
+
33
+ // src/collab/client.ts
34
+ function toWsUrl(url, room) {
35
+ let u = url.replace(/\/+$/, "");
36
+ if (u.startsWith("https://"))
37
+ u = `wss://${u.slice(8)}`;
38
+ else if (u.startsWith("http://"))
39
+ u = `ws://${u.slice(7)}`;
40
+ return `${u}/room/${encodeURIComponent(room)}`;
41
+ }
42
+ function retryDelay(attempt) {
43
+ const base = Math.min(1e3 * 2 ** Math.min(attempt, 5), 3e4);
44
+ const jitter = base * 0.5 * Math.random();
45
+ return base * 0.75 + jitter;
46
+ }
47
+ var CollabClient = class {
48
+ cfg;
49
+ handlers;
50
+ ws = null;
51
+ closed = false;
52
+ retry = 0;
53
+ reconnectTimer = null;
54
+ siteId = 0;
55
+ version = 0;
56
+ clientSeq = 0;
57
+ pending = [];
58
+ peers = /* @__PURE__ */ new Map();
59
+ joined = false;
60
+ constructor(cfg, handlers) {
61
+ this.cfg = cfg;
62
+ this.handlers = handlers;
63
+ this.connect();
64
+ }
65
+ get peersList() {
66
+ return [...this.peers.values()];
67
+ }
68
+ connect() {
69
+ if (this.closed)
70
+ return;
71
+ this.handlers.onStatus?.("connecting");
72
+ const url = toWsUrl(this.cfg.url, this.cfg.room);
73
+ let ws;
74
+ try {
75
+ ws = new WebSocket(url);
76
+ } catch (e) {
77
+ this.handlers.onError?.(e instanceof Error ? e.message : String(e));
78
+ this.scheduleReconnect();
79
+ return;
80
+ }
81
+ this.ws = ws;
82
+ ws.onopen = () => {
83
+ this.retry = 0;
84
+ this.handlers.onStatus?.("open");
85
+ this.send({
86
+ type: "join",
87
+ room: this.cfg.room,
88
+ name: this.cfg.name,
89
+ color: this.cfg.color,
90
+ seed: this.cfg.seed
91
+ });
92
+ };
93
+ ws.onclose = () => {
94
+ this.joined = false;
95
+ this.handlers.onStatus?.("closed");
96
+ if (!this.closed)
97
+ this.scheduleReconnect();
98
+ };
99
+ ws.onerror = () => {
100
+ try {
101
+ ws.close();
102
+ } catch {
103
+ }
104
+ };
105
+ ws.onmessage = (ev) => {
106
+ try {
107
+ const msg = JSON.parse(String(ev.data));
108
+ this.onServer(msg);
109
+ } catch {
110
+ }
111
+ };
112
+ }
113
+ scheduleReconnect() {
114
+ if (this.reconnectTimer || this.closed)
115
+ return;
116
+ const delay = retryDelay(this.retry++);
117
+ this.reconnectTimer = setTimeout(() => {
118
+ this.reconnectTimer = null;
119
+ this.connect();
120
+ }, delay);
121
+ }
122
+ send(msg) {
123
+ if (this.ws?.readyState === WebSocket.OPEN)
124
+ this.ws.send(JSON.stringify(msg));
125
+ }
126
+ onServer(msg) {
127
+ switch (msg.type) {
128
+ case "welcome": {
129
+ this.siteId = msg.siteId;
130
+ this.version = msg.version;
131
+ this.pending = [];
132
+ this.joined = true;
133
+ if (!this.cfg.color)
134
+ this.cfg.color = collabColor(msg.siteId);
135
+ this.peers.clear();
136
+ for (const p of msg.peers) {
137
+ this.peers.set(p.siteId, {
138
+ ...p,
139
+ color: collabColor(p.siteId, p.color)
140
+ });
141
+ }
142
+ this.handlers.onWelcome?.({
143
+ siteId: msg.siteId,
144
+ version: msg.version,
145
+ name: this.cfg.name,
146
+ color: this.cfg.color
147
+ });
148
+ this.handlers.onDoc(msg.doc, msg.version);
149
+ this.handlers.onPeers?.(this.peersList);
150
+ break;
151
+ }
152
+ case "resync": {
153
+ this.version = msg.version;
154
+ this.pending = [];
155
+ this.handlers.onDoc(msg.doc, msg.version);
156
+ break;
157
+ }
158
+ case "op": {
159
+ if (!this.joined)
160
+ return;
161
+ if (msg.siteId === this.siteId) {
162
+ if (msg.clientSeq != null)
163
+ this.pending = this.pending.filter((p) => p.clientSeq > msg.clientSeq);
164
+ this.version = msg.version;
165
+ return;
166
+ }
167
+ const pendingAs = this.pending.map((p) => ({ siteId: this.siteId, steps: p.steps }));
168
+ const { remote, pending: nextP } = transformRemoteAgainstPending(
169
+ msg.steps,
170
+ msg.siteId,
171
+ pendingAs,
172
+ this.siteId
173
+ );
174
+ this.pending = this.pending.map((p, i) => ({
175
+ ...p,
176
+ steps: nextP[i]?.steps ?? p.steps
177
+ }));
178
+ this.version = msg.version;
179
+ if (remote.length)
180
+ this.handlers.onRemote(remote);
181
+ break;
182
+ }
183
+ case "presence": {
184
+ const cur = this.peers.get(msg.siteId) ?? { siteId: msg.siteId };
185
+ this.peers.set(msg.siteId, {
186
+ ...cur,
187
+ name: msg.name ?? cur.name,
188
+ color: collabColor(msg.siteId, msg.color ?? cur.color),
189
+ sel: msg.sel === void 0 ? cur.sel : msg.sel
190
+ });
191
+ this.handlers.onPeers?.(this.peersList);
192
+ break;
193
+ }
194
+ case "peer-join": {
195
+ this.peers.set(msg.siteId, {
196
+ siteId: msg.siteId,
197
+ name: msg.name,
198
+ color: collabColor(msg.siteId, msg.color)
199
+ });
200
+ this.handlers.onPeers?.(this.peersList);
201
+ break;
202
+ }
203
+ case "peer-leave": {
204
+ this.peers.delete(msg.siteId);
205
+ this.handlers.onPeers?.(this.peersList);
206
+ break;
207
+ }
208
+ case "error":
209
+ this.handlers.onError?.(msg.message);
210
+ break;
211
+ case "pong":
212
+ break;
213
+ }
214
+ }
215
+ /** 本地已 apply 的 steps 推上服务器 */
216
+ push(steps) {
217
+ if (!steps.length || !this.joined || this.siteId <= 0)
218
+ return;
219
+ const clientSeq = ++this.clientSeq;
220
+ const baseVersion = this.version;
221
+ this.pending.push({ clientSeq, baseVersion, steps });
222
+ this.send({ type: "op", baseVersion, clientSeq, steps });
223
+ }
224
+ presence(sel) {
225
+ if (!this.joined)
226
+ return;
227
+ this.send({
228
+ type: "presence",
229
+ name: this.cfg.name,
230
+ color: this.cfg.color ?? collabColor(this.siteId),
231
+ sel
232
+ });
233
+ }
234
+ close() {
235
+ this.closed = true;
236
+ if (this.reconnectTimer)
237
+ clearTimeout(this.reconnectTimer);
238
+ try {
239
+ this.ws?.close();
240
+ } catch {
241
+ }
242
+ this.ws = null;
243
+ }
244
+ };
245
+ function connectCollab(cfg, handlers) {
246
+ return new CollabClient(cfg, handlers);
247
+ }
248
+
249
+ export {
250
+ COLLAB_COLORS,
251
+ collabColor,
252
+ collabInitial,
253
+ CollabClient,
254
+ connectCollab
255
+ };