@vite-hub/realtime 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +71 -12
  2. package/dist/agent.d.ts +2 -0
  3. package/dist/agent.js +2 -0
  4. package/dist/bus-Bi-Ec414.js +476 -0
  5. package/dist/bus-protocol-wXkXW28q.d.ts +66 -0
  6. package/dist/bus.d.ts +85 -0
  7. package/dist/bus.js +2 -0
  8. package/dist/client/browser.js +53 -0
  9. package/dist/client.d.ts +25 -4
  10. package/dist/client.js +66 -8
  11. package/dist/conflict-Bg8vCisd.js +63 -0
  12. package/dist/{document-CtY6umWY.d.ts → document-DPaywuCO.d.ts} +2 -2
  13. package/dist/{document-BFaqcCAL.js → document-DjBrcgpY.js} +22 -10
  14. package/dist/durability.d.ts +10 -0
  15. package/dist/durability.js +46 -0
  16. package/dist/{layout-Br1aOL7o.js → editor-BM5-vHqf.js} +30 -36
  17. package/dist/error-diagnostics-B_66irmt.js +141 -0
  18. package/dist/index.d.ts +9 -4
  19. package/dist/index.js +3 -7
  20. package/dist/internal/runtime/unavailable.d.ts +5 -0
  21. package/dist/internal/runtime/unavailable.js +8 -0
  22. package/dist/keepalive-BCs-uXp4.js +33 -0
  23. package/dist/layout-DNaxppTZ.js +34 -0
  24. package/dist/{layout-WNWejwOY.d.ts → layout-fyQnhwCg.d.ts} +1 -1
  25. package/dist/{protocol-9ZDLEcSS.js → object-CzKyK0hX.js} +57 -58
  26. package/dist/presence-Tuy1y_l9.js +53 -0
  27. package/dist/request-BUwa359H.d.ts +48 -0
  28. package/dist/request-CWaHqW3R.js +192 -0
  29. package/dist/server.d.ts +64 -28
  30. package/dist/server.js +1002 -379
  31. package/dist/{types-Bw6-42Se.d.ts → types-1DVVG5ro.d.ts} +118 -14
  32. package/dist/vite.d.ts +109 -12
  33. package/dist/vite.js +469 -138
  34. package/dist/vue.d.ts +8 -5
  35. package/dist/vue.js +25 -11
  36. package/package.json +71 -19
  37. package/dist/application-path-CJblgbWK.js +0 -6
  38. package/dist/conflict-rguoaHlE.js +0 -34
  39. package/dist/durable-key-tnSw58ZK.js +0 -8
  40. package/dist/error-diagnostics-Cvm6vRXQ.js +0 -73
package/dist/client.js CHANGED
@@ -1,21 +1,27 @@
1
- import { t as resolveRealtimeApplicationPath } from "./application-path-CJblgbWK.js";
2
- import { h as getRealtimePeople, i as encodeWorkspaceChange, m as createRealtimeIdentity, n as decodeWorkspaceChangePayload, p as workspaceRoomId, t as decodeRealtimeControlPayload } from "./protocol-9ZDLEcSS.js";
1
+ import { n as resolveRealtimeApplicationPath, t as keepRealtimeSocketAlive } from "./keepalive-BCs-uXp4.js";
2
+ import { a as decodeRealtimeRequestFramePayload, c as encodeRealtimeRequestFrame, i as decodeRealtimeControlPayload, l as encodeWorkspaceChange, o as decodeWorkspaceChangePayload, x as workspaceRoomId } from "./object-CzKyK0hX.js";
3
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
4
+ import { n as getRealtimePeople, t as createRealtimeIdentity } from "./presence-Tuy1y_l9.js";
3
5
  import "lib0/decoding";
4
6
  import * as encoding from "lib0/encoding";
5
7
  import * as awarenessProtocol from "y-protocols/awareness";
6
8
  import { WebsocketProvider } from "y-websocket";
7
9
  import * as Y from "yjs";
8
10
  //#region src/client.ts
11
+ const maxAnswerBytes = 1047552;
9
12
  /**
10
13
  * Joins one room of a Realtime Definition for presence: who is there and what each person shares through awareness,
11
- * such as a cursor. It does not edit the room document. Use it outside Vue, or when a page needs presence without an
12
- * editor; `useRealtimeTiptap()` from `@vite-hub/realtime/vue` is the editor client.
14
+ * such as a cursor. It also reads the room's save status, such as the digest of the stored document. It does not edit
15
+ * the room document and loads no editor. Use it outside Vue, or when a page needs presence or the save status without
16
+ * an editor; `useRealtimeTiptap()` from `@vite-hub/realtime/vue` is the editor client.
13
17
  */
14
18
  function connectRealtimeRoom(definition, documentId, options = {}) {
15
19
  const updateListeners = /* @__PURE__ */ new Set();
16
20
  const changeListeners = /* @__PURE__ */ new Set();
17
21
  const pendingChanges = [];
22
+ let requestHandler;
18
23
  let currentStatus = "connecting";
24
+ let synced = false;
19
25
  let destroyed = false;
20
26
  let document;
21
27
  let provider;
@@ -23,17 +29,23 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
23
29
  for (const listener of updateListeners) listener();
24
30
  };
25
31
  const url = () => {
26
- return `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`, options.baseURL)}`;
32
+ const app = options.origin ? new URL(options.origin) : window.location;
33
+ return `${app.protocol === "https:" ? "wss:" : "ws:"}//${app.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`, options.baseURL)}`;
27
34
  };
28
35
  const room = documentId.split("/").map(encodeURIComponent).join("/");
29
36
  const localState = {};
