@vite-hub/realtime 0.0.4 → 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/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # @vite-hub/realtime
2
2
 
3
3
  <p>
4
- <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
- <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
- <img alt="Yjs" src="https://img.shields.io/badge/Yjs-collaboration-f7df1e?style=flat-square">
7
- <img alt="Vite" src="https://img.shields.io/badge/Vite-discovery-646cff?style=flat-square">
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://comark-ui.onmax.me/badge.svg?label=ViteHub&amp;value=vitehub.dev"></a>
5
+ <img alt="TypeScript" src="https://comark-ui.onmax.me/badge.svg?label=TypeScript&amp;value=ready">
6
+ <img alt="Yjs" src="https://comark-ui.onmax.me/badge.svg?label=Yjs&amp;value=collaboration">
7
+ <img alt="Vite" src="https://comark-ui.onmax.me/badge.svg?label=Vite&amp;value=discovery">
8
8
  </p>
9
9
 
10
10
  `@vite-hub/realtime` synchronizes TipTap editors through Yjs while a ViteHub Workspace owns the canonical Markdown files. Use the package directly when you compose ViteHub's modular Vite integrations. Use [`vite-hub`](https://www.npmjs.com/package/vite-hub) when you want the combined distribution.
@@ -87,12 +87,23 @@ const connection = computed(() =>
87
87
 
88
88
  Open the page in two tabs. Each tab first reports `Realtime: connecting`, then `Document synced`. Edits sync between them, and `realtime.people.value` reports the connected people.
89
89
 
90
+ `realtime.extensions` also draws other people's carets and selections with TipTap's CollaborationCaret classes. Pass `carets: { render, selectionRender }` to change their markup, or `carets: false` to leave them out:
91
+
92
+ ```ts
93
+ const realtime = useRealtimeTiptap("docs", "guides/welcome.md", {
94
+ carets: {
95
+ selectionRender: user => ({ class: "ProseMirror-yjs-selection", style: `background-color: ${user.color}33` }),
96
+ },
97
+ })
98
+ ```
99
+
90
100
  Room updates do not write the Workspace document. Save the current Markdown and create a Workspace snapshot explicitly:
91
101
 
92
102
  ```ts
93
- const checkpoint = await realtime.history.checkpoint()
103
+ const [error, checkpoint] = await realtime.history.checkpoint()
104
+ if (error) throw error
94
105
 
95
- console.log(checkpoint.content)
106
+ console.log(checkpoint.document.body)
96
107
  console.log(checkpoint.snapshot.id)
97
108
  ```
98
109
 
@@ -103,8 +114,11 @@ console.log(checkpoint.snapshot.id)
103
114
  - `authority: "cloudflare"` uses a SQLite-backed Cloudflare Durable Object. `authority: "auto"` selects it only when a Cloudflare Nitro preset or hosting environment can be resolved. Other production builds require an explicit authority.
104
115
  - Durable rooms do not make Workspace files durable. Production checkpoints need a durable Workspace Store with conditional writes; memory Workspace Stores are rejected for durable checkpoints.
105
116
  - Realtime Definitions are public by default. Set `auth: true` only after configuring ViteHub Auth; this verifies the session and replaces client-supplied presence identity. Presence in a public definition is untrusted and must not authorize application actions.
117
+ - Other packages can contribute definitions through `hubRealtime({ contribute })`, such as Content live editing. Realtime adds them only when the build has a room authority and leaves them out without an error otherwise. A file in `server/realtime` with the same name wins.
118
+ - Realtime routes follow the app base, including a Nuxt `app.baseURL`. With Vite `base: "/portal/"`, connections use `/portal/api/_vitehub/realtime/**`; Nitro's own `baseURL` is counted once.
119
+ - `refreshRealtimeDocument(definition, id)` tells an open room that its stored copy changed outside it. Document adapters may implement `hold()` and `release()` to keep a lease while writers are in a room.
106
120
  - One WebSocket message is limited to 1 MiB. Document state and awareness state are each limited to 8 MiB per room, and one peer can own at most 1,024 awareness clients.
107
- - Changing or disabling the document, or disposing its Vue scope, destroys the document provider. The application still owns editor disposal, checkpoint error handling, and reconnect UX.
121
+ - Changing or disabling the document, or disposing its Vue scope, destroys the document provider. `save()`, `history.checkpoint()`, and `refresh()` return `[error, data]` with a `RealtimeRequestErrorCode`. A checkpoint returns `REALTIME_DISCONNECTED` during a document switch until the Vue watcher creates the new document, and when its original document is disconnected or replaced during a retry. The application still owns editor disposal, checkpoint error handling, and reconnect UX.
108
122
 
109
123
  ## Public imports
110
124
 
@@ -119,7 +133,7 @@ Generated files under `.vitehub/nitro/realtime` are inspectable build output, no
119
133
 
120
134
  ## Learn more
121
135
 
122
- - [Realtime collaboration](https://vitehub.dev/docs/reference/realtime) covers authorities, checkpoints, workspace events, quotas, and generated output.
123
- - [Workspace](https://vitehub.dev/docs/server-primitives/workspace) covers stores, write rules, snapshots, and persistence.
124
- - [Auth](https://vitehub.dev/docs/server-primitives/auth) covers session setup and trusted origins.
136
+ - [Realtime collaboration](https://vitehub.dev/docs/realtime) covers authorities, checkpoints, workspace events, quotas, and generated output.
137
+ - [Workspace](https://vitehub.dev/docs/workspace) covers stores, write rules, snapshots, and persistence.
138
+ - [Auth](https://vitehub.dev/docs/auth) covers session setup and trusted origins.
125
139
  - [Configuration options](https://vitehub.dev/docs/reference/config-options) lists every Realtime module option.
@@ -0,0 +1,6 @@
1
+ //#region src/application-path.ts
2
+ function resolveRealtimeApplicationPath(path, baseURL = typeof __VITEHUB_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_APP_BASE_URL__) {
3
+ return baseURL === "/" ? path : `${baseURL.replace(/\/+$/, "")}${path}`;
4
+ }
5
+ //#endregion
6
+ export { resolveRealtimeApplicationPath as t };
@@ -0,0 +1,46 @@
1
+ import { O as RealtimeWorkspaceChange, _ as RealtimePerson } from "./types-Bw6-42Se.js";
2
+ import * as awarenessProtocol from "y-protocols/awareness";
3
+ //#region src/client.d.ts
4
+ export type RealtimeRoomStatus = "connected" | "connecting" | "disconnected";
5
+ export interface RealtimeRoomOptions {
6
+ /** The app base path for a prebuilt client, such as `/portal/`. Defaults to the app's build-time base. */
7
+ baseURL?: string;
8
+ /**
9
+ * The person this browser shows as. A definition with `identify` or `auth: true` replaces it with the server's
10
+ * identity, so only public definitions show it as given.
11
+ */
12
+ identity?: {
13
+ id: string;
14
+ name?: string;
15
+ image?: string;
16
+ };
17
+ /** Also join the workspace events room of the definition, for `notify()` and `onChange()`. Default `false`. */
18
+ changes?: boolean;
19
+ }
20
+ export interface RealtimeRoom {
21
+ /** The Yjs awareness of the room. Set your own fields with `setLocal()`. */
22
+ readonly awareness: awarenessProtocol.Awareness;
23
+ /** This browser's awareness client id. */
24
+ readonly clientId: number;
25
+ /** The people in the room, this browser included. */
26
+ people(): RealtimePerson[];
27
+ /** The field values that each other client set with `setLocal()`, by client id. */
28
+ states(): Map<number, Record<string, unknown>>;
29
+ status(): RealtimeRoomStatus;
30
+ /** Sets one field of this browser's awareness state, such as a cursor. `null` removes it. */
31
+ setLocal(field: string, value: unknown): void;
32
+ /** Sends a change hint to every other browser of the definition. Needs `changes: true`. */
33
+ notify(change: RealtimeWorkspaceChange): void;
34
+ /** Runs when the people, their awareness fields, or the status change. Returns a function that removes it. */
35
+ onUpdate(listener: () => void): () => void;
36
+ /** Runs for each change hint from another browser. Needs `changes: true`. Returns a function that removes it. */
37
+ onChange(listener: (change: RealtimeWorkspaceChange) => void): () => void;
38
+ destroy(): void;
39
+ }
40
+ /**
41
+ * Joins one room of a Realtime Definition for presence: who is there and what each person shares through awareness,
42
+ * such as a cursor. It does not edit the room document. Use it outside Vue, or when a page needs presence without an
43
+ * editor; `useRealtimeTiptap()` from `@vite-hub/realtime/vue` is the editor client.
44
+ */
45
+ export declare function connectRealtimeRoom(definition: string, documentId: string, options?: RealtimeRoomOptions): RealtimeRoom;
46
+ //#endregion
package/dist/client.js ADDED
@@ -0,0 +1,142 @@
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";
3
+ import "lib0/decoding";
4
+ import * as encoding from "lib0/encoding";
5
+ import * as awarenessProtocol from "y-protocols/awareness";
6
+ import { WebsocketProvider } from "y-websocket";
7
+ import * as Y from "yjs";
8
+ //#region src/client.ts
9
+ /**
10
+ * 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.
13
+ */
14
+ function connectRealtimeRoom(definition, documentId, options = {}) {
15
+ const updateListeners = /* @__PURE__ */ new Set();
16
+ const changeListeners = /* @__PURE__ */ new Set();
17
+ const pendingChanges = [];
18
+ let currentStatus = "connecting";
19
+ let destroyed = false;
20
+ let document;
21
+ let provider;
22
+ const emit = () => {
23
+ for (const listener of updateListeners) listener();
24
+ };
25
+ const url = () => {
26
+ return `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`, options.baseURL)}`;
27
+ };
28
+ const room = documentId.split("/").map(encodeURIComponent).join("/");
29
+ const localState = {};
30
+ function connect() {
31
+ document = new Y.Doc();
32
+ provider = new WebsocketProvider(url(), room, document, {
33
+ disableBc: true,
34
+ params: {}
35
+ });
36
+ const current = provider;
37
+ current.messageHandlers[5] = (_encoder, decoder) => {
38
+ const control = decodeRealtimeControlPayload(decoder);
39
+ if (!control) return;
40
+ if (control.type === "session") {
41
+ current.params.epoch = control.epoch;
42
+ return;
43
+ }
44
+ current.destroy();
45
+ document.destroy();
46
+ if (!destroyed) connect();
47
+ };
48
+ current.awareness.off("update", current._awarenessUpdateHandler);
49
+ current.awareness.on("update", ({ added, removed, updated }) => {
50
+ const own = [
51
+ ...added,
52
+ ...updated,
53
+ ...removed
54
+ ].filter((client) => client === current.doc.clientID);
55
+ const socket = current.ws;
56
+ if (!own.length || !current.wsconnected || !socket || socket.readyState !== socket.OPEN) return;
57
+ const encoder = encoding.createEncoder();
58
+ encoding.writeVarUint(encoder, 1);
59
+ encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(current.awareness, own));
60
+ socket.send(encoding.toUint8Array(encoder));
61
+ });
62
+ const identity = options.identity ?? { id: `guest:${document.clientID}` };
63
+ current.awareness.setLocalState({
64
+ ...localState,
65
+ user: createRealtimeIdentity({
66
+ ...identity,
67
+ id: identity.id || `guest:${document.clientID}`
68
+ })
69
+ });
70
+ current.awareness.on("change", emit);
71
+ current.on("status", (event) => {
72
+ currentStatus = event.status;
73
+ emit();
74
+ });
75
+ }
76
+ connect();
77
+ let changes;
78
+ if (options.changes) {
79
+ changes = new WebsocketProvider(url(), encodeURIComponent(workspaceRoomId), new Y.Doc(), {
80
+ disableBc: true,
81
+ params: { workspace: "events" }
82
+ });
83
+ changes.awareness.setLocalState(null);
84
+ changes.messageHandlers[4] = (_encoder, decoder) => {
85
+ const change = decodeWorkspaceChangePayload(decoder);
86
+ if (!change) return;
87
+ for (const listener of changeListeners) listener(change);
88
+ };
89
+ changes.on("status", (event) => {
90
+ if (event.status === "connected") flush();
91
+ });
92
+ }
93
+ function flush() {
94
+ const socket = changes?.ws;
95
+ if (!changes?.wsconnected || !socket || socket.readyState !== socket.OPEN) return;
96
+ while (pendingChanges.length) socket.send(Uint8Array.from(encodeWorkspaceChange(pendingChanges.shift())));
97
+ }
98
+ return {
99
+ get awareness() {
100
+ return provider.awareness;
101
+ },
102
+ get clientId() {
103
+ return document.clientID;
104
+ },
105
+ people: () => getRealtimePeople(provider.awareness.getStates()),
106
+ states: () => {
107
+ const states = new Map(provider.awareness.getStates());
108
+ states.delete(document.clientID);
109
+ return states;
110
+ },
111
+ status: () => currentStatus,
112
+ setLocal(field, value) {
113
+ if (value === null) delete localState[field];
114
+ else localState[field] = value;
115
+ provider.awareness.setLocalStateField(field, value);
116
+ },
117
+ notify(change) {
118
+ if (!changes) return;
119
+ pendingChanges.push(change);
120
+ flush();
121
+ },
122
+ onUpdate(listener) {
123
+ updateListeners.add(listener);
124
+ return () => updateListeners.delete(listener);
125
+ },
126
+ onChange(listener) {
127
+ changeListeners.add(listener);
128
+ return () => changeListeners.delete(listener);
129
+ },
130
+ destroy() {
131
+ destroyed = true;
132
+ provider.destroy();
133
+ document.destroy();
134
+ changes?.destroy();
135
+ changes?.doc.destroy();
136
+ updateListeners.clear();
137
+ changeListeners.clear();
138
+ }
139
+ };
140
+ }
141
+ //#endregion
142
+ export { connectRealtimeRoom };
@@ -0,0 +1,17 @@
1
+ import { Diagnostic } from "nostics";
2
+ //#region src/conflict.d.ts
3
+ /** Thrown by a document adapter when the stored digest no longer matches `ifDigest`. */
4
+ declare class RealtimeDocumentConflict extends Diagnostic {
5
+ constructor(why?: string);
6
+ toJSON(): {
7
+ code: string;
8
+ data: undefined;
9
+ docs: string | undefined;
10
+ fix: string | undefined;
11
+ name: string;
12
+ why: string;
13
+ };
14
+ }
15
+ declare function isRealtimeDocumentConflict(error: unknown): boolean;
16
+ //#endregion
17
+ export { isRealtimeDocumentConflict as n, RealtimeDocumentConflict as t };
@@ -0,0 +1,34 @@
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cvm6vRXQ.js";
2
+ import { Diagnostic } from "nostics";
3
+ //#region src/conflict.ts
4
+ const conflictCode = "REALTIME_DOCUMENT_CONFLICT";
5
+ /** Thrown by a document adapter when the stored digest no longer matches `ifDigest`. */
6
+ var RealtimeDocumentConflict = class RealtimeDocumentConflict extends Diagnostic {
7
+ constructor(why) {
8
+ const { code, docs, fix } = realtimeErrorDiagnostics.REALTIME_DOCUMENT_CONFLICT({ problem: why });
9
+ super({
10
+ code,
11
+ docs,
12
+ fix,
13
+ why: why ?? "The stored document changed since the realtime room loaded it."
14
+ }, RealtimeDocumentConflict);
15
+ this.name = "RealtimeDocumentConflict";
16
+ }
17
+ toJSON() {
18
+ return {
19
+ code: this.code,
20
+ data: void 0,
21
+ docs: this.docs,
22
+ fix: this.fix,
23
+ name: this.name,
24
+ why: this.why
25
+ };
26
+ }
27
+ };
28
+ function isRealtimeDocumentConflict(error) {
29
+ if (error instanceof RealtimeDocumentConflict) return true;
30
+ if (!error || typeof error !== "object" || !("code" in error)) return false;
31
+ return error.code === conflictCode;
32
+ }
33
+ //#endregion
34
+ export { isRealtimeDocumentConflict as n, RealtimeDocumentConflict as t };