@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.
@@ -175,14 +175,7 @@ interface RealtimePersistenceOptions {
175
175
  maxWait?: number;
176
176
  }
177
177
  interface RealtimeDefinitionIdentity {
178
- /** Resolve the user for a request, replacing the ViteHub Auth session. Return `null` for anonymous. */
179
178
  identify?: (context: RealtimeRequestContext) => RealtimeUser | null | undefined | Promise<RealtimeUser | null | undefined>;
180
- /**
181
- * Let a page on another origin connect, such as a script that sites load from the app. Return `true` to accept
182
- * `origin`. Without it, only the app's own origin or an origin trusted by Auth connects. The browser sends cookies with a cross-site handshake
183
- * too, so `identify` and `authorize` must then trust only what the page sends on purpose, such as a ticket in
184
- * `params`, never the session cookie. `authorize: true` without `identify` rejects it: the Auth session is a cookie.
185
- */
186
179
  origins?: (context: RealtimeOriginContext) => boolean | Promise<boolean>;
187
180
  }
188
181
  type RealtimeAuthorize = (context: RealtimeAuthorizeContext) => boolean | Promise<boolean>;
@@ -205,17 +198,12 @@ type RealtimeDefinitionAccess = RealtimeDefinitionIdentity & ({
205
198
  });
206
199
  interface RealtimeDocumentFields {
207
200
  document: RealtimeWorkspaceDocumentOptions | RealtimeDocumentAdapter;
208
- /**
209
- * Editor schema and Markdown codec. Defaults to the built-in Markdown kit. A function picks the codec of each
210
- * document, such as one per Content collection; browsers that open the document must use the same schema.
211
- */
212
201
  editor?: RealtimeEditor | ((context: RealtimeDocumentContext) => RealtimeEditor);
213
202
  history?: {
214
203
  checkpoint: true | {
215
204
  message?: string;
216
205
  };
217
206
  };
218
- /** Idle saves. `false` saves only when a client calls `save()` or `history.checkpoint()`. */
219
207
  persistence?: RealtimePersistenceOptions | false;
220
208
  }
221
209
  /** A definition whose rooms edit one stored document each. */
@@ -225,17 +213,7 @@ interface RealtimePresenceFields {
225
213
  editor?: never;
226
214
  history?: never;
227
215
  persistence?: never;
228
- /**
229
- * Lets server code ask the one browser in a room with `requestRealtimeRoom()` from `@vite-hub/realtime/server`. The
230
- * browser answers with `room.onRequest()`. Default `false`: rooms without it refuse request frames.
231
- */
232
216
  requests?: boolean;
233
- /**
234
- * `"user"`: each person gets their own rooms. A room is keyed by the identity of whoever joins it, so the same room id
235
- * for two people is two rooms, and `requestRealtimeRoom()` must name the person with `{ user }`. The identity is the
236
- * ViteHub Auth session when the app has Auth, read without requiring one; everyone without a session shares one
237
- * `anonymous` scope. With `identify` or `authorize: true`, those decide the identity.
238
- */
239
217
  scope?: "user";
240
218
  }
241
219
  /**
package/dist/vite.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as DiscoveredRealtimeDefinition, v as RealtimeOptions } from "./types-Cvm0G3VJ.js";
1
+ import { t as DiscoveredRealtimeDefinition, v as RealtimeOptions } from "./types-DdY7Vo1H.js";
2
2
  import { Plugin } from "vite";
3
3
  //#region src/discovery.d.ts
4
4
  export declare function discoverRealtimeDefinitions(rootDir: string, serverDirs?: string[]): DiscoveredRealtimeDefinition[];
@@ -57,6 +57,8 @@ interface ViteHubResourceSummary {
57
57
  owner: string;
58
58
  /** Absent when no id is known yet. */
59
59
  source?: ViteHubResourceIdSource;
60
+ /** The resource is in the Wrangler config of a standalone Provider Output Worker, not in Nitro's. */
61
+ standalone?: boolean;
60
62
  }
61
63
  interface ViteHubInspectionContributor {
62
64
  definitions?: readonly ViteHubDefinitionInspector[];
package/dist/vite.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
2
- import { o as realtimeNamespaceVariable, s as realtimePostgresUrlVariable } from "./bus-CKv8gQZf.js";
2
+ import { o as realtimeNamespaceVariable, s as realtimePostgresUrlVariable } from "./bus-Bsdanf5O.js";
3
3
  import { g as realtimeKeepalivePong, h as realtimeKeepalivePing, r as isRecordOrFunction, t as cloneRecord } from "./object-BgPPDLDE.js";
4
4
  import availability from "./internal/runtime/unavailable.js";
5
5
  import { defineDiagnostics } from "nostics";
@@ -126,7 +126,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
126
126
  why: ({ message }) => message === void 0 ? "" : String(message)
127
127
  },
