@vite-hub/realtime 0.4.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.
package/README.md CHANGED
@@ -167,7 +167,7 @@ const [error, answer] = await requestRealtimeRoom("tabs", tabId, { want: "title"
167
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`.
168
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.
169
169
  - `driver: "cloudflare"` uses a SQLite-backed Cloudflare Durable Object. `driver: "auto"` selects it when a Cloudflare host or hosting environment can be resolved.
170
- - 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`.
171
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.
172
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.
173
173
  - Requests with an `Origin` other than the app's get 403 on each definition, unless `origins()` accepts the origin.
@@ -177,6 +177,10 @@ const [error, answer] = await requestRealtimeRoom("tabs", tabId, { want: "title"
177
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.
178
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
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).
183
+
180
184
  ## Public imports
181
185
 
182
186
  | Import | Purpose |
@@ -187,14 +191,14 @@ const [error, answer] = await requestRealtimeRoom("tabs", tabId, { want: "title"
187
191
  | `@vite-hub/realtime/agent` | `agentRealtime`, the handle that ViteHub passes to the Agent `page()` Capability. Apps do not import it. |
188
192
  | `@vite-hub/realtime/client` | `connectRealtimeRoom()` to share presence without an editor, in any framework. |
189
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. |
190
- | `@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. |
191
195
  | `@vite-hub/realtime/bus` | `useRealtimeBus()` and `closeRealtimeBuses()`, the Postgres and Redis buses that the generated Node handler passes to `createRealtimeHandler({ bus })`. |
192
196
 
193
197
  Generated files under `.vitehub/nitro/realtime` are inspectable build output, not application imports.
194
198
 
195
199
  ## Learn more
196
200
 
197
- - [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.
198
202
  - [Workspace](https://vitehub.dev/docs/workspace) covers stores, write rules, snapshots, and persistence.
199
203
  - [Auth](https://vitehub.dev/docs/auth) covers session setup and trusted origins.
200
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-BwaohsJS.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-C_bQc4NE.js";
1
+ import { t as agentRealtime } from "./request-kM5epeSd.js";
2
2
  export { agentRealtime };
@@ -1,4 +1,5 @@
1
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-CKv8gQZf.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/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){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{$s 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 { L as RealtimeWorkspaceChange, d as RealtimeDocumentStatus, x as RealtimePerson } from "./types-Cvm0G3VJ.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";
package/dist/client.js CHANGED
@@ -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,5 +1,5 @@
1
- import { f as RealtimeEditor, u as RealtimeDocumentSnapshot } from "./types-Cvm0G3VJ.js";
2
- import "./layout-B7i6-FnH.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
  } });
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
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-Cvm0G3VJ.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-B7i6-FnH.js";
3
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-VHjYWa-M.js";
4
4
  //#region src/definition.d.ts
5
5
  /**
6
6
  * Checks a definition when the server loads it. A definition must say who can use its rooms: `authorize: true`,
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
2
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-BM5-vHqf.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-Cvm0G3VJ.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
@@ -0,0 +1,7 @@
1
+ import { i as RealtimeRoomRequestResult, n as RealtimeDurableObjectNamespace, o as requestRealtimeRoom, r as RealtimeRoomRequestOptions } from "../request-DAodIqZ8.js";
2
+ import { n as RealtimeBusMessage, r as RealtimeRoomRecord, t as RealtimeBus } from "../bus-protocol-wXkXW28q.js";
3
+ import { n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "../conflict-CmZizTYl.js";
4
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "../layout-VHjYWa-M.js";
5
+ import { C as claimAwarenessClientIds, D as blobDocument, E as RealtimeBlobStore, O as isRealtimeAvailable, S as bindAwarenessIdentity, T as RealtimeBlobDocumentOptions, _ as isRealtimeWorkspaceDocument, a as applyRealtimeSyncMessage, b as readRealtimeRequestState, c as encodeAwarenessState, d as realtimePersistenceDefaults, f as realtimeRoomKey, g as RealtimeWorkspaceDocumentAdapter, h as restoreRealtimeDocument, i as RealtimeSyncOptions, l as encodeSyncStep1, m as resolveRealtimeDefinition, n as RealtimeHandlerOptions, o as assertRealtimeRoomStateQuota, p as refreshRealtimeDocument, r as RealtimeRefreshOptions, s as createRealtimeHandler, t as RealtimeHandler, u as encodeSyncUpdate, v as readRealtimeWorkspaceDocument, w as compactRealtimeAwareness, x as applyRealtimeAwarenessUpdate, y as workspaceDocument } from "../server-Covbc24E.js";
6
+ import { i as readRealtimeYDoc, n as createRealtimeYDoc, r as diffRealtimeYDoc, t as containsRealtimeState } from "../document-b1ShR2S1.js";
7
+ export { type RealtimeBlobDocumentOptions, type RealtimeBlobStore, type RealtimeBus, type RealtimeBusMessage, RealtimeDocumentConflict, type RealtimeDurableObjectNamespace, RealtimeHandler, RealtimeHandlerOptions, RealtimeRefreshOptions, type RealtimeRoomRecord, type RealtimeRoomRequestOptions, type RealtimeRoomRequestResult, RealtimeSyncOptions, type RealtimeWorkspaceDocumentAdapter, applyRealtimeAwarenessUpdate, applyRealtimeSyncMessage, assertRealtimeRoomStateQuota, bindAwarenessIdentity, blobDocument, claimAwarenessClientIds, compactRealtimeAwareness, containsRealtimeState, createRealtimeHandler, createRealtimeYDoc, diffRealtimeYDoc, encodeAwarenessState, encodeSyncStep1, encodeSyncUpdate, isRealtimeAvailable, isRealtimeDocumentConflict, isRealtimeWorkspaceDocument, readRealtimeRequestState, readRealtimeStatus, readRealtimeWorkspaceDocument, readRealtimeYDoc, realtimeDocumentLayout, realtimePersistenceDefaults, realtimeRoomKey, refreshRealtimeDocument, requestRealtimeRoom, resolveRealtimeDefinition, restoreRealtimeDocument, workspaceDocument };
@@ -0,0 +1,6 @@
1
+ import { l as requestRealtimeRoom, m as isRealtimeAvailable } from "../request-kM5epeSd.js";
2
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "../layout-DNaxppTZ.js";
3
+ import { n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "../conflict-DYC_qXzM.js";
4
+ import { _ as applyRealtimeAwarenessUpdate, a as encodeSyncStep1, b as compactRealtimeAwareness, c as realtimeRoomKey, d as restoreRealtimeDocument, f as blobDocument, g as readRealtimeRequestState, h as workspaceDocument, i as encodeAwarenessState, l as refreshRealtimeDocument, m as readRealtimeWorkspaceDocument, n as assertRealtimeRoomStateQuota, o as encodeSyncUpdate, p as isRealtimeWorkspaceDocument, r as createRealtimeHandler, s as realtimePersistenceDefaults, t as applyRealtimeSyncMessage, u as resolveRealtimeDefinition, v as bindAwarenessIdentity, y as claimAwarenessClientIds } from "../server-BSXJP45b.js";
5
+ import { i as diffRealtimeYDoc, n as containsRealtimeState, o as readRealtimeYDoc, r as createRealtimeYDoc } from "../document-U5rzg2vG.js";
6
+ export { RealtimeDocumentConflict, applyRealtimeAwarenessUpdate, applyRealtimeSyncMessage, assertRealtimeRoomStateQuota, bindAwarenessIdentity, blobDocument, claimAwarenessClientIds, compactRealtimeAwareness, containsRealtimeState, createRealtimeHandler, createRealtimeYDoc, diffRealtimeYDoc, encodeAwarenessState, encodeSyncStep1, encodeSyncUpdate, isRealtimeAvailable, isRealtimeDocumentConflict, isRealtimeWorkspaceDocument, readRealtimeRequestState, readRealtimeStatus, readRealtimeWorkspaceDocument, readRealtimeYDoc, realtimeDocumentLayout, realtimePersistenceDefaults, realtimeRoomKey, refreshRealtimeDocument, requestRealtimeRoom, resolveRealtimeDefinition, restoreRealtimeDocument, workspaceDocument };
@@ -1,4 +1,4 @@
1
- import { d as RealtimeDocumentStatus } from "./types-Cvm0G3VJ.js";
1
+ import { d as RealtimeDocumentStatus } from "./types-DdY7Vo1H.js";
2
2
  import * as Y from "yjs";
3
3
  //#region src/layout.d.ts
4
4
  /**
@@ -0,0 +1,159 @@
1
+ //#region ../internal/src/runtime/request-log.ts
2
+ function isRequestLog(value) {
3
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "set") === "function" && typeof Reflect.get(value, "warn") === "function" && typeof Reflect.get(value, "error") === "function";
4
+ }
5
+ function contextLog(value) {
6
+ const context = value !== null && typeof value === "object" ? Reflect.get(value, "context") : void 0;
7
+ return context !== null && typeof context === "object" ? Reflect.get(context, "log") : void 0;
8
+ }
9
+ /**
10
+ * The evlog request logger of a request, or `undefined` when the app does not register evlog. Pass a Nitro v3 event
11
+ * (evlog sets `event.req.context.log`) or its `Request` (`request.context.log`).
12
+ */
13
+ function requestLog(input) {
14
+ const log = contextLog(input !== null && typeof input === "object" ? Reflect.get(input, "req") : void 0) ?? contextLog(input);
15
+ return isRequestLog(log) ? log : void 0;
16
+ }
17
+ /**
18
+ * The `Symbol.for()` key of the bridge on `globalThis`. Every bundled copy of this module and the Nitro plugin that
19
+ * `vitehub()` generates use the same key.
20
+ */
21
+ const evlogBridgeKey = "vitehub.evlog";
22
+ function isEvlogBridge(value) {
23
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "createLogger") === "function";
24
+ }
25
+ /** The evlog bridge of this process, or `undefined` when the app does not register evlog. */
26
+ function evlogBridge() {
27
+ const bridge = globalThis[Symbol.for(evlogBridgeKey)];
28
+ return isEvlogBridge(bridge) ? bridge : void 0;
29
+ }
30
+ function activeBridge() {
31
+ const bridge = evlogBridge();
32
+ try {
33
+ return bridge && bridge.isEnabled?.() !== false ? bridge : void 0;
34
+ } catch {
35
+ return;
36
+ }
37
+ }
38
+ /**
39
+ * A short name for the cause of a failure, safe to put in a log field: the string `code` of the error, such as
40
+ * `ENOSPC` or a ViteHub diagnostic code, else its class name. Never the message, which can hold paths or values.
41
+ */
42
+ function errorCode(error) {
43
+ if (error === null || typeof error !== "object") return void 0;
44
+ const code = Reflect.get(error, "code");
45
+ if (typeof code === "string" && code) return code;
46
+ const name = Reflect.get(error, "name");
47
+ return typeof name === "string" && name && name !== "Error" ? name : void 0;
48
+ }
49
+ /**
50
+ * Emits one evlog event of its own, outside a request's wide event. The event also reaches the app's `evlog:drain`
51
+ * hooks. Returns `false` when the app does not register evlog or turned it off, and never throws.
52
+ */
53
+ function emitLogEvent(event) {
54
+ const bridge = activeBridge();
55
+ if (!bridge) return false;
56
+ try {
57
+ const log = bridge.createLogger({
58
+ action: event.field,
59
+ message: event.message,
60
+ [event.field]: event.fields
61
+ }, event.waitUntil ? { waitUntil: event.waitUntil } : void 0);
62
+ if (event.level === "error") log.error(event.withError && event.error instanceof Error ? event.error : event.message);
63
+ else log[event.level](event.message);
64
+ const emitted = log.emit();
65
+ if (emitted && bridge.drain) {
66
+ const drained = Promise.resolve().then(() => bridge.drain?.(emitted)).catch((error) => {
67
+ console.error("[evlog] drain failed:", error);
68
+ });
69
+ event.waitUntil?.(drained);
70
+ }
71
+ return true;
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+ /**
77
+ * Logs a failure that the caller survives, with a fixed message and the `code` of the error. With the evlog request
78
+ * logger of `request`, it replaces `[field]` on the request's wide event and adds a warning. Pass `request` only when the
79
+ * request has not answered yet: evlog drops fields after it emits the wide event. Otherwise it emits an event of its
80
+ * own. Without evlog, or with evlog off, it calls `fallback`, which prints to the server console as before. It never
81
+ * throws.
82
+ */
83
+ function logFailure(failure, fallback) {
84
+ const code = errorCode(failure.error);
85
+ const fields = {
86
+ ...failure.fields,
87
+ ...code ? { code } : {}
88
+ };
89
+ const log = failure.request !== void 0 && activeBridge() ? requestLog(failure.request) : void 0;
90
+ if (log) try {
91
+ log.set({ [failure.field]: false });
92
+ log.warn(failure.message, { [failure.field]: fields });
93
+ return;
94
+ } catch {}
95
+ if (emitLogEvent({
96
+ ...failure,
97
+ fields,
98
+ level: failure.level ?? "warn"
99
+ })) return;
100
+ try {
101
+ fallback();
102
+ } catch {}
103
+ }
104
+ //#endregion
105
+ //#region src/log.ts
106
+ /**
107
+ * The label of a room in logs. A `document: false` room id can be a random token that lets a person join, such as a
108
+ * page id, so the log gets a short hash of it. A cryptographic hash adds nothing here: a short or guessable id can be
109
+ * found from any hash by trying values.
110
+ */
111
+ function realtimeRoomLabel(documentId, presence) {
112
+ if (!presence) return documentId;
113
+ let hash = 2166136261;
114
+ for (let index = 0; index < documentId.length; index++) {
115
+ hash ^= documentId.charCodeAt(index);
116
+ hash = Math.imul(hash, 16777619);
117
+ }
118
+ return `#${(hash >>> 0).toString(16).padStart(8, "0")}`;
119
+ }
120
+ /** The definition and room of a room key from `realtimeRoomKey()`. Workspace event rooms have no room id. */
121
+ function realtimeRoomFields(key, presence) {
122
+ let parts;
123
+ try {
124
+ parts = JSON.parse(key);
125
+ } catch {
126
+ return {};
127
+ }
128
+ if (!Array.isArray(parts)) return {};
129
+ const [definition, documentId] = parts;
130
+ return {
131
+ ...typeof definition === "string" ? { definition } : {},
132
+ ...typeof documentId === "string" ? { room: realtimeRoomLabel(documentId, presence) } : {}
133
+ };
134
+ }
135
+ /**
136
+ * Logs one Realtime failure as its own evlog event, `{ action: "realtime", message, realtime: fields }`, when the app
137
+ * registers evlog and has it on. The event has the fixed `message` and the error's `code`, never its message. Otherwise
138
+ * it prints to the console, with the error unless the room is private. It never throws: it also runs inside a Durable
139
+ * Object and in socket callbacks, which have no `waitUntil()`.
140
+ */
141
+ function logRealtime(level, message, fields, error, options = {}) {
142
+ logFailure({
143
+ field: "realtime",
144
+ fields: { ...fields },
145
+ level,
146
+ message,
147
+ ...error === void 0 ? {} : { error }
148
+ }, () => {
149
+ if (options.console === false) return;
150
+ const text = `[vitehub] ${message}`;
151
+ if (options.privateRoom) {
152
+ if (level === "error") console.error(text, fields);
153
+ else console.warn(text, fields);
154
+ } else if (level === "error") console.error(text, ...error === void 0 ? [] : [error]);
155
+ else console.warn(text, ...error === void 0 ? [] : [error instanceof Error ? error.message : String(error)]);
156
+ });
157
+ }
158
+ //#endregion
159
+ export { requestLog as i, realtimeRoomFields as n, realtimeRoomLabel as r, logRealtime as t };
@@ -1,4 +1,4 @@
1
- import { j as RealtimeRoomRequestErrorCode } from "./types-Cvm0G3VJ.js";
1
+ import { j as RealtimeRoomRequestErrorCode } from "./types-DdY7Vo1H.js";
2
2
  import { Result } from "@vite-hub/runtime";
3
3
  //#region src/request.d.ts
4
4
  /** The `$DurableObject` namespace binding that holds Realtime rooms on Cloudflare. */
@@ -80,7 +80,6 @@ function localRequesters() {
80
80
  requestScope[localRequestKey] ??= /* @__PURE__ */ new Set();
81
81
  return requestScope[localRequestKey];
82
82
  }
83
- /** The parameters each request error was made with, so a Durable Object can send the same error to the Worker. */
84
83
  const roomRequestErrorParams = /* @__PURE__ */ new WeakMap();
85
84
  function roomRequestError(code, params = {}) {
86
85
  const result = createRoomRequestError(code, params);