@vite-hub/realtime 0.0.3 → 0.1.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.
package/dist/vue.js CHANGED
@@ -1,24 +1,48 @@
1
- import { S as yUndoPluginKey, b as ySyncPluginKey, d as getRealtimePeople, f as absolutePositionToRelativePosition, g as undo, h as relativePositionToAbsolutePosition, i as isRetryableRealtimeCheckpointCode, l as workspaceRoomId, m as redo, n as decodeWorkspaceChangePayload, r as encodeWorkspaceChange, t as createRealtimeEditorExtensions, u as createRealtimeIdentity, x as yUndoPlugin, y as ySyncPlugin } from "./editor-extensions-CZEzrJ-t.js";
2
- import { Extension, MappablePosition, getUpdatedPosition } from "@tiptap/core";
3
- import * as Y from "yjs";
1
+ import { t as resolveRealtimeApplicationPath } from "./application-path-CJblgbWK.js";
2
+ import { a as isRetryableRealtimeRequestCode, h as getRealtimePeople, i as encodeWorkspaceChange, m as createRealtimeIdentity, n as decodeWorkspaceChangePayload, p as workspaceRoomId, t as decodeRealtimeControlPayload } from "./protocol-9ZDLEcSS.js";
3
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cvm6vRXQ.js";
4
+ import { n as realtimeDocumentLayout, r as createRealtimeEditorExtensions, t as readRealtimeStatus } from "./layout-Br1aOL7o.js";
5
+ import { _ as ySyncPluginKey, a as readRealtimeYDoc, d as defaultSelectionBuilder, f as redo, g as ySyncPlugin, h as yCursorPlugin, m as undo, p as relativePositionToAbsolutePosition, u as absolutePositionToRelativePosition, v as yUndoPlugin, y as yUndoPluginKey } from "./document-BFaqcCAL.js";
4
6
  import "lib0/decoding";
7
+ import * as encoding from "lib0/encoding";
8
+ import * as awarenessProtocol from "y-protocols/awareness";
9
+ import { WebsocketProvider } from "y-websocket";
10
+ import * as Y from "yjs";
11
+ import { Extension, MappablePosition, getUpdatedPosition } from "@tiptap/core";
5
12
  import { Plugin, PluginKey } from "@tiptap/pm/state";
6
13
  import { useUserSession } from "@vite-hub/auth/vue";
7
14
  import { computed, markRaw, onScopeDispose, ref, shallowRef, toValue, watch } from "vue";
8
- import { WebsocketProvider } from "y-websocket";
9
- //#region ../../node_modules/.pnpm/@tiptap+extension-collaboration@3.29.2_@tiptap+core@3.29.2_@tiptap+pm@3.29.2__@tiptap+p_894d099a4ad840a9519abb2f14438fb9/node_modules/@tiptap/extension-collaboration/dist/index.js
15
+ //#region ../../node_modules/.pnpm/@tiptap+extension-collaboration@3.31.4_@tiptap+core@3.31.4_@tiptap+pm@3.31.4__@tiptap+p_85015a5a825a0d4859fbb90094e145d9/node_modules/@tiptap/extension-collaboration/dist/index.js
16
+ /**
17
+ * Checks if a transaction was originated from a Yjs change.
18
+ * @param {Transaction} transaction - The transaction to check.
19
+ * @returns {boolean} - True if the transaction was originated from a Yjs change, false otherwise.
20
+ * @example
21
+ * const transaction = new Transaction(doc)
22
+ * const isOrigin = isChangeOrigin(transaction) // returns false
23
+ */
10
24
  function isChangeOrigin(transaction) {
11
25
  return !!transaction.getMeta(ySyncPluginKey);
12
26
  }
27
+ /**
28
+ * Converts a Y.js relative position to a position in the Tiptap document.
29
+ */
13
30
  function getYAbsolutePosition(state, relativePos) {
14
31
  const ystate = ySyncPluginKey.getState(state);
15
32
  return relativePositionToAbsolutePosition(ystate.doc, ystate.type, relativePos, ystate.binding.mapping) || 0;
16
33
  }