128
128
  INTERNAL_R0022: {
129
- fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
129
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields, and the list_operations tool of the ViteHub MCP gives the input schema of each operation.",
130
130
  why: ({ message }) => message === void 0 ? "" : String(message)
131
131
  },
132
132
  INTERNAL_R0024: {
@@ -345,6 +345,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
345
345
  why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
346
346
  fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
347
347
  },
348
+ INTERNAL_RUNTIME_PACKAGE_VERSION_CONFLICT: {
349
+ why: ({ first, name, second }) => `[vitehub] One server function needs ${name} from two installations: ${first} and ${second}.`,
350
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`, then build again."
351
+ },
348
352
  INTERNAL_SECRET_PURPOSE_MISSING: {
349
353
  why: "[vitehub] A derived secret requires a purpose.",
350
354
  fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
@@ -568,7 +572,7 @@ function hasProjectRootDirectoryMarker(root) {
568
572
  for (const marker of projectRootDirectoryMarkers) try {
569
573
  if (statSync(resolve(root, ...marker)).isDirectory()) return true;
570
574
  } catch (error) {
571
- if (error.code !== "ENOENT") throw error;
575
+ if (!isMissingProjectMarker(error)) throw error;
572
576
  }
573
577
  return false;
574
578
  }
@@ -582,11 +586,15 @@ function hasProjectRootFileMarker(root, markers) {
582
586
  try {
583
587
  if (statSync(resolve(root, ...path)).isFile()) return true;
584
588
  } catch (error) {
585
- if (error.code !== "ENOENT") throw error;
589
+ if (!isMissingProjectMarker(error)) throw error;
586
590
  }
587
591
  }
588
592
  return false;
589
593
  }
594
+ function isMissingProjectMarker(error) {
595
+ const code = error.code;
596
+ return code === "ENOENT" || code === "ENOTDIR";
597
+ }
590
598
  /**
591
599
  * The path of an app base, without the trailing slash: `/portal/` and `https://cdn.example/portal/` give `/portal`.
592
600
  * The root and relative bases (`""`, `"./"`) give `""`. The Console mounts its routes with the same rule.
@@ -602,35 +610,15 @@ function viteHubBasePath(base) {
602
610
  if (!pathname.startsWith("/") || pathname.startsWith("//")) return "";
603
611
  return pathname.replace(/\/+$/, "");
604
612
  }
605
- //#endregion
606
- //#region ../internal/src/build/page-tools.ts
607
- function readString(value, key) {
608
- const field = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
609
- return typeof field === "string" ? field : void 0;
610
- }
613
+ Object.freeze({ vitehubAuthAccess: "handler" });
611
614
  /**
612
- * The app base of a Vite configuration. ViteHub's application-base config field or `__VITEHUB_APP_BASE_URL__` constant
613
- * takes precedence over the Vite `base`; the Nuxt module sets both from `app.baseURL`. Only a root-relative Vite `base`
614
- * supplies an application path; absolute and protocol-relative URLs are asset CDN bases. The Nitro base is
615
- * `nitro.baseURL`, else `NITRO_APP_BASE_URL`.
615
+ * The route meta of a generated handler that checks access on every request, even when the app adds no rule: a required
616
+ * `authorize` policy, an explicit `access` rule, a required access token, or a signature. Auth access routes still apply
617
+ * to it, so an app rule stays in force. `checksOwnAccess(event)` of `vite-hub/auth` reads it, so app middleware can skip
618
+ * the route. A route that can run without a check, such as a browser error sink, an optional `authorize`, or a webhook
619
+ * with `secret: false`, must not use it.
616
620
  */
617
- function viteHubPageToolsBase(config, env = process.env) {
618
- const defined = readString(config !== null && typeof config === "object" ? Reflect.get(config, "define") : void 0, "__VITEHUB_APP_BASE_URL__");
619
- const viteBase = readString(config, "base");
620
- let appBase = viteBase?.startsWith("/") && !viteBase.startsWith("//") ? viteBase : void 0;
621
- if (defined) try {
622
- const value = JSON.parse(defined);
623
- if (typeof value === "string") appBase = value;
624
- } catch {}
625
- const base = viteHubBasePath(readString(config, "__vitehubAppBaseURL") ?? appBase);
626
- const nitroBase = viteHubBasePath(readString(config !== null && typeof config === "object" ? Reflect.get(config, "nitro") : void 0, "baseURL") ?? env.NITRO_APP_BASE_URL);
627
- return {
628
- base,
629
- mount: nitroBase && (base === nitroBase || base.startsWith(`${nitroBase}/`)) ? base.slice(nitroBase.length) : base
630
- };
631
- }
632
- //#endregion
633
- //#region ../internal/src/nitro-kit.ts
621
+ const ownAccessRouteMeta = Object.freeze({ vitehubOwnAccess: true });
634
622
  function cloneArray(value) {
635
623
  return Array.isArray(value) ? [...value] : [];
636
624
  }
@@ -658,6 +646,33 @@ function createNitroServerKit(value = {}) {
658
646
  }
659
647
  };
