@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/vue.js ADDED
@@ -0,0 +1,328 @@
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";
4
+ import "lib0/decoding";
5
+ import { Plugin, PluginKey } from "@tiptap/pm/state";
6
+ import { useUserSession } from "@vite-hub/auth/vue";
7
+ 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
10
+ function isChangeOrigin(transaction) {
11
+ return !!transaction.getMeta(ySyncPluginKey);
12
+ }
13
+ function getYAbsolutePosition(state, relativePos) {
14
+ const ystate = ySyncPluginKey.getState(state);
15
+ return relativePositionToAbsolutePosition(ystate.doc, ystate.type, relativePos, ystate.binding.mapping) || 0;
16
+ }
17
+ function getYRelativePosition(state, absolutePos) {
18
+ const ystate = ySyncPluginKey.getState(state);
19
+ return absolutePositionToRelativePosition(absolutePos, ystate.type, ystate.binding.mapping);
20
+ }
21
+ var CollaborationMappablePosition = class _CollaborationMappablePosition extends MappablePosition {
22
+ constructor(position, yRelativePosition) {
23
+ super(position);
24
+ this.yRelativePosition = yRelativePosition;
25
+ }
26
+ /**
27
+ * Creates a CollaborationMappablePosition from a JSON object.
28
+ */
29
+ static fromJSON(json) {
30
+ return new _CollaborationMappablePosition(json.position, json.yRelativePosition);
31
+ }
32
+ /**
33
+ * Converts the CollaborationMappablePosition to a JSON object.
34
+ */
35
+ toJSON() {
36
+ return {
37
+ position: this.position,
38
+ yRelativePosition: this.yRelativePosition
39
+ };
40
+ }
41
+ };
42
+ function createMappablePosition(position, state) {
43
+ return new CollaborationMappablePosition(position, getYRelativePosition(state, position));
44
+ }
45
+ function getUpdatedPosition$1(position, transaction, state) {
46
+ const yRelativePosition = position instanceof CollaborationMappablePosition ? position.yRelativePosition : null;
47
+ if (isChangeOrigin(transaction) && yRelativePosition) return {
48
+ position: new CollaborationMappablePosition(getYAbsolutePosition(state, yRelativePosition), yRelativePosition),
49
+ mapResult: null
50
+ };
51
+ const result = getUpdatedPosition(position, transaction);
52
+ const absolutePosition = result.position.position;
53
+ return {
54
+ position: new CollaborationMappablePosition(absolutePosition, yRelativePosition != null ? yRelativePosition : getYRelativePosition(state, absolutePosition)),
55
+ mapResult: result.mapResult
56
+ };
57
+ }
58
+ var index_default = Extension.create({
59
+ name: "collaboration",
60
+ priority: 1e3,
61
+ addOptions() {
62
+ return {
63
+ document: null,
64
+ field: "default",
65
+ fragment: null,
66
+ provider: null
67
+ };
68
+ },
69
+ addStorage() {
70
+ return { isDisabled: false };
71
+ },
72
+ onCreate() {
73
+ if (this.editor.extensionManager.extensions.find((extension) => extension.name === "undoRedo")) console.warn("[tiptap warn]: \"@tiptap/extension-collaboration\" comes with its own history support and is not compatible with \"@tiptap/extension-undo-redo\".");
74
+ },
75
+ onBeforeCreate() {
76
+ this.editor.utils.getUpdatedPosition = (position, transaction) => getUpdatedPosition$1(position, transaction, this.editor.state);
77
+ this.editor.utils.createMappablePosition = (position) => createMappablePosition(position, this.editor.state);
78
+ },
79
+ addCommands() {
80
+ return {
81
+ undo: () => ({ tr, state, dispatch }) => {
82
+ tr.setMeta("preventDispatch", true);
83
+ if (yUndoPluginKey.getState(state).undoManager.undoStack.length === 0) return false;
84
+ if (!dispatch) return true;
85
+ return undo(state);
86
+ },
87
+ redo: () => ({ tr, state, dispatch }) => {
88
+ tr.setMeta("preventDispatch", true);
89
+ if (yUndoPluginKey.getState(state).undoManager.redoStack.length === 0) return false;
90
+ if (!dispatch) return true;
91
+ return redo(state);
92
+ }
93
+ };
94
+ },
95
+ addKeyboardShortcuts() {
96
+ return {
97
+ "Mod-z": () => this.editor.commands.undo(),
98
+ "Mod-y": () => this.editor.commands.redo(),
99
+ "Shift-Mod-z": () => this.editor.commands.redo()
100
+ };
101
+ },
102
+ addProseMirrorPlugins() {
103
+ const fragment = this.options.fragment ? this.options.fragment : this.options.document.getXmlFragment(this.options.field);
104
+ const yUndoPluginInstance = yUndoPlugin(this.options.yUndoOptions);
105
+ const originalUndoPluginView = yUndoPluginInstance.spec.view;
106
+ yUndoPluginInstance.spec.view = (view) => {
107
+ const { undoManager } = yUndoPluginKey.getState(view.state);
108
+ if (undoManager.restore) {
109
+ undoManager.restore();
110
+ undoManager.restore = () => {};
111
+ }
112
+ const viewRet = originalUndoPluginView ? originalUndoPluginView(view) : void 0;
113
+ return { destroy: () => {
114
+ const hasUndoManSelf = undoManager.trackedOrigins.has(undoManager);
115
+ const observers = undoManager._observers;
116
+ undoManager.restore = () => {
117
+ if (hasUndoManSelf) undoManager.trackedOrigins.add(undoManager);
118
+ undoManager.doc.on("afterTransaction", undoManager.afterTransactionHandler);
119
+ undoManager._observers = observers;
120
+ };
121
+ if (viewRet == null ? void 0 : viewRet.destroy) viewRet.destroy();
122
+ } };
123
+ };
124
+ return [
125
+ ySyncPlugin(fragment, {
126
+ ...this.options.ySyncOptions,
127
+ onFirstRender: this.options.onFirstRender
128
+ }),
129
+ yUndoPluginInstance,
130
+ this.editor.options.enableContentCheck && new Plugin({
131
+ key: new PluginKey("filterInvalidContent"),
132
+ filterTransaction: (transaction) => {
133
+ if (!isChangeOrigin(transaction)) return true;
134
+ if (this.storage.isDisabled) return false;
135
+ if (!transaction.docChanged) return true;
136
+ try {
137
+ transaction.doc.check();
138
+ return true;
139
+ } catch (error) {
140
+ this.storage.isDisabled = true;
141
+ this.editor.emit("contentError", {
142
+ error,
143
+ editor: this.editor,
144
+ disableCollaboration: () => {
145
+ var _a;
146
+ (_a = fragment.doc) == null || _a.destroy();
147
+ }
148
+ });
149
+ return true;
150
+ }
151
+ }
152
+ })
153
+ ].filter(Boolean);
154
+ }
155
+ });
156
+ //#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
+ }
162
+ //#endregion
163
+ //#region src/vue.ts
164
+ const workspaceChangeFlushIntervalMs = 11;
165
+ function useRealtimeTiptap(definition, documentId, options = {}) {
166
+ const { user } = useUserSession();
167
+ const document = shallowRef();
168
+ const provider = shallowRef();
169
+ const workspaceProvider = shallowRef();
170
+ const workspaceChange = shallowRef();
171
+ const people = shallowRef([]);
172
+ const status = ref("disconnected");
173
+ const synced = ref(false);
174
+ const checkpointRequests = ref(0);
175
+ const pendingWorkspaceChanges = [];
176
+ let workspaceChangeTimer;
177
+ const enabled = () => options.enabled === void 0 || toValue(options.enabled);
178
+ function destroyDocument() {
179
+ provider.value?.destroy();
180
+ document.value?.destroy();
181
+ provider.value = void 0;
182
+ document.value = void 0;
183
+ people.value = [];
184
+ status.value = "disconnected";
185
+ synced.value = false;
186
+ }
187
+ function currentPerson(clientId) {
188
+ const value = user.value;
189
+ const id = value?.id || `guest:${clientId}`;
190
+ return createRealtimeIdentity({
191
+ ...value,
192
+ id
193
+ });
194
+ }
195
+ function updatePeople(current) {
196
+ people.value = getRealtimePeople(current.awareness.getStates());
197
+ }
198
+ function flushWorkspaceChanges() {
199
+ if (workspaceChangeTimer) return;
200
+ const current = workspaceProvider.value;
201
+ const socket = current?.ws;
202
+ if (!current?.wsconnected || !socket || socket.readyState !== socket.OPEN) return;
203
+ const change = pendingWorkspaceChanges[0];
204
+ if (!change) return;
205
+ socket.send(Uint8Array.from(encodeWorkspaceChange(change)));
206
+ pendingWorkspaceChanges.shift();
207
+ if (pendingWorkspaceChanges.length) workspaceChangeTimer = setTimeout(() => {
208
+ workspaceChangeTimer = void 0;
209
+ flushWorkspaceChanges();
210
+ }, workspaceChangeFlushIntervalMs);
211
+ }
212
+ function notifyWorkspaceChange(change) {
213
+ if (!enabled()) return;
214
+ pendingWorkspaceChanges.push(change);
215
+ flushWorkspaceChanges();
216
+ }
217
+ function destroy() {
218
+ destroyDocument();
219
+ workspaceProvider.value?.destroy();
220
+ workspaceProvider.value?.doc.destroy();
221
+ workspaceProvider.value = void 0;
222
+ if (workspaceChangeTimer) clearTimeout(workspaceChangeTimer);
223
+ workspaceChangeTimer = void 0;
224
+ pendingWorkspaceChanges.length = 0;
225
+ }
226
+ if (typeof window !== "undefined") {
227
+ const server = `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`)}`;
228
+ const workspaceDocument = markRaw(new Y.Doc());
229
+ const nextWorkspaceProvider = new WebsocketProvider(server, encodeURIComponent(workspaceRoomId), workspaceDocument, {
230
+ connect: false,
231
+ disableBc: true,
232
+ params: { workspace: "events" }
233
+ });
234
+ nextWorkspaceProvider.awareness.setLocalState(null);
235
+ nextWorkspaceProvider.messageHandlers[4] = (_encoder, decoder) => {
236
+ const change = decodeWorkspaceChangePayload(decoder);
237
+ if (change) workspaceChange.value = change;
238
+ };
239
+ nextWorkspaceProvider.on("status", (event) => {
240
+ if (event.status === "connected") flushWorkspaceChanges();
241
+ });
242
+ workspaceProvider.value = nextWorkspaceProvider;
243
+ }
244
+ async function checkpoint() {
245
+ if (!enabled()) throw new Error("Realtime is disabled.");
246
+ checkpointRequests.value++;
247
+ try {
248
+ const id = toValue(documentId);
249
+ if (!id) throw new Error("A realtime document is required before creating a checkpoint.");
250
+ const room = id.split("/").map(encodeURIComponent).join("/");
251
+ 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) {
261
+ await new Promise((resolve) => setTimeout(resolve, 50));
262
+ continue;
263
+ }
264
+ throw Object.assign(new Error(data?.statusMessage || data?.message || "Could not create the realtime checkpoint."), {
265
+ data,
266
+ statusCode: response.status
267
+ });
268
+ }
269
+ } finally {
270
+ checkpointRequests.value--;
271
+ }
272
+ }
273
+ watch([() => toValue(documentId), enabled], ([id, active]) => {
274
+ destroyDocument();
275
+ 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";
292
+ }, { immediate: true });
293
+ watch(enabled, (active) => {
294
+ const current = workspaceProvider.value;
295
+ if (!current) return;
296
+ if (active) current.connect();
297
+ else {
298
+ current.disconnect();
299
+ pendingWorkspaceChanges.length = 0;
300
+ }
301
+ }, { immediate: true });
302
+ watch(user, () => {
303
+ const current = provider.value;
304
+ if (!current) return;
305
+ current.awareness.setLocalStateField("user", currentPerson(current.doc.clientID));
306
+ updatePeople(current);
307
+ });
308
+ onScopeDispose(destroy);
309
+ return {
310
+ document,
311
+ extensions: computed(() => document.value && provider.value ? [...createRealtimeEditorExtensions(), markRaw(index_default.configure({ fragment: markRaw(document.value.getXmlFragment("default")) }))] : []),
312
+ people,
313
+ provider,
314
+ status,
315
+ synced,
316
+ history: {
317
+ checkpoint,
318
+ pending: computed(() => checkpointRequests.value > 0)
319
+ },
320
+ workspace: {
321
+ change: workspaceChange,
322
+ notify: notifyWorkspaceChange
323
+ },
324
+ destroy
325
+ };
326
+ }
327
+ //#endregion
328
+ export { useRealtimeTiptap };
package/package.json ADDED
@@ -0,0 +1,90 @@
1
+ {
2
+ "name": "@vite-hub/realtime",
3
+ "version": "0.0.3",
4
+ "description": "Realtime document primitives and Vite integration for ViteHub.",
5
+ "keywords": [
6
+ "collaboration",
7
+ "h3",
8
+ "realtime",
9
+ "vite",
10
+ "vitehub",
11
+ "yjs"
12
+ ],
13
+ "homepage": "https://github.com/vite-hub/vitehub#readme",
14
+ "bugs": "https://github.com/vite-hub/vitehub/issues",
15
+ "license": "Apache-2.0",
16
+ "author": "onmax <maximogarciamtnez@gmail.com>",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/vite-hub/vitehub.git",
20
+ "directory": "packages/realtime"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "package.json"
25
+ ],
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": "./dist/index.js",
31
+ "./server": "./dist/server.js",
32
+ "./vite": "./dist/vite.js",
33
+ "./vue": "./dist/vue.js",
34
+ "./package.json": "./package.json"
35
+ },
36
+ "dependencies": {
37
+ "@tiptap/core": "^3.29.2",
38
+ "@tiptap/extension-collaboration": "^3.29.2",
39
+ "@tiptap/extension-document": "^3.29.2",
40
+ "@tiptap/extension-image": "^3.29.2",
41
+ "@tiptap/extension-table": "^3.29.2",
42
+ "@tiptap/markdown": "^3.29.2",
43
+ "@tiptap/pm": "^3.29.2",
44
+ "@tiptap/starter-kit": "^3.29.2",
45
+ "@tiptap/y-tiptap": "^3.0.8",
46
+ "@vite-hub/auth": "0.0.3",
47
+ "@vite-hub/workspace": "0.0.3",
48
+ "h3": "2.0.1-rc.25",
49
+ "lib0": "^0.2.114",
50
+ "marked": "17.0.6",
51
+ "pathe": "^2.0.3",
52
+ "y-protocols": "^1.0.6",
53
+ "y-websocket": "^3.0.0",
54
+ "yjs": "^13.6.27"
55
+ },
56
+ "devDependencies": {
57
+ "@types/json-schema": "^7.0.15",
58
+ "@types/node": "^24.13.3",
59
+ "linkedom": "^0.18.12",
60
+ "publint": "^0.3.21",
61
+ "typescript": "^6.0.3",
62
+ "vite": "^8.0.8",
63
+ "vite-plus": "^0.1.24",
64
+ "vitest": "^4.1.4",
65
+ "vue": "^3.5.0",
66
+ "@vite-hub/internal": "0.0.1"
67
+ },
68
+ "peerDependencies": {
69
+ "@types/json-schema": "^7.0.15",
70
+ "vite": ">=8.0.0",
71
+ "vue": "^3.5.0"
72
+ },
73
+ "peerDependenciesMeta": {
74
+ "vite": {
75
+ "optional": true
76
+ },
77
+ "vue": {
78
+ "optional": true
79
+ }
80
+ },
81
+ "engines": {
82
+ "node": ">=24.15.0"
83
+ },
84
+ "scripts": {
85
+ "build": "vp pack",
86
+ "dev": "vp pack --watch",
87
+ "typecheck": "tsc --noEmit -p ./tsconfig.json",
88
+ "test": "vp run -t @vite-hub/realtime#build && vp test"
89
+ }
90
+ }