@vite-hub/realtime 0.0.4 → 0.3.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 +94 -21
- package/dist/agent.d.ts +2 -0
- package/dist/agent.js +2 -0
- package/dist/bus-Bi-Ec414.js +476 -0
- package/dist/bus-protocol-wXkXW28q.d.ts +66 -0
- package/dist/bus.d.ts +85 -0
- package/dist/bus.js +2 -0
- package/dist/client/browser.js +53 -0
- package/dist/client.d.ts +67 -0
- package/dist/client.js +200 -0
- package/dist/conflict-Bg8vCisd.js +63 -0
- package/dist/conflict-CmZizTYl.d.ts +17 -0
- package/dist/document-DPaywuCO.d.ts +16 -0
- package/dist/document-DjBrcgpY.js +2041 -0
- package/dist/durability.d.ts +10 -0
- package/dist/durability.js +46 -0
- package/dist/editor-BM5-vHqf.js +147 -0
- package/dist/error-diagnostics-B_66irmt.js +141 -0
- package/dist/index.d.ts +22 -4
- package/dist/index.js +4 -6
- package/dist/internal/runtime/unavailable.d.ts +5 -0
- package/dist/internal/runtime/unavailable.js +8 -0
- package/dist/keepalive-BCs-uXp4.js +33 -0
- package/dist/layout-DNaxppTZ.js +34 -0
- package/dist/layout-fyQnhwCg.d.ts +18 -0
- package/dist/object-CzKyK0hX.js +145 -0
- package/dist/presence-Tuy1y_l9.js +53 -0
- package/dist/request-BUwa359H.d.ts +48 -0
- package/dist/request-CWaHqW3R.js +192 -0
- package/dist/server.d.ts +132 -27
- package/dist/server.js +2228 -506
- package/dist/types-1DVVG5ro.d.ts +319 -0
- package/dist/vite.d.ts +177 -6
- package/dist/vite.js +930 -55
- package/dist/vue.d.ts +69 -3807
- package/dist/vue.js +353 -65
- package/package.json +117 -36
- package/dist/editor-extensions-CZEzrJ-t.js +0 -4860
- package/dist/types-BSDtKw5d.d.ts +0 -42
|
@@ -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 };
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { Editor, Node } from "@tiptap/core";
|
|
2
|
+
import Blockquote from "@tiptap/extension-blockquote";
|
|
3
|
+
import Code from "@tiptap/extension-code";
|
|
4
|
+
import Image from "@tiptap/extension-image";
|
|
5
|
+
import Document from "@tiptap/extension-document";
|
|
6
|
+
import { TableKit } from "@tiptap/extension-table";
|
|
7
|
+
import { Markdown } from "@tiptap/markdown";
|
|
8
|
+
import StarterKit from "@tiptap/starter-kit";
|
|
9
|
+
import { Marked } from "marked";
|
|
10
|
+
//#region src/frontmatter.ts
|
|
11
|
+
const frontmatterPattern = /^---\r?\n(?:---(?:\r?\n|$)|([\s\S]*?)\r?\n---(?:\r?\n|$))/;
|
|
12
|
+
const Frontmatter = Node.create({
|
|
13
|
+
name: "frontmatter",
|
|
14
|
+
priority: 1e3,
|
|
15
|
+
atom: true,
|
|
16
|
+
selectable: false,
|
|
17
|
+
addAttributes() {
|
|
18
|
+
return { value: { default: null } };
|
|
19
|
+
},
|
|
20
|
+
parseHTML() {
|
|
21
|
+
return [{
|
|
22
|
+
tag: "pre[data-frontmatter]",
|
|
23
|
+
getAttrs: (element) => ({ value: element.hasAttribute("data-frontmatter-empty") ? null : element.getAttribute("data-frontmatter-value") || "" })
|
|
24
|
+
}];
|
|
25
|
+
},
|
|
26
|
+
renderHTML({ node }) {
|
|
27
|
+
return [
|
|
28
|
+
"pre",
|
|
29
|
+
{
|
|
30
|
+
"data-frontmatter": "",
|
|
31
|
+
"data-frontmatter-empty": node.attrs.value === null ? "" : void 0,
|
|
32
|
+
"data-frontmatter-value": node.attrs.value ?? void 0,
|
|
33
|
+
contenteditable: "false"
|
|
34
|
+
},
|
|
35
|
+
node.attrs.value ?? ""
|
|
36
|
+
];
|
|
37
|
+
},
|
|
38
|
+
markdownTokenName: "frontmatter",
|
|
39
|
+
markdownTokenizer: {
|
|
40
|
+
name: "frontmatter",
|
|
41
|
+
level: "block",
|
|
42
|
+
start: (src) => frontmatterPattern.test(src) ? 0 : -1,
|
|
43
|
+
tokenize(src, tokens) {
|
|
44
|
+
if (tokens.length) return;
|
|
45
|
+
const match = frontmatterPattern.exec(src);
|
|
46
|
+
if (!match) return;
|
|
47
|
+
return {
|
|
48
|
+
type: "frontmatter",
|
|
49
|
+
raw: match[0],
|
|
50
|
+
text: match[1]
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
parseMarkdown(token, helpers) {
|
|
55
|
+
return helpers.createNode("frontmatter", { value: token.text ?? null });
|
|
56
|
+
},
|
|
57
|
+
renderMarkdown(node) {
|
|
58
|
+
return node.attrs?.value === null ? "---\n---" : `---\n${node.attrs?.value || ""}\n---`;
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
//#endregion
|
|
62
|
+
//#region src/editor.ts
|
|
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
|
+
} });
|
|
80
|
+
const emptyRealtimeEditorDocument = {
|
|
81
|
+
type: "doc",
|
|
82
|
+
content: [{ type: "paragraph" }]
|
|
83
|
+
};
|
|
84
|
+
function createMarked() {
|
|
85
|
+
return new Marked();
|
|
86
|
+
}
|
|
87
|
+
function createRealtimeEditorExtensions(options = {}) {
|
|
88
|
+
return [
|
|
89
|
+
StarterKit.configure({
|
|
90
|
+
blockquote: false,
|
|
91
|
+
code: false,
|
|
92
|
+
document: false,
|
|
93
|
+
trailingNode: options.collaborative === true ? false : void 0,
|
|
94
|
+
undoRedo: false
|
|
95
|
+
}),
|
|
96
|
+
RealtimeBlockquote,
|
|
97
|
+
RealtimeCode,
|
|
98
|
+
RealtimeDocument,
|
|
99
|
+
Image,
|
|
100
|
+
TableKit,
|
|
101
|
+
Frontmatter,
|
|
102
|
+
Markdown.configure({ marked: createMarked() })
|
|
103
|
+
];
|
|
104
|
+
}
|
|
105
|
+
/** Declares an editor schema and Markdown codec that the server and the browser share. */
|
|
106
|
+
function defineRealtimeEditor(editor) {
|
|
107
|
+
return editor;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* The built-in Markdown kit: StarterKit, images, tables, and raw YAML frontmatter as an
|
|
111
|
+
* atom node, parsed and printed by `@tiptap/markdown`. It runs headless on the server.
|
|
112
|
+
*/
|
|
113
|
+
const realtimeMarkdownEditor = defineRealtimeEditor({
|
|
114
|
+
extensions: createRealtimeEditorExtensions,
|
|
115
|
+
fromMarkdown(markdown) {
|
|
116
|
+
const editor = new Editor({
|
|
117
|
+
content: markdown || emptyRealtimeEditorDocument,
|
|
118
|
+
contentType: "markdown",
|
|
119
|
+
extensions: createRealtimeEditorExtensions(),
|
|
120
|
+
injectCSS: false
|
|
121
|
+
});
|
|
122
|
+
try {
|
|
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;
|
|
129
|
+
} finally {
|
|
130
|
+
editor.destroy();
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
toMarkdown(document) {
|
|
134
|
+
const editor = new Editor({
|
|
135
|
+
content: document,
|
|
136
|
+
extensions: createRealtimeEditorExtensions(),
|
|
137
|
+
injectCSS: false
|
|
138
|
+
});
|
|
139
|
+
try {
|
|
140
|
+
return editor.getMarkdown();
|
|
141
|
+
} finally {
|
|
142
|
+
editor.destroy();
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
//#endregion
|
|
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,6 +1,24 @@
|
|
|
1
|
-
import { i as
|
|
2
|
-
|
|
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
|
+
import { n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "./conflict-CmZizTYl.js";
|
|
3
|
+
import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-fyQnhwCg.js";
|
|
3
4
|
//#region src/definition.d.ts
|
|
4
|
-
|
|
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
|
+
*/
|
|
10
|
+
export declare function defineRealtime(definition: RealtimeDefinition): RealtimeDefinition;
|
|
5
11
|
//#endregion
|
|
6
|
-
|
|
12
|
+
//#region src/editor.d.ts
|
|
13
|
+
export declare function createRealtimeEditorExtensions(options?: {
|
|
14
|
+
collaborative?: boolean;
|
|
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>)[];
|
|
16
|
+
/** Declares an editor schema and Markdown codec that the server and the browser share. */
|
|
17
|
+
export declare function defineRealtimeEditor(editor: RealtimeEditor): RealtimeEditor;
|
|
18
|
+
/**
|
|
19
|
+
* The built-in Markdown kit: StarterKit, images, tables, and raw YAML frontmatter as an
|
|
20
|
+
* atom node, parsed and printed by `@tiptap/markdown`. It runs headless on the server.
|
|
21
|
+
*/
|
|
22
|
+
export declare const realtimeMarkdownEditor: RealtimeEditor;
|
|
23
|
+
//#endregion
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
}
|
|
5
|
-
//#endregion
|
|
6
|
-
export { defineRealtime };
|
|
1
|
+
import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
|
|
2
|
+
import { a as defineRealtime, n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "./conflict-Bg8vCisd.js";
|
|
3
|
+
import { n as defineRealtimeEditor, r as realtimeMarkdownEditor, t as createRealtimeEditorExtensions } from "./editor-BM5-vHqf.js";
|
|
4
|
+
export { RealtimeDocumentConflict, createRealtimeEditorExtensions, defineRealtime, defineRealtimeEditor, isRealtimeDocumentConflict, readRealtimeStatus, realtimeDocumentLayout, realtimeMarkdownEditor };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
//#region src/internal/runtime/unavailable.ts
|
|
2
|
+
const availability = {
|
|
3
|
+
available: false,
|
|
4
|
+
reason: "This build does not enable Realtime.",
|
|
5
|
+
fix: "Enable `realtime` in vitehub() with the Cloudflare or Node preset."
|
|
6
|
+
};
|
|
7
|
+
//#endregion
|
|
8
|
+
export { availability as default };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { h as realtimeKeepalivePing } from "./object-CzKyK0hX.js";
|
|
2
|
+
import * as time from "lib0/time";
|
|
3
|
+
//#region src/application-path.ts
|
|
4
|
+
function resolveRealtimeApplicationPath(path, baseURL = typeof __VITEHUB_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_APP_BASE_URL__) {
|
|
5
|
+
return baseURL === "/" ? path : `${baseURL.replace(/\/+$/, "")}${path}`;
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/keepalive.ts
|
|
9
|
+
const keepaliveIntervalMs = 15e3;
|
|
10
|
+
/**
|
|
11
|
+
* y-websocket closes a socket that received nothing for 30 seconds, then connects again. A room with nobody else in it,
|
|
12
|
+
* and the workspace events room, can stay silent for much longer. So the provider pings every 15 seconds while it is
|
|
13
|
+
* connected, and the pong counts as a received message.
|
|
14
|
+
*/
|
|
15
|
+
function keepRealtimeSocketAlive(provider) {
|
|
16
|
+
let timer;
|
|
17
|
+
provider.on("status", ({ status }) => {
|
|
18
|
+
clearInterval(timer);
|
|
19
|
+
timer = void 0;
|
|
20
|
+
const socket = provider.ws;
|
|
21
|
+
if (status !== "connected" || !socket) return;
|
|
22
|
+
const receive = socket.onmessage;
|
|
23
|
+
socket.onmessage = function(event) {
|
|
24
|
+
if (event.data !== "pong") return receive?.call(this, event);
|
|
25
|
+
if (provider.ws === socket) provider.wsLastMessageReceived = time.getUnixTime();
|
|
26
|
+
};
|
|
27
|
+
timer = setInterval(() => {
|
|
28
|
+
if (provider.ws === socket && socket.readyState === socket.OPEN) socket.send(realtimeKeepalivePing);
|
|
29
|
+
}, keepaliveIntervalMs);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
export { resolveRealtimeApplicationPath as n, keepRealtimeSocketAlive as t };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
//#region src/layout.ts
|
|
2
|
+
/**
|
|
3
|
+
* Root types of every Realtime Y.Doc:
|
|
4
|
+
* - `body`: Y.XmlFragment bound to the editor through TipTap Collaboration.
|
|
5
|
+
* - `fields`: Y.Map with one JSON value per field; concurrent writes to one key resolve last-write-wins.
|
|
6
|
+
* - `status`: Y.Map written only by the server (`digest`, `error`, `issues`, `savedAt`, `savedBy`).
|
|
7
|
+
* The server closes connections whose updates change it.
|
|
8
|
+
*/
|
|
9
|
+
const realtimeDocumentLayout = Object.freeze({
|
|
10
|
+
body: "body",
|
|
11
|
+
fields: "fields",
|
|
12
|
+
status: "status"
|
|
13
|
+
});
|
|
14
|
+
function text(value) {
|
|
15
|
+
return typeof value === "string" ? value : null;
|
|
16
|
+
}
|
|
17
|
+
function readRealtimeStatus(document) {
|
|
18
|
+
const map = document.getMap(realtimeDocumentLayout.status);
|
|
19
|
+
const issues = map.get("issues");
|
|
20
|
+
const savedBy = map.get("savedBy");
|
|
21
|
+
const status = {
|
|
22
|
+
issues: Array.isArray(issues) ? issues : [],
|
|
23
|
+
savedBy: savedBy && !Array.isArray(savedBy) && savedBy instanceof Object ? savedBy : null
|
|
24
|
+
};
|
|
25
|
+
return {
|
|
26
|
+
digest: text(map.get("digest")),
|
|
27
|
+
error: text(map.get("error")),
|
|
28
|
+
issues: status.issues,
|
|
29
|
+
savedAt: text(map.get("savedAt")),
|
|
30
|
+
savedBy: status.savedBy
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { realtimeDocumentLayout as n, readRealtimeStatus as t };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { d as RealtimeDocumentStatus } from "./types-1DVVG5ro.js";
|
|
2
|
+
import * as Y from "yjs";
|
|
3
|
+
//#region src/layout.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Root types of every Realtime Y.Doc:
|
|
6
|
+
* - `body`: Y.XmlFragment bound to the editor through TipTap Collaboration.
|
|
7
|
+
* - `fields`: Y.Map with one JSON value per field; concurrent writes to one key resolve last-write-wins.
|
|
8
|
+
* - `status`: Y.Map written only by the server (`digest`, `error`, `issues`, `savedAt`, `savedBy`).
|
|
9
|
+
* The server closes connections whose updates change it.
|
|
10
|
+
*/
|
|
11
|
+
declare const realtimeDocumentLayout: Readonly<{
|
|
12
|
+
readonly body: "body";
|
|
13
|
+
readonly fields: "fields";
|
|
14
|
+
readonly status: "status";
|
|
15
|
+
}>;
|
|
16
|
+
declare function readRealtimeStatus(document: Y.Doc): RealtimeDocumentStatus;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { realtimeDocumentLayout as n, readRealtimeStatus as t };
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
|
|
2
|
+
import * as decoding from "lib0/decoding";
|
|
3
|
+
import * as encoding from "lib0/encoding";
|
|
4
|
+
import { normalizeSafeWorkspacePath } from "@vite-hub/workspace/internal/path";
|
|
5
|
+
const workspaceRoomId = "@workspace";
|
|
6
|
+
/**
|
|
7
|
+
* Text frames that keep an idle socket open. The client sends the ping, and the server answers with the pong. On
|
|
8
|
+
* Cloudflare the Durable Object answers it without waking.
|
|
9
|
+
*/
|
|
10
|
+
const realtimeKeepalivePing = "ping";
|
|
11
|
+
const realtimeKeepalivePong = "pong";
|
|
12
|
+
const maxAwarenessClients = 1024;
|
|
13
|
+
const realtimeSyncPendingCode = "REALTIME_SYNC_PENDING";
|
|
14
|
+
const realtimeSourceChangedCode = "REALTIME_SOURCE_CHANGED";
|
|
15
|
+
/** A save or checkpoint asked a room whose codec cannot edit the stored document without loss. */
|
|
16
|
+
const realtimeReadOnlyCode = "REALTIME_READ_ONLY";
|
|
17
|
+
/** A save found that the room body does not fit the editor schema, so writing it would lose content. */
|
|
18
|
+
const realtimeInvalidDocumentCode = "REALTIME_INVALID_DOCUMENT";
|
|
19
|
+
/** Close code sent after a reset control frame. The client must drop its Y.Doc. */
|
|
20
|
+
const realtimeResetCloseCode = 4409;
|
|
21
|
+
/** Close code for updates a peer may not write: read-only access or the server-written status. */
|
|
22
|
+
const realtimeForbiddenWriteCloseCode = 4403;
|
|
23
|
+
function isRetryableRealtimeRequestCode(value) {
|
|
24
|
+
return value === realtimeSyncPendingCode;
|
|
25
|
+
}
|
|
26
|
+
function encodeRealtimeControl(message) {
|
|
27
|
+
const encoder = encoding.createEncoder();
|
|
28
|
+
encoding.writeVarUint(encoder, 5);
|
|
29
|
+
encoding.writeVarString(encoder, JSON.stringify(message));
|
|
30
|
+
return encoding.toUint8Array(encoder);
|
|
31
|
+
}
|
|
32
|
+
function decodeRealtimeControlPayload(decoder) {
|
|
33
|
+
try {
|
|
34
|
+
const value = JSON.parse(decoding.readVarString(decoder));
|
|
35
|
+
if (!value || typeof value !== "object" || !("epoch" in value) || !("type" in value)) return;
|
|
36
|
+
if (typeof value.epoch !== "string" || !value.epoch) return;
|
|
37
|
+
if (value.type === "session" && "access" in value && (value.access === "read" || value.access === "write")) {
|
|
38
|
+
if (value.access === "read" && "reason" in value && (value.reason === "access" || value.reason === "document" || value.reason === "version")) return {
|
|
39
|
+
type: "session",
|
|
40
|
+
access: value.access,
|
|
41
|
+
epoch: value.epoch,
|
|
42
|
+
reason: value.reason
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
type: "session",
|
|
46
|
+
access: value.access,
|
|
47
|
+
epoch: value.epoch
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
if (value.type === "reset" && "reason" in value && (value.reason === "source-changed" || value.reason === "stale")) return {
|
|
51
|
+
type: "reset",
|
|
52
|
+
epoch: value.epoch,
|
|
53
|
+
reason: value.reason
|
|
54
|
+
};
|
|
55
|
+
} catch {}
|
|
56
|
+
}
|
|
57
|
+
function validPath(value) {
|
|
58
|
+
if (typeof value !== "string" || value.length === 0 || value.length > 4096 || value.includes("\0")) return false;
|
|
59
|
+
if (value.startsWith("/") || value.endsWith("/") || value.includes("\\") || value.includes("//") || /^[a-z]:/i.test(value)) return false;
|
|
60
|
+
try {
|
|
61
|
+
return normalizeSafeWorkspacePath(value) === value;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function decodeWorkspaceChangePayload(decoder) {
|
|
67
|
+
try {
|
|
68
|
+
const value = JSON.parse(decoding.readVarString(decoder));
|
|
69
|
+
if ((value.operation === "create" || value.operation === "delete" || value.operation === "update") && validPath(value.path)) return {
|
|
70
|
+
operation: value.operation,
|
|
71
|
+
path: value.path
|
|
72
|
+
};
|
|
73
|
+
if (value.operation === "move" && validPath(value.from) && validPath(value.to)) return {
|
|
74
|
+
operation: value.operation,
|
|
75
|
+
from: value.from,
|
|
76
|
+
to: value.to
|
|
77
|
+
};
|
|
78
|
+
} catch {}
|
|
79
|
+
}
|
|
80
|
+
function encodeWorkspaceChange(change) {
|
|
81
|
+
const encoder = encoding.createEncoder();
|
|
82
|
+
encoding.writeVarUint(encoder, 4);
|
|
83
|
+
encoding.writeVarString(encoder, JSON.stringify(change));
|
|
84
|
+
return encoding.toUint8Array(encoder);
|
|
85
|
+
}
|
|
86
|
+
function readAwarenessClientIds(update) {
|
|
87
|
+
const decoder = decoding.createDecoder(update);
|
|
88
|
+
const length = decoding.readVarUint(decoder);
|
|
89
|
+
if (length > 1024) throw realtimeErrorDiagnostics.REALTIME_TOO_MANY_AWARENESS_CLIENTS({});
|
|
90
|
+
const clients = [];
|
|
91
|
+
for (let index = 0; index < length; index++) {
|
|
92
|
+
clients.push(decoding.readVarUint(decoder));
|
|
93
|
+
decoding.readVarUint(decoder);
|
|
94
|
+
decoding.readVarString(decoder);
|
|
95
|
+
}
|
|
96
|
+
return clients;
|
|
97
|
+
}
|
|
98
|
+
function encodeRealtimeRequestFrame(frame) {
|
|
99
|
+
const encoder = encoding.createEncoder();
|
|
100
|
+
encoding.writeVarUint(encoder, 6);
|
|
101
|
+
encoding.writeVarString(encoder, JSON.stringify(frame));
|
|
102
|
+
return encoding.toUint8Array(encoder);
|
|
103
|
+
}
|
|
104
|
+
/** Reads a request frame after its message type, or `undefined` when it is not one. */
|
|
105
|
+
function decodeRealtimeRequestFramePayload(decoder) {
|
|
106
|
+
try {
|
|
107
|
+
const value = JSON.parse(decoding.readVarString(decoder));
|
|
108
|
+
if (!value || typeof value !== "object" || !("id" in value) || typeof value.id !== "string" || !value.id || value.id.length > 128) return;
|
|
109
|
+
if (!("kind" in value)) return;
|
|
110
|
+
if (value.kind === "request") return {
|
|
111
|
+
kind: "request",
|
|
112
|
+
id: value.id,
|
|
113
|
+
body: "body" in value ? value.body : void 0
|
|
114
|
+
};
|
|
115
|
+
if (value.kind !== "answer" || !("ok" in value)) return;
|
|
116
|
+
if (value.ok === true) return {
|
|
117
|
+
kind: "answer",
|
|
118
|
+
id: value.id,
|
|
119
|
+
ok: true,
|
|
120
|
+
body: "body" in value ? value.body : void 0
|
|
121
|
+
};
|
|
122
|
+
if (value.ok === false && "why" in value && typeof value.why === "string") return {
|
|
123
|
+
kind: "answer",
|
|
124
|
+
id: value.id,
|
|
125
|
+
ok: false,
|
|
126
|
+
why: value.why
|
|
127
|
+
};
|
|
128
|
+
} catch {}
|
|
129
|
+
}
|
|
130
|
+
//#endregion
|
|
131
|
+
//#region ../internal/src/object.ts
|
|
132
|
+
/** A non-null object that is not an array. Functions do not pass. */
|
|
133
|
+
function isRecord(value) {
|
|
134
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
135
|
+
}
|
|
136
|
+
/** A non-null object or a function that is not an array. */
|
|
137
|
+
function isRecordOrFunction(value) {
|
|
138
|
+
return Object(value) === value && !Array.isArray(value);
|
|
139
|
+
}
|
|
140
|
+
/** A shallow copy of a non-array object, or an empty object for any other value. */
|
|
141
|
+
function cloneRecord(value) {
|
|
142
|
+
return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
|
143
|
+
}
|
|
144
|
+
//#endregion
|
|
145
|
+
export { realtimeReadOnlyCode as _, decodeRealtimeRequestFramePayload as a, realtimeSyncPendingCode as b, encodeRealtimeRequestFrame as c, maxAwarenessClients as d, readAwarenessClientIds as f, realtimeKeepalivePong as g, realtimeKeepalivePing as h, decodeRealtimeControlPayload as i, encodeWorkspaceChange as l, realtimeInvalidDocumentCode as m, isRecord as n, decodeWorkspaceChangePayload as o, realtimeForbiddenWriteCloseCode as p, isRecordOrFunction as r, encodeRealtimeControl as s, cloneRecord as t, isRetryableRealtimeRequestCode as u, realtimeResetCloseCode as v, workspaceRoomId as x, realtimeSourceChangedCode as y };
|