@singapore-editor/collaboration 0.0.0-stage → 0.0.9

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 (84) hide show
  1. package/README.md +170 -2
  2. package/dist/broadcast-transport.d.ts +29 -0
  3. package/dist/broadcast-transport.d.ts.map +1 -0
  4. package/dist/broadcast-transport.js +120 -0
  5. package/dist/broadcast-transport.js.map +1 -0
  6. package/dist/document.d.ts +55 -0
  7. package/dist/document.d.ts.map +1 -0
  8. package/dist/document.js +263 -0
  9. package/dist/document.js.map +1 -0
  10. package/dist/framing.d.ts +15 -0
  11. package/dist/framing.d.ts.map +1 -0
  12. package/dist/framing.js +107 -0
  13. package/dist/framing.js.map +1 -0
  14. package/dist/index.d.ts +8 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +7 -0
  17. package/dist/merge-review.d.ts +56 -0
  18. package/dist/merge-review.d.ts.map +1 -0
  19. package/dist/merge-review.js +515 -0
  20. package/dist/merge-review.js.map +1 -0
  21. package/dist/peer-history.d.ts +2 -0
  22. package/dist/peer-history.d.ts.map +1 -0
  23. package/dist/peer-history.js +12 -0
  24. package/dist/peer-history.js.map +1 -0
  25. package/dist/plugin.d.ts +33 -0
  26. package/dist/plugin.d.ts.map +1 -0
  27. package/dist/plugin.js +287 -0
  28. package/dist/plugin.js.map +1 -0
  29. package/dist/presence-plugin.d.ts +10 -0
  30. package/dist/presence-plugin.d.ts.map +1 -0
  31. package/dist/presence-plugin.js +15 -0
  32. package/dist/presence-plugin.js.map +1 -0
  33. package/dist/presence-view.d.ts +27 -0
  34. package/dist/presence-view.d.ts.map +1 -0
  35. package/dist/presence-view.js +196 -0
  36. package/dist/presence-view.js.map +1 -0
  37. package/dist/presence.css +68 -0
  38. package/dist/presence.d.ts +87 -0
  39. package/dist/presence.d.ts.map +1 -0
  40. package/dist/presence.js +346 -0
  41. package/dist/presence.js.map +1 -0
  42. package/dist/protocol.d.ts +158 -0
  43. package/dist/protocol.d.ts.map +1 -0
  44. package/dist/protocol.js +33 -0
  45. package/dist/protocol.js.map +1 -0
  46. package/dist/replay-window.d.ts +9 -0
  47. package/dist/replay-window.d.ts.map +1 -0
  48. package/dist/replay-window.js +37 -0
  49. package/dist/replay-window.js.map +1 -0
  50. package/dist/review-view.d.ts +18 -0
  51. package/dist/review-view.d.ts.map +1 -0
  52. package/dist/review-view.js +142 -0
  53. package/dist/review-view.js.map +1 -0
  54. package/dist/review.d.ts +66 -0
  55. package/dist/review.d.ts.map +1 -0
  56. package/dist/review.js +268 -0
  57. package/dist/review.js.map +1 -0
  58. package/dist/room-crypto.d.ts +37 -0
  59. package/dist/room-crypto.d.ts.map +1 -0
  60. package/dist/room-crypto.js +168 -0
  61. package/dist/room-crypto.js.map +1 -0
  62. package/dist/session.d.ts +134 -0
  63. package/dist/session.d.ts.map +1 -0
  64. package/dist/session.js +904 -0
  65. package/dist/session.js.map +1 -0
  66. package/dist/signaling.d.ts +32 -0
  67. package/dist/signaling.d.ts.map +1 -0
  68. package/dist/signaling.js +119 -0
  69. package/dist/signaling.js.map +1 -0
  70. package/dist/transport-router.d.ts +31 -0
  71. package/dist/transport-router.d.ts.map +1 -0
  72. package/dist/transport-router.js +88 -0
  73. package/dist/transport-router.js.map +1 -0
  74. package/dist/transports.d.ts +6 -0
  75. package/dist/transports.d.ts.map +1 -0
  76. package/dist/transports.js +6 -0
  77. package/dist/webrtc-transport.d.ts +53 -0
  78. package/dist/webrtc-transport.d.ts.map +1 -0
  79. package/dist/webrtc-transport.js +379 -0
  80. package/dist/webrtc-transport.js.map +1 -0
  81. package/examples/signaling-server.ts +77 -0
  82. package/package.json +94 -4
  83. package/server/client-address.ts +28 -0
  84. package/server/signaling.ts +266 -0
