@vite-hub/realtime 0.3.1 → 0.5.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.
Files changed (36) hide show
  1. package/README.md +20 -14
  2. package/dist/agent.d.ts +1 -1
  3. package/dist/agent.js +1 -1
  4. package/dist/{bus-Bi-Ec414.js → bus-Bsdanf5O.js} +9 -18
  5. package/dist/bus.js +1 -1
  6. package/dist/client/browser.js +1 -1
  7. package/dist/client.d.ts +2 -2
  8. package/dist/client.js +14 -7
  9. package/dist/{conflict-Bg8vCisd.js → conflict-DYC_qXzM.js} +7 -7
  10. package/dist/{document-DjBrcgpY.js → document-U5rzg2vG.js} +1 -1
  11. package/dist/{document-DPaywuCO.d.ts → document-b1ShR2S1.d.ts} +2 -2
  12. package/dist/durability.js +0 -4
  13. package/dist/{editor-BM5-vHqf.js → editor-IL2jHqn8.js} +0 -1
  14. package/dist/{error-diagnostics-B_66irmt.js → error-diagnostics-Cd-XWNf7.js} +21 -4
  15. package/dist/index.d.ts +4 -4
  16. package/dist/index.js +2 -2
  17. package/dist/internal/runtime/unavailable.d.ts +1 -1
  18. package/dist/internal/server.d.ts +7 -0
  19. package/dist/internal/server.js +6 -0
  20. package/dist/{keepalive-BCs-uXp4.js → keepalive-B4ONG6AD.js} +1 -1
  21. package/dist/{layout-fyQnhwCg.d.ts → layout-VHjYWa-M.d.ts} +1 -1
  22. package/dist/log-E-cH6xkd.js +159 -0
  23. package/dist/{object-CzKyK0hX.js → object-BgPPDLDE.js} +1 -1
  24. package/dist/{presence-Tuy1y_l9.js → presence-B6rvkHqd.js} +2 -2
  25. package/dist/{request-BUwa359H.d.ts → request-DAodIqZ8.d.ts} +1 -1
  26. package/dist/{request-CWaHqW3R.js → request-kM5epeSd.js} +2 -3
  27. package/dist/server-BSXJP45b.js +2606 -0
  28. package/dist/server-Covbc24E.d.ts +140 -0
  29. package/dist/server.d.ts +3 -141
  30. package/dist/server.js +3 -2581
  31. package/dist/{types-1DVVG5ro.d.ts → types-DdY7Vo1H.d.ts} +30 -41
  32. package/dist/vite.d.ts +3 -1
  33. package/dist/vite.js +67 -54
  34. package/dist/vue.d.ts +7 -9
  35. package/dist/vue.js +35 -38
  36. package/package.json +11 -6
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # @vite-hub/realtime
2
2
 
3
3
  <p>
4
- <a href="https://vitehub.dev"><img alt="ViteHub" src="https://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">
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/static/v1?label=ViteHub&amp;message=vitehub.dev&amp;color=blue"></a>
5
+ <img alt="TypeScript" src="https://img.shields.io/static/v1?label=TypeScript&amp;message=ready&amp;color=blue">
6
+ <img alt="Yjs" src="https://img.shields.io/static/v1?label=Yjs&amp;message=collaboration&amp;color=blue">
7
+ <img alt="Vite" src="https://img.shields.io/static/v1?label=Vite&amp;message=discovery&amp;color=blue">
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.
@@ -17,7 +17,7 @@ Realtime is for collaborative documents, presence, explicit Workspace checkpoint
17
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.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.
20
+ ViteHub Realtime requires Node.js 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. 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
 
