@prenta/realtime 0.2.0

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.
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Persistence interface + helpers for `@prenta/realtime`.
3
+ *
4
+ * A `DocumentPersistence` is responsible for loading a Yjs state vector for
5
+ * a room when it boots and writing the state back after edits. The interface
6
+ * is intentionally narrow — implementations may use Prisma, S3, Redis, the
7
+ * filesystem, or anything else.
8
+ *
9
+ * `bindPersistence(room, persistence)` wires the two together: it debounces
10
+ * writes (so we don't hammer the database on every keystroke), flushes on
11
+ * room destruction, and surfaces errors via the optional `onError` hook.
12
+ */
13
+ import * as Y from 'yjs';
14
+ const defaultTimer = {
15
+ setTimeout: (handler, ms) => setTimeout(handler, ms),
16
+ clearTimeout: (handle) => clearTimeout(handle),
17
+ };
18
+ /**
19
+ * Bind a `DocumentPersistence` to a `Room`. Returns a `flush` function that
20
+ * writes any pending state immediately (e.g. on graceful shutdown). The
21
+ * binding listens for Yjs `update` events on the room's doc and debounces
22
+ * writes to avoid hot loops during typing.
23
+ *
24
+ * The caller is responsible for tearing the binding down — pair `bindPersistence`
25
+ * with a `room.destroy()` and a final `await flush()`.
26
+ */
27
+ export function bindPersistence(room, persistence, opts = {}) {
28
+ const debounceMs = opts.debounceMs ?? 1000;
29
+ const maxIdleMs = opts.maxIdleMs ?? 5000;
30
+ const onError = opts.onError ?? defaultErrorHandler;
31
+ const timer = opts.timer ?? defaultTimer;
32
+ let pending = false;
33
+ let lastScheduledAt = 0;
34
+ let timerHandle = null;
35
+ let inflight = null;
36
+ const flush = async () => {
37
+ if (timerHandle !== null) {
38
+ timer.clearTimeout(timerHandle);
39
+ timerHandle = null;
40
+ }
41
+ if (!pending) {
42
+ if (inflight)
43
+ await inflight;
44
+ return;
45
+ }
46
+ pending = false;
47
+ const snapshot = Y.encodeStateAsUpdate(room.doc);
48
+ inflight = (async () => {
49
+ try {
50
+ await persistence.save(room.documentId, snapshot);
51
+ }
52
+ catch (err) {
53
+ onError(err);
54
+ }
55
+ })();
56
+ await inflight;
57
+ inflight = null;
58
+ };
59
+ const schedule = () => {
60
+ pending = true;
61
+ const now = Date.now();
62
+ if (timerHandle === null) {
63
+ lastScheduledAt = now;
64
+ }
65
+ const elapsedSinceFirst = now - lastScheduledAt;
66
+ const remainingBudget = Math.max(0, maxIdleMs - elapsedSinceFirst);
67
+ const delay = Math.min(debounceMs, remainingBudget);
68
+ if (timerHandle !== null) {
69
+ timer.clearTimeout(timerHandle);
70
+ }
71
+ timerHandle = timer.setTimeout(() => {
72
+ timerHandle = null;
73
+ void flush();
74
+ }, delay);
75
+ };
76
+ const onUpdate = (_update, _origin) => {
77
+ schedule();
78
+ };
79
+ room.doc.on('update', onUpdate);
80
+ const unbind = () => {
81
+ room.doc.off('update', onUpdate);
82
+ if (timerHandle !== null) {
83
+ timer.clearTimeout(timerHandle);
84
+ timerHandle = null;
85
+ }
86
+ };
87
+ return { flush, unbind };
88
+ }
89
+ /**
90
+ * Reference implementation backed by an in-memory `Map`. Useful for tests
91
+ * and for transports that don't need durable persistence. Stores a copy of
92
+ * the bytes (callers may mutate the original buffer after save).
93
+ */
94
+ export function createMemoryPersistence(initial) {
95
+ const store = new Map();
96
+ if (initial) {
97
+ for (const [id, bytes] of Object.entries(initial)) {
98
+ store.set(id, copyBytes(bytes));
99
+ }
100
+ }
101
+ return {
102
+ async load(documentId) {
103
+ const value = store.get(documentId);
104
+ return value ? copyBytes(value) : null;
105
+ },
106
+ async save(documentId, state) {
107
+ store.set(documentId, copyBytes(state));
108
+ },
109
+ };
110
+ }
111
+ function copyBytes(src) {
112
+ const dst = new Uint8Array(src.length);
113
+ dst.set(src);
114
+ return dst;
115
+ }
116
+ function defaultErrorHandler(err) {
117
+ // eslint-disable-next-line no-console
118
+ console.error('[@prenta/realtime] persistence save failed:', err);
119
+ }
120
+ //# sourceMappingURL=persistence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persistence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C,EAAE,GAAG,CAAC,CAAA;AACnE,CAAC"}
@@ -0,0 +1,52 @@
1
+ import * as awarenessProtocol from 'y-protocols/awareness';
2
+ import type * as Y from 'yjs';
3
+ export declare const MESSAGE_SYNC = 0;
4
+ export declare const MESSAGE_AWARENESS = 1;
5
+ export declare const MESSAGE_QUERY_AWARENESS = 3;
6
+ /** All recognized top-level message types. */
7
+ export type MessageType = typeof MESSAGE_SYNC | typeof MESSAGE_AWARENESS | typeof MESSAGE_QUERY_AWARENESS;
8
+ /** Result of reading an inbound message — describes any reply that must be sent. */
9
+ export interface ReadResult {
10
+ /** Optional reply bytes (already wrapped with the envelope). Empty if no reply. */
11
+ reply: Uint8Array | null;
12
+ /** The top-level message type that was decoded, or `null` for unknown. */
13
+ type: MessageType | null;
14
+ /** For sync messages, the sub-step that was processed. */
15
+ syncStep: 0 | 1 | 2 | null;
16
+ }
17
+ /**
18
+ * Read an inbound wire message and apply its side effects to `doc` / `awareness`.
19
+ *
20
+ * Returns reply bytes (already wrapped) that must be sent back to the peer,
21
+ * or `null` when no reply is needed. Throws on malformed envelopes; callers
22
+ * should catch and close the connection.
23
+ *
24
+ * `origin` is forwarded to Yjs transactions so applications can distinguish
25
+ * remote updates from local writes.
26
+ */
27
+ export declare function readMessage(message: Uint8Array, doc: Y.Doc, awareness: awarenessProtocol.Awareness, origin: unknown): ReadResult;
28
+ /**
29
+ * Encode a sync step 1 message (state vector) suitable for kicking off
30
+ * synchronization on a fresh connection.
31
+ */
32
+ export declare function encodeSyncStep1(doc: Y.Doc): Uint8Array;
33
+ /**
34
+ * Encode a sync step 2 message replying to a state vector. When `targetStateVector`
35
+ * is omitted the full document state is sent (useful for late joiners).
36
+ */
37
+ export declare function encodeSyncStep2(doc: Y.Doc, targetStateVector?: Uint8Array): Uint8Array;
38
+ /** Encode a sync update message wrapping a raw Yjs update. */
39
+ export declare function encodeUpdateMessage(update: Uint8Array): Uint8Array;
40
+ /**
41
+ * Encode an awareness update message for the given client IDs. Use this to
42
+ * broadcast presence changes to peers.
43
+ */
44
+ export declare function encodeAwarenessUpdate(awareness: awarenessProtocol.Awareness, clients: ReadonlyArray<number>): Uint8Array;
45
+ /** Encode a "send me your awareness state" request. */
46
+ export declare function encodeQueryAwareness(): Uint8Array;
47
+ /**
48
+ * Re-export the `Awareness` class so consumers don't have to add their own
49
+ * `y-protocols` import (and risk a version mismatch).
50
+ */
51
+ export { Awareness } from 'y-protocols/awareness';
52
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,iBAAiB,MAAM,uBAAuB,CAAA;AAE1D,OAAO,KAAK,KAAK,CAAC,MAAM,KAAK,CAAA;AAE7B,eAAO,MAAM,YAAY,IAAI,CAAA;AAC7B,eAAO,MAAM,iBAAiB,IAAI,CAAA;AAClC,eAAO,MAAM,uBAAuB,IAAI,CAAA;AAExC,8CAA8C;AAC9C,MAAM,MAAM,WAAW,GACnB,OAAO,YAAY,GACnB,OAAO,iBAAiB,GACxB,OAAO,uBAAuB,CAAA;AAElC,oFAAoF;AACpF,MAAM,WAAW,UAAU;IACzB,mFAAmF;IACnF,KAAK,EAAE,UAAU,GAAG,IAAI,CAAA;IACxB,0EAA0E;IAC1E,IAAI,EAAE,WAAW,GAAG,IAAI,CAAA;IACxB,0DAA0D;IAC1D,QAAQ,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,CAAA;CAC3B;AAED;;;;;;;;;GASG;AACH,wBAAgB,WAAW,CACzB,OAAO,EAAE,UAAU,EACnB,GAAG,EAAE,CAAC,CAAC,GAAG,EACV,SAAS,EAAE,iBAAiB,CAAC,SAAS,EACtC,MAAM,EAAE,OAAO,GACd,UAAU,CAoCZ;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,CAAC,CAAC,GAAG,GAAG,UAAU,CAKtD;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,iBAAiB,CAAC,EAAE,UAAU,GAAG,UAAU,CAKtF;AAED,8DAA8D;AAC9D,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,UAAU,GAAG,UAAU,CAKlE;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,iBAAiB,CAAC,SAAS,EACtC,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,GAC7B,UAAU,CAQZ;AAED,uDAAuD;AACvD,wBAAgB,oBAAoB,IAAI,UAAU,CAIjD;AAED;;;GAGG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAA"}
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Wire protocol for `@prenta/realtime`.
3
+ *
4
+ * The envelope is binary-compatible with the standard y-websocket protocol:
5
+ *
6
+ * [messageType: varUint][payload: bytes]
7
+ *
8
+ * - `MESSAGE_SYNC` (0) wraps a Yjs sync sub-message produced by
9
+ * `y-protocols/sync` (SyncStep1 / SyncStep2 / Update).
10
+ * - `MESSAGE_AWARENESS` (1) wraps an awareness update produced by
11
+ * `y-protocols/awareness#encodeAwarenessUpdate`.
12
+ * - `MESSAGE_QUERY_AWARENESS` (3) requests a fresh awareness snapshot from
13
+ * the remote peer.
14
+ *
15
+ * Keeping the envelope on the wire identical to y-websocket means existing
16
+ * browser providers (e.g. `y-websocket`'s `WebsocketProvider`) can connect
17
+ * to an Prenta realtime endpoint with no custom client code.
18
+ */
19
+ import * as decoding from 'lib0/decoding';
20
+ import * as encoding from 'lib0/encoding';
21
+ import * as awarenessProtocol from 'y-protocols/awareness';
22
+ import * as syncProtocol from 'y-protocols/sync';
23
+ export const MESSAGE_SYNC = 0;
24
+ export const MESSAGE_AWARENESS = 1;
25
+ export const MESSAGE_QUERY_AWARENESS = 3;
26
+ /**
27
+ * Read an inbound wire message and apply its side effects to `doc` / `awareness`.
28
+ *
29
+ * Returns reply bytes (already wrapped) that must be sent back to the peer,
30
+ * or `null` when no reply is needed. Throws on malformed envelopes; callers
31
+ * should catch and close the connection.
32
+ *
33
+ * `origin` is forwarded to Yjs transactions so applications can distinguish
34
+ * remote updates from local writes.
35
+ */
36
+ export function readMessage(message, doc, awareness, origin) {
37
+ if (message.length === 0) {
38
+ throw new Error('empty realtime message');
39
+ }
40
+ const decoder = decoding.createDecoder(message);
41
+ const encoder = encoding.createEncoder();
42
+ const messageType = decoding.readVarUint(decoder);
43
+ switch (messageType) {
44
+ case MESSAGE_SYNC: {
45
+ encoding.writeVarUint(encoder, MESSAGE_SYNC);
46
+ const syncStep = syncProtocol.readSyncMessage(decoder, encoder, doc, origin);
47
+ // Only send a reply if the sub-protocol actually wrote one.
48
+ const replyLen = encoding.length(encoder);
49
+ const reply = replyLen > 1 ? encoding.toUint8Array(encoder) : null;
50
+ return { reply, type: MESSAGE_SYNC, syncStep: syncStep };
51
+ }
52
+ case MESSAGE_AWARENESS: {
53
+ const update = decoding.readVarUint8Array(decoder);
54
+ awarenessProtocol.applyAwarenessUpdate(awareness, update, origin);
55
+ return { reply: null, type: MESSAGE_AWARENESS, syncStep: null };
56
+ }
57
+ case MESSAGE_QUERY_AWARENESS: {
58
+ const clients = Array.from(awareness.getStates().keys());
59
+ if (clients.length === 0) {
60
+ return { reply: null, type: MESSAGE_QUERY_AWARENESS, syncStep: null };
61
+ }
62
+ return {
63
+ reply: encodeAwarenessUpdate(awareness, clients),
64
+ type: MESSAGE_QUERY_AWARENESS,
65
+ syncStep: null,
66
+ };
67
+ }
68
+ default:
69
+ return { reply: null, type: null, syncStep: null };
70
+ }
71
+ }
72
+ /**
73
+ * Encode a sync step 1 message (state vector) suitable for kicking off
74
+ * synchronization on a fresh connection.
75
+ */
76
+ export function encodeSyncStep1(doc) {
77
+ const encoder = encoding.createEncoder();
78
+ encoding.writeVarUint(encoder, MESSAGE_SYNC);
79
+ syncProtocol.writeSyncStep1(encoder, doc);
80
+ return encoding.toUint8Array(encoder);
81
+ }
82
+ /**
83
+ * Encode a sync step 2 message replying to a state vector. When `targetStateVector`
84
+ * is omitted the full document state is sent (useful for late joiners).
85
+ */
86
+ export function encodeSyncStep2(doc, targetStateVector) {
87
+ const encoder = encoding.createEncoder();
88
+ encoding.writeVarUint(encoder, MESSAGE_SYNC);
89
+ syncProtocol.writeSyncStep2(encoder, doc, targetStateVector);
90
+ return encoding.toUint8Array(encoder);
91
+ }
92
+ /** Encode a sync update message wrapping a raw Yjs update. */
93
+ export function encodeUpdateMessage(update) {
94
+ const encoder = encoding.createEncoder();
95
+ encoding.writeVarUint(encoder, MESSAGE_SYNC);
96
+ syncProtocol.writeUpdate(encoder, update);
97
+ return encoding.toUint8Array(encoder);
98
+ }
99
+ /**
100
+ * Encode an awareness update message for the given client IDs. Use this to
101
+ * broadcast presence changes to peers.
102
+ */
103
+ export function encodeAwarenessUpdate(awareness, clients) {
104
+ const encoder = encoding.createEncoder();
105
+ encoding.writeVarUint(encoder, MESSAGE_AWARENESS);
106
+ encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, [...clients]));
107
+ return encoding.toUint8Array(encoder);
108
+ }
109
+ /** Encode a "send me your awareness state" request. */
110
+ export function encodeQueryAwareness() {
111
+ const encoder = encoding.createEncoder();
112
+ encoding.writeVarUint(encoder, MESSAGE_QUERY_AWARENESS);
113
+ return encoding.toUint8Array(encoder);
114
+ }
115
+ /**
116
+ * Re-export the `Awareness` class so consumers don't have to add their own
117
+ * `y-protocols` import (and risk a version mismatch).
118
+ */
119
+ export { Awareness } from 'y-protocols/awareness';
120
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,K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port-agnostic Yjs room.
3
+ *
4
+ * A `Room` owns a Yjs `Doc` and `Awareness` instance plus a set of
5
+ * `Connection` objects (the actual WebSocket / fetch-streaming / postMessage
6
+ * pipes live outside this package). Inbound bytes flow into `handleMessage`;
7
+ * the room produces outbound bytes via `Connection.send`.
8
+ *
9
+ * This module deliberately knows nothing about HTTP, WebSocket, or the
10
+ * surrounding server framework — it is just protocol mechanics. The
11
+ * cms-core slice (next PR) wraps a `Room` with an HTTP upgrade handler.
12
+ */
13
+ import { Awareness } from 'y-protocols/awareness';
14
+ import * as Y from 'yjs';
15
+ /**
16
+ * A live message pipe to a single peer. The transport layer (WebSocket /
17
+ * EventStream / etc.) creates one of these per connection and hands it to
18
+ * the room via `room.addConnection`.
19
+ */
20
+ export interface Connection {
21
+ /** Stable id for the connection (used to dedupe broadcasts and detach). */
22
+ readonly id: string;
23
+ /** Send a single binary frame to the peer. */
24
+ send(message: Uint8Array): void;
25
+ /** Close the connection. Implementations should be idempotent. */
26
+ close(reason?: string): void;
27
+ }
28
+ export interface RoomOptions {
29
+ /** Logical document id this room represents (used for persistence callbacks). */
30
+ documentId: string;
31
+ /** Optional initial document state (e.g. loaded from `DocumentCRDT`). */
32
+ initialState?: Uint8Array;
33
+ /** Disable Yjs garbage collection (set to `false` when storing history). */
34
+ gcEnabled?: boolean;
35
+ /**
36
+ * Called whenever the doc changes. The bytes are a delta (`encodeUpdate`),
37
+ * not the full state. Use `encodeStateAsUpdate(room.doc)` if you need a
38
+ * snapshot.
39
+ */
40
+ onUpdate?: (update: Uint8Array, origin: unknown) => void;
41
+ /** Called whenever awareness state changes (added / updated / removed client ids). */
42
+ onAwarenessChange?: (change: {
43
+ added: number[];
44
+ updated: number[];
45
+ removed: number[];
46
+ }, origin: unknown) => void;
47
+ }
48
+ /**
49
+ * A live Yjs collaboration room. Multiple `Connection`s may be attached; the
50
+ * room takes care of sync handshakes, update broadcasting, and awareness
51
+ * propagation between them.
52
+ */
53
+ export interface Room {
54
+ readonly documentId: string;
55
+ readonly doc: Y.Doc;
56
+ readonly awareness: Awareness;
57
+ readonly connections: ReadonlyMap<string, Connection>;
58
+ /** Add a connection. Triggers a sync step 1 + awareness snapshot to that peer. */
59
+ addConnection(conn: Connection): void;
60
+ /** Detach a connection and remove its awareness state. */
61
+ removeConnection(connId: string): void;
62
+ /** Process an inbound message from `connId`. Throws on malformed frames. */
63
+ handleMessage(connId: string, message: Uint8Array): void;
64
+ /** Send `message` to every connection except (optionally) one. */
65
+ broadcast(message: Uint8Array, exceptConnId?: string): void;
66
+ /** Tear down the room — releases the Yjs doc and clears listeners. */
67
+ destroy(): void;
68
+ }
69
+ /**
70
+ * Create a transport-agnostic Yjs collaboration room.
71
+ *
72
+ * Wiring guide:
73
+ * const room = createRoom({ documentId: 'doc_1', initialState })
74
+ * // when a new WebSocket connects:
75
+ * room.addConnection({ id, send, close })
76
+ * ws.onmessage = (frame) => room.handleMessage(id, frame.data)
77
+ * ws.onclose = () => room.removeConnection(id)
78
+ * room.destroy() // on shutdown
79
+ */
80
+ export declare function createRoom(opts: RoomOptions): Room;
81
+ /**
82
+ * Force-evict the given awareness clients from a room — useful when a
83
+ * connection dies without sending a graceful `null` state. Called by the
84
+ * transport layer in its disconnect handler when it can map conn → clientID.
85
+ */
86
+ export declare function removeAwarenessClients(room: Room, clientIds: ReadonlyArray<number>, origin?: unknown): void;
87
+ /** Origin tag used when applying the room's initial state on construction. */
88
+ export declare const ROOM_INIT_ORIGIN = "@prenta/realtime#init";
89
+ /** Origin tag used when tearing the room down. */
90
+ export declare const ROOM_DESTROY_ORIGIN = "@prenta/realtime#destroy";
91
+ /** Origin tag used when removing awareness for a force-disconnected client. */
92
+ export declare const ROOM_FORCE_LEAVE_ORIGIN = "@prenta/realtime#force-leave";
93
+ //# sourceMappingURL=room.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"room.d.ts","sourceRoot":"","sources":["../src/room.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OA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C,4EAA4E;IAC5E,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,GAAG,IAAI,CAAA;IACxD,kEAAkE;IAClE,SAAS,CAAC,OAAO,EAAE,UAAU,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC3D,sEAAsE;IACtE,OAAO,IAAI,IAAI,CAAA;CAChB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,WAAW,GAAG,IAAI,CAwIlD;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,IAAI,EACV,SAAS,EAAE,aAAa,CAAC,MAAM,CAAC,EAChC,MAAM,GAAE,OAAiC,GACxC,IAAI,CAGN;AAED,8EAA8E;AAC9E,eAAO,MAAM,gBAAgB,0BAA0B,CAAA;AACvD,kDAAkD;AAClD,eAAO,MAAM,mBAAmB,6BAA6B,CAAA;AAC7D,+EAA+E;AAC/E,eAAO,MAAM,uBAAuB,iCAAiC,CAAA"}
package/dist/room.js ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Transport-agnostic Yjs room.
3
+ *
4
+ * A `Room` owns a Yjs `Doc` and `Awareness` instance plus a set of
5
+ * `Connection` objects (the actual WebSocket / fetch-streaming / postMessage
6
+ * pipes live outside this package). Inbound bytes flow into `handleMessage`;
7
+ * the room produces outbound bytes via `Connection.send`.
8
+ *
9
+ * This module deliberately knows nothing about HTTP, WebSocket, or the
10
+ * surrounding server framework — it is just protocol mechanics. The
11
+ * cms-core slice (next PR) wraps a `Room` with an HTTP upgrade handler.
12
+ */
13
+ import { Awareness, removeAwarenessStates } from 'y-protocols/awareness';
14
+ import * as Y from 'yjs';
15
+ import { encodeAwarenessUpdate, encodeSyncStep1, encodeUpdateMessage, readMessage, } from './protocol.js';
16
+ /**
17
+ * Create a transport-agnostic Yjs collaboration room.
18
+ *
19
+ * Wiring guide:
20
+ * const room = createRoom({ documentId: 'doc_1', initialState })
21
+ * // when a new WebSocket connects:
22
+ * room.addConnection({ id, send, close })
23
+ * ws.onmessage = (frame) => room.handleMessage(id, frame.data)
24
+ * ws.onclose = () => room.removeConnection(id)
25
+ * room.destroy() // on shutdown
26
+ */
27
+ export function createRoom(opts) {
28
+ const doc = new Y.Doc({ gc: opts.gcEnabled ?? true });
29
+ doc.clientID = makeClientId();
30
+ if (opts.initialState && opts.initialState.length > 0) {
31
+ Y.applyUpdate(doc, opts.initialState, ROOM_INIT_ORIGIN);
32
+ }
33
+ const awareness = new Awareness(doc);
34
+ // Server-side has no local presence; only relays peer state.
35
+ awareness.setLocalState(null);
36
+ const connections = new Map();
37
+ function broadcast(message, exceptConnId) {
38
+ for (const conn of connections.values()) {
39
+ if (conn.id === exceptConnId)
40
+ continue;
41
+ try {
42
+ conn.send(message);
43
+ }
44
+ catch {
45
+ // Ignore — transport will surface the failure via its own close path.
46
+ }
47
+ }
48
+ }
49
+ // Forward every Yjs update to every connection (except the connection that
50
+ // produced it, which we identify via the `origin` we set in `handleMessage`).
51
+ const docUpdateListener = (update, origin) => {
52
+ const message = encodeUpdateMessage(update);
53
+ const exceptId = typeof origin === 'string' && origin.startsWith(CONN_ORIGIN_PREFIX)
54
+ ? origin.slice(CONN_ORIGIN_PREFIX.length)
55
+ : undefined;
56
+ broadcast(message, exceptId);
57
+ opts.onUpdate?.(update, origin);
58
+ };
59
+ doc.on('update', docUpdateListener);
60
+ // Forward awareness changes to every connection (so each peer learns about
61
+ // the others). We do NOT scope by origin here: y-websocket's reference
62
+ // implementation broadcasts to everyone including the originator, since
63
+ // the originator already has the state and applying it is a no-op.
64
+ const awarenessChangeListener = (change, origin) => {
65
+ const changedClients = [...change.added, ...change.updated, ...change.removed];
66
+ if (changedClients.length > 0) {
67
+ const message = encodeAwarenessUpdate(awareness, changedClients);
68
+ broadcast(message);
69
+ }
70
+ opts.onAwarenessChange?.(change, origin);
71
+ };
72
+ awareness.on('update', awarenessChangeListener);
73
+ return {
74
+ documentId: opts.documentId,
75
+ doc,
76
+ awareness,
77
+ get connections() {
78
+ return connections;
79
+ },
80
+ addConnection(conn) {
81
+ if (connections.has(conn.id)) {
82
+ throw new Error(`connection ${conn.id} is already in room ${opts.documentId}`);
83
+ }
84
+ connections.set(conn.id, conn);
85
+ // 1. Initiate the sync handshake (server sends SyncStep1; client replies
86
+ // with SyncStep2 + its own SyncStep1; we reply with SyncStep2).
87
+ try {
88
+ conn.send(encodeSyncStep1(doc));
89
+ }
90
+ catch {
91
+ connections.delete(conn.id);
92
+ return;
93
+ }
94
+ // 2. Send the current awareness snapshot so the new peer sees who else is here.
95
+ const states = awareness.getStates();
96
+ if (states.size > 0) {
97
+ const clients = Array.from(states.keys());
98
+ try {
99
+ conn.send(encodeAwarenessUpdate(awareness, clients));
100
+ }
101
+ catch {
102
+ // Connection broke during snapshot send — leave it in the map for
103
+ // now; the transport's close handler will call `removeConnection`.
104
+ }
105
+ }
106
+ },
107
+ removeConnection(connId) {
108
+ const conn = connections.get(connId);
109
+ if (!conn)
110
+ return;
111
+ connections.delete(connId);
112
+ // Remove any awareness state tagged with this connection. The room
113
+ // doesn't track conn -> clientID mapping itself; callers are expected
114
+ // to call `awareness.setLocalState(null)` from the client when leaving
115
+ // gracefully. As a safety net we expose `removeAwarenessClients` below.
116
+ },
117
+ handleMessage(connId, message) {
118
+ const conn = connections.get(connId);
119
+ if (!conn) {
120
+ throw new Error(`no connection ${connId} in room ${opts.documentId}`);
121
+ }
122
+ const result = readMessage(message, doc, awareness, `${CONN_ORIGIN_PREFIX}${connId}`);
123
+ if (result.reply) {
124
+ try {
125
+ conn.send(result.reply);
126
+ }
127
+ catch {
128
+ // ignore — transport will close
129
+ }
130
+ }
131
+ },
132
+ broadcast,
133
+ destroy() {
134
+ doc.off('update', docUpdateListener);
135
+ awareness.off('update', awarenessChangeListener);
136
+ // Forcefully evict every awareness client so any persistence hooks see
137
+ // a clean leave for each one.
138
+ const clientIds = Array.from(awareness.getStates().keys());
139
+ if (clientIds.length > 0) {
140
+ removeAwarenessStates(awareness, clientIds, ROOM_DESTROY_ORIGIN);
141
+ }
142
+ for (const conn of connections.values()) {
143
+ try {
144
+ conn.close('room destroyed');
145
+ }
146
+ catch {
147
+ // ignore
148
+ }
149
+ }
150
+ connections.clear();
151
+ doc.destroy();
152
+ },
153
+ };
154
+ }
155
+ /**
156
+ * Force-evict the given awareness clients from a room — useful when a
157
+ * connection dies without sending a graceful `null` state. Called by the
158
+ * transport layer in its disconnect handler when it can map conn → clientID.
159
+ */
160
+ export function removeAwarenessClients(room, clientIds, origin = ROOM_FORCE_LEAVE_ORIGIN) {
161
+ if (clientIds.length === 0)
162
+ return;
163
+ removeAwarenessStates(room.awareness, [...clientIds], origin);
164
+ }
165
+ /** Origin tag used when applying the room's initial state on construction. */
166
+ export const ROOM_INIT_ORIGIN = '@prenta/realtime#init';
167
+ /** Origin tag used when tearing the room down. */
168
+ export const ROOM_DESTROY_ORIGIN = '@prenta/realtime#destroy';
169
+ /** Origin tag used when removing awareness for a force-disconnected client. */
170
+ export const ROOM_FORCE_LEAVE_ORIGIN = '@prenta/realtime#force-leave';
171
+ const CONN_ORIGIN_PREFIX = 'conn:';
172
+ /**
173
+ * Generate a stable-ish client id for the server-side Yjs doc. We can't use
174
+ * the default (random) client id reliably across reconnects because the room
175
+ * is the single source of truth for the document — keeping it at a known
176
+ * constant per room makes "server-originated" updates easy to recognise in
177
+ * `origin` callbacks (they will all share this id).
178
+ *
179
+ * The actual value is derived from `Date.now()` xor'd with a counter so the
180
+ * value still avoids collisions across rooms within the same process.
181
+ */
182
+ let __clientIdCounter = 0;
183
+ function makeClientId() {
184
+ __clientIdCounter = (__clientIdCounter + 1) >>> 0;
185
+ const stamp = Date.now() & 0xffffffff;
186
+ // Yjs treats clientID as unsigned 32-bit.
187
+ return (stamp ^ (__clientIdCounter * 2654435761)) >>> 0;
188
+ }
189
+ //# sourceMappingURL=room.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"room.js","sourceRoot":"","sources":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