34
+ /**
35
+ * Converts a position in the Tiptap document to a Y.js relative position.
36
+ */
17
37
  function getYRelativePosition(state, absolutePos) {
18
38
  const ystate = ySyncPluginKey.getState(state);
19
39
  return absolutePositionToRelativePosition(absolutePos, ystate.type, ystate.binding.mapping);
20
40
  }
21
- var CollaborationMappablePosition = class _CollaborationMappablePosition extends MappablePosition {
41
+ /**
42
+ * A MappablePosition subclass that includes Y.js relative position information
43
+ * to track positions in collaborative transactions.
44
+ */
45
+ var CollaborationMappablePosition = class CollaborationMappablePosition extends MappablePosition {
22
46
  constructor(position, yRelativePosition) {
23
47
  super(position);
24
48
  this.yRelativePosition = yRelativePosition;
@@ -27,7 +51,7 @@ var CollaborationMappablePosition = class _CollaborationMappablePosition extends
27
51
  * Creates a CollaborationMappablePosition from a JSON object.
28
52
  */
29
53
  static fromJSON(json) {
30
- return new _CollaborationMappablePosition(json.position, json.yRelativePosition);
54
+ return new CollaborationMappablePosition(json.position, json.yRelativePosition);
31
55
  }
32
56
  /**
33
57
  * Converts the CollaborationMappablePosition to a JSON object.
@@ -39,9 +63,17 @@ var CollaborationMappablePosition = class _CollaborationMappablePosition extends
39
63
  };
40
64
  }
41
65
  };
66
+ /**
67
+ * Creates a MappablePosition from a position number.
68
+ * This is the collaboration implementation that returns a CollaborationMappablePosition.
69
+ */
42
70
  function createMappablePosition(position, state) {
43
71
  return new CollaborationMappablePosition(position, getYRelativePosition(state, position));
44
72
  }
73
+ /**
74
+ * Returns the new position after applying a transaction. Handles both Y.js
75
+ * transactions and regular transactions.
76
+ */
45
77
  function getUpdatedPosition$1(position, transaction, state) {
46
78
  const yRelativePosition = position instanceof CollaborationMappablePosition ? position.yRelativePosition : null;
47
79
  if (isChangeOrigin(transaction) && yRelativePosition) return {
@@ -51,11 +83,11 @@ function getUpdatedPosition$1(position, transaction, state) {
51
83
  const result = getUpdatedPosition(position, transaction);
52
84
  const absolutePosition = result.position.position;
53
85
  return {
54
- position: new CollaborationMappablePosition(absolutePosition, yRelativePosition != null ? yRelativePosition : getYRelativePosition(state, absolutePosition)),
86
+ position: new CollaborationMappablePosition(absolutePosition, yRelativePosition !== null && yRelativePosition !== void 0 ? yRelativePosition : getYRelativePosition(state, absolutePosition)),
55
87
  mapResult: result.mapResult
56
88
  };
57
89
  }
58
- var index_default = Extension.create({
90
+ var src_default = Extension.create({
59
91
  name: "collaboration",
60
92
  priority: 1e3,
61
93
  addOptions() {
@@ -118,15 +150,20 @@ var index_default = Extension.create({
118
150
  undoManager.doc.on("afterTransaction", undoManager.afterTransactionHandler);
119
151
  undoManager._observers = observers;
120
152
  };
121
- if (viewRet == null ? void 0 : viewRet.destroy) viewRet.destroy();
153
+ if (viewRet === null || viewRet === void 0 ? void 0 : viewRet.destroy) viewRet.destroy();
122
154
  } };
123
155
  };
156
+ const ySyncPluginOptions = {
157
+ ...this.options.ySyncOptions,
158
+ onFirstRender: this.options.onFirstRender
159
+ };
124
160
  return [
125
- ySyncPlugin(fragment, {
126
- ...this.options.ySyncOptions,
127
- onFirstRender: this.options.onFirstRender
128
- }),
161
+ ySyncPlugin(fragment, ySyncPluginOptions),
129
162
  yUndoPluginInstance,
163
+ new Plugin({ filterTransaction: (transaction, state) => {
164
+ if (transaction.getMeta("inputRule")) yUndoPluginKey.getState(state).undoManager.stopCapturing();
165
+ return true;
166
+ } }),
130
167
  this.editor.options.enableContentCheck && new Plugin({
131
168
  key: new PluginKey("filterInvalidContent"),
132
169
  filterTransaction: (transaction) => {
@@ -142,8 +179,8 @@ var index_default = Extension.create({
142
179
  error,
143
180
  editor: this.editor,
144
181
  disableCollaboration: () => {
145
- var _a;
146
- (_a = fragment.doc) == null || _a.destroy();
182
+ var _fragment$doc;
183
+ (_fragment$doc = fragment.doc) === null || _fragment$doc === void 0 || _fragment$doc.destroy();
147
184
  }
148
185
  });
149
186
  return true;
@@ -154,39 +191,141 @@ var index_default = Extension.create({
154
191
  }
155
192
  });
156
193
  //#endregion
157
- //#region src/application-path.ts
158
- function resolveRealtimeApplicationPath(path) {
159
- const baseURL = typeof __VITEHUB_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_APP_BASE_URL__;
160
- return baseURL === "/" ? path : `${baseURL.replace(/\/+$/, "")}${path}`;
161
- }
194
+ //#region src/caret.ts
195
+ const validColor = /^#[0-9a-f]{6}$/i;
196
+ /**
197
+ * Other people's carets and selections, drawn from the room's awareness. It renders what TipTap's CollaborationCaret
198
+ * renders, under the same extension name, but it uses Realtime's bundled y-tiptap: CollaborationCaret installed next to
199
+ * Realtime has its own copy, cannot find Realtime's sync plugin, and draws nothing. Presence identity stays Realtime's.
200
+ */
201
+ const RealtimeCaret = Extension.create({
202
+ name: "collaborationCaret",
203
+ priority: 999,
204
+ addOptions() {
205
+ return {
206
+ awareness: null,
207
+ render: (user) => {
208
+ const caret = document.createElement("span");
209
+ caret.classList.add("collaboration-carets__caret");
210
+ caret.style.borderColor = user.color;
211
+ const label = document.createElement("div");
212
+ label.classList.add("collaboration-carets__label");
213
+ label.style.backgroundColor = user.color;
214
+ label.append(document.createTextNode(user.name));
215
+ caret.append(label);
216
+ return caret;
217
+ },
218
+ selectionRender: (user) => defaultSelectionBuilder(user)
219
+ };
220
+ },
221
+ addProseMirrorPlugins() {
222
+ const { awareness, render, selectionRender } = this.options;
223
+ if (!awareness) return [];
224
+ const person = (user) => ({
225
+ ...user,
226
+ color: typeof user.color === "string" && validColor.test(user.color) ? user.color : "transparent",
227
+ name: typeof user.name === "string" ? user.name : ""
228
+ });
229
+ return [yCursorPlugin(awareness, {
230
+ cursorBuilder: (user) => render(person(user)),
231
+ selectionBuilder: (user) => {
232
+ const current = person(user);
233
+ return current.color === "transparent" ? {} : selectionRender(current);
234
+ }
235
+ })];
236
+ }
237
+ });
162
238
  //#endregion
163
239
  //#region src/vue.ts
164
240
  const workspaceChangeFlushIntervalMs = 11;
241
+ function isRecord(value) {
242
+ return typeof value === "object" && value !== null && !Array.isArray(value);
243
+ }
244
+ function isString(value) {
245
+ return typeof value === "string";
246
+ }
247
+ function isRealtimeSaved(value) {
248
+ if (!isRecord(value) || !isRecord(value.document) || !isString(value.document.body)) return false;
249
+ if (value.document.fields !== void 0 && !isRecord(value.document.fields)) return false;
250
+ if (value.digest !== null && !isString(value.digest)) return false;
251
+ if (value.savedAt !== null && !isString(value.savedAt)) return false;
252
+ if (value.error !== null && !isString(value.error)) return false;
253
+ return Array.isArray(value.issues) && (value.savedBy === null || isRecord(value.savedBy));
254
+ }
255
+ function isRealtimeCheckpoint(value) {
256
+ if (!isRealtimeSaved(value) || !isString(value.digest)) return false;
257
+ const snapshot = "snapshot" in value ? value.snapshot : void 0;
258
+ if (!isRecord(snapshot)) return false;
259
+ if (typeof snapshot.id !== "string" || typeof snapshot.createdAt !== "string") return false;
260
+ if (snapshot.name !== void 0 && !isString(snapshot.name)) return false;
261
+ if (!isRecord(snapshot.entries)) return false;
262
+ return Object.values(snapshot.entries).every((entry) => {
263
+ if (!isRecord(entry) || entry.type !== "file" && entry.type !== "directory") return false;
264
+ if (entry.digest !== void 0 && !isString(entry.digest)) return false;
265
+ if (entry.metadata !== void 0 && !isRecord(entry.metadata)) return false;
266
+ if (entry.size !== void 0) {
267
+ if (typeof entry.size !== "number" || !Number.isFinite(entry.size)) return false;
268
+ }
269
+ return true;
270
+ });
271
+ }
272
+ function isRefreshResult(value) {
273
+ return isRecord(value) && (value.digest === null || isString(value.digest)) && typeof value.reseeded === "boolean";
274
+ }
165
275
  function useRealtimeTiptap(definition, documentId, options = {}) {
166
- const { user } = useUserSession();
276
+ const sessionUser = options.identity === void 0 ? useUserSession().user : void 0;
277
+ const identity = () => options.identity === void 0 ? sessionUser?.value : toValue(options.identity);
278
+ const createExtensions = () => options.editor ? options.editor.extensions() : createRealtimeEditorExtensions({ collaborative: true });
279
+ const createCarets = (awareness) => {
280
+ if (options.carets === false) return [];
281
+ const { render, selectionRender } = typeof options.carets === "object" ? options.carets : {};
282
+ return [markRaw(RealtimeCaret.configure({
283
+ awareness: markRaw(awareness),
284
+ ...render ? { render } : {},
285
+ ...selectionRender ? { selectionRender } : {}
286
+ }))];
287
+ };
167
288
  const document = shallowRef();
168
289
  const provider = shallowRef();
169
290
  const workspaceProvider = shallowRef();
170
291
  const workspaceChange = shallowRef();
171
292
  const people = shallowRef([]);
293
+ const saveStatus = shallowRef();
172
294
  const status = ref("disconnected");
173
295
  const synced = ref(false);
296
+ const readOnlyReason = ref(null);
174
297
  const checkpointRequests = ref(0);
298
+ const saveRequests = ref(0);
175
299
  const pendingWorkspaceChanges = [];
300
+ const requestControllers = /* @__PURE__ */ new Set();
301
+ const refreshControllers = /* @__PURE__ */ new Set();
302
+ const resetListeners = /* @__PURE__ */ new Set();
303
+ if (options.onReset) resetListeners.add(options.onReset);
304
+ let connectedDocumentId;
176
305
  let workspaceChangeTimer;
177
306
  const enabled = () => options.enabled === void 0 || toValue(options.enabled);
178
- function destroyDocument() {
307
+ function destroyDocument(keepDocument = false, preserveRefresh = false) {
308
+ for (const controller of requestControllers) if (!preserveRefresh || !refreshControllers.has(controller)) controller.abort();
309
+ if (preserveRefresh) {
310
+ for (const controller of requestControllers) if (!refreshControllers.has(controller)) requestControllers.delete(controller);
311
+ } else {
312
+ requestControllers.clear();
313
+ refreshControllers.clear();
314
+ }
315
+ connectedDocumentId = void 0;
179
316
  provider.value?.destroy();
180
- document.value?.destroy();
317
+ if (!keepDocument) document.value?.destroy();
181
318
  provider.value = void 0;
182
319
  document.value = void 0;
183
320
  people.value = [];
321
+ saveStatus.value = void 0;
184
322
  status.value = "disconnected";
185
323
  synced.value = false;
324
+ readOnlyReason.value = null;
186
325
  }
187
326
  function currentPerson(clientId) {
188
- const value = user.value;
189
- const id = value?.id || `guest:${clientId}`;
327
+ const value = identity();
328
+ const id = isString(value?.id) && value.id ? value.id : `guest:${clientId}`;
190
329
  return createRealtimeIdentity({
191
330
  ...value,
192
331
  id
@@ -223,10 +362,12 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
223
362
  workspaceChangeTimer = void 0;
224
363
  pendingWorkspaceChanges.length = 0;
225
364
  }
365
+ function serverURL() {
366
+ return `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`)}`;
367
+ }
226
368
  if (typeof window !== "undefined") {
227
- const server = `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`)}`;
228
369
  const workspaceDocument = markRaw(new Y.Doc());
229
- const nextWorkspaceProvider = new WebsocketProvider(server, encodeURIComponent(workspaceRoomId), workspaceDocument, {
370
+ const nextWorkspaceProvider = new WebsocketProvider(serverURL(), encodeURIComponent(workspaceRoomId), workspaceDocument, {
230
371
  connect: false,
231
372
  disableBc: true,
232
373
  params: { workspace: "events" }
@@ -241,54 +382,174 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
241
382
  });
242
383
  workspaceProvider.value = nextWorkspaceProvider;
243
384
  }
244
- async function checkpoint() {
245
- if (!enabled()) throw new Error("Realtime is disabled.");
246
- checkpointRequests.value++;
385
+ function connect(id) {
386
+ const nextDocument = markRaw(new Y.Doc());
387
+ const room = id.split("/").map(encodeURIComponent).join("/");
388
+ const nextProvider = new WebsocketProvider(serverURL(), room, nextDocument, {
389
+ disableBc: true,
390
+ params: {}
391
+ });
392
+ nextProvider.messageHandlers[5] = (_encoder, decoder) => {
393
+ if (provider.value !== nextProvider) return;
394
+ const control = decodeRealtimeControlPayload(decoder);
395
+ if (!control) return;
396
+ if (control.type === "session") {
397
+ nextProvider.params.epoch = control.epoch;
398
+ readOnlyReason.value = control.access === "read" ? control.reason ?? "access" : null;
399
+ return;
400
+ }
401
+ reset(id, control.reason, control.epoch);
402
+ };
403
+ nextProvider.awareness.off("update", nextProvider._awarenessUpdateHandler);
404
+ nextProvider.awareness.on("update", ({ added, removed, updated }) => {
405
+ const own = [
406
+ ...added,
407
+ ...updated,
408
+ ...removed
409
+ ].filter((client) => client === nextDocument.clientID);
410
+ const socket = nextProvider.ws;
411
+ if (!own.length || !nextProvider.wsconnected || !socket || socket.readyState !== socket.OPEN) return;
412
+ const encoder = encoding.createEncoder();
413
+ encoding.writeVarUint(encoder, 1);
414
+ encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(nextProvider.awareness, own));
415
+ socket.send(encoding.toUint8Array(encoder));
416
+ });
417
+ nextProvider.awareness.setLocalStateField("user", currentPerson(nextDocument.clientID));
418
+ nextProvider.awareness.on("change", () => {
419
+ if (provider.value === nextProvider) updatePeople(nextProvider);
420
+ });
421
+ updatePeople(nextProvider);
422
+ nextDocument.getMap(realtimeDocumentLayout.status).observe(() => {
423
+ if (document.value === nextDocument) saveStatus.value = readRealtimeStatus(nextDocument);
424
+ });
425
+ nextProvider.on("status", (event) => {
426
+ if (provider.value === nextProvider) status.value = event.status;
427
+ });
428
+ nextProvider.on("sync", (value) => {
429
+ if (provider.value !== nextProvider) return;
430
+ synced.value = value;
431
+ if (value) saveStatus.value = readRealtimeStatus(nextDocument);
432
+ });
433
+ connectedDocumentId = id;
434
+ document.value = nextDocument;
435
+ provider.value = nextProvider;
436
+ status.value = "connecting";
437
+ }
438
+ function reset(id, reason, epoch) {
439
+ const previous = document.value;
440
+ destroyDocument(true, true);
441
+ if (previous) try {
442
+ for (const listener of resetListeners) listener({
443
+ epoch,
444
+ previous,
445
+ reason
446
+ });
447
+ } finally {
448
+ previous.destroy();
449
+ }
450
+ if (enabled() && toValue(documentId) === id) connect(id);
451
+ }
452
+ function onReset(listener) {
453
+ resetListeners.add(listener);
454
+ return () => resetListeners.delete(listener);
455
+ }
456
+ async function request(action) {
457
+ const disconnected = () => [realtimeErrorDiagnostics.REALTIME_DISCONNECTED({ action }), void 0];
458
+ const controller = new AbortController();
459
+ requestControllers.add(controller);
460
+ if (action === "refresh") refreshControllers.add(controller);
247
461
  try {
248
462
  const id = toValue(documentId);
249
- if (!id) throw new Error("A realtime document is required before creating a checkpoint.");
463
+ if (!id) return [realtimeErrorDiagnostics.REALTIME_MISSING_DOCUMENT({ action }), void 0];
250
464
  const room = id.split("/").map(encodeURIComponent).join("/");
465
+ const current = document.value;
466
+ const query = action === "checkpoint" ? "history=checkpoint" : `document=${action}`;
467
+ const stillCurrent = () => !controller.signal.aborted && !!current && connectedDocumentId === id && document.value === current && toValue(documentId) === id && enabled();
251
468
  for (let attempt = 0;; attempt++) {
252
- const current = document.value;
253
- if (!current) throw new Error("The realtime document is not connected.");
254
- const response = await fetch(resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}/${room}?history=checkpoint`), {
255
- body: Uint8Array.from(Y.encodeStateAsUpdate(current)).buffer,
256
- method: "POST"
257
- });
258
- if (response.ok) return await response.json();
259
- const data = await response.json().catch(() => void 0);
260
- if (response.status === 409 && isRetryableRealtimeCheckpointCode(data?.data?.code) && attempt < 20) {
469
+ if (action !== "refresh" && !stillCurrent()) return disconnected();
470
+ let response;
471
+ try {
472
+ response = await fetch(resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}/${room}?${query}`), {
473
+ body: action === "refresh" ? void 0 : Uint8Array.from(Y.encodeStateAsUpdate(current)).buffer,
474
+ method: "POST",
475
+ signal: controller.signal
476
+ });
477
+ } catch (cause) {
478
+ if (controller.signal.aborted) return disconnected();
479
+ return [realtimeErrorDiagnostics.REALTIME_REQUEST_FAILED({
480
+ action,
481
+ cause
482
+ }), void 0];
483
+ }
484
+ let data;
485
+ try {
486
+ data = await response.json();
487
+ } catch {
488
+ if (controller.signal.aborted) return disconnected();
489
+ }
490
+ if (action !== "refresh" && !stillCurrent()) return disconnected();
491
+ if (response.ok) return [void 0, data];
492
+ const errorData = isRecord(data) ? data : void 0;
493
+ const nestedData = isRecord(errorData?.data) ? errorData.data : void 0;
494
+ const message = isString(errorData?.statusMessage) && errorData.statusMessage ? errorData.statusMessage : isString(errorData?.message) ? errorData.message : void 0;
495
+ if (response.status === 409 && isRetryableRealtimeRequestCode(isString(nestedData?.code) ? nestedData.code : void 0) && attempt < 20) {
261
496
  await new Promise((resolve) => setTimeout(resolve, 50));
262
497
  continue;
263
498
  }
264
- throw Object.assign(new Error(data?.statusMessage || data?.message || "Could not create the realtime checkpoint."), {
265
- data,
266
- statusCode: response.status
267
- });
499
+ return [realtimeErrorDiagnostics.REALTIME_REQUEST_FAILED({
500
+ action,
501
+ message,
502
+ status: response.status
503
+ }), void 0];
268
504
  }
505
+ } finally {
506
+ requestControllers.delete(controller);
507
+ refreshControllers.delete(controller);
508
+ }
509
+ }
510
+ async function requestResult(action, accepts) {
511
+ if (!enabled()) return [realtimeErrorDiagnostics.REALTIME_DISABLED({ action }), void 0];
512
+ const [error, data] = await request(action);
513
+ if (error) return [error, void 0];
514
+ return accepts(data) ? [void 0, data] : [realtimeErrorDiagnostics.REALTIME_INVALID_RESPONSE({ action }), void 0];
515
+ }
516
+ /**
517
+ * Saves the room through its document adapter now, including every edit this client has sent.
518
+ * Returns `[error, saved]`; `error.code` is a `RealtimeRequestErrorCode`.
519
+ */
520
+ async function save() {
521
+ if (!enabled()) return [realtimeErrorDiagnostics.REALTIME_DISABLED({ action: "save" }), void 0];
522
+ saveRequests.value++;
523
+ try {
524
+ return await requestResult("save", isRealtimeSaved);
525
+ } finally {
526
+ saveRequests.value--;
527
+ }
528
+ }
529
+ /**
530
+ * Saves the room and records a durable history entry through the document adapter.
531
+ * Returns `[error, checkpoint]`; `error.code` is a `RealtimeRequestErrorCode`.
532
+ */
533
+ async function checkpoint() {
534
+ if (!enabled()) return [realtimeErrorDiagnostics.REALTIME_DISABLED({ action: "checkpoint" }), void 0];
535
+ checkpointRequests.value++;
536
+ try {
537
+ return await requestResult("checkpoint", isRealtimeCheckpoint);
269
538
  } finally {
270
539
  checkpointRequests.value--;
271
540
  }
272
541
  }
542
+ /**
543
+ * Asks the room to compare its seed with the stored document. A changed source resets every client.
544
+ * Returns `[error, result]`; `error.code` is a `RealtimeRequestErrorCode`.
545
+ */
546
+ async function refresh() {
547
+ return await requestResult("refresh", isRefreshResult);
548
+ }
273
549
  watch([() => toValue(documentId), enabled], ([id, active]) => {
274
550
  destroyDocument();
275
551
  if (!active || !id || typeof window === "undefined") return;
276
- const nextDocument = markRaw(new Y.Doc());
277
- const nextProvider = new WebsocketProvider(`${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`)}`, id.split("/").map(encodeURIComponent).join("/"), nextDocument, { disableBc: true });
278
- nextProvider.awareness.setLocalStateField("user", currentPerson(nextDocument.clientID));
279
- nextProvider.awareness.on("change", () => {
280
- if (provider.value === nextProvider) updatePeople(nextProvider);
281
- });
282
- updatePeople(nextProvider);
283
- nextProvider.on("status", (event) => {
284
- if (provider.value === nextProvider) status.value = event.status;
285
- });
286
- nextProvider.on("sync", (value) => {
287
- if (provider.value === nextProvider) synced.value = value;
288
- });
289
- document.value = nextDocument;
290
- provider.value = nextProvider;
291
- status.value = "connecting";
552
+ connect(id);
292
553
  }, { immediate: true });
293
554
  watch(enabled, (active) => {
294
555
  const current = workspaceProvider.value;
@@ -299,7 +560,7 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
299
560
  pendingWorkspaceChanges.length = 0;
300
561
  }
301
562
  }, { immediate: true });
302
- watch(user, () => {
563
+ watch(identity, () => {
303
564
  const current = provider.value;
304
565
  if (!current) return;
305
566
  current.awareness.setLocalStateField("user", currentPerson(current.doc.clientID));
@@ -308,9 +569,22 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
308
569
  onScopeDispose(destroy);
309
570
  return {
310
571
  document,
311
- extensions: computed(() => document.value && provider.value ? [...createRealtimeEditorExtensions(), markRaw(index_default.configure({ fragment: markRaw(document.value.getXmlFragment("default")) }))] : []),
572
+ extensions: computed(() => document.value && provider.value ? [
573
+ ...createExtensions(),
574
+ markRaw(src_default.configure({ fragment: markRaw(document.value.getXmlFragment(realtimeDocumentLayout.body)) })),
575
+ ...createCarets(provider.value.awareness)
576
+ ] : []),
577
+ fields: computed(() => document.value?.getMap(realtimeDocumentLayout.fields)),
312
578
  people,
313
579
  provider,
580
+ /** The server rejects edits from this connection. `readOnlyReason` tells why; `saveStatus` holds the details. */
581
+ readOnly: computed(() => readOnlyReason.value !== null),
582
+ readOnlyReason,
583
+ refresh,
584
+ onReset,
585
+ save,
586
+ saveStatus,
587
+ saving: computed(() => saveRequests.value > 0),
314
588
  status,
315
589
  synced,
316
590
  history: {
@@ -325,4 +599,4 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
325
599
  };
326
600
  }
327
601
  //#endregion
328
- export { useRealtimeTiptap };
602
+ export { RealtimeCaret, readRealtimeYDoc, useRealtimeTiptap };