30
37
  function connect() {
38
+ synced = false;
31
39
  document = new Y.Doc();
32
40
  provider = new WebsocketProvider(url(), room, document, {
33
41
  disableBc: true,
34
- params: {}
42
+ params: {
43
+ ...options.params,
44
+ clientId: String(document.clientID)
45
+ }
35
46
  });
36
47
  const current = provider;
48
+ keepRealtimeSocketAlive(current);
37
49
  current.messageHandlers[5] = (_encoder, decoder) => {
38
50
  const control = decodeRealtimeControlPayload(decoder);
39
51
  if (!control) return;
@@ -43,7 +55,13 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
43
55
  }
44
56
  current.destroy();
45
57
  document.destroy();
46
- if (!destroyed) connect();
58
+ if (destroyed) return;
59
+ connect();
60
+ emit();
61
+ };
62
+ current.messageHandlers[6] = (_encoder, decoder) => {
63
+ const frame = decodeRealtimeRequestFramePayload(decoder);
64
+ if (frame?.kind === "request") answer(current, frame.id, frame.body);
47
65
  };
48
66
  current.awareness.off("update", current._awarenessUpdateHandler);
49
67
  current.awareness.on("update", ({ added, removed, updated }) => {
@@ -68,6 +86,12 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
68
86
  })
69
87
  });
70
88
  current.awareness.on("change", emit);
89
+ document.getMap(realtimeDocumentLayout.status).observe(emit);
90
+ current.on("sync", (value) => {
91
+ if (provider !== current) return;
92
+ synced = value;
93
+ emit();
94
+ });
71
95
  current.on("status", (event) => {
72
96
  currentStatus = event.status;
73
97
  emit();
@@ -78,9 +102,13 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
78
102
  if (options.changes) {
79
103
  changes = new WebsocketProvider(url(), encodeURIComponent(workspaceRoomId), new Y.Doc(), {
80
104
  disableBc: true,
81
- params: { workspace: "events" }
105
+ params: {
106
+ ...options.params,
107
+ workspace: "events"
108
+ }
82
109
  });
83
110
  changes.awareness.setLocalState(null);
111
+ keepRealtimeSocketAlive(changes);
84
112
  changes.messageHandlers[4] = (_encoder, decoder) => {
85
113
  const change = decodeWorkspaceChangePayload(decoder);
86
114
  if (!change) return;
@@ -90,6 +118,28 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
90
118
  if (event.status === "connected") flush();
91
119
  });
92
120
  }
121
+ async function answer(current, id, body) {
122
+ const refusal = (why) => encodeRealtimeRequestFrame({
123
+ kind: "answer",
124
+ id,
125
+ ok: false,
126
+ why
127
+ });
128
+ let frame;
129
+ try {
130
+ frame = requestHandler ? encodeRealtimeRequestFrame({
131
+ kind: "answer",
132
+ id,
133
+ ok: true,
134
+ body: await requestHandler(body)
135
+ }) : refusal("This page does not answer requests.");
136
+ if (frame.byteLength > maxAnswerBytes) frame = refusal(`The answer has ${frame.byteLength} bytes, over the 1 MiB limit.`);
137
+ } catch (error) {
138
+ frame = refusal(error instanceof Error ? error.message : String(error));
139
+ }
140
+ const socket = current.ws;
141
+ if (current.wsconnected && socket && socket.readyState === socket.OPEN) socket.send(Uint8Array.from(frame));
142
+ }
93
143
  function flush() {
94
144
  const socket = changes?.ws;
95
145
  if (!changes?.wsconnected || !socket || socket.readyState !== socket.OPEN) return;
@@ -109,6 +159,7 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
109
159
  return states;
110
160
  },
111
161
  status: () => currentStatus,
162
+ saveStatus: () => synced ? readRealtimeStatus(document) : void 0,
112
163
  setLocal(field, value) {
113
164
  if (value === null) delete localState[field];
114
165
  else localState[field] = value;
@@ -127,6 +178,12 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
127
178
  changeListeners.add(listener);
128
179
  return () => changeListeners.delete(listener);
129
180
  },
181
+ onRequest(handler) {
182
+ requestHandler = handler;
183
+ return () => {
184
+ if (requestHandler === handler) requestHandler = void 0;
185
+ };
186
+ },
130
187
  destroy() {
131
188
  destroyed = true;
132
189
  provider.destroy();
@@ -135,6 +192,7 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
135
192
  changes?.doc.destroy();
136
193
  updateListeners.clear();
137
194
  changeListeners.clear();
195
+ requestHandler = void 0;
138
196
  }
139
197
  };
140
198
  }