package/README.md CHANGED
@@ -1,3 +1,171 @@
1
- # Temporary Holding Version
1
+ # @singapore-editor/collaboration
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Editor binding, session protocols, transports, and remote cursor presence for host-ordered collaboration.
4
+
5
+ Part of [Singapore](https://singapore.shaulavo.dev/). A code editor for the browser that keeps every version.
6
+
7
+ ## Install
8
+
9
+ Not on npm yet. Build it from source with the [development guide](https://github.com/ShaulLavo/singapore/blob/main/docs/development.md#set-up).
10
+
11
+ ## Usage
12
+
13
+ This example validates a presence message. A room needs a document engine, authenticated links, and a clock supplied by your app.
14
+
15
+ ```ts
16
+ import { Presence, parsePresence } from '@singapore-editor/collaboration'
17
+
18
+ const presence = new Presence('peer-1', 'document-1')
19
+ const message = parsePresence({ clock: 1, state: null }, 'peer-2', 'document-1')
20
+ if (message) presence.receive('peer-2', message)
21
+ console.log(presence.states)
22
+ presence.dispose()
23
+ ```
24
+
25
+ ## What you set up
26
+
27
+ The library uses no hosted services and has no public defaults. What you need depends on where
28
+ peers are:
29
+
30
+ - **Tabs in one browser:** nothing. They connect over an encrypted `BroadcastChannel`.
31
+ - **Browsers on different machines:** WebRTC, which needs three things you run or choose:
32
+ - A **signaling broker** that introduces peers. It only relays encrypted packets and keeps no
33
+ history. Run the included Bun broker from `@singapore-editor/collaboration/server`
34
+ ([example](https://github.com/ShaulLavo/singapore/blob/main/packages/collaboration/examples/signaling-server.ts)) or any service with the same protocol, behind TLS,
35
+ with an origin allowlist and an admission token per member.
36
+ - **STUN servers** so peers can find a direct route.
37
+ - A **TURN relay** (for example coturn) for networks where a direct route fails, with
38
+ credentials your app issues.
39
+ - **The invitation:** `createRoomInvitation()` makes a room ID and secret. Send them to the other
40
+ people yourself, for example in the fragment of a link; they never go through the broker.
41
+
42
+ Pass the broker URLs, ICE servers and credentials to the transports when joining. The
43
+ [integration guide](https://github.com/ShaulLavo/singapore/blob/main/packages/collaboration/docs/integration.md#browser-transports) covers each option.
44
+
45
+ ## No end-to-end quick start yet
46
+
47
+ There is no step-by-step guide that takes two editors from nothing to a synchronized document, and the example above does not start a session. To see the pieces wired together, read the demo app's collaboration page: [`collaboration.html`](https://github.com/ShaulLavo/singapore/blob/main/examples/app/collaboration.html) and [`collaboration.ts`](https://github.com/ShaulLavo/singapore/blob/main/examples/app/src/collaboration.ts). It is source to read, not a tested tutorial. The [integration guide](https://github.com/ShaulLavo/singapore/blob/main/packages/collaboration/docs/integration.md#editor-attachment) covers attaching the plugin to an editor.
48
+
49
+ ## API highlights
50
+
51
+ - `createCollaborationPlugin()` attaches shared editing and selective Undo to an editor view.
52
+ - `CollaborationDocument` bridges the collab engine to session history.
53
+ - `Session` runs the transport-neutral protocol with a host-supplied document engine.
54
+ - `Presence` tracks remote selections and cursors.
55
+ - `parsePresence()` validates received presence messages.
56
+
57
+ [Generated API reference](https://singapore.shaulavo.dev/docs/reference/api/collaboration/overview/)
58
+
59
+ [Integration guide](https://github.com/ShaulLavo/singapore/blob/main/packages/collaboration/docs/integration.md)
60
+
61
+ ## Confirmed merge review
62
+
63
+ Import `MergeReviewDetector` from `@singapore-editor/collaboration/merge-review` and supply a
64
+ `MergeReviewSyntax` reader. `detect(window, confirmedSnapshot, batch?)` returns `overlap`,
65
+ `parse`, `signature` and `orphan` marks. Pass the snapshot produced by the accepted history;
66
+ local pending typing stays outside that input. Each mark contains a unit ID built from the
67
+ unit kind and its first character's identity, sorted authors/edit IDs, and exact concurrent
68
+ pairs. Concurrency edges remain distinct because concurrency is non-transitive.
69
+
70
+ The syntax reader returns a group of units per requested range, in request order, using
71
+ UTF-16 offsets into the supplied snapshot. The default `enclosing` selection returns one unit
72
+ in each group. `touching` selection returns the smallest units for every touched portion of an
73
+ interval, including ancestors whose headers are touched outside nested units. Large pastes
74
+ use identity-piece intervals and query syntax nodes, so their request count follows pieces
75
+ and units rather than character count. Units include language, original signature spelling,
76
+ error state, and parent range/commutativity. A `contentKey` request asks for syntax shape and
77
+ leaf spelling with inter-token whitespace excluded. Formatting classification compares
78
+ snapshots differing by one operation with all surrounding effects retained. Signature marks
79
+ require a duplicate introduced by the edits; formatting or content-only changes to existing
80
+ duplicates stay unmarked. Return `null` when a snapshot is unavailable or a request is
81
+ cancelled. The detector then returns `unavailable` with an empty mark set so a host can retry
82
+ the whole batch.
83
+
84
+ With `batch` supplied, results concern concurrent pairs involving those IDs. A host that needs
85
+ a replacement mark set after undo, eviction or dismissal should request the whole retained
86
+ window by omitting `batch`. Marks and their settlement are caller-owned.
87
+
88
+ The detector is demand-only: it adds no subscriptions, timers, typing hooks or default syntax
89
+ reader. A null session window or a window without cross-author pairs returns before syntax
90
+ work. The coordinator, identity mapping, signature/orphan checks and `projectEffects` run on
91
+ the invoking thread; the supplied reader determines where syntax queries and projected-snapshot
92
+ parsing run. Worker `mergeUnit` requests support `analysis: true`, optional `contentKey: true`,
93
+ and cancellation, including line-fallback languages. A production bridge that registers
94
+ confirmed/projected snapshots in that worker and schedules review after confirmed batches
95
+ remains to be wired. The Node correctness
96
+ and cost fixtures use real grammars and queries on the test thread.
97
+
98
+ Run `bun run bench:merge-review` from this package for the shared-machine cost experiment and
99
+ CPU profile. The current 8,192-record workload exceeds the plan's unchanged 2 ms budget;
100
+ `bench/detector-evidence.json` records gate measurements and `bench/detector-profile-evidence.json`
101
+ records separately instrumented attribution. `bench/detector-baseline-evidence.json` is the
102
+ intermediate cached-state baseline before token fingerprints became demand-only. The profile
103
+ uses independent units, so projected-snapshot rebuilding and parsing are zero inside its timed
104
+ region; their cost is still unbounded by that experiment. The revised 2/4/8-author medians at
105
+ 8,192 records are 3.218/3.058/3.100 ms, with p95 5.478/4.823/5.060 ms.
106
+
107
+ `bench/paste-evidence.json` separately records the paste interval experiment against the reviewed
108
+ implementation: 16,001 syntax ranges become two for a 16,000-character insertion, with a trivial
109
+ reader. A real 100,000-character multi-unit paste uses two ranges and 20 query matches while
110
+ retaining both signature marks. These results measure paste range collection independently of
111
+ the unchanged ordinary batch gate.
112
+
113
+ ## Transport status
114
+
115
+ Transport options accept an optional `onRecovery` callback. Match all scope arguments
116
+ with `onError` when tracking outstanding failures:
117
+
118
+ - `BroadcastTransport` reports `send` after a successful channel send and `receive` after
119
+ accepting an authenticated packet for the document. Recovery in one direction clears
120
+ failures in that direction.
121
+ - `WebSocketSignaling` reports `(url, direction)`. A successful publication reports `send`;
122
+ a subscription acknowledgement or publication received from that broker reports `receive`.
123
+ Credential, subscription-send, and socket errors use the broker's `send` scope.
124
+ - `WebRTCTransport` reports the remote peer ID when its current data channel opens and the
125
+ router accepts the link. Signaling reports `(undefined, 'send')` after publication succeeds
126
+ and `(undefined, 'receive')` after an authenticated packet is accepted. The matching
127
+ `onError` arguments include the error first. Peer-scoped failures remain until that peer's
128
+ link opens again.
129
+
130
+ Receive recovery preserves outstanding send failures, and send recovery preserves outstanding
131
+ receive failures. A healthy broker or peer leaves failures at other brokers or peers intact.
132
+
133
+ `WebRTCTransport.onPeerLeft(peer)` reports an authenticated departure. Applications can
134
+ remove that departed peer's outstanding failures. Discovery-record expiry leaves
135
+ outstanding failures intact until a matching recovery or authenticated departure.
136
+
137
+ ## Connection lifecycle
138
+
139
+ `Session.disconnect(peer)` records loss of the last transport path. Membership and presence remain during `suspicionTimeout`; caller-driven `Session.tick(now)` evicts the peer when that deadline passes. `Session.connect(peer)` cancels pending eviction and refreshes local presence. `Session.retire(peer)` and received `LEAVE` messages remove presence immediately and fence the departed incarnation.
140
+
141
+ Custom `PresenceObserver` implementations receive `connected()` when a new or restored link becomes available. Attached `Presence` instances use it to republish current selections or offline removals with a fresh clock. Removed peers retain their clock floors so delayed messages cannot restore old carets.
142
+
143
+ ## TURN verification
144
+
145
+ The browser suite skips its TURN-only case until `COLLABORATION_TEST_TURN` contains an
146
+ array of `RTCIceServer` objects for a relay you control. Run this from the package directory:
147
+
148
+ ```sh
149
+ COLLABORATION_TEST_TURN='[{"urls":"turn:127.0.0.1:3478?transport=udp","username":"test-member","credential":"your-ephemeral-credential"}]' \
150
+ bun run test:browser -- test/transports.browser.test.ts -t TURN-only
151
+ ```
152
+
153
+ Configure the relay's listening address, relay address, credentials and UDP port range.
154
+ A loopback-only coturn instance also needs `--allow-loopback-peers` for two local browser
155
+ peers. Keep that instance bound to loopback and stop it after the test. For checks across
156
+ machines, use a private interface both machines can reach and allow its relay port range.
157
+
158
+ The case uses two real browser pages with `iceTransportPolicy: 'relay'` and exchanges
159
+ chunked edits. It checks that both peers select a `relay` local and remote ICE candidate
160
+ and that the selected pairs send and receive bytes. A configured relay that fails to
161
+ connect fails the test.
162
+
163
+ ## In the Singapore family
164
+
165
+ You can use this package on its own. `@singapore-editor/core` owns editor views; optional packages add syntax, search, gutters, and language features.
166
+
167
+ [Singapore README](https://github.com/ShaulLavo/singapore/blob/main/README.md) · [Documentation](https://singapore.shaulavo.dev/docs/start-here/introduction/)
168
+
169
+ ## License
170
+
171
+ MIT. [License](https://github.com/ShaulLavo/singapore/blob/main/LICENSE)
@@ -0,0 +1,29 @@
1
+ import type { EditEnvelope } from './protocol';
2
+ import { RoomCrypto } from './room-crypto';
3
+ import { TransportRouter } from './transport-router';
4
+ export interface BroadcastTransportOptions<E extends EditEnvelope> {
5
+ readonly router: TransportRouter<E>;
6
+ readonly crypto: RoomCrypto;
7
+ readonly heartbeatInterval: number;
8
+ readonly peerTimeout: number;
9
+ readonly onError: (error: unknown, direction: 'send' | 'receive') => void;
10
+ readonly onRecovery?: (direction: 'send' | 'receive') => void;
11
+ }
12
+ export declare class BroadcastTransport<E extends EditEnvelope = EditEnvelope> {
13
+ private readonly options;
14
+ private readonly channel;
15
+ private readonly generation;
16
+ private readonly peers;
17
+ private readonly timer;
18
+ private outbound;
19
+ private inbound;
20
+ private queued;
21
+ private inboundBytes;
22
+ private closed;
23
+ constructor(options: BroadcastTransportOptions<E>);
24
+ close(): Promise<void>;
25
+ private publish;
26
+ private receive;
27
+ private remove;
28
+ }
29
+ //# sourceMappingURL=broadcast-transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"broadcast-transport.d.ts","sourceRoot":"","sources":["../src/broadcast-transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAW,MAAM,YAAY,CAAA;AAEvD,OAAO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"./room-crypto.js";
3
+ // src/broadcast-transport.ts
4
+ var BroadcastTransport = class {
5
+ options;
6
+ channel;
7
+ generation = crypto.randomUUID();
8
+ peers = /* @__PURE__ */ new Map();
9
+ timer;
10
+ outbound = Promise.resolve();
11
+ inbound = Promise.resolve();
12
+ queued = 0;
13
+ inboundBytes = 0;
14
+ closed = false;
15
+ constructor(options) {
16
+ this.options = options;
17
+ const { router, crypto: roomCrypto, heartbeatInterval, peerTimeout } = options;
18
+ if (roomCrypto.room !== router.identity.room || roomCrypto.peer !== router.identity.peer) throw new TypeError("Room crypto must match the transport identity");
19
+ if (!Number.isFinite(heartbeatInterval) || heartbeatInterval <= 0 || !Number.isFinite(peerTimeout) || peerTimeout <= heartbeatInterval) throw new RangeError("Peer timeout must exceed the positive heartbeat interval");
20
+ this.channel = new BroadcastChannel(`singapore-collaboration:${router.identity.room}`);
21
+ this.channel.onmessage = (event) => {
22
+ const size = sealedPacketSize(event.data);
23
+ if (size === void 0 || this.inboundBytes + size > 33554432) return;
24
+ this.inboundBytes += size;
25
+ this.inbound = this.inbound.then(() => this.receive(event.data)).catch(async (error) => {
26
+ options.onError(error, "receive");
27
+ if (error instanceof DuplicatePeerSessionError) await this.close();
28
+ }).finally(() => {
29
+ this.inboundBytes -= size;
30
+ });
31
+ };
32
+ this.timer = setInterval(() => {
33
+ for (const [peer, state] of this.peers) if (Date.now() - state.time > peerTimeout) this.remove(peer);
34
+ this.publish({
35
+ document: router.identity.document,
36
+ type: "announce"
37
+ });
38
+ }, heartbeatInterval);
39
+ this.publish({
40
+ document: router.identity.document,
41
+ type: "announce"
42
+ });
43
+ }
44
+ async close() {
45
+ if (this.closed) return;
46
+ this.closed = true;
47
+ clearInterval(this.timer);
48
+ await this.outbound;
49
+ try {
50
+ this.channel.postMessage(await this.options.crypto.seal(this.generation, {
51
+ document: this.options.router.identity.document,
52
+ type: "leave"
53
+ }));
54
+ } finally {
55
+ this.channel.close();
56
+ for (const peer of this.peers.keys()) this.remove(peer);
57
+ }
58
+ }
59
+ publish(payload) {
60
+ if (this.closed) return;
61
+ const size = new TextEncoder().encode(JSON.stringify(payload)).byteLength;
62
+ if (size > 8388608 || this.queued + size > 16777216) {
63
+ this.options.onError(/* @__PURE__ */ new RangeError("Broadcast send queue exceeds its byte limit"), "send");
64
+ return;
65
+ }
66
+ this.queued += size;
67
+ this.outbound = this.outbound.then(async () => {
68
+ const packet = await this.options.crypto.seal(this.generation, payload);
69
+ if (this.closed) return;
70
+ this.channel.postMessage(packet);
71
+ this.options.onRecovery?.("send");
72
+ }).catch((error) => this.options.onError(error, "send")).finally(() => {
73
+ this.queued -= size;
74
+ });
75
+ }
76
+ async receive(input) {
77
+ if (this.closed) return;
78
+ const opened = await this.options.crypto.open(input);
79
+ if (!opened || this.closed || !isPayload(opened.payload) || opened.payload.document !== this.options.router.identity.document) return;
80
+ this.options.onRecovery?.("receive");
81
+ const { sender, generation, sequence } = opened.packet;
82
+ const previous = this.peers.get(sender);
83
+ if (previous && sequence <= previous.sequence) return;
84
+ const payload = opened.payload;
85
+ if (payload.type === "leave") {
86
+ if (previous?.generation !== generation) return;
87
+ this.remove(sender);
88
+ return;
89
+ }
90
+ const known = this.peers.has(sender);
91
+ if (!known && !this.options.router.add(sender, "broadcast", (message) => this.publish({
92
+ document: this.options.router.identity.document,
93
+ type: "message",
94
+ to: sender,
95
+ message
96
+ }))) return;
97
+ this.peers.set(sender, {
98
+ time: Date.now(),
99
+ generation,
100
+ sequence
101
+ });
102
+ if (!known) this.publish({
103
+ document: this.options.router.identity.document,
104
+ type: "announce"
105
+ });
106
+ if (payload.type === "message" && payload.to === this.options.router.identity.peer) this.options.router.receive(sender, payload.message);
107
+ }
108
+ remove(peer) {
109
+ this.peers.delete(peer);
110
+ this.options.router.remove(peer, "broadcast");
111
+ }
112
+ };
113
+ function isPayload(value) {
114
+ if (!value || typeof value !== "object") return false;
115
+ const payload = value;
116
+ return typeof payload.document === "string" && (payload.type === "announce" || payload.type === "leave" || payload.type === "message" && typeof payload.to === "string" && "message" in payload);
117
+ }
118
+ export { BroadcastTransport };
119
+
120
+ //# sourceMappingURL=broadcast-transport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"broadcast-transport.js","names":[],"sources":["../src/broadcast-transport.ts"],"sourcesContent":["import type { EditEnvelope, Message } from './protocol'\nimport { MESSAGE_LIMIT } from './framing'\nimport { DuplicatePeerSessionError, RoomCrypto, sealedPacketSize } from './room-crypto'\nimport { TransportRouter } from './transport-router'\n\nexport interface BroadcastTransportOptions<E extends EditEnvelope> {\n readonly router: TransportRouter<E>\n readonly crypto: RoomCrypto\n readonly heartbeatInterval: number\n readonly peerTimeout: number\n readonly onError: (error: unknown, direction: 'send' | 'receive') => void\n readonly onRecovery?: (direction: 'send' | 'receive') => void\n}\n\ntype BroadcastPayload =\n | { readonly document: string; readonly type: 'announce' | 'leave' }\n | {\n readonly document: string\n readonly type: 'message'\n readonly to: string\n readonly message: unknown\n }\n\nexport class BroadcastTransport<E extends EditEnvelope = EditEnvelope> {\n private readonly channel: BroadcastChannel\n private readonly generation = crypto.randomUUID()\n private readonly peers = new Map<string, { time: number; generation: string; sequence: number }>()\n private readonly timer: ReturnType<typeof setInterval>\n private outbound: Promise<void> = Promise.resolve()\n private inbound: Promise<void> = Promise.resolve()\n private queued = 0\n private inboundBytes = 0\n private closed = false\n\n constructor(private readonly options: BroadcastTransportOptions<E>) {\n const { router, crypto: roomCrypto, heartbeatInterval, peerTimeout } = options\n if (roomCrypto.room !== router.identity.room || roomCrypto.peer !== router.identity.peer)\n throw new TypeError('Room crypto must match the transport identity')\n if (\n !Number.isFinite(heartbeatInterval) ||\n heartbeatInterval <= 0 ||\n !Number.isFinite(peerTimeout) ||\n peerTimeout <= heartbeatInterval\n )\n throw new RangeError('Peer timeout must exceed the positive heartbeat interval')\n this.channel = new BroadcastChannel(`singapore-collaboration:${router.identity.room}`)\n this.channel.onmessage = (event) => {\n const size = sealedPacketSize(event.data)\n if (size === undefined || this.inboundBytes + size > 4 * MESSAGE_LIMIT) return\n this.inboundBytes += size\n this.inbound = this.inbound\n .then(() => this.receive(event.data))\n .catch(async (error) => {\n options.onError(error, 'receive')\n if (error instanceof DuplicatePeerSessionError) await this.close()\n })\n .finally(() => {\n this.inboundBytes -= size\n })\n }\n // @justification BroadcastChannel has no remote-close or crash event; this heartbeat expires\n // silent peers and advertises membership, and close clears the interval.\n this.timer = setInterval(() => {\n for (const [peer, state] of this.peers)\n if (Date.now() - state.time > peerTimeout) this.remove(peer)\n this.publish({ document: router.identity.document, type: 'announce' })\n }, heartbeatInterval)\n this.publish({ document: router.identity.document, type: 'announce' })\n }\n\n async close(): Promise<void> {\n if (this.closed) return\n this.closed = true\n clearInterval(this.timer)\n await this.outbound\n try {\n this.channel.postMessage(\n await this.options.crypto.seal(this.generation, {\n document: this.options.router.identity.document,\n type: 'leave',\n }),\n )\n } finally {\n this.channel.close()\n for (const peer of this.peers.keys()) this.remove(peer)\n }\n }\n\n private publish(payload: BroadcastPayload): void {\n if (this.closed) return\n const size = new TextEncoder().encode(JSON.stringify(payload)).byteLength\n if (size > MESSAGE_LIMIT || this.queued + size > 2 * MESSAGE_LIMIT) {\n this.options.onError(new RangeError('Broadcast send queue exceeds its byte limit'), 'send')\n return\n }\n this.queued += size\n this.outbound = this.outbound\n .then(async () => {\n const packet = await this.options.crypto.seal(this.generation, payload)\n if (this.closed) return\n this.channel.postMessage(packet)\n this.options.onRecovery?.('send')\n })\n .catch((error) => this.options.onError(error, 'send'))\n .finally(() => {\n this.queued -= size\n })\n }\n\n private async receive(input: unknown): Promise<void> {\n if (this.closed) return\n const opened = await this.options.crypto.open(input)\n if (\n !opened ||\n this.closed ||\n !isPayload(opened.payload) ||\n opened.payload.document !== this.options.router.identity.document\n )\n return\n this.options.onRecovery?.('receive')\n const { sender, generation, sequence } = opened.packet\n const previous = this.peers.get(sender)\n if (previous && sequence <= previous.sequence) return\n const payload = opened.payload\n if (payload.type === 'leave') {\n if (previous?.generation !== generation) return\n this.remove(sender)\n return\n }\n const known = this.peers.has(sender)\n if (\n !known &&\n !this.options.router.add(sender, 'broadcast', (message: Message<E>) =>\n this.publish({\n document: this.options.router.identity.document,\n type: 'message',\n to: sender,\n message,\n }),\n )\n )\n return\n this.peers.set(sender, { time: Date.now(), generation, sequence })\n if (!known) this.publish({ document: this.options.router.identity.document, type: 'announce' })\n if (payload.type === 'message' && payload.to === this.options.router.identity.peer)\n this.options.router.receive(sender, payload.message)\n }\n\n private remove(peer: string): void {\n this.peers.delete(peer)\n this.options.router.remove(peer, 'broadcast')\n }\n}\n\nfunction isPayload(value: unknown): value is BroadcastPayload {\n if (!value || typeof value !== 'object') return false\n const payload = value as Partial<BroadcastPayload>\n return (\n typeof payload.document === 'string' &&\n (payload.type === 'announce' ||\n payload.type === 'leave' ||\n (payload.type === 'message' && typeof payload.to === 'string' && 'message' in payload))\n )\n}\n"],"mappings":";;;AAuBA,IAAa,qBAAb,MAAuE;CAWxC;CAV7B;CACA,aAA8B,OAAO,WAAW;CAChD,wBAAyB,IAAI,IAAoE;CACjG;CACA,WAAkC,QAAQ,QAAQ;CAClD,UAAiC,QAAQ,QAAQ;CACjD,SAAiB;CACjB,eAAuB;CACvB,SAAiB;CAEjB,YAAY,SAAwD;EAAvC,KAAA,UAAA;EAC3B,MAAM,EAAE,QAAQ,QAAQ,YAAY,mBAAmB,gBAAgB;EACvE,IAAI,WAAW,SAAS,OAAO,SAAS,QAAQ,WAAW,SAAS,OAAO,SAAS,MAClF,MAAM,IAAI,UAAU,+CAA+C;EACrE,IACE,CAAC,OAAO,SAAS,iBAAiB,KAClC,qBAAqB,KACrB,CAAC,OAAO,SAAS,WAAW,KAC5B,eAAe,mBAEf,MAAM,IAAI,WAAW,0DAA0D;EACjF,KAAK,UAAU,IAAI,iBAAiB,2BAA2B,OAAO,SAAS,MAAM;EACrF,KAAK,QAAQ,aAAa,UAAU;GAClC,MAAM,OAAO,iBAAiB,MAAM,IAAI;GACxC,IAAI,SAAS,KAAA,KAAa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,QAAQ,OAAO,KAAK,QAAQ,OAAO,SAAS,MAC5E,KAAK,QAAQ,OAAO,QAAQ,QAAQ,QAAQ,OAAO;CACvD;CAEA,OAAe,MAAoB;EACjC,KAAK,MAAM,OAAO,IAAI;EACtB,KAAK,QAAQ,OAAO,OAAO,MAAM,WAAW;CAC9C;AACF;AAEA,SAAS,UAAU,OAA2C;CAC5D,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,MAAM,UAAU;CAChB,OACE,OAAO,QAAQ,aAAa,aAC3B,QAAQ,SAAS,cAChB,QAAQ,SAAS,WAChB,QAAQ,SAAS,aAAa,OAAO,QAAQ,OAAO,YAAY,aAAa;AAEpF"}
@@ -0,0 +1,55 @@
1
+ import { Participant, TextbufferEngine, type Envelope, type UndoOptions } from '@singapore-editor/collab';
2
+ import { type Checkpoint, type Confirmation, type DocumentEngine, type EditId, type Outcome } from './protocol';
3
+ export interface CollaborationDocumentOptions {
4
+ readonly peer: string;
5
+ readonly document: string;
6
+ readonly epoch: string;
7
+ readonly text: string;
8
+ }
9
+ /** Confirmed ordering and optimistic text have independent engines and snapshot ownership. */
10
+ export declare class CollaborationDocument implements DocumentEngine<Envelope> {
11
+ private readonly options;
12
+ readonly engine: TextbufferEngine;
13
+ readonly participant: Participant<ReturnType<TextbufferEngine['snapshot']>>;
14
+ readonly genesis: Checkpoint;
15
+ private readonly base;
16
+ private hostEngine;
17
+ private host;
18
+ private history;
19
+ private readonly records;
20
+ private confirmations;
21
+ private allocated;
22
+ private batching;
23
+ private readonly confirmedObservers;
24
+ confirmedSnapshot(): ReturnType<TextbufferEngine['snapshot']>;
25
+ subscribeConfirmed(observer: (reset: boolean, remote: boolean) => void): () => void;
26
+ constructor(options: CollaborationDocumentOptions, undo?: UndoOptions);
27
+ private createHost;
28
+ /** Bind local effect state and retain every already-known foreign identity. */
29
+ historyIdentity(): string;
30
+ authoredEffects(): readonly {
31
+ readonly op: EditId;
32
+ readonly active: boolean;
33
+ }[];
34
+ matchesHistoryIdentity(saved: string): boolean;
35
+ checkpoint(): Checkpoint;
36
+ outcome(id: EditId): Outcome | undefined;
37
+ sequence(edit: Envelope, rejection?: string): Confirmation<Envelope>;
38
+ apply(record: Confirmation<Envelope>): boolean;
39
+ sequenceBatch(edits: readonly {
40
+ readonly edit: Envelope;
41
+ readonly rejection?: string;
42
+ }[]): readonly Confirmation<Envelope>[];
43
+ applyBatch(records: readonly Confirmation<Envelope>[]): boolean;
44
+ private batch;
45
+ private confirmation;
46
+ private settleProjection;
47
+ private append;
48
+ exportHistory(from: Checkpoint): readonly Confirmation<Envelope>[] | undefined;
49
+ verify(history: readonly Confirmation<Envelope>[], tip: Checkpoint): boolean;
50
+ private validNext;
51
+ install(history: readonly Confirmation<Envelope>[], recovered?: readonly Envelope[]): void;
52
+ private restoreHost;
53
+ uniquePending(history: readonly Confirmation<Envelope>[]): readonly Envelope[];
54
+ }
55
+ //# sourceMappingURL=document.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document.d.ts","sourceRoot":"","sources":["../src/document.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,WAAW,EACX,gBAAgB,EAChB,KAAK,QAAQ,EAEb,KAAK,WAAW,EACjB,MAAM,0BAA0B,CAAA;AAEjC,OAAO,EAGL,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,MAAM,EACX,KAAK,OAAO,EACb,MAAM,YAAY,CAAA;AA2BnB,MAAM,WAAW,4BAA4B;IAC3C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CACtB;AAED,8FAA8F;AAC9F,qBAAa,qBAAsB,YAAW,cAAc,CAAC,QAAQ,CAAC;IAwBlE,OAAO,CAAC,QAAQ,CAAC,OAAO;IAvB1B,QAAQ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