@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 CHANGED
@@ -1,23 +1,23 @@
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.
11
11
 
12
- Realtime is for collaborative documents, presence, and explicit Workspace checkpoints. It is not a general-purpose WebSocket or event-broadcasting API.
12
+ Realtime is for collaborative documents, presence, explicit Workspace checkpoints, and requests from the server to one browser in a room. It is not a general-purpose WebSocket or event-broadcasting API.
13
13
 
14
14
  ## Install
15
15
 
16
16
  ```sh
17
- pnpm add @vite-hub/realtime @vite-hub/workspace @tiptap/vue-3 h3 nitro vite vue
17
+ pnpm add @vite-hub/realtime @vite-hub/workspace @tiptap/vue-3 drizzle-orm@1.0.0-rc.5 h3 nitro vite vue
18
18
  ```
19
19
 
20
- ViteHub Realtime requires Node 24.15 or newer. The published client adapter is for Vue. The package declares `vite` and `vue` as optional peers so server-only integrations do not install unused framework tooling; this walkthrough uses both.
20
+ ViteHub Realtime requires Node.js 22.18 or newer. The published client adapter is for Vue. The package declares `vite` and `vue` as optional peers so server-only integrations do not install unused framework tooling; this walkthrough uses both. It also declares `drizzle-orm` as a peer: Realtime depends on Auth, and Auth uses the app's copy of Drizzle.
21
21
 
22
22
  ## Connect one document
23
23
 
@@ -32,7 +32,7 @@ import { defineConfig } from "vite"
32
32
  export default defineConfig({
33
33
  plugins: [
34
34
  hubWorkspace(),
35
- hubRealtime({ authority: "memory" }),
35
+ hubRealtime({ driver: "memory" }),
36
36
  ],
37
37
  })
38
38
  ```
@@ -44,7 +44,7 @@ Declare a writable Workspace and a Realtime Definition with the same Workspace n
44
44
  import { defineWorkspace } from "@vite-hub/workspace"
45
45
 
46
46
  export default defineWorkspace({
47
- store: { provider: "memory" },
47
+ store: { driver: "memory" },
48
48
  rules: {
49
49
  "/**": { write: true, mediaType: "text/markdown" },
50
50
  },
@@ -56,6 +56,7 @@ export default defineWorkspace({
56
56
  import { defineRealtime } from "@vite-hub/realtime"
57
57
 
58
58
  export default defineRealtime({
59
+ auth: true,
59
60
  document: { workspace: "docs" },
60
61
  history: { checkpoint: true },
61
62
  })
@@ -87,24 +88,92 @@ const connection = computed(() =>
87
88
 
88
89
  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
90
 
90
- Room updates do not write the Workspace document. Save the current Markdown and create a Workspace snapshot explicitly:
91
+ `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
 
92
93
  ```ts
93
- const checkpoint = await realtime.history.checkpoint()
94
+ import { useRealtimeTiptap } from "@vite-hub/realtime/vue"
95
+
96
+ const realtime = useRealtimeTiptap("docs", "guides/welcome.md", {
97
+ carets: {
98
+ selectionRender: user => ({ class: "ProseMirror-yjs-selection", style: `background-color: ${user.color}33` }),
99
+ },
100
+ })
101
+ ```
102
+
103
+ Room updates do not write the Workspace document. Save the current Markdown and create a Workspace snapshot explicitly:
104
+
105
+ ```ts fragment
106
+ const [error, checkpoint] = await realtime.history.checkpoint()
107
+ if (error) throw error
94
108
 
95
- console.log(checkpoint.content)
109
+ console.log(checkpoint.document.body)
96
110
  console.log(checkpoint.snapshot.id)
97
111
  ```
98
112
 