@@ -0,0 +1,63 @@
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
2
+ import { Diagnostic } from "nostics";
3
+ //#region src/definition.ts
4
+ /**
5
+ * Checks a definition when the server loads it. A definition must say who can use its rooms: `auth: true`,
6
+ * `authorize()`, or `access: "public"`. `history.checkpoint` needs a document that can record history: a Workspace
7
+ * document, or an adapter with `checkpoint()`.
8
+ */
9
+ function defineRealtime(definition) {
10
+ assertRealtimeAccess(definition);
11
+ assertRealtimeCheckpoint(definition);
12
+ return definition;
13
+ }
14
+ /** Rejects a definition that reaches the server without an access rule, such as a plain object in a JavaScript file. */
15
+ function assertRealtimeAccess(definition) {
16
+ const access = definition.access;
17
+ const authorize = definition.authorize;
18
+ const auth = definition.auth === true;
19
+ const hasAuthorize = typeof authorize === "function";
20
+ if (access !== void 0) {
21
+ if (access !== "public") throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "not-public" });
22
+ if (definition.auth !== void 0 || authorize !== void 0) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "public-with-rule" });
23
+ } else if (!auth && !hasAuthorize) throw realtimeErrorDiagnostics.REALTIME_MISSING_ACCESS();
24
+ if (auth && !definition.identify && definition.origins) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "origins-without-identify" });
25
+ }
26
+ function assertRealtimeCheckpoint(definition) {
27
+ if (!definition.document || !definition.history?.checkpoint) return;
28
+ const document = definition.document;
29
+ if ("load" in document && typeof document.checkpoint !== "function") throw realtimeErrorDiagnostics.REALTIME_CHECKPOINT_UNSUPPORTED();
30
+ }
31
+ //#endregion
32
+ //#region src/conflict.ts
33
+ const conflictCode = "REALTIME_DOCUMENT_CONFLICT";
34
+ /** Thrown by a document adapter when the stored digest no longer matches `ifDigest`. */
35
+ var RealtimeDocumentConflict = class RealtimeDocumentConflict extends Diagnostic {
36
+ constructor(why) {
37
+ const { code, docs, fix } = realtimeErrorDiagnostics.REALTIME_DOCUMENT_CONFLICT({ problem: why });
38
+ super({
39
+ code,
40
+ docs,
41
+ fix,
42
+ why: why ?? "The stored document changed since the realtime room loaded it."
43
+ }, RealtimeDocumentConflict);
44
+ this.name = "RealtimeDocumentConflict";
45
+ }
46
+ toJSON() {
47
+ return {
48
+ code: this.code,
49
+ data: void 0,
50
+ docs: this.docs,
51
+ fix: this.fix,
52
+ name: this.name,
53
+ why: this.why
54
+ };
55
+ }
56
+ };
57
+ function isRealtimeDocumentConflict(error) {
58
+ if (error instanceof RealtimeDocumentConflict) return true;
59
+ if (!error || typeof error !== "object" || !("code" in error)) return false;
60
+ return error.code === conflictCode;
61
+ }
62
+ //#endregion
63
+ export { defineRealtime as a, assertRealtimeCheckpoint as i, isRealtimeDocumentConflict as n, assertRealtimeAccess as r, RealtimeDocumentConflict as t };
@@ -1,5 +1,5 @@
1
- import { l as RealtimeEditor, s as RealtimeDocumentSnapshot } from "./types-Bw6-42Se.js";
2
- import "./layout-WNWejwOY.js";
1
+ import { f as RealtimeEditor, u as RealtimeDocumentSnapshot } from "./types-1DVVG5ro.js";
2
+ import "./layout-fyQnhwCg.js";
3
3
  import * as Y from "yjs";
4
4
  //#region src/document.d.ts
5
5
  /** Builds a new room document from a stored snapshot. Only use it for rooms no client holds yet. */
@@ -1,4 +1,5 @@
1
- import { n as realtimeDocumentLayout } from "./layout-Br1aOL7o.js";
1
+ import { n as isRecord } from "./object-CzKyK0hX.js";
2
+ import { n as realtimeDocumentLayout } from "./layout-DNaxppTZ.js";
2
3
  import "y-protocols/awareness";
3
4
  import * as Y from "yjs";
4
5
  import { ContentType, Item, Text, UndoManager, XmlElement } from "yjs";
@@ -1910,9 +1911,6 @@ function realtimeEditorSchema(editor) {
1910
1911
  }
1911
1912
  return schema;
1912
1913
  }