@@ -56,7 +56,7 @@ export default defineWorkspace({
56
56
  import { defineRealtime } from "@vite-hub/realtime"
57
57
 
58
58
  export default defineRealtime({
59
- auth: true,
59
+ authorize: true,
60
60
  document: { workspace: "docs" },
61
61
  history: { checkpoint: true },
62
62
  })
@@ -110,6 +110,8 @@ console.log(checkpoint.document.body)
110
110
  console.log(checkpoint.snapshot.id)
111
111
  ```
112
112
 
113
+ Checkpoints use the Workspace Store's author by default. Set `document.checkpointAuthor` only to look up a Git identity approved for publication for the identified requester. Leave it unset for GitHub branches that require signed commits.
114
+
113
115
  ## Share presence without a document
114
116
 
115
117
  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.
@@ -119,7 +121,7 @@ Set `document: false` when a room only shows who is there and what each person s
119
121
  import { defineRealtime } from "@vite-hub/realtime"
120
122
 
121
123
  export default defineRealtime({
122
- auth: true,
124
+ authorize: true,
123
125
  document: false,
124
126
  })
125
127
  ```
@@ -162,18 +164,22 @@ const [error, answer] = await requestRealtimeRoom("tabs", tabId, { want: "title"
162
164
 
163
165
  ## Deployment and security boundaries
164
166
 
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`.
167
+ - The Vue adapter connects to the generated same-origin `/_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
168
  - `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
169
  - `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`.
170
+ - On a Node build, `driver: "auto"` picks when the server starts: `redis` with `REDIS_URL`, else `postgres` with `REALTIME_POSTGRES_URL` or the postgres.js client of a Postgres Default Database (`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`.
169
171
  - 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.
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.
172
+ - Each Realtime Definition must set `authorize: 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. It also runs for signed-out callers, with `user: null`. `authorize: 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
173
  - Requests with an `Origin` other than the app's get 403 on each definition, unless `origins()` accepts the origin.
172
174
  - 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.
175
+ - Realtime routes follow the app base, including a Nuxt `app.baseURL`. With Vite `base: "/portal/"`, connections use `/portal/_vitehub/realtime/**`; Nitro's own `baseURL` is counted once.
174
176
  - `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.
175
177
  - 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.
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.
178
+ - 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 `REALTIME_REQUEST_FAILED` error has the HTTP status in `error.data.status`. A refused request returns the code that the server names, such as `REALTIME_SOURCE_CHANGED` when the stored document changed, or `REALTIME_SYNC_PENDING` after 20 retries. 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.
179
+
180
+ ## Refusals and failures in logs
181
+
182
+ With the evlog Nitro module registered, a refused connection, save, checkpoint, or refresh gets a `realtime` field on its request's wide event: `{ definition, room, refused, status, code? }`. A room id of a `document: false` Definition is a short hash, because it can be a token. After the WebSocket opens, close codes, connection errors, failed sync between Node instances, and failed background saves are their own evlog events, `{ action: "realtime", message, realtime: { definition, room, closed | failed } }`. Without evlog, Realtime prints the sync and save failures to the console. See [Limits and errors](https://vitehub.dev/docs/realtime/limits-and-errors#see-refusals-and-failures-in-logs).
177
183
 
178
184
  ## Public imports
179
185
 
@@ -185,14 +191,14 @@ const [error, answer] = await requestRealtimeRoom("tabs", tabId, { want: "title"
185
191
  | `@vite-hub/realtime/agent` | `agentRealtime`, the handle that ViteHub passes to the Agent `page()` Capability. Apps do not import it. |
186
192
  | `@vite-hub/realtime/client` | `connectRealtimeRoom()` to share presence without an editor, in any framework. |
187
193
  | `@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. |
194
+ | `@vite-hub/realtime/server` | `refreshRealtimeDocument()`, `isRealtimeAvailable()`, `requestRealtimeRoom()`, `workspaceDocument()`, `blobDocument()`, and `createRealtimeHandler()` for a manual H3 server integration. Normal ViteHub apps use the generated route. |
189
195
  | `@vite-hub/realtime/bus` | `useRealtimeBus()` and `closeRealtimeBuses()`, the Postgres and Redis buses that the generated Node handler passes to `createRealtimeHandler({ bus })`. |
190
196
 
191
197
  Generated files under `.vitehub/nitro/realtime` are inspectable build output, not application imports.
192
198
 
193
199
  ## Learn more
194
200
 
195
- - [Realtime collaboration](https://vitehub.dev/docs/realtime) covers authorities, checkpoints, workspace events, quotas, and generated output.
201
+ - [Realtime collaboration](https://vitehub.dev/docs/realtime) covers drivers, checkpoints, workspace events, quotas, and generated output.
196
202
  - [Workspace](https://vitehub.dev/docs/workspace) covers stores, write rules, snapshots, and persistence.
197
203
  - [Auth](https://vitehub.dev/docs/auth) covers session setup and trusted origins.
198
204
  - [Configuration options](https://vitehub.dev/docs/reference/config-options) lists every Realtime module option.
package/dist/agent.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as agentRealtime, t as AgentRealtime } from "./request-BUwa359H.js";
1
+ import { a as agentRealtime, t as AgentRealtime } from "./request-DAodIqZ8.js";
2
2
  export { type AgentRealtime, agentRealtime };
package/dist/agent.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as agentRealtime } from "./request-CWaHqW3R.js";
1
+ import { t as agentRealtime } from "./request-kM5epeSd.js";
2
2
  export { agentRealtime };
@@ -1,4 +1,5 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
2
+ import { n as realtimeRoomFields, t as logRealtime } from "./log-E-cH6xkd.js";
2
3
  import { createHash } from "node:crypto";
3
4
  import * as decoding from "lib0/decoding";
4
5
  import * as encoding from "lib0/encoding";
@@ -104,7 +105,6 @@ function resolveRealtimeNodeDriver(driver, options = {}) {
104
105
  function describeChoice(choice) {
105
106
  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
  }
107
- /** The postgres.js client of the Default Database, or undefined when it is not one. */
108
108
  async function defaultDatabaseClient(databases) {
109
109
  const entry = databases ? (await databases()).default : void 0;
110
110
  const client = entry ? Reflect.get(entry.db, "$client") : void 0;
@@ -181,7 +181,6 @@ function createBusBase() {
181
181
  onClose(hook) {
182
182
  hooks.push(hook);
183
183
  },
184
- /** Runs the close hooks once, then `end`. */
185
184
  close(end) {
186
185
  closing ??= (async () => {
187
186
  await Promise.allSettled(hooks.map((hook) => hook()));
@@ -191,10 +190,6 @@ function createBusBase() {
191
190
  }
192
191
  };
193
192
  }
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
193
  function createDelivery(instance, read, start) {
199
194
  let queue = Promise.resolve();
200
195
  const listeners = /* @__PURE__ */ new Set();
@@ -216,12 +211,11 @@ function createDelivery(instance, read, start) {
216
211
  if (!message || message.instance === instance) return;
217
212
  for (const listener of listeners) await listener(message);
218
213
  }).catch((error) => {
219
- console.error("[vitehub] Realtime could not apply a message from another instance.", error);
214
+ logRealtime("error", "Realtime could not apply a message from another instance.", { failed: "bus-receive" }, error);
220
215
  });
221
216
  }
222
217
  };
223
218
  }
224
- /** Sends messages one at a time, so that the other instances receive them in the order this instance sent them. */
225
219
  function createSendQueue() {
226
220
  let queue = Promise.resolve();
227
221
  return (send) => {
@@ -230,7 +224,6 @@ function createSendQueue() {
230
224
  return sent;
231
225
  };
232
226
  }
233
- /** Runs at most `limit` tasks at a time. */
234
227
  function createLimit(limit) {
235
228
  let active = 0;
236
229
  const waiting = [];
@@ -246,14 +239,10 @@ function createLimit(limit) {
246
239
  };
247
240
  }
248
241
  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
242
  const maxNotifyPayload = 7900;
251
- /** Large messages stay this long for instances that read them late. */
252
243
  const postgresMessageRetentionSeconds = 300;
253
- /** Pool size for room records and notifications. Locks use their own pool so adapter queries cannot wait on them. */
254
244
  const postgresConnections = 6;
255
245
  const postgresLockedSaves = 3;
256
- /** A stable number for `pg_advisory_xact_lock()` while the tables are created: "vhrt" in ASCII. */
257
246
  const postgresSetupLock = 1986556532;
258
247
  function isPostgresClient(value) {
259
248
  return typeof value === "function" && [
@@ -374,9 +363,7 @@ async function createPostgresRealtimeBus(connection) {
374
363
  };
375
364
  }
376
365
  const redisPrefix = "vitehub:realtime:";
377
- /** A lock whose holder stopped expires after this time. */
378
366
  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
367
  const redisWriteRoomScript = `
381
368
  local current = redis.call('HGET', KEYS[1], 'epoch')
382
369
  if (ARGV[1] == '' and current == false) or (current ~= false and current == ARGV[1]) then
@@ -385,7 +372,6 @@ if (ARGV[1] == '' and current == false) or (current ~= false and current == ARGV
385
372
  end
386
373
  return 0
387
374
  `;
388
- /** Extends the lock while its holder still runs, so a save that takes longer than 30 seconds keeps it. */
389
375
  const redisRenewLockScript = `
390
376
  if redis.call('GET', KEYS[1]) == ARGV[1] then
391
377
  return redis.call('PEXPIRE', KEYS[1], ARGV[2])
@@ -458,7 +444,12 @@ async function createRedisRealtimeBus(url, options = {}) {
458
444
  await new Promise((resolve) => setTimeout(resolve, 25 + Math.random() * 50));
459
445
  }
460
446
  const renew = setInterval(() => {
461
- client.eval(redisRenewLockScript, 1, key, token, redisLockMs).catch(() => {});
447
+ client.eval(redisRenewLockScript, 1, key, token, redisLockMs).catch((error) => {
448
+ logRealtime("warn", "Realtime could not renew a room lock.", {
449
+ ...realtimeRoomFields(room, false),
450
+ failed: "bus-lock"
451
+ }, error);
452
+ });
462
453
  }, redisLockRenewMs);
463
454
  try {
464
455
  return await task();
package/dist/bus.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as logRealtimeNodeDriver, c as resolveRealtimeNamespace, i as createRedisRealtimeBus, l as resolveRealtimeNodeDriver, n as createPostgresRealtimeBus, o as realtimeNamespaceVariable, r as createRealtimeNodeBus, s as realtimePostgresUrlVariable, t as closeRealtimeBuses, u as useRealtimeBus } from "./bus-Bi-Ec414.js";
1
+ import { a as logRealtimeNodeDriver, c as resolveRealtimeNamespace, i as createRedisRealtimeBus, l as resolveRealtimeNodeDriver, n as createPostgresRealtimeBus, o as realtimeNamespaceVariable, r as createRealtimeNodeBus, s as realtimePostgresUrlVariable, t as closeRealtimeBuses, u as useRealtimeBus } from "./bus-Bsdanf5O.js";
2
2
  export { closeRealtimeBuses, createPostgresRealtimeBus, createRealtimeNodeBus, createRedisRealtimeBus, logRealtimeNodeDriver, realtimeNamespaceVariable, realtimePostgresUrlVariable, resolveRealtimeNamespace, resolveRealtimeNodeDriver, useRealtimeBus };
@@ -50,4 +50,4 @@ var Wo=class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.
50
50
  /* c8 ignore stop */
51
51
  /* c8 ignore next */
52
52
  const Go=typeof BroadcastChannel>`u`?Wo:BroadcastChannel,Ko=e=>k(Uo,e,()=>{let t=l(),n=new Go(e);return n.onmessage=e=>t.forEach(t=>t(e.data,`broadcastchannel`)),{bc:n,subs:t}}),qo=(e,t)=>(Ko(e).subs.add(t),t),Jo=(e,t)=>{let n=Ko(e),r=n.subs.delete(t);return r&&n.subs.size===0&&(n.bc.close(),Uo.delete(e)),r},Yo=(e,t,n=null)=>{let r=Ko(e);r.bc.postMessage(t),r.subs.forEach(e=>e(t,n))},Xo=(e,t)=>{b(e,0);let n=pi(t);S(e,n)},Zo=(e,t,n)=>{b(e,1),S(e,si(t,n))},Qo=(e,t,n)=>Zo(t,n,w(e)),$o=(e,t,n,r)=>{try{ii(t,w(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},es=(e,t)=>{b(e,2),S(e,t)},ts=$o,ns=(e,t,n,r,i)=>{let a=T(e);switch(a){case 0:Qo(e,t,n);break;case 1:$o(e,n,r,i);break;case 2:ts(e,n,r,i);break;default:throw Error(`Unknown message type`)}return a},rs=(e,t,n)=>{T(e)===0&&n(t,E(e))},is=e=>ct(e,(e,t)=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join(`&`),as=[];as[0]=(e,t,n,r,i)=>{b(e,0);let a=ns(t,e,n.doc,n);r&&a===1&&!n.synced&&(n.synced=!0)},as[3]=(e,t,n,r,i)=>{b(e,1),S(e,Vo(n.awareness,Array.from(n.awareness.getStates().keys())))},as[1]=(e,t,n,r,i)=>{Ho(n.awareness,w(t),n)},as[2]=(e,t,n,r,i)=>{rs(t,n.doc,(e,t)=>ss(n,t))};const os=3e4,ss=(e,t)=>console.warn(`Permission denied to access ${e.url}.\n${t}`),cs=(e,t,n)=>{let r=C(t),i=_(),a=T(r),o=e.messageHandlers[a];return o?o(i,r,e,n,a):console.error(`Unable to compute message`),i},ls=e=>!(e.code>=4400&&e.code<4500),us=(e,t,r)=>{if(t!==null&&t===e.ws){e.emit(`connection-close`,[r,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,Bo(e.awareness,Array.from(e.awareness.getStates().keys()).filter(t=>t!==e.doc.clientID),e),e.emit(`status`,[{status:`disconnected`}])),e.wsUnsuccessfulReconnects++;let a=null;r!=null&&!e.shouldReconnect(r,e)&&(e.shouldConnect=!1,a={code:r.code,reason:r.reason}),setTimeout(ds,n(i(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),a!==null&&e.emit(`closed`,[a,e])}},ds=e=>{if(e.shouldConnect&&e.ws===null){let t=new e._WS(e.url,e.protocols);t.binaryType=`arraybuffer`,e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=D();let r=cs(e,new Uint8Array(n.data),!0);he(r)>1&&t.send(v(r))},t.onerror=n=>{e.ws===t&&e.emit(`connection-error`,[n,e])},t.onclose=n=>{us(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=D(),e.wsconnecting=!1,e.wsconnected=!0,e.emit(`status`,[{status:`connected`}]);let n=_();if(b(n,0),Xo(n,e.doc),t.send(v(n)),e.awareness.getLocalState()!==null){let n=_();b(n,1),S(n,Vo(e.awareness,[e.doc.clientID])),t.send(v(n))}},e.emit(`status`,[{status:`connecting`}])}},fs=(e,t)=>{let n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&Yo(e.bcChannel,t,e)};var ps=class extends et{constructor(e,t,n,{connect:r=!0,awareness:i=new zo(n),params:a={},protocols:o=[],WebSocketPolyfill:s=WebSocket,resyncInterval:c=-1,maxBackoffTime:l=2500,disableBc:u=!1,shouldReconnect:d=ls}={}){for(super();e[e.length-1]===`/`;)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+`/`+t,this.maxBackoffTime=l,this.shouldReconnect=d,this.params=a,this.protocols=o,this.roomname=t,this.doc=n,this._WS=s,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=as.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,c>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let e=_();b(e,0),Xo(e,n),this.ws.send(v(e))}},c)),this._bcSubscriber=(e,t)=>{if(t!==this){let t=cs(this,new Uint8Array(e),!1);he(t)>1&&Yo(this.bcChannel,v(t),this)}},this._updateHandler=(e,t)=>{if(t!==this){let t=_();b(t,0),es(t,e),fs(this,v(t))}},this.doc.on(`update`,this._updateHandler),this._awarenessUpdateHandler=({added:e,updated:t,removed:n},r)=>{let a=e.concat(t).concat(n),o=_();b(o,1),S(o,Vo(i,a)),fs(this,v(o))},this._exitHandler=()=>{Bo(this.awareness,[n.clientID],`app closed`)},A&&typeof process<`u`&&process.on(`exit`,this._exitHandler),i.on(`update`,this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&os<D()-this.wsLastMessageReceived&&us(this,this.ws,null)},os/10),r&&this.connect()}get url(){let e=is(this.params);return this.serverUrl+`/`+this.roomname+(e.length===0?``:`?`+e)}get synced(){return this._synced}set synced(e){this._synced!==e&&(this._synced=e,e&&(this.wsUnsuccessfulReconnects=0),this.emit(`synced`,[e]),this.emit(`sync`,[e]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),A&&typeof process<`u`&&process.off(`exit`,this._exitHandler),this.awareness.off(`update`,this._awarenessUpdateHandler),this.doc.off(`update`,this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||=(qo(this.bcChannel,this._bcSubscriber),!0);let e=_();b(e,0),Xo(e,this.doc),Yo(this.bcChannel,v(e),this);let t=_();b(t,0),Zo(t,this.doc),Yo(this.bcChannel,v(t),this);let n=_();b(n,3),Yo(this.bcChannel,v(n),this);let r=_();b(r,1),S(r,Vo(this.awareness,[this.doc.clientID])),Yo(this.bcChannel,v(r),this)}disconnectBc(){let e=_();b(e,1),S(e,Vo(this.awareness,[this.doc.clientID],/* @__PURE__ */ new Map)),fs(this,v(e)),this.bcconnected&&=(Jo(this.bcChannel,this._bcSubscriber),!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&us(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(ds(this),this.connectBc())}};function ms(e,t=typeof __VITEHUB_APP_BASE_URL__>`u`?`/`:__VITEHUB_APP_BASE_URL__){return t===`/`?e:`${t.replace(/\/+$/,``)}${e}`}function hs(e,...t){return typeof e==`function`?e(...t):e}const gs=Error.captureStackTrace;var _s=class e extends Error{get why(){return this.message}constructor(t,n=e){super(t.why,{cause:t.cause}),this.code=this.name=t.code,this.docs=t.docs,this.fix=t.fix,this.sources=t.sources,this.data=t.data,gs?.(this,n)}toJSON(){return{name:this.name,why:this.why,fix:this.fix,docs:this.docs,sources:this.sources,cause:this.cause,data:this.data,stack:this.stack}}};function vs(e,t){return typeof e==`string`?`${e}/${t.toLowerCase()}`:e?.(t)}const ys=e=>t=>t instanceof _s&&e in t;/* @__NO_SIDE_EFFECTS__ */
53
- function bs(e){let t=e.reporters??[],n=Symbol(),r=Object.defineProperty({},"is",{value:ys(n)}),{docsBase:i}=e;for(let a of Object.keys(e.codes)){let o=e.codes[a],s=o.docs===!1?void 0:o.docs||vs(i,a),c=(e={},r={})=>{let i=new _s({code:a,why:hs(o.why,e),fix:hs(o.fix,e),docs:s,cause:e.cause,sources:e.sources,data:hs(o.data,e)},c);i[n]=1;for(let e of t)e(i,r);return i};c.is=e=>r.is(e)&&e.code===a,r[a]=c}return r}const X={why:({message:e})=>e===void 0?``:String(e)},xs=/*#__PURE__*/ bs({docsBase:`https://vitehub.dev/docs/development/diagnostics`,codes:{RUNTIME_R0001:{...X,fix:"Pass `maxDepth` to `normalizeRuntimeDiagnosticError()` as an integer of 0 or more, or remove it to use the default."},RUNTIME_R0002:{...X,fix:"Pass `maxErrors` to `normalizeRuntimeDiagnosticError()` as an integer of 1 or more, or remove it to use the default."},RUNTIME_R0003:{...X,fix:"Pass `maxStringLength` to `normalizeRuntimeDiagnosticError()` as an integer of 64 or more, or remove it to use the default."},RUNTIME_R0004:{...X,fix:"Read the logs of the process that `vitehub drain` waited for to find why its drain failed, then fix that failure and run `vitehub drain` again."},RUNTIME_R0005:{...X,fix:"Read the logs of the process that the message names to find why it stopped, then start it again before you run `vitehub drain`."},RUNTIME_R0006:{...X,fix:"Pass `new ViteHubError()` a nonempty `code` and `message` string within the length limits, and plain JSON `details`."},RUNTIME_R0007:{...X,fix:"Give the execution authority a valid value for each of `credentials`, `environment`, `filesystem.access`, `filesystem.scope`, `isolation`, `network`, and `processes`."},RUNTIME_R0009:{...X,fix:"Set `intervalMs` of the process reconciler to a number of milliseconds from 1 to 2147483647."},RUNTIME_R0010:{...X,fix:"Give the process reconciler a `signal` other than `SIGKILL` or `SIGSTOP`, or set `signal: false`."},RUNTIME_R0011:{...X,fix:"Call `drain()` of the process reconciler after its callback returns, not from inside the callback."},RUNTIME_R0015:{...X,fix:"Pass the `Request` of a Fetchable handler, or the event of an H3 or Nitro route, to `getStandardContext()`."},RUNTIME_R0016:{...X,fix:"Return the body or a `Response` from the handler, in place of setting `~standard.res.body`."},RUNTIME_R0017:X,RUNTIME_R0018:X,RUNTIME_CONSOLE_PATH_INVALID:{why:({value:e})=>`${e} is not a Console path. Use a path that starts with one /, such as /agents/<agent>.`,fix:"Pass `hostedConsoleUrl()` a Console path that starts with one `/`, such as `/kv` or `/agents/<agent>/invocations/<id>`."},RUNTIME_CONSOLE_PROJECT_URL_INVALID:{why:({value:e})=>`${e} is not a project URL. Use the https:// origin of the app, with its base path if it has one.`,fix:"Pass `hostedConsoleUrl()` the `https://` origin of the app, or `http://localhost` in development, with its base path and without a user name or password."},RUNTIME_EXECUTION_BUDGET_AMOUNT_INVALID:{why:({counter:e})=>`[vitehub] Execution budget ${e} amount must be a finite non-negative number.`,fix:"Pass `consume()` and the `record*()` methods of the execution budget a finite number of 0 or more."},RUNTIME_EXECUTION_BUDGET_EXCEEDED:{why:({counter:e})=>`[vitehub] Execution budget exhausted for ${e}.`,fix:"Raise the `executionBudget` limit that `error.counter` names, such as `maxToolCalls`, `maxRetries`, `maxInputBytes`, or `maxOutputBytes`, or give the run less work."},RUNTIME_EXECUTION_BUDGET_LIMIT_INVALID:{why:()=>`[vitehub] Execution budget limits must be finite non-negative numbers.`,fix:"Set each limit of `executionBudget`, such as `maxToolCalls` or `maxOutputBytes`, to a finite number of 0 or more, or remove it."},RUNTIME_SERIALIZED_RESPONSE_INVALID:{why:()=>`Invalid serialized Response`,fix:"Pass `deserializeResponse()` the record that `serializeResponse()` returned, unchanged. Check it first with `isSerializedResponse()`."}}});function Ss(e){return e!==null&&Object(e)===e}const Cs=/* @__PURE__ */ new WeakMap;function Z(){throw xs.RUNTIME_R0006({message:`[vitehub] ViteHubError requires a valid public error contract.`})}function ws(e){try{return Array.isArray(e)}catch{Z()}}function Q(e,t,n=!1){try{let r=Object.getOwnPropertyDescriptor(e,t);return r===void 0?void 0:((!(`value`in r)||n&&!r.enumerable)&&Z(),r.value)}catch{Z()}}function Ts(e,t,n,r){if(t.nodes+=1,t.nodes>1024&&Z(),e===void 0&&r)return;if(e===null||typeof e==`boolean`||typeof e==`string`&&e.length<=16384||typeof e==`number`&&Number.isFinite(e))return e;(typeof e!=`object`||n>8||t.ancestors.has(e))&&Z();let i,a;try{i=Object.getPrototypeOf(e),a=Reflect.ownKeys(e)}catch{Z()}t.ancestors.add(e);try{if(ws(e)){let r=Q(e,`length`);(!Number.isSafeInteger(r)||r<0||r>128||a.length!==r+1||!a.includes(`length`))&&Z();let i=[];for(let o=0;o<r;o+=1){let r=String(o);a.includes(r)||Z(),i.push(Ts(Q(e,r,!0),t,n+1,!1))}return Object.freeze(i)}i!==Object.prototype&&i!==null&&Z(),(a.length>128||a.some(e=>typeof e!=`string`))&&Z();let r={};for(let i of a)(i.length===0||i.length>128)&&Z(),Object.defineProperty(r,i,{enumerable:!0,value:Ts(Q(e,i,!0),t,n+1,!0),writable:!0});return Object.freeze(r)}finally{t.ancestors.delete(e)}}function Es(e){if(e!==void 0)return(typeof e!=`object`||!e||ws(e))&&Z(),Ts(e,{ancestors:/* @__PURE__ */ new Set,nodes:0},0,!1)}function Ds(e,t,n){(typeof e!=`string`||e.length===0||e.length>128)&&Z(),(typeof t!=`string`||t.length===0||t.length>16384)&&Z(),(typeof n!=`object`||!n||ws(n))&&Z();let r=Q(n,`cause`),i=Es(Q(n,`details`)),a=Q(n,`requestId`);return a!==void 0&&(typeof a!=`string`||a.length===0||a.length>256)&&Z(),{cause:r,code:e,details:i,message:t,name:`ViteHubError`,requestId:a,shape:Object.freeze({code:e,...i===void 0?{}:{details:i},message:t,name:`ViteHubError`,...a===void 0?{}:{requestId:a}})}}var Os=class extends Error{code;details;requestId;constructor(e,t,n={}){let r=Ds(e,t,n);super(r.message,r.cause===void 0?void 0:{cause:r.cause}),this.name=`ViteHubError`,this.code=r.code,this.details=r.details,this.requestId=r.requestId;let i=this.toJSON.bind(this);Object.defineProperties(this,{code:{configurable:!0,enumerable:!0,value:r.code,writable:!1},details:{configurable:!0,enumerable:!0,value:r.details,writable:!1},message:{configurable:!0,enumerable:!1,value:r.message,writable:!1},name:{configurable:!1,enumerable:!1,value:r.name,writable:!1},requestId:{configurable:!0,enumerable:!0,value:r.requestId,writable:!1},toJSON:{configurable:!1,enumerable:!1,value:i,writable:!1}}),Cs.set(this,r.shape)}toJSON(){let e=Cs.get(this);if(e)return e;let t=Ds(Q(this,`code`),Q(this,`message`),{details:Q(this,`details`),requestId:Q(this,`requestId`)});return Cs.set(this,t.shape),t.shape}};function ks(e){if(!Ss(e))return!1;try{let t=Reflect.get(Error,`isError`);if(!(typeof t==`function`?t(e)===!0:e instanceof Error||!(Symbol.toStringTag in e)&&Object.prototype.toString.call(e)===`[object Error]`))return!1;let n=Reflect.get(e,`message`),r=Reflect.get(e,`code`),i=Reflect.get(e,`name`),a=Reflect.get(e,`why`),o=Reflect.get(e,`fix`),s=Reflect.get(e,`docs`),c=Reflect.get(e,`sources`);return typeof r==`string`&&r.length>0&&typeof i==`string`&&typeof n==`string`&&a===n&&(o===void 0||typeof o==`string`)&&(s===void 0||typeof s==`string`)&&(c===void 0||Array.isArray(c)&&c.every(e=>typeof e==`string`))&&typeof Reflect.get(e,`toJSON`)==`function`}catch{return!1}}function As(e){let t=t=>{let n=Object.getOwnPropertyDescriptor(e,t);return n?n.configurable===!0:Object.isExtensible(e)},n=t(`name`)&&t(`toJSON`)?e:new _s({code:e.code,why:e.why,fix:e.fix,docs:e.docs,cause:e.cause,data:e.data,sources:e.sources});return n!==e&&(n.stack=e.stack),Object.defineProperty(n,"name",{configurable:!0,value:n.code,writable:!0}),Object.defineProperty(n,"toJSON",{configurable:!0,value:()=>({code:n.code,docs:n.docs,fix:n.fix,name:n.name,why:n.why})}),n}function js(e){let t=/* @__PURE__ */ bs({codes:e.codes,docsBase:e.docs}),n=new Set(Object.keys(e.codes)),r=Object.defineProperty({},"is",{value:e=>ks(e)&&n.has(e.code)});for(let e of n){let n=t[e];r[e]=Object.assign(e=>As(n(e)),{is:t=>ks(t)&&t.code===e})}return r}function Ms(e){let t=e.slice(0,4096);return new Os(`WORKSPACE_PATH_INVALID`,`[vitehub] Workspace path escapes the workspace root: ${JSON.stringify(t)}.`,{details:{path:t}})}function Ns(e){let t=e.toLowerCase().split(`:`,1)[0];return{normalized:t.replace(/[ .]+$/,``),isTraversal:/^(?:\.(?: +[. ]*)?|\.\.(?: +[. ]*)?)$/.test(t)}}function Ps(e=``,t={}){let n=e.replace(/\\/g,`/`),r=n.replace(/^\/+/,``).replace(/\/+$/,``),i=r.split(`/`).filter(Boolean);if(!t.allowEmpty&&!r||n.startsWith(`/`)||/^[a-z]:/i.test(n)||n.includes(`\0`)||i.some((e,n)=>{let r=e.toLowerCase(),i=Ns(e),a=i.normalized===`.git`||/^git~\d+$/.test(i.normalized)||n===0&&i.normalized===`.vitehub`||n===0&&/^vitehu~\d+$/.test(i.normalized),o=(i.normalized===`.git`||n===0&&i.normalized===`.vitehub`)&&r===i.normalized;return i.isTraversal||a&&(!t.allowReserved||!o)}))throw Ms(e);return r}const Fs=/*#__PURE__*/ js({docs:`https://vitehub.dev/docs/realtime/diagnostics`,codes:{REALTIME_DISABLED:{why:({action:e})=>`Realtime is disabled, so \`${e}()\` cannot run.`,fix:"Set `enabled` to `true` on `useRealtimeTiptap()` before you call the method."},REALTIME_DISCONNECTED:{why:({action:e})=>`The realtime document disconnected or changed during \`${e}()\`.`,fix:"Call the method again after the new document connects. Read `synced` to know when it is ready."},REALTIME_INVALID_RESPONSE:{why:({action:e})=>`The realtime server answered \`${e}()\` with a response that the client cannot use.`,fix:"Use the same `@vite-hub/realtime` version on the client and the server, and build again."},REALTIME_MISSING_DOCUMENT:{why:({action:e})=>`\`${e}()\` needs a document, and \`documentId\` is empty.`,fix:"Pass a document path to `useRealtimeTiptap(definition, documentId)` before you call the method."},REALTIME_REQUEST_FAILED:{why:({action:e,message:t,status:n})=>`The realtime \`${e}()\` request failed${n===void 0?``:` with HTTP ${n}`}${t?`: ${t}`:`.`}`,fix:"Read `error.why` for the server message, and `error.cause` for a network error. Retry when the server is available again."},REALTIME_ROOM_ABORTED:{why:`The request to the room stopped because its signal aborted.`,fix:`Nothing to fix when the caller stopped on purpose, such as a cancelled Agent run. Call again to ask once more.`},REALTIME_ROOM_CROWDED:{why:({count:e})=>`${e} browsers are in the room, and a request goes to one browser only.`,fix:`Give each browser its own room, such as a random id for each tab, so that one browser answers.`},REALTIME_ROOM_ELSEWHERE:{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.`,fix:`Route the browser and the caller to the same instance, such as with sticky sessions, or run one Node instance.`},REALTIME_ROOM_EMPTY:{why:`No browser is in the room. The page is closed, or it has not joined yet.`,fix:`Open the page again. The request waits a few seconds for a browser to join before it gives up.`},REALTIME_ROOM_REFUSED:{why:({reason:e})=>`The browser could not answer: ${e}`,fix:"Read the reason. Add `room.onRequest(handler)` on the page, and keep each answer under 1 MiB."},REALTIME_ROOM_REQUESTS_OFF:{why:({definition:e})=>`The Realtime Definition "${e}" does not take requests.`,fix:'Define it with `defineRealtime({ access: "public", document: false, requests: true })`.'},REALTIME_ROOM_TIMEOUT:{why:({timeout:e})=>`The browser did not answer in ${e/1e3} seconds.`,fix:"Make the page answer sooner, or pass a longer `timeout` to `requestRealtimeRoom()`."},REALTIME_AWARENESS_OWNERSHIP_CONFLICT:{why:`A realtime awareness client id belongs to another peer.`,fix:`Let each editor tab use its own Yjs awareness client. Do not reuse a client id on two connections.`},REALTIME_AWARENESS_TOO_LARGE:{why:`Realtime awareness state exceeds the 8 MiB room quota.`,fix:`Keep less data in awareness state. Store large values in the document or in Workspace.`},REALTIME_DOCUMENT_TOO_LARGE:{why:`The realtime document exceeds the 8 MiB room quota.`,fix:`Split the document into smaller documents, or keep large assets in Workspace or Blob.`},REALTIME_INVALID_AWARENESS:{why:`A realtime awareness update has a state that is not a plain object.`,fix:"Set awareness state to a plain object, for example `awareness.setLocalStateField('user', { name })`."},REALTIME_TOO_MANY_AWARENESS_CLIENTS:{why:`One realtime peer sent more than 1,024 awareness clients.`,fix:`Use one awareness client for each editor tab.`},REALTIME_ROOM_WRITE_CONFLICT:{why:`Realtime room record compare-and-set failed.`,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.`},REALTIME_WRITE_REJECTED:{why:({problem:e,readOnly:t})=>e===`missing-state`?`Realtime update depends on state this room does not have.`:e===`status`?`Realtime document status is written by the server.`:t??`This realtime connection is read-only.`,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."},REALTIME_DOCUMENT_CONFLICT:{why:({problem:e})=>e??`The stored document changed since the realtime room loaded it.`,fix:"Realtime re-seeds the room from the stored document. Listen to `onReset()` to recover text that the room did not save."},REALTIME_BLOB_ETAG_MISSING:{why:({pathname:e})=>`The Blob store returned no \`httpEtag\` for ${e}, so \`blobDocument()\` cannot save the file only if it is unchanged.`,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()`."},REALTIME_INVALID_PERSISTENCE:{why:({name:e,reason:t})=>t===`below-debounce`?"Realtime `persistence.maxWait` must be at least `persistence.debounce`.":`Realtime \`persistence.${e}\` must be a non-negative number of milliseconds.`,fix:"Set `persistence: { debounce: 2_000, maxWait: 10_000 }`, or remove the option to use these defaults."},REALTIME_MISSING_ACCESS:{why:`The Realtime definition sets no access rule, so it does not say who can read and write its rooms.`,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.'},REALTIME_INVALID_ACCESS:{why:({reason:e})=>e===`public-with-rule`?'The Realtime definition sets `access: "public"` together with `auth` or `authorize()`, so its access rule is not clear.':e===`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.",fix:({reason:e})=>e===`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()`.'},REALTIME_CHECKPOINT_UNSUPPORTED:{why:"The Realtime definition sets `history.checkpoint`, but its document adapter has no `checkpoint()` method, so `history.checkpoint()` could never run.",fix:"Add `checkpoint(context, { digest, message, user })` to the document adapter, use `document: { workspace }`, or remove `history`."},REALTIME_INVALID_USER:{why:"The realtime identity needs a user `id` that is a non-empty string of at most 256 characters.",fix:"Return a user with an `id` from the Auth session or from `authorize()`."},REALTIME_MISSING_DIGEST:{why:({operation:e})=>e===`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.`,fix:"Use a Workspace Store that returns file digests, or return `digest` from the document adapter `save()`."},REALTIME_INVALID_POSTGRES_URL:{why:"REALTIME_POSTGRES_URL is set, and it is not a `postgres://` or `postgresql://` URL.",fix:`Set REALTIME_POSTGRES_URL to a Postgres URL, or remove it so that Realtime uses the connection of the Default Database.`},REALTIME_MISSING_BUS_CONNECTION:{why:({driver:e})=>e===`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.`,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".'},REALTIME_ROOM_LOCK_TIMEOUT:{why:`Realtime waited 30 seconds for the save lock of a room, and another instance still holds it.`,fix:"Make the document adapter `save()` finish in less than 30 seconds. Realtime tries the save again."},REALTIME_DRIVER_CONFLICT:{why:({driver:e,host:t})=>e===`memory`?`Realtime driver "memory" is single-process only, and the ${t} host runs more than one process.`:e===`cloudflare`?`Realtime driver "cloudflare" does not work with the ${t} host.`:`Realtime driver "${e}" needs a Node.js server, and the ${t} host does not run one.`,fix:'Set `realtime.driver` to "cloudflare" with a Cloudflare host. With the Node host, use "auto", "postgres", "redis", or "memory".'},REALTIME_MISSING_DRIVER:{why:`Realtime production builds need one room driver, and ViteHub cannot select one for this deployment.`,fix:`Deploy with a Cloudflare host to use Durable Objects, or with the Node host to share rooms through Postgres or Redis.`},REALTIME_RENAMED_AUTHORITY_KEY:{why:({value:e})=>`\`realtime.authority\` is ${e}. ViteHub renamed this key to \`driver\`, and it does not read \`authority\`, so Realtime would not use the driver you chose.`,fix:({value:e})=>`Set \`realtime: { driver: ${e} }\`, or run \`npx @vite-hub/codemods driver-key\` to rename it in every config file.`}}});function Is(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`epoch`in t)||!(`type`in t)||typeof t.epoch!=`string`||!t.epoch)return;if(t.type===`session`&&`access`in t&&(t.access===`read`||t.access===`write`))return t.access===`read`&&`reason`in t&&(t.reason===`access`||t.reason===`document`||t.reason===`version`)?{type:`session`,access:t.access,epoch:t.epoch,reason:t.reason}:{type:`session`,access:t.access,epoch:t.epoch};if(t.type===`reset`&&`reason`in t&&(t.reason===`source-changed`||t.reason===`stale`))return{type:`reset`,epoch:t.epoch,reason:t.reason}}catch{}}function Ls(e){if(typeof e!=`string`||e.length===0||e.length>4096||e.includes(`\0`)||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`\\`)||e.includes(`//`)||/^[a-z]:/i.test(e))return!1;try{return Ps(e)===e}catch{return!1}}function Rs(e){try{let t=JSON.parse(E(e));if((t.operation===`create`||t.operation===`delete`||t.operation===`update`)&&Ls(t.path))return{operation:t.operation,path:t.path};if(t.operation===`move`&&Ls(t.from)&&Ls(t.to))return{operation:t.operation,from:t.from,to:t.to}}catch{}}function zs(e){let t=_();return b(t,4),x(t,JSON.stringify(e)),v(t)}function Bs(e){let t=_();return b(t,6),x(t,JSON.stringify(e)),v(t)}function Vs(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`id`in t)||typeof t.id!=`string`||!t.id||t.id.length>128||!(`kind`in t))return;if(t.kind===`request`)return{kind:`request`,id:t.id,body:`body`in t?t.body:void 0};if(t.kind!==`answer`||!(`ok`in t))return;if(t.ok===!0)return{kind:`answer`,id:t.id,ok:!0,body:`body`in t?t.body:void 0};if(t.ok===!1&&`why`in t&&typeof t.why==`string`)return{kind:`answer`,id:t.id,ok:!1,why:t.why}}catch{}}function Hs(e){let t;e.on(`status`,({status:n})=>{clearInterval(t),t=void 0;let r=e.ws;if(n!==`connected`||!r)return;let i=r.onmessage;r.onmessage=function(t){if(t.data!==`pong`)return i?.call(this,t);e.ws===r&&(e.wsLastMessageReceived=D())},t=setInterval(()=>{e.ws===r&&r.readyState===r.OPEN&&r.send(`ping`)},15e3)})}const Us=Object.freeze({body:`body`,fields:`fields`,status:`status`});function Ws(e){return typeof e==`string`?e:null}function Gs(e){let t=e.getMap(Us.status),n=t.get(`issues`),r=t.get(`savedBy`),i={issues:Array.isArray(n)?n:[],savedBy:r&&!Array.isArray(r)&&r instanceof Object?r:null};return{digest:Ws(t.get(`digest`)),error:Ws(t.get(`error`)),issues:i.issues,savedAt:Ws(t.get(`savedAt`)),savedBy:i.savedBy}}function Ks(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const qs=[`#E11D48`,`#D97706`,`#059669`,`#0891B2`,`#2563EB`,`#7C3AED`,`#C026D3`];function $(e){try{return String(e)===e}catch{return!1}}function Js(e){if(!$(e.id)||!e.id||e.id.length>256)throw Fs.REALTIME_INVALID_USER();let t=0;for(let n=0;n<e.id.length;n++)t=Math.imul(31,t)+e.id.charCodeAt(n)|0;let n=($(e.name)&&e.name||$(e.email)&&e.email||`Anonymous`).slice(0,256),r={color:qs[Math.abs(t)%qs.length],id:e.id,name:n};return $(e.image)&&e.image&&e.image.length<=2048&&(r.image=e.image),r}function Ys(e){return Ks(e)?$(e.id)&&e.id.length>0&&e.id.length<=256&&$(e.name)&&e.name.length>0&&e.name.length<=256&&$(e.color)&&/^#[\da-f]{6}$/i.test(e.color)&&(e.image===void 0||$(e.image)&&e.image.length<=2048):!1}function Xs(e){let t=[];for(let[n,r]of e)if(Ys(r.user)){let{color:e,id:i,image:a,name:o}=r.user,s={color:e,id:i,name:o,clientId:n};a!==void 0&&(s.image=a),t.push(s)}return t}function Zs(e,t,n={}){let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=[],o,s=`connecting`,c=!1,l=!1,u,d,f=()=>{for(let e of r)e()},ee=()=>{let t=n.origin?new URL(n.origin):window.location;return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${ms(`/api/_vitehub/realtime/${encodeURIComponent(e)}`,n.baseURL)}`},te=t.split(`/`).map(encodeURIComponent).join(`/`),ne={};function re(){c=!1,u=new Hr,d=new ps(ee(),te,u,{disableBc:!0,params:{...n.params,clientId:String(u.clientID)}});let e=d;Hs(e),e.messageHandlers[5]=(t,n)=>{let r=Is(n);if(r){if(r.type===`session`){e.params.epoch=r.epoch;return}e.destroy(),u.destroy(),!l&&(re(),f())}},e.messageHandlers[6]=(t,n)=>{let r=Vs(n);r?.kind===`request`&&ie(e,r.id,r.body)},e.awareness.off(`update`,e._awarenessUpdateHandler),e.awareness.on(`update`,({added:t,removed:n,updated:r})=>{let i=[...t,...r,...n].filter(t=>t===e.doc.clientID),a=e.ws;if(!i.length||!e.wsconnected||!a||a.readyState!==a.OPEN)return;let o=_();b(o,1),S(o,Vo(e.awareness,i)),a.send(v(o))});let t=n.identity??{id:`guest:${u.clientID}`};e.awareness.setLocalState({...ne,user:Js({...t,id:t.id||`guest:${u.clientID}`})}),e.awareness.on(`change`,f),u.getMap(Us.status).observe(f),e.on(`sync`,t=>{d===e&&(c=t,f())}),e.on(`status`,e=>{s=e.status,f()})}re();let p;n.changes&&(p=new ps(ee(),`%40workspace`,new Hr,{disableBc:!0,params:{...n.params,workspace:`events`}}),p.awareness.setLocalState(null),Hs(p),p.messageHandlers[4]=(e,t)=>{let n=Rs(t);if(n)for(let e of i)e(n)},p.on(`status`,e=>{e.status===`connected`&&ae()}));async function ie(e,t,n){let r=e=>Bs({kind:`answer`,id:t,ok:!1,why:e}),i;try{i=o?Bs({kind:`answer`,id:t,ok:!0,body:await o(n)}):r(`This page does not answer requests.`),i.byteLength>1047552&&(i=r(`The answer has ${i.byteLength} bytes, over the 1 MiB limit.`))}catch(e){i=r(e instanceof Error?e.message:String(e))}let a=e.ws;e.wsconnected&&a&&a.readyState===a.OPEN&&a.send(Uint8Array.from(i))}function ae(){let e=p?.ws;if(p?.wsconnected&&e&&e.readyState===e.OPEN)for(;a.length;)e.send(Uint8Array.from(zs(a.shift())))}return{get awareness(){return d.awareness},get clientId(){return u.clientID},people:()=>Xs(d.awareness.getStates()),states:()=>{let e=new Map(d.awareness.getStates());return e.delete(u.clientID),e},status:()=>s,saveStatus:()=>c?Gs(u):void 0,setLocal(e,t){t===null?delete ne[e]:ne[e]=t,d.awareness.setLocalStateField(e,t)},notify(e){p&&(a.push(e),ae())},onUpdate(e){return r.add(e),()=>r.delete(e)},onChange(e){return i.add(e),()=>i.delete(e)},onRequest(e){return o=e,()=>{o===e&&(o=void 0)}},destroy(){l=!0,d.destroy(),u.destroy(),p?.destroy(),p?.doc.destroy(),r.clear(),i.clear(),o=void 0}}}export{Zs as connectRealtimeRoom};
53
+ function bs(e){let t=e.reporters??[],n=Symbol(),r=Object.defineProperty({},"is",{value:ys(n)}),{docsBase:i}=e;for(let a of Object.keys(e.codes)){let o=e.codes[a],s=o.docs===!1?void 0:o.docs||vs(i,a),c=(e={},r={})=>{let i=new _s({code:a,why:hs(o.why,e),fix:hs(o.fix,e),docs:s,cause:e.cause,sources:e.sources,data:hs(o.data,e)},c);i[n]=1;for(let e of t)e(i,r);return i};c.is=e=>r.is(e)&&e.code===a,r[a]=c}return r}const X={why:({message:e})=>e===void 0?``:String(e)},xs=/*#__PURE__*/ bs({docsBase:`https://vitehub.dev/docs/runtime/diagnostics`,codes:{RUNTIME_R0001:{...X,fix:"Pass `maxDepth` to `normalizeRuntimeDiagnosticError()` as an integer of 0 or more, or remove it to use the default."},RUNTIME_R0002:{...X,fix:"Pass `maxErrors` to `normalizeRuntimeDiagnosticError()` as an integer of 1 or more, or remove it to use the default."},RUNTIME_R0003:{...X,fix:"Pass `maxStringLength` to `normalizeRuntimeDiagnosticError()` as an integer of 64 or more, or remove it to use the default."},RUNTIME_R0004:{...X,fix:"Read the logs of the process that `vitehub drain` waited for to find why its drain failed, then fix that failure and run `vitehub drain` again."},RUNTIME_R0005:{...X,fix:"Read the logs of the process that the message names to find why it stopped, then start it again before you run `vitehub drain`."},RUNTIME_R0006:{...X,fix:"Pass `new ViteHubError()` a nonempty `code` and `message` string within the length limits, and plain JSON `details`."},RUNTIME_R0007:{...X,fix:"Give the execution authority a valid value for each of `credentials`, `environment`, `filesystem.access`, `filesystem.scope`, `isolation`, `network`, and `processes`."},RUNTIME_R0009:{...X,fix:"Set `intervalMs` of the process reconciler to a number of milliseconds from 1 to 2147483647."},RUNTIME_R0010:{...X,fix:"Give the process reconciler a `signal` other than `SIGKILL` or `SIGSTOP`, or set `signal: false`."},RUNTIME_R0011:{...X,fix:"Call `drain()` of the process reconciler after its callback returns, not from inside the callback."},RUNTIME_R0015:{...X,fix:"Pass the `Request` of a Fetchable handler, or the event of an H3 or Nitro route, to `getStandardContext()`."},RUNTIME_R0016:{...X,fix:"Return the body or a `Response` from the handler, in place of setting `~standard.res.body`."},RUNTIME_R0017:X,RUNTIME_R0018:X,RUNTIME_CONSOLE_PATH_INVALID:{why:({value:e})=>`${e} is not a Console path. Use a path that starts with one /, such as /agents/<agent>.`,fix:"Pass `hostedConsoleUrl()` a Console path that starts with one `/`, such as `/kv` or `/agents/<agent>/invocations/<id>`."},RUNTIME_CONSOLE_PROJECT_URL_INVALID:{why:({value:e})=>`${e} is not a project URL. Use the https:// origin of the app, with its base path if it has one.`,fix:"Pass `hostedConsoleUrl()` the `https://` origin of the app, or `http://localhost` in development, with its base path and without a user name or password."},RUNTIME_DURATION_INVALID:{why:({option:e,value:t})=>`${e?`\`${e}\``:`The value`} is ${t}, which is not a duration. A duration is a string with a number of 0 or more and a unit, such as "30s", "5m", or "1 day".`,fix:({suggestion:e,unit:t=`milliseconds`,value:n})=>e?`Write the time as a string with a unit: ${n} ${t} is ${e}.`:'Write a number of 0 or more and one unit: `ms`, `s`, `m`, `h`, `d`, or `w`, or a long name such as `minutes` or `days`. For example `"30s"`, `"5m"`, or `"1 day"`.'},RUNTIME_EXECUTION_BUDGET_AMOUNT_INVALID:{why:({counter:e})=>`[vitehub] Execution budget ${e} amount must be a finite non-negative number.`,fix:"Pass `consume()` and the `record*()` methods of the execution budget a finite number of 0 or more."},RUNTIME_EXECUTION_BUDGET_EXCEEDED:{why:({counter:e})=>`[vitehub] Execution budget exhausted for ${e}.`,fix:"Raise the `executionBudget` limit that `error.counter` names, such as `maxToolCalls`, `maxRetries`, `maxInputBytes`, or `maxOutputBytes`, or give the run less work."},RUNTIME_EXECUTION_BUDGET_LIMIT_INVALID:{why:()=>`[vitehub] Execution budget limits must be finite non-negative numbers.`,fix:"Set each limit of `executionBudget`, such as `maxToolCalls` or `maxOutputBytes`, to a finite number of 0 or more, or remove it."},RUNTIME_HIDDEN_ERROR:{why:()=>`The server failed. The error is not a ViteHub error, so its message and stack stay on the server.`,fix:"Read the server logs for the error. To send a code, a why, and a fix to the client, return a `ResultError` from `defineErrors()` and pass it to `toResponse()`."},RUNTIME_SERIALIZED_RESPONSE_INVALID:{why:()=>`Invalid serialized Response`,fix:"Pass `deserializeResponse()` the record that `serializeResponse()` returned, unchanged. Check it first with `isSerializedResponse()`."}}});function Ss(e){return e!==null&&Object(e)===e}const Cs=/* @__PURE__ */ new WeakMap;function Z(){throw xs.RUNTIME_R0006({message:`[vitehub] ViteHubError requires a valid public error contract.`})}function ws(e){try{return Array.isArray(e)}catch{Z()}}function Q(e,t,n=!1){try{let r=Object.getOwnPropertyDescriptor(e,t);return r===void 0?void 0:((!(`value`in r)||n&&!r.enumerable)&&Z(),r.value)}catch{Z()}}function Ts(e,t,n,r){if(t.nodes+=1,t.nodes>1024&&Z(),e===void 0&&r)return;if(e===null||typeof e==`boolean`||typeof e==`string`&&e.length<=16384||typeof e==`number`&&Number.isFinite(e))return e;(typeof e!=`object`||n>8||t.ancestors.has(e))&&Z();let i,a;try{i=Object.getPrototypeOf(e),a=Reflect.ownKeys(e)}catch{Z()}t.ancestors.add(e);try{if(ws(e)){let r=Q(e,`length`);(!Number.isSafeInteger(r)||r<0||r>128||a.length!==r+1||!a.includes(`length`))&&Z();let i=[];for(let o=0;o<r;o+=1){let r=String(o);a.includes(r)||Z(),i.push(Ts(Q(e,r,!0),t,n+1,!1))}return Object.freeze(i)}i!==Object.prototype&&i!==null&&Z(),(a.length>128||a.some(e=>typeof e!=`string`))&&Z();let r={};for(let i of a)(i.length===0||i.length>128)&&Z(),Object.defineProperty(r,i,{enumerable:!0,value:Ts(Q(e,i,!0),t,n+1,!0),writable:!0});return Object.freeze(r)}finally{t.ancestors.delete(e)}}function Es(e){if(e!==void 0)return(typeof e!=`object`||!e||ws(e))&&Z(),Ts(e,{ancestors:/* @__PURE__ */ new Set,nodes:0},0,!1)}function Ds(e,t,n){(typeof e!=`string`||e.length===0||e.length>128)&&Z(),(typeof t!=`string`||t.length===0||t.length>16384)&&Z(),(typeof n!=`object`||!n||ws(n))&&Z();let r=Q(n,`cause`),i=Es(Q(n,`details`)),a=Q(n,`requestId`);return a!==void 0&&(typeof a!=`string`||a.length===0||a.length>256)&&Z(),{cause:r,code:e,details:i,message:t,name:`ViteHubError`,requestId:a,shape:Object.freeze({code:e,...i===void 0?{}:{details:i},message:t,name:`ViteHubError`,...a===void 0?{}:{requestId:a}})}}var Os=class extends Error{code;details;requestId;constructor(e,t,n={}){let r=Ds(e,t,n);super(r.message,r.cause===void 0?void 0:{cause:r.cause}),this.name=`ViteHubError`,this.code=r.code,this.details=r.details,this.requestId=r.requestId;let i=this.toJSON.bind(this);Object.defineProperties(this,{code:{configurable:!0,enumerable:!0,value:r.code,writable:!1},details:{configurable:!0,enumerable:!0,value:r.details,writable:!1},message:{configurable:!0,enumerable:!1,value:r.message,writable:!1},name:{configurable:!1,enumerable:!1,value:r.name,writable:!1},requestId:{configurable:!0,enumerable:!0,value:r.requestId,writable:!1},toJSON:{configurable:!1,enumerable:!1,value:i,writable:!1}}),Cs.set(this,r.shape)}toJSON(){let e=Cs.get(this);if(e)return e;let t=Ds(Q(this,`code`),Q(this,`message`),{details:Q(this,`details`),requestId:Q(this,`requestId`)});return Cs.set(this,t.shape),t.shape}};function ks(e){if(!Ss(e))return!1;try{let t=Reflect.get(Error,`isError`);return typeof t==`function`?t(e)===!0:e instanceof Error||!(Symbol.toStringTag in e)&&Object.prototype.toString.call(e)===`[object Error]`}catch{return!1}}function As(e){if(!ks(e))return!1;try{let t=Reflect.get(e,`message`),n=Reflect.get(e,`code`),r=Reflect.get(e,`name`),i=Reflect.get(e,`why`),a=Reflect.get(e,`fix`),o=Reflect.get(e,`docs`),s=Reflect.get(e,`sources`);return typeof n==`string`&&n.length>0&&typeof r==`string`&&typeof t==`string`&&i===t&&(a===void 0||typeof a==`string`)&&(o===void 0||typeof o==`string`)&&(s===void 0||Array.isArray(s)&&s.every(e=>typeof e==`string`))&&typeof Reflect.get(e,`toJSON`)==`function`}catch{return!1}}const js=Symbol.for(`vitehub.runtime.resultError`);function Ms(e){let t=t=>{let n=Object.getOwnPropertyDescriptor(e,t);return n?n.configurable===!0:Object.isExtensible(e)},n=t(`name`)&&t(`toJSON`)&&(Object.hasOwn(e,js)||Object.isExtensible(e))?e:new _s({code:e.code,why:e.why,fix:e.fix,docs:e.docs,cause:e.cause,data:e.data,sources:e.sources});if(n!==e){n.stack=e.stack;let t=Reflect.get(e,`status`);typeof t==`number`&&Object.defineProperty(n,"status",{configurable:!0,value:t})}return Object.defineProperty(n,"name",{configurable:!0,value:n.code,writable:!0}),Object.defineProperty(n,js,{value:!0}),Object.defineProperty(n,"toJSON",{configurable:!0,value:()=>({code:n.code,docs:n.docs,fix:n.fix,name:n.name,why:n.why})}),n}function Ns(e){let t=/* @__PURE__ */ bs({codes:e.codes,docsBase:e.docs}),n=new Set(Object.keys(e.codes)),r=Object.defineProperty({},"is",{value:e=>As(e)&&n.has(e.code)});for(let i of n){let n=t[i],a=e.codes[i]?.status;r[i]=Object.assign(e=>{let t=Ms(n(e));return a!==void 0&&Object.defineProperty(t,"status",{configurable:!0,enumerable:!1,value:a}),t},{is:e=>As(e)&&e.code===i})}return r}function Ps(e){let t=e.slice(0,4096);return new Os(`WORKSPACE_PATH_INVALID`,`[vitehub] Workspace path escapes the workspace root: ${JSON.stringify(t)}.`,{details:{path:t}})}function Fs(e){let t=e.toLowerCase().split(`:`,1)[0];return{normalized:t.replace(/[ .]+$/,``),isTraversal:/^(?:\.(?: +[. ]*)?|\.\.(?: +[. ]*)?)$/.test(t)}}function Is(e=``,t={}){let n=e.replace(/\\/g,`/`),r=n.replace(/^\/+/,``).replace(/\/+$/,``),i=r.split(`/`).filter(Boolean);if(!t.allowEmpty&&!r||n.startsWith(`/`)||/^[a-z]:/i.test(n)||n.includes(`\0`)||i.some((e,n)=>{let r=e.toLowerCase(),i=Fs(e),a=i.normalized===`.git`||/^git~\d+$/.test(i.normalized)||n===0&&i.normalized===`.vitehub`||n===0&&/^vitehu~\d+$/.test(i.normalized),o=(i.normalized===`.git`||n===0&&i.normalized===`.vitehub`)&&r===i.normalized;return i.isTraversal||a&&(!t.allowReserved||!o)}))throw Ps(e);return r}const Ls=/*#__PURE__*/ Ns({docs:`https://vitehub.dev/docs/realtime/diagnostics`,codes:{REALTIME_DISABLED:{why:({action:e})=>`Realtime is disabled, so \`${e}()\` cannot run.`,fix:"Set `enabled` to `true` on `useRealtimeTiptap()` before you call the method."},REALTIME_DISCONNECTED:{why:({action:e})=>`The realtime document disconnected or changed during \`${e}()\`.`,fix:"Call the method again after the new document connects. Read `synced` to know when it is ready."},REALTIME_INVALID_DOCUMENT:{why:({action:e})=>`The room body does not fit the editor schema, so \`${e}()\` did not write it. Writing it would lose content.`,fix:`Keep editing until the document fits the editor extensions of the Realtime Definition, then call the method again. The room keeps the edits.`},REALTIME_INVALID_RESPONSE:{why:({action:e})=>`The realtime server answered \`${e}()\` with a response that the client cannot use.`,fix:"Use the same `@vite-hub/realtime` version on the client and the server, and build again."},REALTIME_MISSING_DOCUMENT:{why:({action:e})=>`\`${e}()\` needs a document, and \`documentId\` is empty.`,fix:"Pass a document path to `useRealtimeTiptap(definition, documentId)` before you call the method."},REALTIME_READ_ONLY:{why:({action:e})=>`The room is read-only, so \`${e}()\` cannot write the document.`,fix:"Read `readOnlyReason` of `useRealtimeTiptap()` for the reason. Do not offer save or publish while it is set."},REALTIME_REQUEST_FAILED:{why:({action:e,message:t,status:n})=>`The realtime \`${e}()\` request failed${n===void 0?``:` with HTTP ${n}`}${t?`: ${t}`:`.`}`,fix:"Read `error.why` for the server message, `error.data.status` for the HTTP status, and `error.cause` for a network error. Retry when the server is available again.",data:({status:e})=>({status:e})},REALTIME_SOURCE_CHANGED:{why:({action:e})=>`The server refused \`${e}()\` because the stored document changed outside the room.`,fix:"Tell the person that the stored document changed. Use `onReset()` to detect a room reset and read unsaved edits from the event's `previous` document."},REALTIME_SYNC_PENDING:{why:({action:e})=>`The room did not receive every edit of this client in time, so \`${e}()\` did not run. The composable tried 20 times.`,fix:"Call the method again when `synced` is true. When it keeps failing, check that the WebSocket stays connected."},REALTIME_ROOM_ABORTED:{why:`The request to the room stopped because its signal aborted.`,fix:`Nothing to fix when the caller stopped on purpose, such as a cancelled Agent run. Call again to ask once more.`},REALTIME_ROOM_CROWDED:{why:({count:e})=>`${e} browsers are in the room, and a request goes to one browser only.`,fix:`Give each browser its own room, such as a random id for each tab, so that one browser answers.`},REALTIME_ROOM_ELSEWHERE:{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.`,fix:`Route the browser and the caller to the same instance, such as with sticky sessions, or run one Node instance.`},REALTIME_ROOM_EMPTY:{why:`No browser is in the room. The page is closed, or it has not joined yet.`,fix:`Open the page again. The request waits a few seconds for a browser to join before it gives up.`},REALTIME_ROOM_REFUSED:{why:({reason:e})=>`The browser could not answer: ${e}`,fix:"Read the reason. Add `room.onRequest(handler)` on the page, and keep each answer under 1 MiB."},REALTIME_ROOM_REQUESTS_OFF:{why:({definition:e})=>`The Realtime Definition "${e}" does not take requests.`,fix:'Define it with `defineRealtime({ access: "public", document: false, requests: true })`.'},REALTIME_ROOM_TIMEOUT:{why:({timeout:e})=>`The browser did not answer in ${e/1e3} seconds.`,fix:"Make the page answer sooner, or pass a longer `timeout` to `requestRealtimeRoom()`."},REALTIME_AWARENESS_OWNERSHIP_CONFLICT:{why:`A realtime awareness client id belongs to another peer.`,fix:`Let each editor tab use its own Yjs awareness client. Do not reuse a client id on two connections.`},REALTIME_AWARENESS_TOO_LARGE:{why:`Realtime awareness state exceeds the 8 MiB room quota.`,fix:`Keep less data in awareness state. Store large values in the document or in Workspace.`},REALTIME_DOCUMENT_TOO_LARGE:{why:`The realtime document exceeds the 8 MiB room quota.`,fix:`Split the document into smaller documents, or keep large assets in Workspace or Blob.`},REALTIME_INVALID_AWARENESS:{why:`A realtime awareness update has a state that is not a plain object.`,fix:"Set awareness state to a plain object, for example `awareness.setLocalStateField('user', { name })`."},REALTIME_TOO_MANY_AWARENESS_CLIENTS:{why:`One realtime peer sent more than 1,024 awareness clients.`,fix:`Use one awareness client for each editor tab.`},REALTIME_ROOM_WRITE_CONFLICT:{why:`Realtime room record compare-and-set failed.`,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.`},REALTIME_WRITE_REJECTED:{why:({problem:e,readOnly:t})=>e===`missing-state`?`Realtime update depends on state this room does not have.`:e===`status`?`Realtime document status is written by the server.`:t??`This realtime connection is read-only.`,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."},REALTIME_DOCUMENT_CONFLICT:{why:({problem:e})=>e??`The stored document changed since the realtime room loaded it.`,fix:"Realtime re-seeds the room from the stored document. Listen to `onReset()` to recover text that the room did not save."},REALTIME_BLOB_ETAG_MISSING:{why:({pathname:e})=>`The Blob store returned no \`httpEtag\` for ${e}, so \`blobDocument()\` cannot save the file only if it is unchanged.`,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()`."},REALTIME_INVALID_PERSISTENCE:{why:({name:e,reason:t})=>t===`below-debounce`?"Realtime `persistence.maxWait` must be at least `persistence.debounce`.":`Realtime \`persistence.${e}\` must be a non-negative number of milliseconds.`,fix:"Set `persistence: { debounce: 2_000, maxWait: 10_000 }`, or remove the option to use these defaults."},REALTIME_MISSING_ACCESS:{why:`The Realtime definition sets no access rule, so it does not say who can read and write its rooms.`,fix:'Set `authorize: true` to require a signed-in user, set `authorize()` to decide each request, or set `access: "public"` to let anyone read and write.'},REALTIME_INVALID_ACCESS:{why:({reason:e})=>e===`auth`?"The Realtime definition sets `auth`. Realtime replaced it with `authorize: true`, and an `authorize()` callback now also runs for signed-out callers.":e===`public-with-rule`?'The Realtime definition sets `access: "public"` together with `authorize`, so its access rule is not clear.':e===`not-public`?'The Realtime definition sets `access` to a value other than "public".':e===`not-authorize`?"The Realtime definition sets `authorize` to a value that is not `true` or a function.":"The Realtime definition sets `origins()` with `authorize: true` and no `identify()`. Only the Auth trusted-origin policy can allow a different origin to use the ViteHub Auth session.",fix:({reason:e})=>e===`auth`?"Replace `auth: true` with `authorize: true`. With an `authorize()` callback, remove `auth` and return `false` from the callback when `user` is `null`.":e===`origins-without-identify`?"Remove `origins()`, or add `identify()` that reads a credential the page sends on purpose, such as a ticket in `params`.":e===`not-authorize`?"Set `authorize: true` to require a signed-in user, or set `authorize()` to a function that returns `true` to allow.":'Use `access: "public"` alone for open rooms. To limit access, remove `access` and set `authorize`.'},REALTIME_CHECKPOINT_UNSUPPORTED:{why:"The Realtime definition sets `history.checkpoint`, but its document adapter has no `checkpoint()` method, so `history.checkpoint()` could never run.",fix:"Add `checkpoint(context, { digest, message, user })` to the document adapter, use `document: { workspace }`, or remove `history`."},REALTIME_INVALID_USER:{why:"The realtime identity needs a user `id` that is a non-empty string of at most 256 characters.",fix:"Return a user with an `id` from the Auth session or from `authorize()`."},REALTIME_MISSING_DIGEST:{why:({operation:e})=>e===`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.`,fix:"Use a Workspace Store that returns file digests, or return `digest` from the document adapter `save()`."},REALTIME_INVALID_POSTGRES_URL:{why:"REALTIME_POSTGRES_URL is set, and it is not a `postgres://` or `postgresql://` URL.",fix:`Set REALTIME_POSTGRES_URL to a Postgres URL, or remove it so that Realtime uses the connection of the Default Database.`},REALTIME_MISSING_BUS_CONNECTION:{why:({driver:e})=>e===`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.`,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".'},REALTIME_ROOM_LOCK_TIMEOUT:{why:`Realtime waited 30 seconds for the save lock of a room, and another instance still holds it.`,fix:"Make the document adapter `save()` finish in less than 30 seconds. Realtime tries the save again."},REALTIME_DRIVER_CONFLICT:{why:({driver:e,host:t})=>e===`memory`?`Realtime driver "memory" is single-process only, and the ${t} host runs more than one process.`:e===`cloudflare`?`Realtime driver "cloudflare" does not work with the ${t} host.`:`Realtime driver "${e}" needs a Node.js server, and the ${t} host does not run one.`,fix:'Set `realtime.driver` to "cloudflare" with a Cloudflare host. With the Node host, use "auto", "postgres", "redis", or "memory".'},REALTIME_MISSING_DRIVER:{why:`Realtime production builds need one room driver, and ViteHub cannot select one for this deployment.`,fix:`Deploy with a Cloudflare host to use Durable Objects, or with the Node host to share rooms through Postgres or Redis.`},REALTIME_RENAMED_AUTHORITY_KEY:{why:({value:e})=>`\`realtime.authority\` is ${e}. ViteHub renamed this key to \`driver\`, and it does not read \`authority\`, so Realtime would not use the driver you chose.`,fix:({value:e})=>`Set \`realtime: { driver: ${e} }\`, or run \`npx @vite-hub/codemods driver-key\` to rename it in every config file.`}}});function Rs(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`epoch`in t)||!(`type`in t)||typeof t.epoch!=`string`||!t.epoch)return;if(t.type===`session`&&`access`in t&&(t.access===`read`||t.access===`write`))return t.access===`read`&&`reason`in t&&(t.reason===`access`||t.reason===`document`||t.reason===`version`)?{type:`session`,access:t.access,epoch:t.epoch,reason:t.reason}:{type:`session`,access:t.access,epoch:t.epoch};if(t.type===`reset`&&`reason`in t&&(t.reason===`source-changed`||t.reason===`stale`))return{type:`reset`,epoch:t.epoch,reason:t.reason}}catch{}}function zs(e){if(typeof e!=`string`||e.length===0||e.length>4096||e.includes(`\0`)||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`\\`)||e.includes(`//`)||/^[a-z]:/i.test(e))return!1;try{return Is(e)===e}catch{return!1}}function Bs(e){try{let t=JSON.parse(E(e));if((t.operation===`create`||t.operation===`delete`||t.operation===`update`)&&zs(t.path))return{operation:t.operation,path:t.path};if(t.operation===`move`&&zs(t.from)&&zs(t.to))return{operation:t.operation,from:t.from,to:t.to}}catch{}}function Vs(e){let t=_();return b(t,4),x(t,JSON.stringify(e)),v(t)}function Hs(e){let t=_();return b(t,6),x(t,JSON.stringify(e)),v(t)}function Us(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`id`in t)||typeof t.id!=`string`||!t.id||t.id.length>128||!(`kind`in t))return;if(t.kind===`request`)return{kind:`request`,id:t.id,body:`body`in t?t.body:void 0};if(t.kind!==`answer`||!(`ok`in t))return;if(t.ok===!0)return{kind:`answer`,id:t.id,ok:!0,body:`body`in t?t.body:void 0};if(t.ok===!1&&`why`in t&&typeof t.why==`string`)return{kind:`answer`,id:t.id,ok:!1,why:t.why}}catch{}}function Ws(e){let t;e.on(`status`,({status:n})=>{clearInterval(t),t=void 0;let r=e.ws;if(n!==`connected`||!r)return;let i=r.onmessage;r.onmessage=function(t){if(t.data!==`pong`)return i?.call(this,t);e.ws===r&&(e.wsLastMessageReceived=D())},t=setInterval(()=>{e.ws===r&&r.readyState===r.OPEN&&r.send(`ping`)},15e3)})}const Gs=Object.freeze({body:`body`,fields:`fields`,status:`status`});function Ks(e){return typeof e==`string`?e:null}function qs(e){let t=e.getMap(Gs.status),n=t.get(`issues`),r=t.get(`savedBy`),i={issues:Array.isArray(n)?n:[],savedBy:r&&!Array.isArray(r)&&r instanceof Object?r:null};return{digest:Ks(t.get(`digest`)),error:Ks(t.get(`error`)),issues:i.issues,savedAt:Ks(t.get(`savedAt`)),savedBy:i.savedBy}}function Js(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ys=[`#E11D48`,`#D97706`,`#059669`,`#0891B2`,`#2563EB`,`#7C3AED`,`#C026D3`];function $(e){try{return String(e)===e}catch{return!1}}function Xs(e){if(!$(e.id)||!e.id||e.id.length>256)throw Ls.REALTIME_INVALID_USER();let t=0;for(let n=0;n<e.id.length;n++)t=Math.imul(31,t)+e.id.charCodeAt(n)|0;let n=($(e.name)&&e.name||$(e.email)&&e.email||`Anonymous`).slice(0,256),r={color:Ys[Math.abs(t)%Ys.length],id:e.id,name:n};return $(e.image)&&e.image&&e.image.length<=2048&&(r.image=e.image),r}function Zs(e){return Js(e)?$(e.id)&&e.id.length>0&&e.id.length<=256&&$(e.name)&&e.name.length>0&&e.name.length<=256&&$(e.color)&&/^#[\da-f]{6}$/i.test(e.color)&&(e.image===void 0||$(e.image)&&e.image.length<=2048):!1}function Qs(e){let t=[];for(let[n,r]of e)if(Zs(r.user)){let{color:e,id:i,image:a,name:o}=r.user,s={color:e,id:i,name:o,clientId:n};a!==void 0&&(s.image=a),t.push(s)}return t}function $s(e,t,n={}){let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=[],o,s=`connecting`,c=!1,l=!1,u,d,f=()=>{for(let e of r)e()},ee=()=>{let t=n.origin?new URL(n.origin):window.location;return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${ms(`/_vitehub/realtime/${encodeURIComponent(e)}`,n.baseURL)}`},te=t.split(`/`).map(encodeURIComponent).join(`/`),ne={};function re(){c=!1,u=new Hr,d=new ps(ee(),te,u,{disableBc:!0,params:{...n.params,clientId:String(u.clientID)}});let e=d;Ws(e),e.messageHandlers[5]=(t,n)=>{let r=Rs(n);if(r){if(r.type===`session`){e.params.epoch=r.epoch;return}e.destroy(),u.destroy(),!l&&(re(),f())}},e.messageHandlers[6]=(t,n)=>{let r=Us(n);r?.kind===`request`&&ie(e,r.id,r.body)},e.awareness.off(`update`,e._awarenessUpdateHandler),e.awareness.on(`update`,({added:t,removed:n,updated:r})=>{let i=[...t,...r,...n].filter(t=>t===e.doc.clientID),a=e.ws;if(!i.length||!e.wsconnected||!a||a.readyState!==a.OPEN)return;let o=_();b(o,1),S(o,Vo(e.awareness,i)),a.send(v(o))});let t=n.identity??{id:`guest:${u.clientID}`};e.awareness.setLocalState({...ne,user:Xs({...t,id:t.id||`guest:${u.clientID}`})}),e.awareness.on(`change`,f),u.getMap(Gs.status).observe(f),e.on(`sync`,t=>{d===e&&(c=t,f())}),e.on(`status`,e=>{s=e.status,f()})}re();let p;n.changes&&(p=new ps(ee(),`%40workspace`,new Hr,{disableBc:!0,params:{...n.params,workspace:`events`}}),p.awareness.setLocalState(null),Ws(p),p.messageHandlers[4]=(e,t)=>{let n=Bs(t);if(n)for(let e of i)e(n)},p.on(`status`,e=>{e.status===`connected`&&ae()}));async function ie(e,t,n){let r=e=>Hs({kind:`answer`,id:t,ok:!1,why:e}),i;try{i=o?Hs({kind:`answer`,id:t,ok:!0,body:await o(n)}):r(`This page does not answer requests.`),i.byteLength>1047552&&(i=r(`The answer has ${i.byteLength} bytes, over the 1 MiB limit.`))}catch(e){i=r(e instanceof Error?e.message:String(e))}let a=e.ws;e.wsconnected&&a&&a.readyState===a.OPEN&&a.send(Uint8Array.from(i))}function ae(){let e=p?.ws;if(p?.wsconnected&&e&&e.readyState===e.OPEN)for(;a.length;)e.send(Uint8Array.from(Vs(a.shift())))}return{get awareness(){return d.awareness},get clientId(){return u.clientID},people:()=>Qs(d.awareness.getStates()),states:()=>{let e=new Map(d.awareness.getStates());return e.delete(u.clientID),e},status:()=>s,saveStatus:()=>c?qs(u):void 0,setLocal(e,t){if(t!==null){ne[e]=t,d.awareness.setLocalStateField(e,t);return}delete ne[e];let n=d.awareness.getLocalState();if(!n||!Object.hasOwn(n,e))return;let{[e]:r,...i}=n;d.awareness.setLocalState(i)},notify(e){p&&(a.push(e),ae())},onUpdate(e){return r.add(e),()=>r.delete(e)},onChange(e){return i.add(e),()=>i.delete(e)},onRequest(e){return o=e,()=>{o===e&&(o=void 0)}},destroy(){l=!0,d.destroy(),u.destroy(),p?.destroy(),p?.doc.destroy(),r.clear(),i.clear(),o=void 0}}}export{$s as connectRealtimeRoom};
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { F as RealtimeWorkspaceChange, d as RealtimeDocumentStatus, x as RealtimePerson } from "./types-1DVVG5ro.js";
1
+ import { L as RealtimeWorkspaceChange, d as RealtimeDocumentStatus, x as RealtimePerson } from "./types-DdY7Vo1H.js";
2
2
  import * as awarenessProtocol from "y-protocols/awareness";
3
3
  //#region src/client.d.ts
4
4
  export type RealtimeRoomStatus = "connected" | "connecting" | "disconnected";
@@ -15,7 +15,7 @@ export interface RealtimeRoomOptions {
15
15
  /** Query parameters sent to the definition's authorization on presence and workspace connections. */
16
16
  params?: Record<string, string>;
17
17
  /**
18
- * The person this browser shows as. A definition with `identify` or `auth: true` replaces it with the server's
18
+ * The person this browser shows as. A definition with `identify` or `authorize: true` replaces it with the server's
19
19
  * identity, so only public definitions show it as given.
20
20
  */
21
21
  identity?: {
package/dist/client.js CHANGED
@@ -1,7 +1,7 @@
1
- import { n as resolveRealtimeApplicationPath, t as keepRealtimeSocketAlive } from "./keepalive-BCs-uXp4.js";
2
- import { a as decodeRealtimeRequestFramePayload, c as encodeRealtimeRequestFrame, i as decodeRealtimeControlPayload, l as encodeWorkspaceChange, o as decodeWorkspaceChangePayload, x as workspaceRoomId } from "./object-CzKyK0hX.js";
1
+ import { n as resolveRealtimeApplicationPath, t as keepRealtimeSocketAlive } from "./keepalive-B4ONG6AD.js";
2
+ import { a as decodeRealtimeRequestFramePayload, c as encodeRealtimeRequestFrame, i as decodeRealtimeControlPayload, l as encodeWorkspaceChange, o as decodeWorkspaceChangePayload, x as workspaceRoomId } from "./object-BgPPDLDE.js";
3
3
  import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
4
- import { n as getRealtimePeople, t as createRealtimeIdentity } from "./presence-Tuy1y_l9.js";
4
+ import { n as getRealtimePeople, t as createRealtimeIdentity } from "./presence-B6rvkHqd.js";
5
5
  import "lib0/decoding";
6
6
  import * as encoding from "lib0/encoding";
7
7
  import * as awarenessProtocol from "y-protocols/awareness";
@@ -30,7 +30,7 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
30
30
  };
31
31
  const url = () => {
32
32
  const app = options.origin ? new URL(options.origin) : window.location;
33
- return `${app.protocol === "https:" ? "wss:" : "ws:"}//${app.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`, options.baseURL)}`;
33
+ return `${app.protocol === "https:" ? "wss:" : "ws:"}//${app.host}${resolveRealtimeApplicationPath(`/_vitehub/realtime/${encodeURIComponent(definition)}`, options.baseURL)}`;
34
34
  };
35
35
  const room = documentId.split("/").map(encodeURIComponent).join("/");
36
36
  const localState = {};
@@ -161,9 +161,16 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
161
161
  status: () => currentStatus,
162
162
  saveStatus: () => synced ? readRealtimeStatus(document) : void 0,
163
163
  setLocal(field, value) {
164
- if (value === null) delete localState[field];
165
- else localState[field] = value;
166
- provider.awareness.setLocalStateField(field, value);
164
+ if (value !== null) {
165
+ localState[field] = value;
166
+ provider.awareness.setLocalStateField(field, value);
167
+ return;
168
+ }
169
+ delete localState[field];
170
+ const state = provider.awareness.getLocalState();
171
+ if (!state || !Object.hasOwn(state, field)) return;
172
+ const { [field]: _removed, ...rest } = state;
173
+ provider.awareness.setLocalState(rest);
167
174
  },
168
175
  notify(change) {
169
176
  if (!changes) return;
@@ -1,8 +1,8 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
2
2
  import { Diagnostic } from "nostics";
3
3
  //#region src/definition.ts
4
4
  /**
5
- * Checks a definition when the server loads it. A definition must say who can use its rooms: `auth: true`,
5
+ * Checks a definition when the server loads it. A definition must say who can use its rooms: `authorize: true`,
6
6
  * `authorize()`, or `access: "public"`. `history.checkpoint` needs a document that can record history: a Workspace
7
7
  * document, or an adapter with `checkpoint()`.
8
8
  */
@@ -15,13 +15,13 @@ function defineRealtime(definition) {
15
15
  function assertRealtimeAccess(definition) {
16
16
  const access = definition.access;
17
17
  const authorize = definition.authorize;
18
- const auth = definition.auth === true;
19
- const hasAuthorize = typeof authorize === "function";
18
+ if ("auth" in definition) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "auth" });
20
19
  if (access !== void 0) {
21
20
  if (access !== "public") throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "not-public" });
22
- if (definition.auth !== void 0 || authorize !== void 0) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "public-with-rule" });
23
- } else if (!auth && !hasAuthorize) throw realtimeErrorDiagnostics.REALTIME_MISSING_ACCESS();
24
- if (auth && !definition.identify && definition.origins) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "origins-without-identify" });
21
+ if (authorize !== void 0) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "public-with-rule" });
22
+ } else if (authorize === void 0) throw realtimeErrorDiagnostics.REALTIME_MISSING_ACCESS();
23
+ else if (authorize !== true && typeof authorize !== "function") throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "not-authorize" });
24
+ if (authorize === true && !definition.identify && definition.origins) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "origins-without-identify" });
25
25
  }