113
+ ## Share presence without a document
114
+
115
+ Set `document: false` when a room only shows who is there and what each person shares, such as a cursor. Nothing loads or saves, `authorize()` is asked only for `read`, and the rooms work with every Realtime driver.
116
+
117
+ ```ts
118
+ // server/realtime/presence.ts
119
+ import { defineRealtime } from "@vite-hub/realtime"
120
+
121
+ export default defineRealtime({
122
+ auth: true,
123
+ document: false,
124
+ })
125
+ ```
126
+
127
+ Join a room with `connectRealtimeRoom()` from `@vite-hub/realtime/client`:
128
+
129
+ ```ts fragment
130
+ import { connectRealtimeRoom } from "@vite-hub/realtime/client"
131
+
132
+ const room = connectRealtimeRoom("presence", "boards/42")
133
+ room.setLocal("cursor", { x: 120, y: 80 })
134
+ room.onUpdate(() => console.log(room.people(), room.states()))
135
+ ```
136
+
137
+ A client that sends a document update is disconnected. `save()`, `refresh()`, and `history.checkpoint()` requests get HTTP 404, and `refreshRealtimeDocument()` returns `false`.
138
+
139
+ ## Ask one browser from the server
140
+
141
+ A presence Definition with `requests: true` lets server code ask the one browser in a room and wait for its answer. The Agent page bridge uses it.
142
+
143
+ ```ts
144
+ // server/realtime/tabs.ts
145
+ import { defineRealtime } from "@vite-hub/realtime"
146
+
147
+ export default defineRealtime({ access: "public", document: false, requests: true })
148
+ ```
149
+
150
+ ```ts fragment
151
+ // In the browser
152
+ const room = connectRealtimeRoom("tabs", tabId)
153
+ room.onRequest(body => ({ title: document.title }))
154
+
155
+ // On the server
156
+ import { requestRealtimeRoom } from "@vite-hub/realtime/server"
157
+
158
+ const [error, answer] = await requestRealtimeRoom("tabs", tabId, { want: "title" })
159
+ ```
160
+
161
+ `scope: "user"` keeps a room per person: the same room id for two signed-in people is two rooms, and `requestRealtimeRoom(..., { user })` asks only that person's room (`user: null` for everyone without a session). One browser answers: a room with two browsers returns `REALTIME_ROOM_CROWDED`. A room without one waits 5 seconds (`wait`) for it to join, then returns `REALTIME_ROOM_EMPTY`. The answer must come within 30 seconds (`timeout`), from the browser that was asked, and be under 1 MiB. On Cloudflare the request goes through the Durable Object. With Redis or Postgres it reaches only browsers on the same instance (`REALTIME_ROOM_ELSEWHERE`).
162
+
99
163
  ## Deployment and security boundaries
100
164
 