660
648
  }
649
+ //#endregion
650
+ //#region ../internal/src/build/page-tools.ts
651
+ function readString(value, key) {
652
+ const field = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
653
+ return typeof field === "string" ? field : void 0;
654
+ }
655
+ /**
656
+ * The app base of a Vite configuration. ViteHub's application-base config field or `__VITEHUB_APP_BASE_URL__` constant
657
+ * takes precedence over the Vite `base`; the Nuxt module sets both from `app.baseURL`. Only a root-relative Vite `base`
658
+ * supplies an application path; absolute and protocol-relative URLs are asset CDN bases. The Nitro base is
659
+ * `nitro.baseURL`, else `NITRO_APP_BASE_URL`.
660
+ */
661
+ function viteHubPageToolsBase(config, env = process.env) {
662
+ const defined = readString(config !== null && typeof config === "object" ? Reflect.get(config, "define") : void 0, "__VITEHUB_APP_BASE_URL__");
663
+ const viteBase = readString(config, "base");
664
+ let appBase = viteBase?.startsWith("/") && !viteBase.startsWith("//") ? viteBase : void 0;
665
+ if (defined) try {
666
+ const value = JSON.parse(defined);
667
+ if (typeof value === "string") appBase = value;
668
+ } catch {}
669
+ const base = viteHubBasePath(readString(config, "__vitehubAppBaseURL") ?? appBase);
670
+ const nitroBase = viteHubBasePath(readString(config !== null && typeof config === "object" ? Reflect.get(config, "nitro") : void 0, "baseURL") ?? env.NITRO_APP_BASE_URL);
671
+ return {
672
+ base,
673
+ mount: nitroBase && (base === nitroBase || base.startsWith(`${nitroBase}/`)) ? base.slice(nitroBase.length) : base
674
+ };
675
+ }
661
676
  /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
662
677
  function hostFromNitroPreset(value) {
663
678
  const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
@@ -805,7 +820,6 @@ function describePersistence(node) {
805
820
  } else if (node) return "dynamic";
806
821
  return `idle save after ${debounce} ms (at most ${maxWait} ms) and when the last client leaves`;
807
822
  }
808
- /** Reads the static shape of one Realtime Definition file without executing it. */
809
823
  function describeRealtimeDefinitionSource(parse, file, source) {
810
824
  let object;
811
825
  let builder;
@@ -911,7 +925,6 @@ function configureCloudflareRealtime(nitro) {
911
925
  cloudflare.wrangler = wrangler;
912
926
  nitro.cloudflare = cloudflare;
913
927
  }
914
- /** Packages that share the Yjs runtime on the server. They must load as one module graph. */
915
928
  const realtimeServerYjsPackages = [
916
929
  "yjs",
917
930
  "y-protocols",
@@ -934,14 +947,9 @@ function findDatabasePlugin(plugins) {
934
947
  if (found) return found;
935
948
  } else if (plugin && typeof plugin === "object" && "name" in plugin && plugin.name === databaseVitePluginName) return plugin;
936
949
  }
937
- /** Whether the Database integration resolved the Default Database on Postgres. The Postgres bus then uses its client. */
938
950
  function hasPostgresDefaultDatabase(plugin) {
939
951
  return plugin?.api?.getConfig?.()?.databases.default?.dialect === "postgresql";
940
952
  }
941
- /**
942
- * The handler and the Nitro plugin of a Node build. `database` is the module that exports the app's `databases`, when
943
- * the Default Database is on Postgres: the bus then borrows the postgres.js client of that Database.
944
- */
945
953
  function renderNodeFiles(input) {
946
954
  const { busPlugin, database, handlerFile, importBase, namespace, nodeDriver, registryFile } = input;
947
955
  const busOptions = `, { ${database ? `databases: () => import(${JSON.stringify(database)}).then(module => module.databases), ` : ""}namespace: ${JSON.stringify(namespace)} }`;
@@ -970,7 +978,6 @@ function renderNodeFiles(input) {
970
978
  ""
971
979
  ].join("\n")]];
