@vite-hub/realtime 0.0.3

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.
package/dist/server.js ADDED
@@ -0,0 +1,859 @@
1
+ import { _ as updateYFragment, c as realtimeSyncPendingCode, n as decodeWorkspaceChangePayload, o as readAwarenessClientIds, p as prosemirrorJSONToYDoc, r as encodeWorkspaceChange, s as realtimeCheckpointRejectedCode, t as createRealtimeEditorExtensions, u as createRealtimeIdentity, v as yDocToProsemirrorJSON } from "./editor-extensions-CZEzrJ-t.js";
2
+ import { Editor } from "@tiptap/core";
3
+ import * as Y from "yjs";
4
+ import * as awarenessProtocol from "y-protocols/awareness";
5
+ import { assertAuthOrigin } from "@vite-hub/auth/server";
6
+ import { isWorkspaceConflict, normalizeSafeWorkspacePath, resolveWorkspaceStoreTarget, useWorkspace } from "@vite-hub/workspace";
7
+ import { HTTPError, defineEventHandler, defineWebSocketHandler } from "h3";
8
+ import * as decoding from "lib0/decoding";
9
+ import * as encoding from "lib0/encoding";
10
+ import * as syncProtocol from "y-protocols/sync";
11
+ //#region src/server.ts
12
+ const routePrefix = "/api/_vitehub/realtime/";
13
+ const maxMessageBytes = 1024 * 1024;
14
+ const maxRoomStateBytes = 8 * 1024 * 1024;
15
+ const maxRoomAwarenessBytes = 8 * 1024 * 1024;
16
+ const maxMemoryRooms = 128;
17
+ const awarenessQueryIntervalMs = 1e4;
18
+ const awarenessUpdateIntervalMs = 50;
19
+ const workspaceChangeLimit = 100;
20
+ const workspaceChangeWindowMs = 1e3;
21
+ const syncUpdateIntervalMs = 50;
22
+ const pendingCheckpointRetentionMs = 3e4;
23
+ const durableUpdateCompactionInterval = 128;
24
+ const messageSync = 0;
25
+ const fragmentName = "default";
26
+ function markdownToYDoc(markdown) {
27
+ const editor = new Editor({
28
+ content: markdown || {
29
+ type: "doc",
30
+ content: [{ type: "paragraph" }]
31
+ },
32
+ contentType: "markdown",
33
+ extensions: createRealtimeEditorExtensions()
34
+ });
35
+ try {
36
+ return prosemirrorJSONToYDoc(editor.schema, editor.getJSON(), fragmentName);
37
+ } finally {
38
+ editor.destroy();
39
+ }
40
+ }
41
+ function yDocToMarkdown(document) {
42
+ const editor = new Editor({
43
+ content: yDocToProsemirrorJSON(document, fragmentName),
44
+ extensions: createRealtimeEditorExtensions()
45
+ });
46
+ try {
47
+ return editor.getMarkdown();
48
+ } finally {
49
+ editor.destroy();
50
+ }
51
+ }
52
+ function replaceRealtimeDocument(document, markdown) {
53
+ const editor = new Editor({
54
+ content: markdown || {
55
+ type: "doc",
56
+ content: [{ type: "paragraph" }]
57
+ },
58
+ contentType: "markdown",
59
+ extensions: createRealtimeEditorExtensions()
60
+ });
61
+ const state = Y.encodeStateVector(document);
62
+ try {
63
+ updateYFragment(document, document.getXmlFragment(fragmentName), editor.state.doc, {
64
+ isOMark: /* @__PURE__ */ new Map(),
65
+ mapping: /* @__PURE__ */ new Map()
66
+ });
67
+ return Y.encodeStateAsUpdate(document, state);
68
+ } finally {
69
+ editor.destroy();
70
+ }
71
+ }
72
+ function claimAwarenessClientIds(owners, peer, clients) {
73
+ for (const client of clients) {
74
+ const owner = owners.get(client);
75
+ if (owner && owner !== peer) throw new AwarenessOwnershipConflict();
76
+ }
77
+ const ownedClients = new Set([...owners].filter(([, owner]) => owner === peer).map(([client]) => client));
78
+ for (const client of clients) ownedClients.add(client);
79
+ if (ownedClients.size > 1024) throw new TypeError("Peer owns too many awareness clients.");
80
+ const claimed = clients.filter((client) => !owners.has(client));
81
+ for (const client of clients) owners.set(client, peer);
82
+ return claimed;
83
+ }
84
+ function realtimeRoomKey(definitionName, documentId) {
85
+ return JSON.stringify([definitionName, documentId]);
86
+ }
87
+ var AwarenessOwnershipConflict = class extends TypeError {
88
+ constructor() {
89
+ super("Awareness client id is already owned by another peer.");
90
+ }
91
+ };
92
+ function bindAwarenessIdentity(update, identity) {
93
+ return awarenessProtocol.modifyAwarenessUpdate(update, (state) => {
94
+ if (state === null) return null;
95
+ if (!state || typeof state !== "object" || Array.isArray(state)) throw new TypeError("Invalid awareness state.");
96
+ return {
97
+ ...state,
98
+ user: identity
99
+ };
100
+ });
101
+ }
102
+ async function writeRealtimeDocument(workspace, documentId, document, ifDigest) {
103
+ const current = ifDigest ? await workspace.fs.stat(documentId) : void 0;
104
+ return await workspace.fs.writeFile(documentId, yDocToMarkdown(document), {
105
+ ifDigest,
106
+ mediaType: current?.mediaType,
107
+ metadata: current?.metadata,
108
+ preservePath: true
109
+ });
110
+ }
111
+ async function readRealtimeCheckpointState(request, maxBytes = maxRoomStateBytes) {
112
+ if (Number(request.headers.get("content-length") || 0) > maxBytes) throw new HTTPError({
113
+ status: 413,
114
+ message: "Realtime checkpoint state exceeds 8 MiB."
115
+ });
116
+ if (!request.body) return new Uint8Array();
117
+ const reader = request.body.getReader();
118
+ const chunks = [];
119
+ let byteLength = 0;
120
+ try {
121
+ while (true) {
122
+ const { done, value } = await reader.read();
123
+ if (done) break;
124
+ byteLength += value.byteLength;
125
+ if (byteLength > maxBytes) {
126
+ await reader.cancel();
127
+ throw new HTTPError({
128
+ status: 413,
129
+ message: "Realtime checkpoint state exceeds 8 MiB."
130
+ });
131
+ }
132
+ chunks.push(value);
133
+ }
134
+ } finally {
135
+ reader.releaseLock();
136
+ }
137
+ const state = new Uint8Array(byteLength);
138
+ let offset = 0;
139
+ for (const chunk of chunks) {
140
+ state.set(chunk, offset);
141
+ offset += chunk.byteLength;
142
+ }
143
+ return state;
144
+ }
145
+ function encodeSyncUpdate(update) {
146
+ const encoder = encoding.createEncoder();
147
+ encoding.writeVarUint(encoder, messageSync);
148
+ syncProtocol.writeUpdate(encoder, update);
149
+ return encoding.toUint8Array(encoder);
150
+ }
151
+ function encodeSyncStep1(document) {
152
+ const encoder = encoding.createEncoder();
153
+ encoding.writeVarUint(encoder, messageSync);
154
+ syncProtocol.writeSyncStep1(encoder, document);
155
+ return encoding.toUint8Array(encoder);
156
+ }
157
+ function matchesRealtimeState(document, expected) {
158
+ return matchesBytes(Y.encodeStateAsUpdate(document), expected);
159
+ }
160
+ function applyRealtimeSyncMessage(data, document, origin, maxStateBytes = maxRoomStateBytes) {
161
+ const apply = (target) => {
162
+ const decoder = decoding.createDecoder(data);
163
+ decoding.readVarUint(decoder);
164
+ const encoder = encoding.createEncoder();
165
+ encoding.writeVarUint(encoder, messageSync);
166
+ syncProtocol.readSyncMessage(decoder, encoder, target, origin);
167
+ return encoding.length(encoder) > 1 ? encoding.toUint8Array(encoder) : void 0;
168
+ };
169
+ const messageDecoder = decoding.createDecoder(data);
170
+ decoding.readVarUint(messageDecoder);
171
+ if (decoding.readVarUint(messageDecoder) === 0) return apply(document);
172
+ const candidate = new Y.Doc();
173
+ Y.applyUpdate(candidate, Y.encodeStateAsUpdate(document));
174
+ apply(candidate);
175
+ const stateBytes = Y.encodeStateAsUpdate(candidate).byteLength;
176
+ candidate.destroy();
177
+ if (stateBytes > maxStateBytes) throw new Error("Realtime document exceeds its 8 MiB room quota.");
178
+ return apply(document);
179
+ }
180
+ function assertRealtimeRoomStateQuota(document, maxStateBytes = maxRoomStateBytes) {
181
+ if (Y.encodeStateAsUpdate(document).byteLength > maxStateBytes) throw new HTTPError({
182
+ status: 413,
183
+ message: "Realtime document exceeds its 8 MiB room quota."
184
+ });
185
+ }
186
+ function applyRealtimeAwarenessUpdate(awareness, update, origin, maxStateBytes = maxRoomAwarenessBytes) {
187
+ const candidateDocument = new Y.Doc();
188
+ const candidate = new awarenessProtocol.Awareness(candidateDocument);
189
+ candidate.setLocalState(null);
190
+ const currentClients = [...awareness.getStates().keys()];
191
+ if (currentClients.length) awarenessProtocol.applyAwarenessUpdate(candidate, awarenessProtocol.encodeAwarenessUpdate(awareness, currentClients), origin);
192
+ awarenessProtocol.applyAwarenessUpdate(candidate, update, origin);
193
+ const candidateClients = [...candidate.getStates().keys()];
194
+ const stateBytes = candidateClients.length ? awarenessProtocol.encodeAwarenessUpdate(candidate, candidateClients).byteLength : 0;
195
+ candidate.destroy();
196
+ candidateDocument.destroy();
197
+ if (stateBytes > maxStateBytes) throw new Error("Realtime awareness exceeds its 8 MiB room quota.");
198
+ awarenessProtocol.applyAwarenessUpdate(awareness, update, origin);
199
+ }
200
+ function compactRealtimeAwareness(awareness) {
201
+ const clients = [...awareness.getStates().keys()];
202
+ const update = clients.length ? awarenessProtocol.encodeAwarenessUpdate(awareness, clients) : void 0;
203
+ const compacted = new awarenessProtocol.Awareness(awareness.doc);
204
+ compacted.setLocalState(null);
205
+ if (update) awarenessProtocol.applyAwarenessUpdate(compacted, update, "compaction");
206
+ awareness.destroy();
207
+ return compacted;
208
+ }
209
+ function matchesBytes(actual, expected) {
210
+ return !!actual && actual.length === expected.length && actual.every((byte, index) => byte === expected[index]);
211
+ }
212
+ function storedUpdate(value) {
213
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
214
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
215
+ }
216
+ function restoreRealtimeDocument(markdown, baselineDigest, stored) {
217
+ const update = storedUpdate(stored?.update_blob);
218
+ const storedDigest = typeof stored?.baseline_digest === "string" ? stored.baseline_digest : void 0;
219
+ if (!update || storedDigest !== baselineDigest) return markdownToYDoc(markdown);
220
+ const document = new Y.Doc();
221
+ Y.applyUpdate(document, update);
222
+ return document;
223
+ }
224
+ function canRestoreRealtimeDocument(baselineDigest, stored) {
225
+ const storedDigest = typeof stored?.baseline_digest === "string" ? stored.baseline_digest : void 0;
226
+ return !!storedUpdate(stored?.update_blob) && storedDigest === baselineDigest;
227
+ }
228
+ async function readRealtimeWorkspaceDocument(readable, writable, documentId) {
229
+ const stat = () => writable.fs.stat(documentId);
230
+ for (let attempt = 0; attempt < 3; attempt++) {
231
+ const before = await stat();
232
+ let markdown = "";
233
+ const source = await readable.fs.exists(documentId) ? readable.fs : before ? writable.fs : void 0;
234
+ if (source) try {
235
+ markdown = await source.readFile(documentId, { encoding: "utf8" });
236
+ } catch (error) {
237
+ if (!await stat()) continue;
238
+ throw error;
239
+ }
240
+ const after = await stat();
241
+ if (before?.digest === after?.digest) return {
242
+ baselineDigest: after?.digest,
243
+ markdown
244
+ };
245
+ }
246
+ throw new HTTPError({
247
+ status: 409,
248
+ message: "The Workspace document changed while opening its realtime room."
249
+ });
250
+ }
251
+ function encodeAwarenessState(awareness, clients) {
252
+ const encoder = encoding.createEncoder();
253
+ encoding.writeVarUint(encoder, 1);
254
+ encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, clients));
255
+ return encoding.toUint8Array(encoder);
256
+ }
257
+ function parseRoomPath(url) {
258
+ const parsed = new URL(url);
259
+ const path = parsed.pathname;
260
+ if (!path.startsWith(routePrefix)) throw new HTTPError({ status: 404 });
261
+ let parts;
262
+ try {
263
+ parts = path.slice(23).split("/").map(decodeURIComponent);
264
+ } catch {
265
+ throw new HTTPError({
266
+ status: 400,
267
+ message: "Realtime route components must be valid URL encoding."
268
+ });
269
+ }
270
+ const [definitionName, ...documentParts] = parts;
271
+ if (!definitionName || documentParts.length === 0 || documentParts.some((part) => !part)) throw new HTTPError({
272
+ status: 400,
273
+ message: "Realtime definition and document path are required."
274
+ });
275
+ const documentId = documentParts.join("/");
276
+ try {
277
+ if (normalizeSafeWorkspacePath(documentId) !== documentId) throw new Error();
278
+ } catch {
279
+ throw new HTTPError({
280
+ status: 400,
281
+ message: "Realtime document paths must be safe Workspace paths."
282
+ });
283
+ }
284
+ return {
285
+ definitionName,
286
+ documentId,
287
+ workspaceEvents: parsed.searchParams.get("workspace") === "events"
288
+ };
289
+ }
290
+ async function authorize(request, required, event) {
291
+ if (!required) return;
292
+ let auth;
293
+ try {
294
+ auth = await assertAuthOrigin(request, event);
295
+ } catch {
296
+ throw new HTTPError({ status: 403 });
297
+ }
298
+ const session = await auth.api.getSession({ headers: request.headers });
299
+ if (!session?.user) throw new HTTPError({ status: 401 });
300
+ return createRealtimeIdentity(session.user);
301
+ }
302
+ function createRealtimeHandler(registry) {
303
+ const inactiveMemoryRoomKeys = /* @__PURE__ */ new Set();
304
+ const memoryRoomKeys = /* @__PURE__ */ new Set();
305
+ const rooms = /* @__PURE__ */ new Map();
306
+ const peerAwarenessClients = /* @__PURE__ */ new WeakMap();
307
+ const peerAwarenessQueryAt = /* @__PURE__ */ new WeakMap();
308
+ const peerAwarenessUpdateAt = /* @__PURE__ */ new WeakMap();
309
+ const peerPendingAwareness = /* @__PURE__ */ new WeakMap();
310
+ const peerWorkspaceChanges = /* @__PURE__ */ new WeakMap();
311
+ const peerInitialSyncStep2 = /* @__PURE__ */ new WeakSet();
312
+ const peerSyncUpdateAt = /* @__PURE__ */ new WeakMap();
313
+ const workspaceCheckpointQueues = /* @__PURE__ */ new Map();
314
+ async function serializeWorkspaceCheckpoint(workspaceName, operation) {
315
+ const previous = workspaceCheckpointQueues.get(workspaceName) || Promise.resolve();
316
+ let release;
317
+ const current = new Promise((resolve) => {
318
+ release = resolve;
319
+ });
320
+ workspaceCheckpointQueues.set(workspaceName, current);
321
+ await previous;
322
+ try {
323
+ return await operation();
324
+ } finally {
325
+ release();
326
+ if (workspaceCheckpointQueues.get(workspaceName) === current) workspaceCheckpointQueues.delete(workspaceName);
327
+ }
328
+ }
329
+ async function refreshWritableWorkspace(workspaceName) {
330
+ return useWorkspace(workspaceName, { mode: "write" });
331
+ }
332
+ function resolveCloudflare(event) {
333
+ const runtime = event.req.runtime?.cloudflare;
334
+ const platform = event.context._platform?.cloudflare;
335
+ if (!runtime) return platform;
336
+ if (!platform) return runtime;
337
+ return {
338
+ ...runtime,
339
+ ...platform,
340
+ context: runtime.context ?? platform.context,
341
+ env: platform.env ?? runtime.env
342
+ };
343
+ }
344
+ async function forwardToCloudflareDurableObject(event) {
345
+ const cloudflare = resolveCloudflare(event);
346
+ const context = cloudflare?.context;
347
+ const binding = (cloudflare?.env)?.$DurableObject;
348
+ if (!binding || typeof context === "object" && context !== null && "storage" in context) return;
349
+ const { definitionName, documentId, workspaceEvents } = parseRoomPath(event.req.url);
350
+ const key = workspaceEvents ? JSON.stringify([definitionName, { workspaceEvents: true }]) : realtimeRoomKey(definitionName, documentId);
351
+ return await binding.get(binding.idFromName(key)).fetch(event.req);
352
+ }
353
+ function resolveRealtimeRoomSql(event) {
354
+ return (resolveCloudflare(event)?.context)?.storage?.sql;
355
+ }
356
+ async function getDefinition(definitionName) {
357
+ const module = await (Object.hasOwn(registry, definitionName) ? registry[definitionName] : void 0)?.();
358
+ if (!module) throw new HTTPError({
359
+ status: 404,
360
+ message: `Unknown realtime definition ${JSON.stringify(definitionName)}.`
361
+ });
362
+ return module.default;
363
+ }
364
+ async function getRoom(definitionName, documentId, definition, sql, workspaceEvents = false) {
365
+ const key = workspaceEvents ? JSON.stringify([definitionName, { workspaceEvents: true }]) : realtimeRoomKey(definitionName, documentId);
366
+ let room = rooms.get(key);
367
+ if (!room) {
368
+ if (!sql && memoryRoomKeys.size >= maxMemoryRooms) {
369
+ const inactiveKey = inactiveMemoryRoomKeys.values().next().value;
370
+ const inactiveRoom = inactiveKey ? await rooms.get(inactiveKey) : void 0;
371
+ if (inactiveRoom && inactiveKey && inactiveMemoryRoomKeys.has(inactiveKey) && inactiveRoom.peers.size === 0 && !inactiveRoom.mutated && !inactiveRoom.checkpoint && !inactiveRoom.pendingCheckpoint) destroyRoom(inactiveRoom);
372
+ if (memoryRoomKeys.size >= maxMemoryRooms) throw new HTTPError({
373
+ status: 503,
374
+ message: "The in-memory realtime authority reached its active room limit."
375
+ });
376
+ }
377
+ if (!sql) memoryRoomKeys.add(key);
378
+ room = (async () => {
379
+ const workspaceDocument = !workspaceEvents;
380
+ const workspace = workspaceDocument ? useWorkspace(definition.document.workspace) : void 0;
381
+ const writableWorkspace = workspaceDocument ? useWorkspace(definition.document.workspace, { mode: "write" }) : void 0;
382
+ const initial = workspace && writableWorkspace ? await readRealtimeWorkspaceDocument(workspace, writableWorkspace, documentId) : {
383
+ baselineDigest: void 0,
384
+ markdown: ""
385
+ };
386
+ if (workspaceDocument && sql) {
387
+ sql.exec("CREATE TABLE IF NOT EXISTS vitehub_realtime_rooms (room_key TEXT PRIMARY KEY, baseline_digest TEXT, update_blob BLOB NOT NULL)");
388
+ sql.exec("CREATE TABLE IF NOT EXISTS vitehub_realtime_updates (sequence INTEGER PRIMARY KEY AUTOINCREMENT, room_key TEXT NOT NULL, update_blob BLOB NOT NULL)");
389
+ }
390
+ const stored = workspaceDocument && sql ? sql.exec("SELECT baseline_digest, update_blob FROM vitehub_realtime_rooms WHERE room_key = ?", key).toArray()[0] : void 0;
391
+ const restoresStoredDocument = workspaceDocument && canRestoreRealtimeDocument(initial.baselineDigest, stored);
392
+ const document = workspaceDocument ? restoreRealtimeDocument(initial.markdown, initial.baselineDigest, stored) : new Y.Doc();
393
+ const storedUpdates = restoresStoredDocument && sql ? sql.exec("SELECT update_blob FROM vitehub_realtime_updates WHERE room_key = ? ORDER BY sequence", key).toArray() : [];
394
+ for (const row of storedUpdates) {
395
+ const update = storedUpdate(row.update_blob);
396
+ if (update) Y.applyUpdate(document, update);
397
+ }
398
+ assertRealtimeRoomStateQuota(document);
399
+ const awareness = new awarenessProtocol.Awareness(document);
400
+ awareness.setLocalState(null);
401
+ const value = {
402
+ awareness,
403
+ awarenessClientOwners: /* @__PURE__ */ new Map(),
404
+ baselineDigest: initial.baselineDigest,
405
+ channel: `vitehub:realtime:${key}`,
406
+ document,
407
+ durableReady: !!sql || !!initial.baselineDigest,
408
+ key,
409
+ mutated: false,
410
+ peers: /* @__PURE__ */ new Set(),
411
+ persistedUpdates: storedUpdates.length,
412
+ sql: workspaceDocument ? sql : void 0
413
+ };
414
+ value.document.on("update", (update, origin) => {
415
+ value.mutated = true;
416
+ persistRoomUpdate(value, update);
417
+ if (origin && typeof origin === "object" && "publish" in origin) origin.publish(value.channel, encodeSyncUpdate(update));
418
+ });
419
+ if (value.sql && !restoresStoredDocument) persistRoom(value);
420
+ return value;
421
+ })();
422
+ rooms.set(key, room);
423
+ room.catch(() => {
424
+ rooms.delete(key);
425
+ inactiveMemoryRoomKeys.delete(key);
426
+ memoryRoomKeys.delete(key);
427
+ });
428
+ }
429
+ const value = await room;
430
+ inactiveMemoryRoomKeys.delete(key);
431
+ return value;
432
+ }
433
+ function persistRoom(room) {
434
+ if (!room.sql || !room.durableReady) return;
435
+ room.sql.exec("INSERT OR REPLACE INTO vitehub_realtime_rooms (room_key, baseline_digest, update_blob) VALUES (?, ?, ?)", room.key, room.baselineDigest ?? null, Uint8Array.from(Y.encodeStateAsUpdate(room.document)).buffer);
436
+ room.sql.exec("DELETE FROM vitehub_realtime_updates WHERE room_key = ?", room.key);
437
+ room.persistedUpdates = 0;
438
+ }
439
+ function persistRoomUpdate(room, update) {
440
+ if (!room.sql || !room.durableReady) return;
441
+ room.sql.exec("INSERT INTO vitehub_realtime_updates (room_key, update_blob) VALUES (?, ?)", room.key, Uint8Array.from(update).buffer);
442
+ room.persistedUpdates++;
443
+ if (room.persistedUpdates >= durableUpdateCompactionInterval) persistRoom(room);
444
+ }
445
+ function evictRoom(room) {
446
+ if (room.peers.size > 0 || room.checkpoint || room.pendingCheckpoint) return;
447
+ if (!room.sql) {
448
+ if (room.mutated) return;
449
+ inactiveMemoryRoomKeys.delete(room.key);
450
+ inactiveMemoryRoomKeys.add(room.key);
451
+ return;
452
+ }
453
+ destroyRoom(room);
454
+ }
455
+ function destroyRoom(room) {
456
+ room.awareness.destroy();
457
+ room.document.destroy();
458
+ rooms.delete(room.key);
459
+ inactiveMemoryRoomKeys.delete(room.key);
460
+ memoryRoomKeys.delete(room.key);
461
+ }
462
+ function clearPendingCheckpoint(room, pending) {
463
+ if (room.pendingCheckpoint !== pending) return;
464
+ room.pendingCheckpoint = void 0;
465
+ if (room.pendingCheckpointTimer) clearTimeout(room.pendingCheckpointTimer);
466
+ room.pendingCheckpointTimer = void 0;
467
+ pending.submittedDocument.destroy();
468
+ }
469
+ function reconcilePendingCheckpoint(room, pending, content) {
470
+ if (content === yDocToMarkdown(pending.submittedDocument)) return;
471
+ const update = replaceRealtimeDocument(pending.submittedDocument, content);
472
+ Y.applyUpdate(room.document, update);
473
+ if (update.byteLength > 0) {
474
+ const message = encodeSyncUpdate(update);
475
+ for (const peer of room.peers) peer.send(message);
476
+ }
477
+ }
478
+ async function recoverPendingCheckpoint(room, pending) {
479
+ const current = await readRealtimeWorkspaceDocument(pending.workspace, pending.workspace, pending.path);
480
+ room.baselineDigest = current.baselineDigest;
481
+ room.durableReady = !!room.sql || !!room.baselineDigest;
482
+ reconcilePendingCheckpoint(room, pending, current.markdown);
483
+ persistRoom(room);
484
+ clearPendingCheckpoint(room, pending);
485
+ }
486
+ function schedulePendingCheckpointExpiry(room, pending) {
487
+ if (room.pendingCheckpoint !== pending || room.pendingCheckpointTimer) return;
488
+ const expire = () => {
489
+ room.pendingCheckpointTimer = void 0;
490
+ (async () => {
491
+ try {
492
+ await recoverPendingCheckpoint(room, pending);
493
+ } catch {
494
+ if (room.pendingCheckpoint === pending) room.pendingCheckpointTimer = setTimeout(expire, pendingCheckpointRetentionMs);
495
+ return;
496
+ }
497
+ clearPendingCheckpoint(room, pending);
498
+ evictRoom(room);
499
+ })();
500
+ };
501
+ room.pendingCheckpointTimer = setTimeout(expire, pendingCheckpointRetentionMs);
502
+ }
503
+ async function checkpointRoom(documentId, definition, room, state) {
504
+ const configured = definition.history?.checkpoint;
505
+ if (!configured) throw new HTTPError({ status: 404 });
506
+ if (room.checkpoint) {
507
+ const active = room.checkpoint;
508
+ if (matchesBytes(room.checkpointState, state)) return await active;
509
+ await active;
510
+ return await checkpointRoom(documentId, definition, room, state);
511
+ }
512
+ const checkpoint = serializeWorkspaceCheckpoint(definition.document.workspace, async () => {
513
+ let pending = room.pendingCheckpoint;
514
+ if (pending && (pending.content === void 0 || pending.digest === void 0)) {
515
+ await recoverPendingCheckpoint(room, pending);
516
+ throw new HTTPError({
517
+ status: 409,
518
+ message: "The Workspace document changed while recovering its realtime checkpoint.",
519
+ data: { code: realtimeCheckpointRejectedCode }
520
+ });
521
+ }
522
+ if (pending && !matchesBytes(pending.state, state)) {
523
+ const current = await readRealtimeWorkspaceDocument(pending.workspace, pending.workspace, pending.path);
524
+ room.baselineDigest = current.baselineDigest;
525
+ room.durableReady = !!room.sql || !!room.baselineDigest;
526
+ if (current.markdown !== yDocToMarkdown(pending.submittedDocument)) {
527
+ reconcilePendingCheckpoint(room, pending, current.markdown);
528
+ persistRoom(room);
529
+ clearPendingCheckpoint(room, pending);
530
+ throw new HTTPError({
531
+ status: 409,
532
+ message: "The Workspace document changed while recovering its realtime checkpoint.",
533
+ data: { code: realtimeCheckpointRejectedCode }
534
+ });
535
+ }
536
+ clearPendingCheckpoint(room, pending);
537
+ pending = void 0;
538
+ }
539
+ if (!pending) {
540
+ const workspace = useWorkspace(definition.document.workspace, { mode: "write" });
541
+ const submittedDocument = new Y.Doc();
542
+ Y.applyUpdate(submittedDocument, Y.encodeStateAsUpdate(room.document));
543
+ const message = typeof configured === "object" && configured.message ? configured.message : `docs: checkpoint ${documentId}`;
544
+ let path;
545
+ try {
546
+ path = await writeRealtimeDocument(workspace, documentId, submittedDocument, room.baselineDigest ?? null);
547
+ } catch (error) {
548
+ submittedDocument.destroy();
549
+ if (isWorkspaceConflict(error)) throw new HTTPError({
550
+ status: 409,
551
+ message: "The document changed in Workspace after this realtime room opened."
552
+ });
553
+ room.baselineDigest = (await (await refreshWritableWorkspace(definition.document.workspace)).fs.stat(documentId))?.digest;
554
+ room.durableReady = !!room.sql || !!room.baselineDigest;
555
+ persistRoom(room);
556
+ throw error;
557
+ }
558
+ try {
559
+ const written = await readRealtimeWorkspaceDocument(workspace, workspace, path);
560
+ if (!written.baselineDigest) throw new Error("Realtime checkpoints require Workspace file digests.");
561
+ pending = {
562
+ content: written.markdown,
563
+ digest: written.baselineDigest,
564
+ message,
565
+ path,
566
+ state: Uint8Array.from(state),
567
+ submittedDocument,
568
+ workspace
569
+ };
570
+ } catch (error) {
571
+ room.pendingCheckpoint = {
572
+ message,
573
+ path,
574
+ state: Uint8Array.from(state),
575
+ submittedDocument,
576
+ workspace
577
+ };
578
+ schedulePendingCheckpointExpiry(room, room.pendingCheckpoint);
579
+ throw error;
580
+ }
581
+ room.pendingCheckpoint = pending;
582
+ }
583
+ let snapshot;
584
+ try {
585
+ try {
586
+ snapshot = await pending.workspace.history.checkpoint({ message: pending.message });
587
+ } catch (error) {
588
+ if (!isWorkspaceConflict(error)) throw error;
589
+ await pending.workspace.history.rebase({ takeRemote: [pending.path] });
590
+ snapshot = await pending.workspace.history.checkpoint({ message: pending.message });
591
+ }
592
+ } catch (error) {
593
+ if (isWorkspaceConflict(error)) {
594
+ schedulePendingCheckpointExpiry(room, pending);
595
+ throw new HTTPError({
596
+ status: 409,
597
+ message: "The Workspace changed while checkpointing this realtime document.",
598
+ data: { code: realtimeCheckpointRejectedCode }
599
+ });
600
+ }
601
+ schedulePendingCheckpointExpiry(room, pending);
602
+ throw error;
603
+ }
604
+ if (snapshot.entries[pending.path]?.digest !== pending.digest) {
605
+ let current;
606
+ try {
607
+ current = await readRealtimeWorkspaceDocument(pending.workspace, pending.workspace, pending.path);
608
+ } catch (error) {
609
+ pending.content = void 0;
610
+ pending.digest = void 0;
611
+ schedulePendingCheckpointExpiry(room, pending);
612
+ throw error;
613
+ }
614
+ room.baselineDigest = current.baselineDigest;
615
+ room.durableReady = !!room.sql || !!room.baselineDigest;
616
+ reconcilePendingCheckpoint(room, pending, current.markdown);
617
+ persistRoom(room);
618
+ clearPendingCheckpoint(room, pending);
619
+ throw new HTTPError({
620
+ status: 409,
621
+ message: "The Workspace document changed while creating its realtime checkpoint.",
622
+ data: { code: realtimeCheckpointRejectedCode }
623
+ });
624
+ }
625
+ room.baselineDigest = snapshot.entries[pending.path]?.digest;
626
+ room.durableReady = !!room.sql || !!room.baselineDigest;
627
+ reconcilePendingCheckpoint(room, pending, pending.content);
628
+ room.mutated = !matchesRealtimeState(room.document, Y.encodeStateAsUpdate(pending.submittedDocument));
629
+ persistRoom(room);
630
+ clearPendingCheckpoint(room, pending);
631
+ return {
632
+ content: pending.content,
633
+ snapshot
634
+ };
635
+ });
636
+ room.checkpoint = checkpoint;
637
+ room.checkpointState = state;
638
+ try {
639
+ return await checkpoint;
640
+ } finally {
641
+ if (room.checkpoint === checkpoint) {
642
+ room.checkpoint = void 0;
643
+ room.checkpointState = void 0;
644
+ }
645
+ evictRoom(room);
646
+ }
647
+ }
648
+ const httpHandler = defineEventHandler(async (event) => {
649
+ if (event.req.method !== "POST" || new URL(event.req.url).searchParams.get("history") !== "checkpoint") throw new HTTPError({ status: 405 });
650
+ const { definitionName, documentId, workspaceEvents } = parseRoomPath(event.req.url);
651
+ if (workspaceEvents) throw new HTTPError({
652
+ status: 400,
653
+ message: "Workspace events cannot be checkpointed."
654
+ });
655
+ const definition = await getDefinition(definitionName);
656
+ await authorize(event.req, definition.auth, event);
657
+ if (!definition.history?.checkpoint) throw new HTTPError({ status: 404 });
658
+ const workspace = useWorkspace(definition.document.workspace, { mode: "write" });
659
+ if (!(await workspace.capabilities()).conditionalWrites) throw new HTTPError({
660
+ status: 501,
661
+ message: "Realtime checkpoints require a Workspace Store with conditional writes."
662
+ });
663
+ const sql = resolveRealtimeRoomSql(event);
664
+ if (sql && (await resolveWorkspaceStoreTarget(workspace))?.provider === "memory") throw new HTTPError({
665
+ status: 501,
666
+ message: "Durable realtime checkpoints require a durable Workspace Store."
667
+ });
668
+ const state = await readRealtimeCheckpointState(event.req);
669
+ if (!state.byteLength) throw new HTTPError({
670
+ status: 400,
671
+ message: "Realtime checkpoint state is required."
672
+ });
673
+ const room = await getRoom(definitionName, documentId, definition, sql, workspaceEvents);
674
+ if (!matchesRealtimeState(room.document, state)) {
675
+ evictRoom(room);
676
+ throw new HTTPError({
677
+ status: 409,
678
+ message: "The realtime document is still syncing.",
679
+ data: { code: realtimeSyncPendingCode }
680
+ });
681
+ }
682
+ return await checkpointRoom(documentId, definition, room, state);
683
+ });
684
+ const websocketHandler = defineWebSocketHandler(async (event) => {
685
+ const { definitionName, documentId, workspaceEvents } = parseRoomPath(event.req.url);
686
+ const definition = await getDefinition(definitionName);
687
+ const identity = await authorize(event.req, definition.auth, event);
688
+ const room = await getRoom(definitionName, documentId, definition, resolveRealtimeRoomSql(event), workspaceEvents);
689
+ function leave(peer) {
690
+ if (!room.peers.delete(peer)) return;
691
+ const pendingAwareness = peerPendingAwareness.get(peer);
692
+ if (pendingAwareness) clearTimeout(pendingAwareness.timer);
693
+ peerPendingAwareness.delete(peer);
694
+ const clients = [...peerAwarenessClients.get(peer) || []];
695
+ peerAwarenessClients.delete(peer);
696
+ if (clients.length) {
697
+ for (const client of clients) if (room.awarenessClientOwners.get(client) === peer) room.awarenessClientOwners.delete(client);
698
+ awarenessProtocol.removeAwarenessStates(room.awareness, clients, peer);
699
+ peer.publish(room.channel, encodeAwarenessState(room.awareness, clients));
700
+ room.awareness = compactRealtimeAwareness(room.awareness);
701
+ }
702
+ peer.unsubscribe(room.channel);
703
+ evictRoom(room);
704
+ }
705
+ function applyAwareness(peer, input) {
706
+ let update = input;
707
+ let clients;
708
+ let claimed = [];
709
+ try {
710
+ clients = readAwarenessClientIds(update);
711
+ claimed = claimAwarenessClientIds(room.awarenessClientOwners, peer, clients);
712
+ if (identity) update = bindAwarenessIdentity(update, identity);
713
+ applyRealtimeAwarenessUpdate(room.awareness, update, peer);
714
+ const ownedClients = peerAwarenessClients.get(peer) || /* @__PURE__ */ new Set();
715
+ for (const client of clients) ownedClients.add(client);
716
+ peerAwarenessClients.set(peer, ownedClients);
717
+ } catch (error) {
718
+ for (const client of claimed) if (room.awarenessClientOwners.get(client) === peer) room.awarenessClientOwners.delete(client);
719
+ peer.close(error instanceof AwarenessOwnershipConflict ? 4500 : 4400, "Invalid awareness update.");
720
+ return;
721
+ }
722
+ peer.publish(room.channel, encodeAwarenessState(room.awareness, clients));
723
+ }
724
+ return {
725
+ open(peer) {
726
+ room.peers.add(peer);
727
+ peer.subscribe(room.channel);
728
+ peer.send(encodeSyncStep1(room.document));
729
+ const clients = [...room.awareness.getStates().keys()];
730
+ if (clients.length) peer.send(encodeAwarenessState(room.awareness, clients));
731
+ },
732
+ message(peer, message) {
733
+ const data = message.uint8Array();
734
+ if (data.byteLength > maxMessageBytes) {
735
+ peer.close(4400, "Realtime message exceeds 1 MiB.");
736
+ return;
737
+ }
738
+ const decoder = decoding.createDecoder(data);
739
+ let messageType;
740
+ try {
741
+ messageType = decoding.readVarUint(decoder);
742
+ } catch {
743
+ peer.close(4400, "Invalid realtime message.");
744
+ return;
745
+ }
746
+ if (messageType === 4) {
747
+ if (!workspaceEvents) {
748
+ peer.close(4400, "Workspace changes require the workspace room.");
749
+ return;
750
+ }
751
+ let change;
752
+ try {
753
+ change = decodeWorkspaceChangePayload(decoder);
754
+ } catch {
755
+ peer.close(4400, "Invalid workspace change.");
756
+ return;
757
+ }
758
+ if (!change) {
759
+ peer.close(4400, "Invalid workspace change.");
760
+ return;
761
+ }
762
+ const now = Date.now();
763
+ let quota = peerWorkspaceChanges.get(peer);
764
+ if (!quota || now - quota.startedAt >= workspaceChangeWindowMs) {
765
+ quota = {
766
+ count: 0,
767
+ startedAt: now
768
+ };
769
+ peerWorkspaceChanges.set(peer, quota);
770
+ }
771
+ quota.count++;
772
+ if (quota.count > workspaceChangeLimit) {
773
+ peer.close(4429, "Workspace change rate limit exceeded.");
774
+ return;
775
+ }
776
+ peer.publish(room.channel, encodeWorkspaceChange(change));
777
+ return;
778
+ }
779
+ if (messageType === 3) {
780
+ const now = Date.now();
781
+ const previous = peerAwarenessQueryAt.get(peer);
782
+ if (previous !== void 0 && now - previous < awarenessQueryIntervalMs) return;
783
+ peerAwarenessQueryAt.set(peer, now);
784
+ const clients = [...room.awareness.getStates().keys()];
785
+ if (clients.length) peer.send(encodeAwarenessState(room.awareness, clients));
786
+ return;
787
+ }
788
+ if (messageType === 1) {
789
+ let update;
790
+ try {
791
+ update = decoding.readVarUint8Array(decoder);
792
+ } catch {
793
+ peer.close(4400, "Invalid awareness update.");
794
+ return;
795
+ }
796
+ const now = Date.now();
797
+ const previous = peerAwarenessUpdateAt.get(peer);
798
+ if (previous !== void 0 && now - previous < awarenessUpdateIntervalMs) {
799
+ const pending = peerPendingAwareness.get(peer);
800
+ if (pending) pending.update = update;
801
+ else {
802
+ const next = {
803
+ timer: setTimeout(() => {
804
+ peerPendingAwareness.delete(peer);
805
+ peerAwarenessUpdateAt.set(peer, Date.now());
806
+ applyAwareness(peer, next.update);
807
+ }, awarenessUpdateIntervalMs - (now - previous)),
808
+ update
809
+ };
810
+ peerPendingAwareness.set(peer, next);
811
+ }
812
+ return;
813
+ }
814
+ peerAwarenessUpdateAt.set(peer, now);
815
+ applyAwareness(peer, update);
816
+ return;
817
+ }
818
+ if (messageType !== messageSync) return;
819
+ try {
820
+ const syncType = decoding.readVarUint(decoder);
821
+ if (workspaceEvents) {
822
+ if (syncType === syncProtocol.messageYjsSyncStep1) {
823
+ const response = applyRealtimeSyncMessage(data, room.document, peer);
824
+ if (response) peer.send(response);
825
+ } else if (syncType !== syncProtocol.messageYjsSyncStep2) peer.close(4400, "Document updates cannot use the workspace room.");
826
+ return;
827
+ }
828
+ if (syncType === syncProtocol.messageYjsSyncStep2 && !peerInitialSyncStep2.has(peer)) peerInitialSyncStep2.add(peer);
829
+ else if (syncType === syncProtocol.messageYjsSyncStep2 || syncType === syncProtocol.messageYjsUpdate) {
830
+ const now = Date.now();
831
+ const previous = peerSyncUpdateAt.get(peer);
832
+ if (previous !== void 0 && now - previous < syncUpdateIntervalMs) {
833
+ peer.close(1013, "Realtime updates are arriving too quickly.");
834
+ return;
835
+ }
836
+ peerSyncUpdateAt.set(peer, now);
837
+ }
838
+ const response = applyRealtimeSyncMessage(data, room.document, peer);
839
+ if (response) peer.send(response);
840
+ } catch {
841
+ peer.close(4400, "Realtime document exceeds its 8 MiB room quota.");
842
+ }
843
+ },
844
+ close(peer) {
845
+ leave(peer);
846
+ },
847
+ error(peer) {
848
+ leave(peer);
849
+ }
850
+ };
851
+ });
852
+ return defineEventHandler(async (event) => {
853
+ const forwarded = await forwardToCloudflareDurableObject(event);
854
+ if (forwarded) return forwarded;
855
+ return event.req.headers.get("upgrade")?.toLowerCase() === "websocket" ? websocketHandler(event) : httpHandler(event);
856
+ });
857
+ }
858
+ //#endregion
859
+ export { applyRealtimeAwarenessUpdate, applyRealtimeSyncMessage, assertRealtimeRoomStateQuota, bindAwarenessIdentity, claimAwarenessClientIds, compactRealtimeAwareness, createRealtimeHandler, encodeAwarenessState, encodeSyncStep1, encodeSyncUpdate, markdownToYDoc, matchesRealtimeState, readRealtimeCheckpointState, readRealtimeWorkspaceDocument, realtimeRoomKey, replaceRealtimeDocument, restoreRealtimeDocument, writeRealtimeDocument, yDocToMarkdown };