101
- - The Vue adapter connects to the generated same-origin `/api/_vitehub/realtime/**` WebSocket route. The Vite integration registers that route and discovers `server/realtime` definitions.
102
- - `authority: "memory"` is single-process and loses room state when the process stops. ViteHub rejects it for known distributed host presets. It retains at most 128 active rooms.
103
- - `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.
165
+ - The Vue adapter connects to the generated same-origin `/api/_vitehub/realtime/**` WebSocket route. The Vite integration registers that route and discovers `server/realtime` definitions. In a component it prepares the editor extensions during setup and connects when the component mounts, so the server render and the first browser render both have `status` `disconnected`.
166
+ - `driver: "memory"` is single-process and loses room state when the process stops. ViteHub rejects it for known distributed hosts. It retains at most 128 active rooms.
167
+ - `driver: "cloudflare"` uses a SQLite-backed Cloudflare Durable Object. `driver: "auto"` selects it when a Cloudflare host or hosting environment can be resolved.
168
+ - On a Node build, `driver: "auto"` picks when the server starts: `redis` with `REDIS_URL`, else `postgres` on the postgres.js client of the Default Database when it is on Postgres (`REALTIME_POSTGRES_URL` overrides it; `DATABASE_URL` is not read), else `memory`. A borrowed Database client is never closed. It prints the choice at boot. With `redis` or `postgres`, each instance holds its rooms in memory and shares Yjs updates and awareness with the other instances through Redis pub/sub or Postgres `LISTEN`/`NOTIFY`. The instances start each room from one shared record (`vitehub_realtime_rooms` on Postgres), and saves of one room run one at a time under a lock, so `ifDigest` stays correct across instances. `NOTIFY` payloads over 8,000 bytes go through the `vitehub_realtime_messages` table. Each app has its own namespace on the bus (`realtime.namespace`, else the app name; `REALTIME_NAMESPACE` replaces it at runtime), so two apps on one Redis or Postgres never share a room. Presence of a stopped instance leaves at once, and that of a crashed instance after the 30 second Yjs awareness timeout. Other production builds fail with `REALTIME_MISSING_DRIVER`.
104
169
  - 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
- - 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.
170
+ - Each Realtime Definition must set `auth: true`, `authorize()`, or `access: "public"`. Otherwise the server rejects it with `REALTIME_MISSING_ACCESS`. `authorize()` allows only when it returns `true`; `undefined` and `false` deny. `auth: true` needs ViteHub Auth or `identify()`; it verifies the user and replaces client-supplied presence identity. `access: "public"` lets each person read and write each Realtime. Presence in a public definition is untrusted and must not authorize application actions.
171
+ - Requests with an `Origin` other than the app's get 403 on each definition, unless `origins()` accepts the origin.
172
+ - Other packages can contribute definitions through `hubRealtime({ contribute })`, such as Content live editing. Realtime adds them only when the build has a Realtime driver and leaves them out without an error otherwise. A file in `server/realtime` with the same name wins.
173
+ - 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.
174
+ - `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
175
  - 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.
176
+ - 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
177
 
109
178
  ## Public imports
110
179
 
@@ -113,13 +182,17 @@ console.log(checkpoint.snapshot.id)
113
182
  | `@vite-hub/realtime` | `defineRealtime()` and portable Realtime types. |
114
183
  | `@vite-hub/realtime/vite` | `hubRealtime()` definition discovery and generated server wiring. |
115
184
  | `@vite-hub/realtime/vue` | `useRealtimeTiptap()` for Vue, TipTap, presence, status, and checkpoints. |
116
- | `@vite-hub/realtime/server` | `createRealtimeHandler()` for a manual H3 server integration. Normal ViteHub apps use the generated route. |
185
+ | `@vite-hub/realtime/agent` | `agentRealtime`, the handle that ViteHub passes to the Agent `page()` Capability. Apps do not import it. |
186
+ | `@vite-hub/realtime/client` | `connectRealtimeRoom()` to share presence without an editor, in any framework. |
187
+ | `@vite-hub/realtime/client/browser.js` | The same client as one prebuilt ES module with no imports, for a script that another site loads from your app without a bundler. |
188
+ | `@vite-hub/realtime/server` | `requestRealtimeRoom()` to ask one browser in a room, and `createRealtimeHandler()` for a manual H3 server integration. Normal ViteHub apps use the generated route. |
189
+ | `@vite-hub/realtime/bus` | `useRealtimeBus()` and `closeRealtimeBuses()`, the Postgres and Redis buses that the generated Node handler passes to `createRealtimeHandler({ bus })`. |
117
190
 
118
191
  Generated files under `.vitehub/nitro/realtime` are inspectable build output, not application imports.
119
192
 
120
193
  ## Learn more
121
194
 
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.
195
+ - [Realtime collaboration](https://vitehub.dev/docs/realtime) covers authorities, checkpoints, workspace events, quotas, and generated output.
196
+ - [Workspace](https://vitehub.dev/docs/workspace) covers stores, write rules, snapshots, and persistence.
197
+ - [Auth](https://vitehub.dev/docs/auth) covers session setup and trusted origins.
125
198
  - [Configuration options](https://vitehub.dev/docs/reference/config-options) lists every Realtime module option.
@@ -0,0 +1,2 @@
1
+ import { a as agentRealtime, t as AgentRealtime } from "./request-BUwa359H.js";
2
+ export { type AgentRealtime, agentRealtime };
package/dist/agent.js ADDED
@@ -0,0 +1,2 @@
1
+ import { t as agentRealtime } from "./request-CWaHqW3R.js";
2
+ export { agentRealtime };
@@ -0,0 +1,476 @@
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
2
+ import { createHash } from "node:crypto";
3
+ import * as decoding from "lib0/decoding";
4
+ import * as encoding from "lib0/encoding";
5
+ //#region src/bus-protocol.ts
6
+ /**
7
+ * What one instance tells the other instances about a room:
8
+ * - `update`: a Yjs update of the room document.
9
+ * - `awareness`: an awareness update of the room's clients.
10
+ * - `claim`: the connection-time awareness client id of a peer; retires that client's old socket ownership.
11
+ * - `sync`: an instance opened the room and asks for what it lacks. `data` is its Yjs state vector.
12
+ * - `reset`: the room re-seeded at `epoch`. Instances at another epoch load the room again.
13
+ * - `refresh`: `refreshRealtimeDocument()` ran on an instance.
14
+ * - `frame`: a protocol frame to relay to every peer as it is, such as a Workspace change.
15
+ */
16
+ const realtimeBusMessageTypes = Object.freeze({
17
+ update: 0,
18
+ awareness: 1,
19
+ sync: 2,
20
+ reset: 3,
21
+ refresh: 4,
22
+ frame: 5,
23
+ claim: 6
24
+ });
25
+ const envelopeVersion = 1;
26
+ function encodeRealtimeBusMessage(message) {
27
+ const encoder = encoding.createEncoder();
28
+ encoding.writeVarUint(encoder, envelopeVersion);
29
+ encoding.writeVarUint(encoder, realtimeBusMessageTypes[message.type]);
30
+ encoding.writeVarString(encoder, message.instance);
31
+ encoding.writeVarString(encoder, message.room);
32
+ encoding.writeVarString(encoder, message.epoch);
33
+ encoding.writeVarUint8Array(encoder, message.data);
34
+ return encoding.toUint8Array(encoder);
35
+ }
36
+ const typesByCode = new Map(Object.entries(realtimeBusMessageTypes).map(([type, code]) => [code, type]));
37
+ /** Reads a bus message, or `undefined` when it is not one of this version. */
38
+ function decodeRealtimeBusMessage(bytes) {
39
+ try {
40
+ const decoder = decoding.createDecoder(bytes);
41
+ if (decoding.readVarUint(decoder) !== envelopeVersion) return;
42
+ const type = typesByCode.get(decoding.readVarUint(decoder));
43
+ if (!type) return;
44
+ return {
45
+ type,
46
+ instance: decoding.readVarString(decoder),
47
+ room: decoding.readVarString(decoder),
48
+ epoch: decoding.readVarString(decoder),
49
+ data: decoding.readVarUint8Array(decoder)
50
+ };
51
+ } catch {
52
+ return;
53
+ }
54
+ }
55
+ //#endregion
56
+ //#region src/bus.ts
57
+ /** The variable that points the Postgres bus at its own database, instead of the connection of the Default Database. */
58
+ const realtimePostgresUrlVariable = "REALTIME_POSTGRES_URL";
59
+ /** The variable that replaces the namespace of the build, such as to keep staging and production apart on one Redis. */
60
+ const realtimeNamespaceVariable = "REALTIME_NAMESPACE";
61
+ /**
62
+ * The namespace of the rooms of one app on a shared Redis or Postgres. Rooms with the same key in two namespaces never
63
+ * meet. `REALTIME_NAMESPACE` wins over the namespace of the build.
64
+ */
65
+ function resolveRealtimeNamespace(namespace, env = globalThis.process?.env ?? {}) {
66
+ return env["REALTIME_NAMESPACE"]?.trim() || namespace?.trim() || "default";
67
+ }
68
+ const postgresUrl = /^postgres(?:ql)?:\/\//i;
69
+ function readVariable(env, name) {
70
+ return env[name]?.trim() || void 0;
71
+ }
72
+ /**
73
+ * Picks the room driver of a Node server: `REDIS_URL` selects Redis. Else `REALTIME_POSTGRES_URL`, or the Default
74
+ * Database when it is on Postgres, selects Postgres. Else the rooms stay in this process. An explicit `postgres` or
75
+ * `redis` requires its connection. `database` is true when the build found the Default Database on Postgres.
76
+ */
77
+ function resolveRealtimeNodeDriver(driver, options = {}) {
78
+ const env = options.env ?? globalThis.process?.env ?? {};
79
+ const redis = readVariable(env, "REDIS_URL");
80
+ const override = readVariable(env, realtimePostgresUrlVariable);
81
+ if (driver === "redis" || driver === "auto" && redis) {
82
+ if (!redis) throw realtimeErrorDiagnostics.REALTIME_MISSING_BUS_CONNECTION({ driver: "redis" });
83
+ return {
84
+ driver: "redis",
85
+ source: "REDIS_URL",
86
+ url: redis
87
+ };
88
+ }
89
+ if (override) {
90
+ if (!postgresUrl.test(override)) throw realtimeErrorDiagnostics.REALTIME_INVALID_POSTGRES_URL();
91
+ return {
92
+ driver: "postgres",
93
+ source: realtimePostgresUrlVariable,
94
+ url: override
95
+ };
96
+ }
97
+ if (options.database) return {
98
+ driver: "postgres",
99
+ source: "Default Database"
100
+ };
101
+ if (driver === "postgres") throw realtimeErrorDiagnostics.REALTIME_MISSING_BUS_CONNECTION({ driver: "postgres" });
102
+ return { driver: "memory" };
103
+ }
104
+ function describeChoice(choice) {
105
+ return choice.driver === "memory" ? "[vitehub] Realtime keeps rooms in this process. Set REDIS_URL, or use a Postgres Default Database, to share rooms across instances." : `[vitehub] Realtime shares rooms across instances through ${choice.driver === "redis" ? "Redis" : "Postgres"} (${choice.source}).`;
106
+ }
107
+ /** The postgres.js client of the Default Database, or undefined when it is not one. */
108
+ async function defaultDatabaseClient(databases) {
109
+ const entry = databases ? (await databases()).default : void 0;
110
+ const client = entry ? Reflect.get(entry.db, "$client") : void 0;
111
+ return isPostgresClient(client) ? client : void 0;
112
+ }
113
+ /**
114
+ * Creates the bus for `driver`, or `undefined` when the rooms stay in this process. `useRealtimeBus()` keeps one per
115
+ * process. A bus on the Default Database borrows its client and never closes it.
116
+ */
117
+ async function createRealtimeNodeBus(driver, options = {}) {
118
+ const choice = resolveRealtimeNodeDriver(driver, {
119
+ database: !!options.databases,
120
+ env: options.env
121
+ });
122
+ const namespace = resolveRealtimeNamespace(options.namespace, options.env);
123
+ if (choice.driver === "redis") return await createRedisRealtimeBus(choice.url, { namespace });
124
+ if (choice.driver === "memory") return void 0;
125
+ if (choice.url) return await createPostgresRealtimeBus({
126
+ namespace,
127
+ url: choice.url
128
+ });
129
+ const client = await defaultDatabaseClient(options.databases);
130
+ if (!client) throw realtimeErrorDiagnostics.REALTIME_MISSING_BUS_CONNECTION({ driver: "postgres" });
131
+ return await createPostgresRealtimeBus({
132
+ client,
133
+ namespace
134
+ });
135
+ }
136
+ const busesKey = Symbol.for("vitehub.realtime.buses");
137
+ const busScope = globalThis;
138
+ function buses() {
139
+ busScope[busesKey] ??= /* @__PURE__ */ new Map();
140
+ return busScope[busesKey];
141
+ }
142
+ /**
143
+ * The bus of this process for `driver`, created on first use, or `undefined` when the rooms stay in this process.
144
+ * The generated Realtime handler of a Node build calls it.
145
+ */
146
+ function useRealtimeBus(driver = "auto", options = {}) {
147
+ const existing = buses().get(driver);
148
+ if (existing) return existing;
149
+ const pending = createRealtimeNodeBus(driver, options);
150
+ buses().set(driver, pending);
151
+ pending.catch(() => {
152
+ if (buses().get(driver) === pending) buses().delete(driver);
153
+ });
154
+ return pending;
155
+ }
156
+ /**
157
+ * Prints the Realtime driver that this server uses. The generated Nitro plugin calls it when the server starts.
158
+ * `database` is true when the build found the Default Database on Postgres.
159
+ */
160
+ function logRealtimeNodeDriver(driver = "auto", options = {}) {
161
+ try {
162
+ const choice = resolveRealtimeNodeDriver(driver, options);
163
+ console.info(choice.driver === "memory" ? describeChoice(choice) : `${describeChoice(choice).slice(0, -1)}, namespace "${resolveRealtimeNamespace(options.namespace)}".`);
164
+ } catch (error) {
165
+ console.error(error);
166
+ }
167
+ }
168
+ /** Removes this instance's presence from the other instances and closes every bus. Nitro calls it when the server closes. */
169
+ async function closeRealtimeBuses() {
170
+ const pending = [...buses().values()];
171
+ buses().clear();
172
+ await Promise.allSettled(pending.map(async (bus) => {
173
+ await (await bus.catch(() => void 0))?.close();
174
+ }));
175
+ }
176
+ function createBusBase() {
177
+ const hooks = [];
178
+ let closing;
179
+ return {
180
+ instance: crypto.randomUUID(),
181
+ onClose(hook) {
182
+ hooks.push(hook);
183
+ },
184
+ /** Runs the close hooks once, then `end`. */
185
+ close(end) {
186
+ closing ??= (async () => {
187
+ await Promise.allSettled(hooks.map((hook) => hook()));
188
+ await end();
189
+ })();
190
+ return closing;
191
+ }
192
+ };
193
+ }
194
+ /**
195
+ * Runs the listeners on each message in arrival order, also when one message needs an async step to read. `start`
196
+ * subscribes once, for the first listener.
197
+ */
198
+ function createDelivery(instance, read, start) {
199
+ let queue = Promise.resolve();
200
+ const listeners = /* @__PURE__ */ new Set();
201
+ const resubscribers = /* @__PURE__ */ new Set();
202
+ let started;
203
+ return {
204
+ async subscribe(listener, resubscribed) {
205
+ listeners.add(listener);
206
+ if (resubscribed) resubscribers.add(resubscribed);
207
+ started ??= start(() => {
208
+ for (const hook of resubscribers) hook();
209
+ });
210
+ await started;
211
+ },
212
+ push(raw) {
213
+ queue = queue.then(async () => {
214
+ const bytes = await read(raw);
215
+ const message = bytes && decodeRealtimeBusMessage(bytes);
216
+ if (!message || message.instance === instance) return;
217
+ for (const listener of listeners) await listener(message);
218
+ }).catch((error) => {
219
+ console.error("[vitehub] Realtime could not apply a message from another instance.", error);
220
+ });
221
+ }
222
+ };
223
+ }
224
+ /** Sends messages one at a time, so that the other instances receive them in the order this instance sent them. */
225
+ function createSendQueue() {
226
+ let queue = Promise.resolve();
227
+ return (send) => {
228
+ const sent = queue.then(send);
229
+ queue = sent.then(() => {}, () => {});
230
+ return sent;
231
+ };
232
+ }
233
+ /** Runs at most `limit` tasks at a time. */
234
+ function createLimit(limit) {
235
+ let active = 0;
236
+ const waiting = [];
237
+ return async (task) => {
238
+ if (active >= limit) await new Promise((resolve) => waiting.push(resolve));
239
+ active++;
240
+ try {
241
+ return await task();
242
+ } finally {
243
+ active--;
244
+ waiting.shift()?.();
245
+ }
246
+ };
247
+ }
248
+ const postgresChannel = "vitehub_realtime";
249
+ /** `NOTIFY` payloads stop at 8000 bytes. A larger message goes to a table, and the notification carries its id. */
250
+ const maxNotifyPayload = 7900;
251
+ /** Large messages stay this long for instances that read them late. */
252
+ const postgresMessageRetentionSeconds = 300;
253
+ /** Pool size for room records and notifications. Locks use their own pool so adapter queries cannot wait on them. */
254
+ const postgresConnections = 6;
255
+ const postgresLockedSaves = 3;
256
+ /** A stable number for `pg_advisory_xact_lock()` while the tables are created: "vhrt" in ASCII. */
257
+ const postgresSetupLock = 1986556532;
258
+ function isPostgresClient(value) {
259
+ return typeof value === "function" && [
260
+ "begin",
261
+ "end",
262
+ "listen"
263
+ ].every((name) => typeof Reflect.get(value, name) === "function") && typeof Reflect.get(value, "options") === "object" && Reflect.get(value, "options") !== null;
264
+ }
265
+ function bytes(value) {
266
+ return value instanceof Uint8Array ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : void 0;
267
+ }
268
+ function toRecord(row) {
269
+ const state = bytes(row?.state);
270
+ if (!row || typeof row.epoch !== "string" || !state) return void 0;
271
+ return {
272
+ epoch: row.epoch,
273
+ digest: typeof row.digest === "string" ? row.digest : null,
274
+ state,
275
+ pending: row.pending === true
276
+ };
277
+ }
278
+ /**
279
+ * Shares rooms through Postgres: `LISTEN`/`NOTIFY` carries room traffic, `vitehub_realtime_rooms` holds the shared
280
+ * room records, and a transaction-scoped advisory lock orders saves. Creates its two tables when it connects. With
281
+ * `{ client }`, the bus borrows the postgres.js client of a Database: it stops listening on close, and leaves the client
282
+ * open.
283
+ */
284
+ async function createPostgresRealtimeBus(connection) {
285
+ const namespace = connection.namespace ?? "default";
286
+ const channel = `${postgresChannel}_${createHash("sha256").update(namespace).digest("hex").slice(0, 16)}`;
287
+ let sql;
288
+ const owned = "url" in connection;
289
+ if ("url" in connection) {
290
+ const { default: postgres } = await import("postgres");
291
+ sql = postgres(connection.url, {
292
+ max: postgresConnections,
293
+ onnotice: () => {}
294
+ });
295
+ } else if (isPostgresClient(connection.client)) sql = connection.client;
296
+ else throw realtimeErrorDiagnostics.REALTIME_MISSING_BUS_CONNECTION({ driver: "postgres" });
297
+ const { default: postgres } = await import("postgres");
298
+ const locks = postgres({
299
+ ...sql.options,
300
+ max: postgresLockedSaves,
301
+ onnotice: () => {}
302
+ });
303
+ const end = async () => {
304
+ await locks.end({ timeout: 5 });
305
+ if (owned) await sql.end({ timeout: 5 });
306
+ };
307
+ try {
308
+ await sql.begin(async (transaction) => {
309
+ await transaction`select pg_advisory_xact_lock(${postgresSetupLock})`;
310
+ await transaction`create table if not exists vitehub_realtime_rooms (namespace text not null, room_key text not null, epoch text not null, digest text, state bytea not null, updated_at timestamptz not null default now(), primary key (namespace, room_key))`;
311
+ await transaction`alter table vitehub_realtime_rooms add column if not exists pending boolean not null default false`;
312
+ await transaction`create table if not exists vitehub_realtime_messages (id bigserial primary key, payload bytea not null, created_at timestamptz not null default now())`;
313
+ });
314
+ } catch (error) {
315
+ await locks.end({ timeout: 1 }).catch(() => {});
316
+ if (owned) await sql.end({ timeout: 1 }).catch(() => {});
317
+ throw error;
318
+ }
319
+ const base = createBusBase();
320
+ let published = 0;
321
+ let listening;
322
+ const send = createSendQueue();
323
+ const locked = createLimit(postgresLockedSaves);
324
+ const delivery = createDelivery(base.instance, async (raw) => {
325
+ if (typeof raw !== "string") return;
326
+ if (raw.startsWith("m")) return Uint8Array.from(Buffer.from(raw.slice(1), "base64"));
327
+ if (!raw.startsWith("r")) return;
328
+ const [row] = await sql`select payload from vitehub_realtime_messages where id = ${raw.slice(1)}`;
329
+ return bytes(row?.payload);
330
+ }, async (resubscribed) => {
331
+ let started = false;
332
+ listening = await sql.listen(channel, (payload) => delivery.push(payload), () => {
333
+ if (started) resubscribed();
334
+ started = true;
335
+ });
336
+ });
337
+ return {
338
+ authority: "postgres",
339
+ instance: base.instance,
340
+ onClose: base.onClose,
341
+ publish: (message) => send(async () => {
342
+ const encoded = encodeRealtimeBusMessage({
343
+ ...message,
344
+ instance: base.instance
345
+ });
346
+ const inline = `m${Buffer.from(encoded).toString("base64")}`;
347
+ if (inline.length <= maxNotifyPayload) {
348
+ await sql`select pg_notify(${channel}, ${inline})`;
349
+ return;
350
+ }
351
+ const [row] = await sql`insert into vitehub_realtime_messages (payload) values (${Buffer.from(encoded)}) returning id`;
352
+ await sql`select pg_notify(${channel}, ${`r${String(row?.id)}`})`;
353
+ if (++published % 100 === 1) await sql`delete from vitehub_realtime_messages where created_at < now() - make_interval(secs => ${postgresMessageRetentionSeconds})`;
354
+ }),
355
+ subscribe: (listener, resubscribed) => delivery.subscribe(listener, resubscribed),
356
+ async readRoom(room) {
357
+ const [row] = await sql`select epoch, digest, state, pending from vitehub_realtime_rooms where namespace = ${namespace} and room_key = ${room}`;
358
+ return toRecord(row);
359
+ },
360
+ async writeRoom(room, record, ifEpoch) {
361
+ const state = Buffer.from(record.state);
362
+ return (ifEpoch === null ? await sql`insert into vitehub_realtime_rooms (namespace, room_key, epoch, digest, state, pending) values (${namespace}, ${room}, ${record.epoch}, ${record.digest}, ${state}, ${record.pending ?? false}) on conflict (namespace, room_key) do nothing returning room_key` : await sql`update vitehub_realtime_rooms set epoch = ${record.epoch}, digest = ${record.digest}, state = ${state}, pending = ${record.pending ?? false}, updated_at = now() where namespace = ${namespace} and room_key = ${room} and epoch = ${ifEpoch} returning room_key`).length === 1;
363
+ },
364
+ withRoomLock: (room, task) => locked(async () => {
365
+ return (await locks.begin(async (transaction) => {
366
+ await transaction`select pg_advisory_xact_lock(hashtextextended(${`vitehub_realtime:${namespace}:${room}`}, 0))`;
367
+ return { value: await task() };
368
+ })).value;
369
+ }),
370
+ close: () => base.close(async () => {
371
+ await listening?.unlisten().catch(() => {});
372
+ await end();
373
+ })
374
+ };
375
+ }
376
+ const redisPrefix = "vitehub:realtime:";
377
+ /** A lock whose holder stopped expires after this time. */
378
+ const redisLockMs = 3e4;
379
+ /** Writes the record when the stored epoch is ARGV[1], or when there is no record and ARGV[1] is empty. */
380
+ const redisWriteRoomScript = `
381
+ local current = redis.call('HGET', KEYS[1], 'epoch')
382
+ if (ARGV[1] == '' and current == false) or (current ~= false and current == ARGV[1]) then
383
+ redis.call('HSET', KEYS[1], 'epoch', ARGV[2], 'digest', ARGV[3], 'hasDigest', ARGV[4], 'state', ARGV[5], 'pending', ARGV[6])
384
+ return 1
385
+ end
386
+ return 0
387
+ `;
388
+ /** Extends the lock while its holder still runs, so a save that takes longer than 30 seconds keeps it. */
389
+ const redisRenewLockScript = `
390
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
391
+ return redis.call('PEXPIRE', KEYS[1], ARGV[2])
392
+ end
393
+ return 0
394
+ `;
395
+ const redisLockRenewMs = 1e4;
396
+ const redisReleaseLockScript = `
397
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
398
+ return redis.call('DEL', KEYS[1])
399
+ end
400
+ return 0
401
+ `;
402
+ /**
403
+ * Shares rooms through Redis: pub/sub carries room traffic, one hash per room holds the shared room record, and a
404
+ * `SET NX PX` lock orders saves.
405
+ */
406
+ async function createRedisRealtimeBus(url, options = {}) {
407
+ const prefix = `${redisPrefix}${options.namespace ?? "default"}:`;
408
+ const redisChannel = `${prefix}channel`;
409
+ const redisRoomPrefix = `${prefix}room:`;
410
+ const redisLockPrefix = `${prefix}lock:`;
411
+ const { Redis } = await import("ioredis");
412
+ const client = new Redis(url, { lazyConnect: true });
413
+ const subscriber = client.duplicate();
414
+ try {
415
+ await Promise.all([client.connect(), subscriber.connect()]);
416
+ } catch (error) {
417
+ client.disconnect();
418
+ subscriber.disconnect();
419
+ throw error;
420
+ }
421
+ const base = createBusBase();
422
+ const send = createSendQueue();
423
+ const delivery = createDelivery(base.instance, async (raw) => typeof raw === "string" ? void 0 : raw, async (resubscribed) => {
424
+ subscriber.on("messageBuffer", (_channel, message) => delivery.push(Uint8Array.from(message)));
425
+ await subscriber.subscribe(redisChannel);
426
+ subscriber.on("ready", resubscribed);
427
+ });
428
+ return {
429
+ authority: "redis",
430
+ instance: base.instance,
431
+ onClose: base.onClose,
432
+ publish: (message) => send(async () => {
433
+ await client.publish(redisChannel, Buffer.from(encodeRealtimeBusMessage({
434
+ ...message,
435
+ instance: base.instance
436
+ })));
437
+ }),
438
+ subscribe: (listener, resubscribed) => delivery.subscribe(listener, resubscribed),
439
+ async readRoom(room) {
440
+ const fields = await client.hgetallBuffer(`${redisRoomPrefix}${room}`);
441
+ if (!fields.epoch || !fields.state) return void 0;
442
+ return {
443
+ epoch: fields.epoch.toString(),
444
+ digest: fields.hasDigest?.toString() === "1" ? fields.digest?.toString() ?? null : null,
445
+ state: Uint8Array.from(fields.state),
446
+ pending: fields.pending?.toString() === "1"
447
+ };
448
+ },
449
+ async writeRoom(room, record, ifEpoch) {
450
+ return await client.eval(redisWriteRoomScript, 1, `${redisRoomPrefix}${room}`, ifEpoch ?? "", record.epoch, record.digest ?? "", record.digest === null ? "0" : "1", Buffer.from(record.state), record.pending ? "1" : "0") === 1;
451
+ },
452
+ async withRoomLock(room, task) {
453
+ const key = `${redisLockPrefix}${room}`;
454
+ const token = crypto.randomUUID();
455
+ const deadline = Date.now() + redisLockMs;
456
+ while (await client.set(key, token, "PX", redisLockMs, "NX") !== "OK") {
457
+ if (Date.now() > deadline) throw realtimeErrorDiagnostics.REALTIME_ROOM_LOCK_TIMEOUT();
458
+ await new Promise((resolve) => setTimeout(resolve, 25 + Math.random() * 50));
459
+ }
460
+ const renew = setInterval(() => {
461
+ client.eval(redisRenewLockScript, 1, key, token, redisLockMs).catch(() => {});
462
+ }, redisLockRenewMs);
463
+ try {
464
+ return await task();
465
+ } finally {
466
+ clearInterval(renew);
467
+ await client.eval(redisReleaseLockScript, 1, key, token).catch(() => {});
468
+ }
469
+ },
470
+ close: () => base.close(async () => {
471
+ await Promise.allSettled([client.quit(), subscriber.quit()]);
472
+ })
473
+ };
474
+ }
475
+ //#endregion
476
+ export { logRealtimeNodeDriver as a, resolveRealtimeNamespace as c, createRedisRealtimeBus as i, resolveRealtimeNodeDriver as l, createPostgresRealtimeBus as n, realtimeNamespaceVariable as o, createRealtimeNodeBus as r, realtimePostgresUrlVariable as s, closeRealtimeBuses as t, useRealtimeBus as u };