972
980
  }
973
- /** The app name: the `name` in the root `package.json`, else the root folder name. */
974
981
  function defaultNamespace(root) {
975
982
  try {
976
983
  const name = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")).name;
@@ -1127,6 +1134,7 @@ function hubRealtime(options = {}) {
1127
1134
  kit.addHandler({
1128
1135
  handler: handlerFile,
1129
1136
  lazy: true,
1137
+ meta: { ...ownAccessRouteMeta },
1130
1138
  route: `${mount}/_vitehub/realtime/**`
1131
1139
  });
1132
1140
  if (durablePlugin) kit.addPlugin(durablePlugin);
package/dist/vue.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as RealtimeResetReason, C as RealtimeReadOnlyReason, D as RealtimeRequestErrorCode, E as RealtimeRequestError, F as RealtimeUser, L as RealtimeWorkspaceChange, P as RealtimeSaved, d as RealtimeDocumentStatus, f as RealtimeEditor, i as RealtimeCheckpoint, k as RealtimeRequestResult, x as RealtimePerson, z as RealtimeRequestFailure } from "./types-Cvm0G3VJ.js";
2
- import { i as readRealtimeYDoc } from "./document-BfMW1zYU.js";
1
+ import { A as RealtimeResetReason, C as RealtimeReadOnlyReason, D as RealtimeRequestErrorCode, E as RealtimeRequestError, F as RealtimeUser, L as RealtimeWorkspaceChange, P as RealtimeSaved, d as RealtimeDocumentStatus, f as RealtimeEditor, i as RealtimeCheckpoint, k as RealtimeRequestResult, x as RealtimePerson, z as RealtimeRequestFailure } from "./types-DdY7Vo1H.js";
2
+ import { i as readRealtimeYDoc } from "./document-b1ShR2S1.js";
3
3
  import { Awareness } from "y-protocols/awareness";
4
4
  import { WebsocketProvider } from "y-websocket";
5
5
  import * as Y from "yjs";
@@ -60,7 +60,6 @@ export declare function useRealtimeTiptap(definition: string, documentId: MaybeR
60
60
  fields: import("vue").ComputedRef<Y.Map<unknown> | undefined>;
61
61
  people: import("vue").ShallowRef<RealtimePerson[], RealtimePerson[]>;
62
62
  provider: import("vue").ShallowRef<WebsocketProvider | undefined, WebsocketProvider | undefined>;
63
- /** The server rejects edits from this connection. `readOnlyReason` tells why; `saveStatus` holds the details. */
64
63
  readOnly: import("vue").ComputedRef<boolean>;
65
64
  readOnlyReason: Ref<RealtimeReadOnlyReason | null, RealtimeReadOnlyReason | null>;
66
65
  refresh: () => Promise<RealtimeRequestResult<{
package/dist/vue.js CHANGED
@@ -3,7 +3,7 @@ import { n as resolveRealtimeApplicationPath, t as keepRealtimeSocketAlive } fro
3
3
  import { _ as realtimeReadOnlyCode, b as realtimeSyncPendingCode, i as decodeRealtimeControlPayload, l as encodeWorkspaceChange, m as realtimeInvalidDocumentCode, n as isRecord, o as decodeWorkspaceChangePayload, u as isRetryableRealtimeRequestCode, x as workspaceRoomId, y as realtimeSourceChangedCode } from "./object-BgPPDLDE.js";
4
4
  import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
5
5
  import { n as getRealtimePeople, t as createRealtimeIdentity } from "./presence-B6rvkHqd.js";
6
- import { t as createRealtimeEditorExtensions } from "./editor-BM5-vHqf.js";
6
+ import { t as createRealtimeEditorExtensions } from "./editor-IL2jHqn8.js";
7
7
  import { _ as yCursorPlugin, b as yUndoPlugin, f as absolutePositionToRelativePosition, g as undo, h as relativePositionToAbsolutePosition, m as redo, o as readRealtimeYDoc, p as defaultSelectionBuilder, v as ySyncPlugin, x as yUndoPluginKey, y as ySyncPluginKey } from "./document-U5rzg2vG.js";
8
8
  import "lib0/decoding";
9
9
  import * as encoding from "lib0/encoding";
@@ -239,7 +239,6 @@ const RealtimeCaret = Extension.create({
239
239
  });
240
240
  //#endregion
241
241
  //#region src/vue.ts
242
- /** The error for a code that the server put in `data.code` of a refused request, so the app can tell the reasons apart. */
243
242
  function serverRequestError(code, action) {
244
243
  switch (code) {
245
244
  case realtimeInvalidDocumentCode: return realtimeErrorDiagnostics.REALTIME_INVALID_DOCUMENT({ action });
@@ -531,10 +530,6 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
531
530
  if (error) return [error, void 0];
532
531
  return accepts(data) ? [void 0, data] : [realtimeErrorDiagnostics.REALTIME_INVALID_RESPONSE({ action }), void 0];
533
532
  }
534
- /**
535
- * Saves the room through its document adapter now, including every edit this client has sent.
536
- * Returns `[error, saved]`; `error.code` is a `RealtimeRequestErrorCode`; `REALTIME_REQUEST_FAILED` has the HTTP status in `error.data.status`.
537
- */
538
533
  async function save() {
539
534
  if (!enabled()) return [realtimeErrorDiagnostics.REALTIME_DISABLED({ action: "save" }), void 0];
540
535
  saveRequests.value++;
@@ -544,10 +539,6 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
544
539
  saveRequests.value--;
545
540
  }
546
541
  }
547
- /**
548
- * Saves the room and records a durable history entry through the document adapter.
549
- * Returns `[error, checkpoint]`; `error.code` is a `RealtimeRequestErrorCode`; `REALTIME_REQUEST_FAILED` has the HTTP status in `error.data.status`.
550
- */
551
542
  async function checkpoint() {
552
543
  if (!enabled()) return [realtimeErrorDiagnostics.REALTIME_DISABLED({ action: "checkpoint" }), void 0];
553
544
  checkpointRequests.value++;
@@ -557,10 +548,6 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
557
548
  checkpointRequests.value--;
558
549
  }
559
550
  }
560
- /**
561
- * Asks the room to compare its seed with the stored document. A changed source resets every client.
562
- * Returns `[error, result]`; `error.code` is a `RealtimeRequestErrorCode`; `REALTIME_REQUEST_FAILED` has the HTTP status in `error.data.status`.
563
- */
564
551
  async function refresh() {
565
552
  return await requestResult("refresh", isRefreshResult);
566
553
  }
@@ -602,7 +589,6 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
602
589
  fields: computed(() => document.value?.getMap(realtimeDocumentLayout.fields)),
603
590
  people,
604
591
  provider,
605
- /** The server rejects edits from this connection. `readOnlyReason` tells why; `saveStatus` holds the details. */
606
592
  readOnly: computed(() => readOnlyReason.value !== null),
607
593
  readOnlyReason,
608
594
  refresh,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/realtime",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Realtime document primitives and Vite integration for ViteHub.",
5
5
  "keywords": [
6
6
  "collaboration",
@@ -67,6 +67,11 @@
67
67
  "import": "./dist/internal/runtime/unavailable.js",
68
68
  "default": "./dist/internal/runtime/unavailable.js"
69
69
  },
70
+ "./internal/server": {
71
+ "types": "./dist/internal/server.d.ts",
72
+ "import": "./dist/internal/server.js",
73
+ "default": "./dist/internal/server.js"
74
+ },
70
75
  "./server": {
71
76
  "types": "./dist/server.d.ts",
72
77
  "import": "./dist/server.js",
@@ -91,8 +96,8 @@
91
96
  "dependencies": {
92
97
  "@tiptap/extension-collaboration": "^3.31.4",
93
98
  "@tiptap/y-tiptap": "^3.0.9",
94
- "@vite-hub/auth": "0.4.1",
95
- "@vite-hub/workspace": "0.4.1",
99
+ "@vite-hub/auth": "0.5.0",
100
+ "@vite-hub/workspace": "0.5.0",
96
101
  "h3": "^2.0.8",
97
102
  "ioredis": "^5.11.1",
98
103
  "lib0": "^0.2.119",
@@ -105,7 +110,7 @@
105
110
  "prosemirror-view": "^1.42.3",
106
111
  "y-protocols": "^1.0.7",
107
112
  "y-websocket": "^3.1.0",
108
- "@vite-hub/runtime": "0.4.1"
113
+ "@vite-hub/runtime": "0.5.0"
109
114
  },
110
115
  "devDependencies": {
111
116
  "@tiptap/core": "^3.31.4",
@@ -119,7 +124,7 @@
119
124
  "@tiptap/starter-kit": "^3.31.4",
120
125
  "@types/json-schema": "^7.0.15",
121
126
  "@types/node": "^24.19.1",
122
- "@vite-hub/database": "0.4.1",
127
+ "@vite-hub/database": "0.5.0",
123
128
  "@vite-hub/internal": "0.0.1",
124
129
  "happy-dom": "21.0.3",
125
130
  "linkedom": "^0.18.13",