1913
- function isRecord(value) {
1914
- return !!value && typeof value === "object" && !Array.isArray(value);
1915
- }
1916
1914
  function stableJson(value) {
1917
1915
  if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
1918
1916
  if (isRecord(value)) {
@@ -1924,7 +1922,8 @@ function stableJson(value) {
1924
1922
  function realtimeJsonEqual(left, right) {
1925
1923
  return stableJson(left) === stableJson(right);
1926
1924
  }
1927
- function writeFields(map, fields) {
1925
+ /** Writes fields into a document's field map, inserting, replacing, and deleting only what differs. */
1926
+ function writeRealtimeFields(map, fields) {
1928
1927
  const next = fields ?? {};
1929
1928
  for (const key of map.keys()) if (!Object.hasOwn(next, key)) map.delete(key);
1930
1929
  for (const [key, value] of Object.entries(next)) {
@@ -1939,7 +1938,7 @@ async function createRealtimeYDoc(editor, snapshot) {
1939
1938
  try {
1940
1939
  document.transact(() => {
1941
1940
  prosemirrorJSONToYXmlFragment(realtimeEditorSchema(editor), content, document.getXmlFragment(realtimeDocumentLayout.body));
1942
- writeFields(document.getMap(realtimeDocumentLayout.fields), snapshot.fields);
1941
+ writeRealtimeFields(document.getMap(realtimeDocumentLayout.fields), snapshot.fields);
1943
1942
  });
1944
1943
  return document;
1945
1944
  } catch (error) {
@@ -1950,19 +1949,32 @@ async function createRealtimeYDoc(editor, snapshot) {
1950
1949
  function readRealtimeFields(document) {
1951
1950
  return document.getMap(realtimeDocumentLayout.fields).toJSON();
1952
1951
  }
1952
+ function readRealtimeBody(editor, document) {
1953
+ return {
1954
+ ...yXmlFragmentToProsemirrorJSON(document.getXmlFragment(realtimeDocumentLayout.body)),
1955
+ type: realtimeEditorSchema(editor).topNodeType.name
1956
+ };
1957
+ }
1953
1958
  async function readRealtimeYDoc(editor, document) {
1954
- const content = yXmlFragmentToProsemirrorJSON(document.getXmlFragment(realtimeDocumentLayout.body));
1959
+ const content = readRealtimeBody(editor, document);
1955
1960
  const fields = readRealtimeFields(document);
1956
1961
  return {
1957
1962
  body: await editor.toMarkdown(content),
1958
1963
  fields
1959
1964
  };
1960
1965
  }
1966
+ /**
1967
+ * Throws when the body of `document` does not fit the editor schema, such as a node type the schema does not know.
1968
+ * A codec that builds an editor from such JSON writes an empty or partial document.
1969
+ */
1970
+ function checkRealtimeBody(editor, document) {
1971
+ realtimeEditorSchema(editor).nodeFromJSON(readRealtimeBody(editor, document)).check();
1972
+ }
1961
1973
  /** Whether `fromMarkdown(body)` gives back the body of `document`, where `body` is what `toMarkdown` wrote for it. */
1962
1974
  async function realtimeCodecReadsBack(editor, document, body) {
1963
1975
  const schema = realtimeEditorSchema(editor);
1964
1976
  try {
1965
- return schema.nodeFromJSON(yXmlFragmentToProsemirrorJSON(document.getXmlFragment(realtimeDocumentLayout.body))).eq(schema.nodeFromJSON(await editor.fromMarkdown(body)));
1977
+ return schema.nodeFromJSON(readRealtimeBody(editor, document)).eq(schema.nodeFromJSON(await editor.fromMarkdown(body)));
1966
1978
  } catch {
1967
1979
  return false;
1968
1980
  }
@@ -1992,7 +2004,7 @@ async function diffRealtimeYDoc(editor, base, target) {
1992
2004
  isOMark: /* @__PURE__ */ new Map(),
1993
2005
  mapping: /* @__PURE__ */ new Map()
1994
2006
  });
1995
- if (fieldsChanged) writeFields(clone.getMap(realtimeDocumentLayout.fields), target.fields);
2007
+ if (fieldsChanged) writeRealtimeFields(clone.getMap(realtimeDocumentLayout.fields), target.fields);
1996
2008
  });
1997
2009
  return Y.encodeStateAsUpdate(clone, state);
1998
2010
  } finally {
@@ -2026,4 +2038,4 @@ function containsRealtimeState(document, state) {
2026
2038
  }
2027
2039
  }
2028
2040
  //#endregion
2029
- export { ySyncPluginKey as _, readRealtimeYDoc as a, realtimeStatusFingerprint as c, defaultSelectionBuilder as d, redo as f, ySyncPlugin as g, yCursorPlugin as h, keepRealtimeFinalNewline as i, writeRealtimeStatus as l, undo as m, createRealtimeYDoc as n, realtimeCodecReadsBack as o, relativePositionToAbsolutePosition as p, diffRealtimeYDoc as r, realtimeJsonEqual as s, containsRealtimeState as t, absolutePositionToRelativePosition as u, yUndoPlugin as v, yUndoPluginKey as y };
2041
+ export { yCursorPlugin as _, keepRealtimeFinalNewline as a, yUndoPlugin as b, realtimeJsonEqual as c, writeRealtimeStatus as d, absolutePositionToRelativePosition as f, undo as g, relativePositionToAbsolutePosition as h, diffRealtimeYDoc as i, realtimeStatusFingerprint as l, redo as m, containsRealtimeState as n, readRealtimeYDoc as o, defaultSelectionBuilder as p, createRealtimeYDoc as r, realtimeCodecReadsBack as s, checkRealtimeBody as t, writeRealtimeFields as u, ySyncPlugin as v, yUndoPluginKey as x, ySyncPluginKey as y };
@@ -0,0 +1,10 @@
1
+ import { Durability, DurabilityContext } from "@vite-hub/runtime/durability";
2
+ //#region src/durability.d.ts
3
+ /** What the build passes to `realtimeDurability()`: the Realtime driver that the build resolved. */
4
+ export interface RealtimeDurabilityInput {
5
+ /** `cloudflare`, `memory`, `postgres`, `redis`, or `auto` / `node` when the server picks it at boot. */
6
+ driver: string;
7
+ }
8
+ /** The durability of Realtime rooms, from the driver that the server uses at boot. */
9
+ export declare function realtimeDurability(input: RealtimeDurabilityInput, context: DurabilityContext): Durability[];
10
+ //#endregion
@@ -0,0 +1,46 @@
1
+ //#region src/durability.ts
2
+ const shared = {
3
+ cloudflare: "One Durable Object owns each room.",
4
+ postgres: "Postgres carries room updates between instances.",
5
+ redis: "Redis carries room updates between instances."
6
+ };
7
+ /**
8
+ * The driver that the server uses. An `auto` or `node` driver picks it at boot: `REDIS_URL`, then
9
+ * `REALTIME_POSTGRES_URL`, then a Postgres Default Database, then memory.
10
+ */
11
+ function resolveDriver(input, context) {
12
+ if (input.driver !== "auto" && input.driver !== "node") return { driver: input.driver };
13
+ if (context.env.REDIS_URL?.trim()) return {
14
+ driver: "redis",
15
+ source: "REDIS_URL"
16
+ };
17
+ if (context.env.REALTIME_POSTGRES_URL?.trim()) return {
18
+ driver: "postgres",
19
+ source: "REALTIME_POSTGRES_URL"
20
+ };
21
+ if (context.find("database")?.store === "postgres") return {
22
+ driver: "postgres",
23
+ source: "the Default Database"
24
+ };
25
+ return { driver: "memory" };
26
+ }
27
+ /** The durability of Realtime rooms, from the driver that the server uses at boot. */
28
+ function realtimeDurability(input, context) {
29
+ const { driver, source } = resolveDriver(input, context);
30
+ const reason = shared[driver];
31
+ if (reason) return [{
32
+ primitive: "realtime",
33
+ store: driver,
34
+ scope: "shared",
35
+ reason: source ? `${reason.slice(0, -1)}, from ${source}.` : reason
36
+ }];
37
+ return [{
38
+ primitive: "realtime",
39
+ store: "memory",
40
+ scope: "process",
41
+ reason: "Rooms live in the memory of this process. Clients on other instances do not see each other.",
42
+ fix: "Set REDIS_URL, or use a Postgres Default Database, so instances share rooms. Or send every Realtime connection to one instance."
43
+ }];
44
+ }
45
+ //#endregion
46
+ export { realtimeDurability };
@@ -1,4 +1,6 @@
1
1
  import { Editor, Node } from "@tiptap/core";
2
+ import Blockquote from "@tiptap/extension-blockquote";
3
+ import Code from "@tiptap/extension-code";
2
4
  import Image from "@tiptap/extension-image";
3
5
  import Document from "@tiptap/extension-document";
4
6
  import { TableKit } from "@tiptap/extension-table";
@@ -58,7 +60,23 @@ const Frontmatter = Node.create({
58
60
  });
59
61
  //#endregion
60
62
  //#region src/editor.ts
61
- const RealtimeDocument = Document.extend({ content: "frontmatter? block+" });
63
+ const RealtimeDocument = Document.extend({
64
+ content: "frontmatter? block+",
65
+ renderMarkdown(node, helpers, context) {
66
+ const [frontmatter, paragraph] = node.content ?? [];
67
+ const content = node.content?.length === 2 && frontmatter?.type === "frontmatter" && paragraph?.type === "paragraph" && !paragraph.content?.length ? [frontmatter] : node.content;
68
+ return this.parent?.({
69
+ ...node,
70
+ content
71
+ }, helpers, context) ?? "";
72
+ }
73
+ });
74
+ const RealtimeCode = Code.extend({ excludes: "" });
75
+ const escapedAlertMarker = /^> \\\[!(note|tip|important|warning|caution)\\\](?=\n|$)/i;
76
+ /** A blockquote that writes a GitHub alert's first line (`> [!NOTE]`) as it read it, so the alert stays an alert. */
77
+ const RealtimeBlockquote = Blockquote.extend({ renderMarkdown(node, helpers, context) {
78
+ return (this.parent?.(node, helpers, context) ?? "").replace(escapedAlertMarker, "> [!$1]");
79
+ } });
62
80
  const emptyRealtimeEditorDocument = {
63
81
  type: "doc",
64
82
  content: [{ type: "paragraph" }]
@@ -69,10 +87,14 @@ function createMarked() {
69
87
  function createRealtimeEditorExtensions(options = {}) {
70
88
  return [
71
89
  StarterKit.configure({
90
+ blockquote: false,
91
+ code: false,
72
92
  document: false,
73
93
  trailingNode: options.collaborative === true ? false : void 0,
74
94
  undoRedo: false
75
95
  }),
96
+ RealtimeBlockquote,
97
+ RealtimeCode,
76
98
  RealtimeDocument,
77
99
  Image,
78
100
  TableKit,
@@ -98,7 +120,12 @@ const realtimeMarkdownEditor = defineRealtimeEditor({
98
120
  injectCSS: false
99
121
  });
100
122
  try {
101
- return editor.getJSON();
123
+ const document = editor.getJSON();
124
+ if (document.content?.length === 1 && document.content[0]?.type === "frontmatter") document.content.push({
125
+ type: "paragraph",
126
+ attrs: {}
127
+ });
128
+ return document;
102
129
  } finally {
103
130
  editor.destroy();
104
131
  }
@@ -117,37 +144,4 @@ const realtimeMarkdownEditor = defineRealtimeEditor({
117
144
  }
118
145
  });
119
146
  //#endregion
120
- //#region src/layout.ts
121
- /**
122
- * Root types of every Realtime Y.Doc:
123
- * - `body`: Y.XmlFragment bound to the editor through TipTap Collaboration.
124
- * - `fields`: Y.Map with one JSON value per field; concurrent writes to one key resolve last-write-wins.
125
- * - `status`: Y.Map written only by the server (`digest`, `error`, `issues`, `savedAt`, `savedBy`).
126
- * The server closes connections whose updates change it.
127
- */
128
- const realtimeDocumentLayout = Object.freeze({
129
- body: "body",
130
- fields: "fields",
131
- status: "status"
132
- });
133
- function text(value) {
134
- return typeof value === "string" ? value : null;
135
- }
136
- function readRealtimeStatus(document) {
137
- const map = document.getMap(realtimeDocumentLayout.status);
138
- const issues = map.get("issues");
139
- const savedBy = map.get("savedBy");
140
- const status = {
141
- issues: Array.isArray(issues) ? issues : [],
142
- savedBy: savedBy && !Array.isArray(savedBy) && savedBy instanceof Object ? savedBy : null
143
- };
144
- return {
145
- digest: text(map.get("digest")),
146
- error: text(map.get("error")),
147
- issues: status.issues,
148
- savedAt: text(map.get("savedAt")),
149
- savedBy: status.savedBy
150
- };
151
- }
152
- //#endregion
153
- export { realtimeMarkdownEditor as a, defineRealtimeEditor as i, realtimeDocumentLayout as n, createRealtimeEditorExtensions as r, readRealtimeStatus as t };
147
+ export { defineRealtimeEditor as n, realtimeMarkdownEditor as r, createRealtimeEditorExtensions as t };
@@ -0,0 +1,141 @@
1
+ import { defineErrors } from "@vite-hub/runtime";
2
+ //#region src/error-diagnostics.ts
3
+ const realtimeErrorDiagnostics = /*#__PURE__*/ defineErrors({
4
+ docs: "https://vitehub.dev/docs/realtime/diagnostics",
5
+ codes: {
6
+ REALTIME_DISABLED: {
7
+ why: ({ action }) => `Realtime is disabled, so \`${action}()\` cannot run.`,
8
+ fix: "Set `enabled` to `true` on `useRealtimeTiptap()` before you call the method."
9
+ },
10
+ REALTIME_DISCONNECTED: {
11
+ why: ({ action }) => `The realtime document disconnected or changed during \`${action}()\`.`,
12
+ fix: "Call the method again after the new document connects. Read `synced` to know when it is ready."
13
+ },
14
+ REALTIME_INVALID_RESPONSE: {
15
+ why: ({ action }) => `The realtime server answered \`${action}()\` with a response that the client cannot use.`,
16
+ fix: "Use the same `@vite-hub/realtime` version on the client and the server, and build again."
17
+ },
18
+ REALTIME_MISSING_DOCUMENT: {
19
+ why: ({ action }) => `\`${action}()\` needs a document, and \`documentId\` is empty.`,
20
+ fix: "Pass a document path to `useRealtimeTiptap(definition, documentId)` before you call the method."
21
+ },
22
+ REALTIME_REQUEST_FAILED: {
23
+ why: ({ action, message, status }) => `The realtime \`${action}()\` request failed${status === void 0 ? "" : ` with HTTP ${status}`}${message ? `: ${message}` : "."}`,
24
+ fix: "Read `error.why` for the server message, and `error.cause` for a network error. Retry when the server is available again."
25
+ },
26
+ REALTIME_ROOM_ABORTED: {
27
+ why: "The request to the room stopped because its signal aborted.",
28
+ fix: "Nothing to fix when the caller stopped on purpose, such as a cancelled Agent run. Call again to ask once more."
29
+ },
30
+ REALTIME_ROOM_CROWDED: {
31
+ why: ({ count }) => `${count} browsers are in the room, and a request goes to one browser only.`,
32
+ fix: "Give each browser its own room, such as a random id for each tab, so that one browser answers."
33
+ },
34
+ REALTIME_ROOM_ELSEWHERE: {
35
+ why: "No browser in this instance is in the room. With Redis or Postgres, the browser can be connected to another instance, and requests reach only the browsers of the same instance.",
36
+ fix: "Route the browser and the caller to the same instance, such as with sticky sessions, or run one Node instance."
37
+ },
38
+ REALTIME_ROOM_EMPTY: {
39
+ why: "No browser is in the room. The page is closed, or it has not joined yet.",
40
+ fix: "Open the page again. The request waits a few seconds for a browser to join before it gives up."
41
+ },
42
+ REALTIME_ROOM_REFUSED: {
43
+ why: ({ reason }) => `The browser could not answer: ${reason}`,
44
+ fix: "Read the reason. Add `room.onRequest(handler)` on the page, and keep each answer under 1 MiB."
45
+ },
46
+ REALTIME_ROOM_REQUESTS_OFF: {
47
+ why: ({ definition }) => `The Realtime Definition "${definition}" does not take requests.`,
48
+ fix: "Define it with `defineRealtime({ access: \"public\", document: false, requests: true })`."
49
+ },
50
+ REALTIME_ROOM_TIMEOUT: {
51
+ why: ({ timeout }) => `The browser did not answer in ${timeout / 1e3} seconds.`,
52
+ fix: "Make the page answer sooner, or pass a longer `timeout` to `requestRealtimeRoom()`."
53
+ },
54
+ REALTIME_AWARENESS_OWNERSHIP_CONFLICT: {
55
+ why: "A realtime awareness client id belongs to another peer.",
56
+ fix: "Let each editor tab use its own Yjs awareness client. Do not reuse a client id on two connections."
57
+ },
58
+ REALTIME_AWARENESS_TOO_LARGE: {
59
+ why: "Realtime awareness state exceeds the 8 MiB room quota.",
60
+ fix: "Keep less data in awareness state. Store large values in the document or in Workspace."
61
+ },
62
+ REALTIME_DOCUMENT_TOO_LARGE: {
63
+ why: "The realtime document exceeds the 8 MiB room quota.",
64
+ fix: "Split the document into smaller documents, or keep large assets in Workspace or Blob."
65
+ },
66
+ REALTIME_INVALID_AWARENESS: {
67
+ why: "A realtime awareness update has a state that is not a plain object.",
68
+ fix: "Set awareness state to a plain object, for example `awareness.setLocalStateField('user', { name })`."
69
+ },
70
+ REALTIME_TOO_MANY_AWARENESS_CLIENTS: {
71
+ why: "One realtime peer sent more than 1,024 awareness clients.",
72
+ fix: "Use one awareness client for each editor tab."
73
+ },
74
+ REALTIME_ROOM_WRITE_CONFLICT: {
75
+ why: "Realtime room record compare-and-set failed.",
76
+ fix: "Connect again. Another Realtime instance changed the room at the same time. If it keeps failing, check that every instance uses the same Realtime bus."
77
+ },
78
+ REALTIME_WRITE_REJECTED: {
79
+ why: ({ problem, readOnly }) => problem === "missing-state" ? "Realtime update depends on state this room does not have." : problem === "status" ? "Realtime document status is written by the server." : readOnly ?? "This realtime connection is read-only.",
80
+ fix: "Write only through a writable connection, and do not change the `status` map, which the server writes. A client that misses room state connects again to sync it."
81
+ },
82
+ REALTIME_DOCUMENT_CONFLICT: {
83
+ why: ({ problem }) => problem ?? "The stored document changed since the realtime room loaded it.",
84
+ fix: "Realtime re-seeds the room from the stored document. Listen to `onReset()` to recover text that the room did not save."
85
+ },
86
+ REALTIME_BLOB_ETAG_MISSING: {
87
+ why: ({ pathname }) => `The Blob store returned no \`httpEtag\` for ${pathname}, so \`blobDocument()\` cannot save the file only if it is unchanged.`,
88
+ fix: "Pass a ViteHub Blob store, such as `blob` from `vite-hub/blob`, whose `head()` returns `httpEtag` on every driver. A store of your own must return `httpEtag` from `head()` and accept `ifMatch` in `put()`."
89
+ },
90
+ REALTIME_INVALID_PERSISTENCE: {
91
+ why: ({ name, reason }) => reason === "below-debounce" ? "Realtime `persistence.maxWait` must be at least `persistence.debounce`." : `Realtime \`persistence.${name}\` must be a non-negative number of milliseconds.`,
92
+ fix: "Set `persistence: { debounce: 2_000, maxWait: 10_000 }`, or remove the option to use these defaults."
93
+ },
94
+ REALTIME_MISSING_ACCESS: {
95
+ why: "The Realtime definition sets no access rule, so it does not say who can read and write its rooms.",
96
+ fix: "Set `auth: true` to require a signed-in user, add `authorize()` to decide each request, or set `access: \"public\"` to let anyone read and write."
97
+ },
98
+ REALTIME_INVALID_ACCESS: {
99
+ why: ({ reason }) => reason === "public-with-rule" ? "The Realtime definition sets `access: \"public\"` together with `auth` or `authorize()`, so its access rule is not clear." : reason === "not-public" ? "The Realtime definition sets `access` to a value other than \"public\"." : "The Realtime definition sets `origins()` with `auth: true` and no `identify()`. The ViteHub Auth session is a cookie, so ViteHub accepts it only from the app's own origin.",
100
+ fix: ({ reason }) => reason === "origins-without-identify" ? "Remove `origins()`, or add `identify()` that reads a credential the page sends on purpose, such as a ticket in `params`." : "Use `access: \"public\"` alone for open rooms. To limit access, remove `access` and set `auth: true` or `authorize()`."
101
+ },
102
+ REALTIME_CHECKPOINT_UNSUPPORTED: {
103
+ why: "The Realtime definition sets `history.checkpoint`, but its document adapter has no `checkpoint()` method, so `history.checkpoint()` could never run.",
104
+ fix: "Add `checkpoint(context, { digest, message, user })` to the document adapter, use `document: { workspace }`, or remove `history`."
105
+ },
106
+ REALTIME_INVALID_USER: {
107
+ why: "The realtime identity needs a user `id` that is a non-empty string of at most 256 characters.",
108
+ fix: "Return a user with an `id` from the Auth session or from `authorize()`."
109
+ },
110
+ REALTIME_MISSING_DIGEST: {
111
+ why: ({ operation }) => operation === "save" ? "Realtime saves need Workspace file digests, and the Workspace Store did not return one." : "Realtime checkpoints need a stored document, and the save returned no digest.",
112
+ fix: "Use a Workspace Store that returns file digests, or return `digest` from the document adapter `save()`."
113
+ },
114
+ REALTIME_INVALID_POSTGRES_URL: {
115
+ why: "REALTIME_POSTGRES_URL is set, and it is not a `postgres://` or `postgresql://` URL.",
116
+ fix: "Set REALTIME_POSTGRES_URL to a Postgres URL, or remove it so that Realtime uses the connection of the Default Database."
117
+ },
118
+ REALTIME_MISSING_BUS_CONNECTION: {
119
+ why: ({ driver }) => driver === "redis" ? "Realtime driver \"redis\" shares rooms through Redis, and REDIS_URL is not set." : "Realtime driver \"postgres\" shares rooms through Postgres, and the app has no Postgres Default Database and no REALTIME_POSTGRES_URL.",
120
+ fix: "Set REDIS_URL for Redis. For Postgres, define the Default Database with `dialect: \"postgresql\"`, or set REALTIME_POSTGRES_URL. Or set `realtime.driver` to \"auto\"."
121
+ },
122
+ REALTIME_ROOM_LOCK_TIMEOUT: {
123
+ why: "Realtime waited 30 seconds for the save lock of a room, and another instance still holds it.",
124
+ fix: "Make the document adapter `save()` finish in less than 30 seconds. Realtime tries the save again."
125
+ },
126
+ REALTIME_DRIVER_CONFLICT: {
127
+ why: ({ driver, host }) => driver === "memory" ? `Realtime driver "memory" is single-process only, and the ${host} host runs more than one process.` : driver === "cloudflare" ? `Realtime driver "cloudflare" does not work with the ${host} host.` : `Realtime driver "${driver}" needs a Node.js server, and the ${host} host does not run one.`,
128
+ fix: "Set `realtime.driver` to \"cloudflare\" with a Cloudflare host. With the Node host, use \"auto\", \"postgres\", \"redis\", or \"memory\"."
129
+ },
130
+ REALTIME_MISSING_DRIVER: {
131
+ why: "Realtime production builds need one room driver, and ViteHub cannot select one for this deployment.",
132
+ fix: "Deploy with a Cloudflare host to use Durable Objects, or with the Node host to share rooms through Postgres or Redis."
133
+ },
134
+ REALTIME_RENAMED_AUTHORITY_KEY: {
135
+ why: ({ value }) => `\`realtime.authority\` is ${value}. ViteHub renamed this key to \`driver\`, and it does not read \`authority\`, so Realtime would not use the driver you chose.`,
136
+ fix: ({ value }) => `Set \`realtime: { driver: ${value} }\`, or run \`npx @vite-hub/codemods driver-key\` to rename it in every config file.`
137
+ }
138
+ }
139
+ });
140
+ //#endregion
141
+ export { realtimeErrorDiagnostics as t };
package/dist/index.d.ts CHANGED
@@ -1,13 +1,18 @@
1
- import { C as RealtimeSaveOptions, D as RealtimeVerifyResult, E as RealtimeUser, O as RealtimeWorkspaceChange, S as RealtimeResetReason, T as RealtimeSaved, _ as RealtimePerson, a as RealtimeDocumentAdapter, b as RealtimeRequestContext, c as RealtimeDocumentStatus, d as RealtimeHistoryOptions, f as RealtimeHoldOptions, g as RealtimePersistenceOptions, h as RealtimeModuleOptions, i as RealtimeDefinition, k as RealtimeWorkspaceDocumentOptions, l as RealtimeEditor, m as RealtimeLoadedDocument, n as RealtimeAuthorizeContext, o as RealtimeDocumentContext, p as RealtimeIssue, r as RealtimeCheckpoint, s as RealtimeDocumentSnapshot, u as RealtimeFieldValue, v as RealtimeReadOnlyReason, w as RealtimeSaveResult, x as RealtimeRequestErrorCode } from "./types-Bw6-42Se.js";
1
+ import { A as RealtimeSaveOptions, C as RealtimeReadOnlyReason, D as RealtimeRequestEvent, E as RealtimeRequestErrorCode, F as RealtimeWorkspaceChange, I as RealtimeWorkspaceDocumentOptions, M as RealtimeSaved, N as RealtimeUser, O as RealtimeResetReason, P as RealtimeVerifyResult, S as RealtimePresenceDefinition, T as RealtimeRequestContext, _ as RealtimeLoadedDocument, a as RealtimeDefinition, b as RealtimePersistenceOptions, c as RealtimeDocumentContext, d as RealtimeDocumentStatus, f as RealtimeEditor, g as RealtimeIssue, h as RealtimeHoldOptions, i as RealtimeCheckpoint, j as RealtimeSaveResult, k as RealtimeRoomRequestErrorCode, l as RealtimeDocumentDefinition, m as RealtimeHistoryOptions, n as RealtimeAuthorizeContext, o as RealtimeDefinitionAccess, p as RealtimeFieldValue, s as RealtimeDocumentAdapter, u as RealtimeDocumentSnapshot, v as RealtimeOptions, x as RealtimePerson, y as RealtimeOriginContext } from "./types-1DVVG5ro.js";
2
2
  import { n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "./conflict-CmZizTYl.js";
3
- import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-WNWejwOY.js";
3
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-fyQnhwCg.js";
4
4
  //#region src/definition.d.ts
5
+ /**
6
+ * Checks a definition when the server loads it. A definition must say who can use its rooms: `auth: true`,
7
+ * `authorize()`, or `access: "public"`. `history.checkpoint` needs a document that can record history: a Workspace
8
+ * document, or an adapter with `checkpoint()`.
9
+ */
5
10
  export declare function defineRealtime(definition: RealtimeDefinition): RealtimeDefinition;
6
11
  //#endregion
7
12
  //#region src/editor.d.ts
8
13
  export declare function createRealtimeEditorExtensions(options?: {
9
14
  collaborative?: boolean;
10
- }): (import("@tiptap/core").Extension<import("@tiptap/starter-kit").StarterKitOptions, any> | import("@tiptap/core").Node<any, any> | import("@tiptap/core").Node<import("@tiptap/extension-image").ImageOptions, any> | import("@tiptap/core").Extension<import("@tiptap/extension-table").TableKitOptions, any> | import("@tiptap/core").Extension<import("@tiptap/markdown").MarkdownExtensionOptions, import("@tiptap/markdown").MarkdownExtensionStorage>)[];
15
+ }): (import("@tiptap/core").Extension<import("@tiptap/starter-kit").StarterKitOptions, any> | import("@tiptap/core").Node<import("@tiptap/extension-blockquote").BlockquoteOptions, any> | import("@tiptap/core").Mark<import("@tiptap/extension-code").CodeOptions, any> | import("@tiptap/core").Node<any, any> | import("@tiptap/core").Node<import("@tiptap/extension-image").ImageOptions, any> | import("@tiptap/core").Extension<import("@tiptap/extension-table").TableKitOptions, any> | import("@tiptap/core").Extension<import("@tiptap/markdown").MarkdownExtensionOptions, import("@tiptap/markdown").MarkdownExtensionStorage>)[];
11
16
  /** Declares an editor schema and Markdown codec that the server and the browser share. */
12
17
  export declare function defineRealtimeEditor(editor: RealtimeEditor): RealtimeEditor;
13
18
  /**
@@ -16,4 +21,4 @@ export declare function defineRealtimeEditor(editor: RealtimeEditor): RealtimeEd
16
21
  */
17
22
  export declare const realtimeMarkdownEditor: RealtimeEditor;
18
23
  //#endregion
19
- export { type RealtimeAuthorizeContext, type RealtimeCheckpoint, type RealtimeDefinition, type RealtimeDocumentAdapter, RealtimeDocumentConflict, type RealtimeDocumentContext, type RealtimeDocumentSnapshot, type RealtimeDocumentStatus, type RealtimeEditor, type RealtimeFieldValue, type RealtimeHistoryOptions, type RealtimeHoldOptions, type RealtimeIssue, type RealtimeLoadedDocument, type RealtimeModuleOptions, type RealtimePersistenceOptions, type RealtimePerson, type RealtimeReadOnlyReason, type RealtimeRequestContext, type RealtimeRequestErrorCode, type RealtimeResetReason, type RealtimeSaveOptions, type RealtimeSaveResult, type RealtimeSaved, type RealtimeUser, type RealtimeVerifyResult, type RealtimeWorkspaceChange, type RealtimeWorkspaceDocumentOptions, isRealtimeDocumentConflict, readRealtimeStatus, realtimeDocumentLayout };
24
+ export { type RealtimeAuthorizeContext, type RealtimeCheckpoint, type RealtimeDefinition, type RealtimeDefinitionAccess, type RealtimeDocumentAdapter, RealtimeDocumentConflict, type RealtimeDocumentContext, type RealtimeDocumentDefinition, type RealtimeDocumentSnapshot, type RealtimeDocumentStatus, type RealtimeEditor, type RealtimeFieldValue, type RealtimeHistoryOptions, type RealtimeHoldOptions, type RealtimeIssue, type RealtimeLoadedDocument, type RealtimeOptions, type RealtimeOriginContext, type RealtimePersistenceOptions, type RealtimePerson, type RealtimePresenceDefinition, type RealtimeReadOnlyReason, type RealtimeRequestContext, type RealtimeRequestErrorCode, type RealtimeRequestEvent, type RealtimeResetReason, type RealtimeRoomRequestErrorCode, type RealtimeSaveOptions, type RealtimeSaveResult, type RealtimeSaved, type RealtimeUser, type RealtimeVerifyResult, type RealtimeWorkspaceChange, type RealtimeWorkspaceDocumentOptions, isRealtimeDocumentConflict, readRealtimeStatus, realtimeDocumentLayout };