26
26
  function assertRealtimeCheckpoint(definition) {
27
27
  if (!definition.document || !definition.history?.checkpoint) return;
@@ -1,4 +1,4 @@
1
- import { n as isRecord } from "./object-CzKyK0hX.js";
1
+ import { n as isRecord } from "./object-BgPPDLDE.js";
2
2
  import { n as realtimeDocumentLayout } from "./layout-DNaxppTZ.js";
3
3
  import "y-protocols/awareness";
4
4
  import * as Y from "yjs";
@@ -1,5 +1,5 @@
1
- import { f as RealtimeEditor, u as RealtimeDocumentSnapshot } from "./types-1DVVG5ro.js";
2
- import "./layout-fyQnhwCg.js";
1
+ import { f as RealtimeEditor, u as RealtimeDocumentSnapshot } from "./types-DdY7Vo1H.js";
2
+ import "./layout-VHjYWa-M.js";
3
3
  import * as Y from "yjs";
4
4
  //#region src/document.d.ts
5
5
  /** Builds a new room document from a stored snapshot. Only use it for rooms no client holds yet. */
@@ -4,10 +4,6 @@ const shared = {
4
4
  postgres: "Postgres carries room updates between instances.",
5
5
  redis: "Redis carries room updates between instances."
6
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
7
  function resolveDriver(input, context) {
12
8
  if (input.driver !== "auto" && input.driver !== "node") return { driver: input.driver };
13
9
  if (context.env.REDIS_URL?.trim()) return {
@@ -73,7 +73,6 @@ const RealtimeDocument = Document.extend({
73
73
  });
74
74
  const RealtimeCode = Code.extend({ excludes: "" });
75
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
76
  const RealtimeBlockquote = Blockquote.extend({ renderMarkdown(node, helpers, context) {
78
77
  return (this.parent?.(node, helpers, context) ?? "").replace(escapedAlertMarker, "> [!$1]");
79
78
  } });
@@ -11,6 +11,10 @@ const realtimeErrorDiagnostics = /*#__PURE__*/ defineErrors({
11
11
  why: ({ action }) => `The realtime document disconnected or changed during \`${action}()\`.`,
12
12
  fix: "Call the method again after the new document connects. Read `synced` to know when it is ready."
13
13
  },
14
+ REALTIME_INVALID_DOCUMENT: {
15
+ why: ({ action }) => `The room body does not fit the editor schema, so \`${action}()\` did not write it. Writing it would lose content.`,
16
+ fix: "Keep editing until the document fits the editor extensions of the Realtime Definition, then call the method again. The room keeps the edits."
17
+ },
14
18
  REALTIME_INVALID_RESPONSE: {
15
19
  why: ({ action }) => `The realtime server answered \`${action}()\` with a response that the client cannot use.`,
16
20
  fix: "Use the same `@vite-hub/realtime` version on the client and the server, and build again."
@@ -19,9 +23,22 @@ const realtimeErrorDiagnostics = /*#__PURE__*/ defineErrors({
19
23
  why: ({ action }) => `\`${action}()\` needs a document, and \`documentId\` is empty.`,
20
24
  fix: "Pass a document path to `useRealtimeTiptap(definition, documentId)` before you call the method."
21
25
  },
26
+ REALTIME_READ_ONLY: {
27
+ why: ({ action }) => `The room is read-only, so \`${action}()\` cannot write the document.`,
28
+ fix: "Read `readOnlyReason` of `useRealtimeTiptap()` for the reason. Do not offer save or publish while it is set."
29
+ },
22
30
  REALTIME_REQUEST_FAILED: {
23
31
  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."
32
+ fix: "Read `error.why` for the server message, `error.data.status` for the HTTP status, and `error.cause` for a network error. Retry when the server is available again.",
33
+ data: ({ status }) => ({ status })
34
+ },
35
+ REALTIME_SOURCE_CHANGED: {
36
+ why: ({ action }) => `The server refused \`${action}()\` because the stored document changed outside the room.`,
37
+ fix: "Tell the person that the stored document changed. Use `onReset()` to detect a room reset and read unsaved edits from the event's `previous` document."
38
+ },
39
+ REALTIME_SYNC_PENDING: {
40
+ why: ({ action }) => `The room did not receive every edit of this client in time, so \`${action}()\` did not run. The composable tried 20 times.`,
41
+ fix: "Call the method again when `synced` is true. When it keeps failing, check that the WebSocket stays connected."
25
42
  },
26
43
  REALTIME_ROOM_ABORTED: {
27
44
  why: "The request to the room stopped because its signal aborted.",
@@ -93,11 +110,11 @@ const realtimeErrorDiagnostics = /*#__PURE__*/ defineErrors({
93
110
  },
94
111
  REALTIME_MISSING_ACCESS: {
95
112
  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."
113
+ fix: "Set `authorize: true` to require a signed-in user, set `authorize()` to decide each request, or set `access: \"public\"` to let anyone read and write."
97
114
  },
98
115
  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()`."
116
+ why: ({ reason }) => reason === "auth" ? "The Realtime definition sets `auth`. Realtime replaced it with `authorize: true`, and an `authorize()` callback now also runs for signed-out callers." : reason === "public-with-rule" ? "The Realtime definition sets `access: \"public\"` together with `authorize`, so its access rule is not clear." : reason === "not-public" ? "The Realtime definition sets `access` to a value other than \"public\"." : reason === "not-authorize" ? "The Realtime definition sets `authorize` to a value that is not `true` or a function." : "The Realtime definition sets `origins()` with `authorize: true` and no `identify()`. Only the Auth trusted-origin policy can allow a different origin to use the ViteHub Auth session.",
117
+ fix: ({ reason }) => reason === "auth" ? "Replace `auth: true` with `authorize: true`. With an `authorize()` callback, remove `auth` and return `false` from the callback when `user` is `null`." : reason === "origins-without-identify" ? "Remove `origins()`, or add `identify()` that reads a credential the page sends on purpose, such as a ticket in `params`." : reason === "not-authorize" ? "Set `authorize: true` to require a signed-in user, or set `authorize()` to a function that returns `true` to allow." : "Use `access: \"public\"` alone for open rooms. To limit access, remove `access` and set `authorize`."
101
118
  },
102
119
  REALTIME_CHECKPOINT_UNSUPPORTED: {
103
120
  why: "The Realtime definition sets `history.checkpoint`, but its document adapter has no `checkpoint()` method, so `history.checkpoint()` could never run.",
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
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";
1
+ import { A as RealtimeResetReason, C as RealtimeReadOnlyReason, D as RealtimeRequestErrorCode, E as RealtimeRequestError, F as RealtimeUser, I as RealtimeVerifyResult, L as RealtimeWorkspaceChange, M as RealtimeSaveOptions, N as RealtimeSaveResult, O as RealtimeRequestEvent, P as RealtimeSaved, R as RealtimeWorkspaceDocumentOptions, 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 RealtimeRoomRequestErrorCode, k as RealtimeRequestResult, 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, z as RealtimeRequestFailure } from "./types-DdY7Vo1H.js";
2
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
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-VHjYWa-M.js";
4
4
  //#region src/definition.d.ts
5
5
  /**
6
- * Checks a definition when the server loads it. A definition must say who can use its rooms: `auth: true`,
6
+ * Checks a definition when the server loads it. A definition must say who can use its rooms: `authorize: true`,
7
7
  * `authorize()`, or `access: "public"`. `history.checkpoint` needs a document that can record history: a Workspace
8
8
  * document, or an adapter with `checkpoint()`.
9
9
  */
@@ -21,4 +21,4 @@ export declare function defineRealtimeEditor(editor: RealtimeEditor): RealtimeEd
21
21
  */
22
22
  export declare const realtimeMarkdownEditor: RealtimeEditor;
23
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 };
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 RealtimeRequestError, type RealtimeRequestErrorCode, type RealtimeRequestEvent, type RealtimeRequestFailure, type RealtimeRequestResult, 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,4 +1,4 @@
1
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";
2
+ import { a as defineRealtime, n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "./conflict-DYC_qXzM.js";
3
+ import { n as defineRealtimeEditor, r as realtimeMarkdownEditor, t as createRealtimeEditorExtensions } from "./editor-IL2jHqn8.js";
4
4
  export { RealtimeDocumentConflict, createRealtimeEditorExtensions, defineRealtime, defineRealtimeEditor, isRealtimeDocumentConflict, readRealtimeStatus, realtimeDocumentLayout, realtimeMarkdownEditor };
@@ -1,4 +1,4 @@
1
- import { r as RealtimeAvailability } from "../../types-1DVVG5ro.js";
1
+ import { r as RealtimeAvailability } from "../../types-DdY7Vo1H.js";
2
2
  //#region src/internal/runtime/unavailable.d.ts
3
3
  declare const availability: RealtimeAvailability;
4
4
  //#endregion