@vite-hub/realtime 0.0.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js CHANGED
@@ -1,12 +1,374 @@
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
2
+ import { o as realtimeNamespaceVariable, s as realtimePostgresUrlVariable } from "./bus-Bi-Ec414.js";
3
+ import { g as realtimeKeepalivePong, h as realtimeKeepalivePing, r as isRecordOrFunction, t as cloneRecord } from "./object-CzKyK0hX.js";
4
+ import availability from "./internal/runtime/unavailable.js";
5
+ import { defineDiagnostics } from "nostics";
6
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
1
7
  import { mkdir, writeFile } from "node:fs/promises";
2
8
  import { basename, dirname, parse, relative, resolve } from "node:path";
3
- import { existsSync, readdirSync, statSync } from "node:fs";
4
- import { relative as relative$1, resolve as resolve$1 } from "pathe";
9
+ import { fileURLToPath } from "node:url";
5
10
  import { tmpdir } from "node:os";
11
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
12
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
13
+ function normalizeWindowsPath(input = "") {
14
+ if (!input) return input;
15
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
16
+ }
17
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
18
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
19
+ function cwd() {
20
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
21
+ return "/";
22
+ }
23
+ const resolve$1 = function(...arguments_) {
24
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
25
+ let resolvedPath = "";
26
+ let resolvedAbsolute = false;
27
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
28
+ const path = index >= 0 ? arguments_[index] : cwd();
29
+ if (!path || path.length === 0) continue;
30
+ resolvedPath = `${path}/${resolvedPath}`;
31
+ resolvedAbsolute = isAbsolute(path);
32
+ }
33
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
34
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
35
+ return resolvedPath.length > 0 ? resolvedPath : ".";
36
+ };
37
+ function normalizeString(path, allowAboveRoot) {
38
+ let res = "";
39
+ let lastSegmentLength = 0;
40
+ let lastSlash = -1;
41
+ let dots = 0;
42
+ let char = null;
43
+ for (let index = 0; index <= path.length; ++index) {
44
+ if (index < path.length) char = path[index];
45
+ else if (char === "/") break;
46
+ else char = "/";
47
+ if (char === "/") {
48
+ if (lastSlash === index - 1 || dots === 1);
49
+ else if (dots === 2) {
50
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
51
+ if (res.length > 2) {
52
+ const lastSlashIndex = res.lastIndexOf("/");
53
+ if (lastSlashIndex === -1) {
54
+ res = "";
55
+ lastSegmentLength = 0;
56
+ } else {
57
+ res = res.slice(0, lastSlashIndex);
58
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
59
+ }
60
+ lastSlash = index;
61
+ dots = 0;
62
+ continue;
63
+ } else if (res.length > 0) {
64
+ res = "";
65
+ lastSegmentLength = 0;
66
+ lastSlash = index;
67
+ dots = 0;
68
+ continue;
69
+ }
70
+ }
71
+ if (allowAboveRoot) {
72
+ res += res.length > 0 ? "/.." : "..";
73
+ lastSegmentLength = 2;
74
+ }
75
+ } else {
76
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
77
+ else res = path.slice(lastSlash + 1, index);
78
+ lastSegmentLength = index - lastSlash - 1;
79
+ }
80
+ lastSlash = index;
81
+ dots = 0;
82
+ } else if (char === "." && dots !== -1) ++dots;
83
+ else dots = -1;
84
+ }
85
+ return res;
86
+ }
87
+ const isAbsolute = function(p) {
88
+ return _IS_ABSOLUTE_RE.test(p);
89
+ };
90
+ const relative$1 = function(from, to) {
91
+ const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
92
+ const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
93
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
94
+ const _fromCopy = [..._from];
95
+ for (const segment of _fromCopy) {
96
+ if (_to[0] !== segment) break;
97
+ _from.shift();
98
+ _to.shift();
99
+ }
100
+ return [..._from.map(() => ".."), ..._to].join("/");
101
+ };
102
+ //#endregion
103
+ //#region ../internal/src/error-diagnostics.ts
104
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
105
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
106
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
107
+ codes: {
108
+ INTERNAL_R0012: {
109
+ ...dynamicError,
110
+ fix: "Check the URL, the headers, and the credentials of the HTTP request. `error.status` holds the status that the server sent."
111
+ },
112
+ INTERNAL_R0013: {
113
+ ...dynamicError,
114
+ fix: "Check that the provider token can manage the resource in the path that the message names. `error.kind` and `error.codes` hold the provider failure."
115
+ },
116
+ INTERNAL_R0014: {
117
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
118
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
119
+ },
120
+ INTERNAL_R0020: {
121
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
122
+ why: ({ message }) => message === void 0 ? "" : String(message)
123
+ },
124
+ INTERNAL_R0021: {
125
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
126
+ why: ({ message }) => message === void 0 ? "" : String(message)
127
+ },
128
+ INTERNAL_R0022: {
129
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
130
+ why: ({ message }) => message === void 0 ? "" : String(message)
131
+ },
132
+ INTERNAL_R0024: {
133
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app and set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key whose public key the app has in VITEHUB_CONSOLE_KEY_<NAME>.",
134
+ why: ({ message }) => message === void 0 ? "" : String(message)
135
+ },
136
+ INTERNAL_R0023: {
137
+ fix: "Ask for access to the section of this operation.",
138
+ why: ({ message }) => message === void 0 ? "" : String(message)
139
+ },
140
+ INTERNAL_B0001: {
141
+ ...dynamicError,
142
+ fix: "Give the resource that the message names another name or binding in the `vitehub()` options of its feature, so that two different Cloudflare resources do not share one name."
143
+ },
144
+ INTERNAL_B0015: {
145
+ ...dynamicError,
146
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
147
+ },
148
+ INTERNAL_B0016: {
149
+ ...dynamicError,
150
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
151
+ },
152
+ INTERNAL_B0017: {
153
+ ...dynamicError,
154
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
155
+ },
156
+ INTERNAL_B0018: {
157
+ ...dynamicError,
158
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
159
+ },
160
+ INTERNAL_B0019: {
161
+ ...dynamicError,
162
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
163
+ },
164
+ INTERNAL_B0020: {
165
+ ...dynamicError,
166
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
167
+ },
168
+ INTERNAL_B0021: {
169
+ ...dynamicError,
170
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
171
+ },
172
+ INTERNAL_B0022: {
173
+ ...dynamicError,
174
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
175
+ },
176
+ INTERNAL_B0025: {
177
+ ...dynamicError,
178
+ fix: "Replace the `new URL(\"./...\", import.meta.url)` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` of that file."
179
+ },
180
+ INTERNAL_B0026: {
181
+ ...dynamicError,
182
+ fix: "Replace the computed `import()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` or with `import(\"<literal path>\")`."
183
+ },
184
+ INTERNAL_B0027: {
185
+ ...dynamicError,
186
+ fix: "Replace the computed `require()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import`."
187
+ },
188
+ INTERNAL_B0028: {
189
+ ...dynamicError,
190
+ fix: "Wait for the other build of this app to finish, or stop the process that the message names, then build again."
191
+ },
192
+ INTERNAL_B0029: {
193
+ ...dynamicError,
194
+ fix: "Stop the other builds that write the same Deno output folder, delete the `.vitehub-lock` folder next to that output folder, such as `.output.vitehub-lock`, then build again."
195
+ },
196
+ INTERNAL_B0031: {
197
+ ...dynamicError,
198
+ fix: "Import `./schedule/deno-cron.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./schedule/deno-cron.mjs\", import.meta.url).href)` outside any condition."
199
+ },
200
+ INTERNAL_B0032: {
201
+ ...dynamicError,
202
+ fix: "Import `./server/index.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./server/index.mjs\", import.meta.url).href)` outside any condition."
203
+ },
204
+ INTERNAL_B0035: {
205
+ ...dynamicError,
206
+ fix: "Delete the provider output folder that holds the file that the message names, such as `dist/<app>` for Cloudflare, and build again."
207
+ },
208
+ INTERNAL_B0039: {
209
+ ...dynamicError,
210
+ fix: "Fix the build error that ViteHub showed before this one. ViteHub stops writing the provider output when another part of the build fails."
211
+ },
212
+ INTERNAL_B0040: {
213
+ ...dynamicError,
214
+ fix: "Remove the custom Nitro `output.serverDir`, so that the Nitro preset of the host writes the server entry that the message names."
215
+ },
216
+ INTERNAL_B0043: {
217
+ ...dynamicError,
218
+ fix: "Delete the build output folder, such as `.output` or `.vercel/output`, and build again."
219
+ },
220
+ INTERNAL_B0046: {
221
+ ...dynamicError,
222
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
223
+ },
224
+ INTERNAL_B0047: {
225
+ ...dynamicError,
226
+ fix: "Correct the `package.json` file that the message names so that it holds one JSON object, or run `pnpm install` again to restore an installed package."
227
+ },
228
+ INTERNAL_B0048: {
229
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
230
+ why: ({ message }) => message === void 0 ? "" : String(message)
231
+ },
232
+ INTERNAL_B0049: {
233
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
234
+ why: ({ message }) => message === void 0 ? "" : String(message)
235
+ },
236
+ INTERNAL_B0050: {
237
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
238
+ why: ({ message }) => message === void 0 ? "" : String(message)
239
+ },
240
+ INTERNAL_B0051: {
241
+ why: ({ field, generated, name, path, project, scope }) => `The Cloudflare ${path} entry "${name}"${scope} is written by ViteHub and by the project's Wrangler config with a different ${field}: ${generated} and ${project}.`,
242
+ fix: "Remove the entry from the project's Wrangler config, since ViteHub writes it, or give one of them another name."
243
+ },
244
+ INTERNAL_B0052: {
245
+ why: ({ column, section }) => `The column "${column}" of the Console section "${section}" needs both \`format: "switch"\` and a \`switch\` operation name such as "skills.set".`,
246
+ fix: "Give a switch column `format: \"switch\"` and `switch: { operation, input }` with a registered operation name, or remove both."
247
+ },
248
+ INTERNAL_R0025: {
249
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
250
+ why: ({ message }) => message === void 0 ? "" : String(message)
251
+ },
252
+ INTERNAL_R0026: {
253
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
254
+ fix: "Review the operation, then run it again with --yes to confirm the change."
255
+ },
256
+ INTERNAL_C0001: {
257
+ ...dynamicError,
258
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
259
+ },
260
+ INTERNAL_C0002: {
261
+ ...dynamicError,
262
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
263
+ },
264
+ INTERNAL_R0001: {
265
+ ...dynamicError,
266
+ fix: "Set `host` in `vitehub()`, or in the `vitehub` options of `nuxt.config.ts`, to `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. Or remove `host` so that ViteHub finds the host from the environment."
267
+ },
268
+ INTERNAL_R0002: {
269
+ ...dynamicError,
270
+ fix: "Stop using the feature that the message names, or set `host` in `vitehub()` to a host that provides it. For Blob, you can also set `blob: { driver: \"s3\" }` with a remote store."
271
+ },
272
+ INTERNAL_R0004: {
273
+ ...dynamicError,
274
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `fetch()` Source options, or ask the server for a smaller response."
275
+ },
276
+ INTERNAL_R0005: {
277
+ ...dynamicError,
278
+ fix: "Set `method` of the HTTP request to `GET`, `HEAD`, or `POST`."
279
+ },
280
+ INTERNAL_R0006: {
281
+ ...dynamicError,
282
+ fix: "Set `timeout` of the HTTP request to a number of milliseconds from 1 to 2147483647, or remove it to use the default."
283
+ },
284
+ INTERNAL_R0007: {
285
+ ...dynamicError,
286
+ fix: "Set `maxResponseBytes` of the HTTP request to a positive integer no greater than the limit that the message names, or remove it to use the default."
287
+ },
288
+ INTERNAL_R0008: {
289
+ ...dynamicError,
290
+ fix: "Make the value that the message names match its schema: the input, query, or body that you send, or the response schema that you declare for the request."
291
+ },
292
+ INTERNAL_R0009: {
293
+ ...dynamicError,
294
+ fix: "Use a Standard Schema whose `validate()` returns `{ value }` or `{ issues }` for the value that the message names."
295
+ },
296
+ INTERNAL_R0010: {
297
+ ...dynamicError,
298
+ fix: "Run the command again. If the error stays, check the Cloudflare API status, because Cloudflare sent a response that ViteHub cannot read."
299
+ },
300
+ INTERNAL_R0011: {
301
+ ...dynamicError,
302
+ fix: "Pass an h3 app, an object with a `fetch(request)` method, or a fetch function as `app`."
303
+ },
304
+ INTERNAL_CONSOLE_KEY_NAME_INVALID: {
305
+ why: ({ name }) => `[vitehub] The Console key name ${JSON.stringify(name)} must be 1 to 64 of A-Z, 0-9, and _.`,
306
+ fix: "Name the Console key with 1 to 64 characters from A-Z, 0-9, and _, such as `CI`. The app reads its public key from `VITEHUB_CONSOLE_KEY_<NAME>`."
307
+ },
308
+ INTERNAL_CONSOLE_PRIVATE_KEY_INVALID: {
309
+ why: "[vitehub] A Console private key is the 32-byte Ed25519 seed as base64url (43 characters). `vitehub secret console-key` makes one.",
310
+ fix: "Run `vitehub secret console-key` and use the 43-character private key that it prints, without spaces or quotes."
311
+ },
312
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE: {
313
+ why: ({ prefix, variables }) => `[vitehub] Set one ${prefix}<NAME> variable. This environment has ${variables}.`,
314
+ fix: "Keep one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable in the environment of the command, and unset the others that the message names."
315
+ },
316
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID: {
317
+ why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
318
+ fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
319
+ },
320
+ INTERNAL_FORGE_NOT_INSTALLED: {
321
+ why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
322
+ fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
323
+ },
324
+ INTERNAL_MCP_ARGUMENTS_INVALID: {
325
+ why: ({ detail }) => detail,
326
+ fix: "Pass the prompt or resource the arguments that `prompts/list` or `resources/templates/list` describes for it."
327
+ },
328
+ INTERNAL_MCP_METHOD_FAILED: {
329
+ why: ({ name }) => `${name} failed on the server.`,
330
+ fix: "Read the server log for the error of the MCP prompt or resource that the message names, and fix its handler."
331
+ },
332
+ INTERNAL_MCP_RESOURCE_NOT_FOUND: {
333
+ why: ({ uri }) => `Resource not found: ${uri}. Call resources/list or resources/templates/list for the resources of this server.`,
334
+ fix: "Call `resources/list` or `resources/templates/list`, and read a URI that one of them returns."
335
+ },
336
+ INTERNAL_PRESET_OPTION_UNKNOWN: {
337
+ why: ({ key, label }) => `[vitehub] Unknown ${label} option "${key}".`,
338
+ fix: "Remove the option that the message names from the preset options, or correct its spelling to an option that the preset declares."
339
+ },
340
+ INTERNAL_PRESET_TUPLE_INVALID: {
341
+ why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
342
+ fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
343
+ },
344
+ INTERNAL_SECRET_PURPOSE_MISSING: {
345
+ why: "[vitehub] A derived secret requires a purpose.",
346
+ fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
347
+ },
348
+ INTERNAL_SECRET_TOO_SHORT: {
349
+ why: ({ minimum }) => `[vitehub] VITEHUB_SECRET must be at least ${minimum} characters. Generate one with \`openssl rand -base64 32\`.`,
350
+ fix: "Set `VITEHUB_SECRET` to the output of `openssl rand -base64 32`, which has 44 characters."
351
+ },
352
+ INTERNAL_SQLITE_ARGUMENT_INVALID: {
353
+ why: ({ value }) => value === "undefined" ? "undefined cannot be passed as argument to the database" : "Only finite numbers (not Infinity or NaN) can be passed as arguments",
354
+ fix: "Pass query arguments as finite numbers, strings, booleans, bigints, dates, byte arrays, or null. Replace undefined with null, and check numbers with `Number.isFinite()` before the query."
355
+ },
356
+ INTERNAL_SQLITE_INTEGER_UNSAFE: {
357
+ why: "Received integer which cannot be safely represented as a JavaScript number",
358
+ fix: "Create the client with `intMode: \"bigint\"` or `intMode: \"string\"`, or read the column with `CAST(column AS TEXT)` in the query."
359
+ },
360
+ INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED: {
361
+ why: ({ target }) => `[vitehub] Valibot cannot convert a schema to the ${target} JSON Schema target.`,
362
+ fix: "Ask for the `draft-07`, `draft-2020-12`, or `openapi-3.0` JSON Schema target, or pass one of them as `withValibotJsonSchema(schema, { target })`."
363
+ }
364
+ }
365
+ });
366
+ //#endregion
6
367
  //#region ../internal/src/definition-catalog.ts
7
368
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
8
369
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
9
- const ignoredDirs = new Set([
370
+ const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
371
+ const ignoredDirs = /* @__PURE__ */ new Set([
10
372
  "node_modules",
11
373
  "dist",
12
374
  ".output",
@@ -51,8 +413,12 @@ function listMatchingFiles(root, predicate, options = {}) {
51
413
  }
52
414
  return files.sort();
53
415
  }
416
+ /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
417
+ function isDefinitionSourceFile(name) {
418
+ return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
419
+ }
54
420
  function listSourceFiles(root, options = {}) {
55
- return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
421
+ return listMatchingFiles(root, isDefinitionSourceFile, options);
56
422
  }
57
423
  function normalizePathDefinitionName(rootDir, file) {
58
424
  return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
@@ -62,7 +428,7 @@ function sortDefinitions(definitions) {
62
428
  }
63
429
  function registerDefinition(definitions, definition, sourceLabel) {
64
430
  const existing = definitions.get(definition.name);
65
- if (existing) throw new Error(`Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}`);
431
+ if (existing) throw internalErrorDiagnostics.INTERNAL_C0001({ message: `Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}` });
66
432
  definitions.set(definition.name, definition);
67
433
  }
68
434
  function mergeDefinitions(feature, ...sources) {
@@ -71,7 +437,7 @@ function mergeDefinitions(feature, ...sources) {
71
437
  if (!source) continue;
72
438
  for (const definition of source) {
73
439
  const existing = definitions.get(definition.name);
74
- if (existing && existing.handler !== definition.handler) throw new Error(`Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})`);
440
+ if (existing && existing.handler !== definition.handler) throw internalErrorDiagnostics.INTERNAL_C0002({ message: `Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})` });
75
441
  if (!existing) definitions.set(definition.name, definition);
76
442
  }
77
443
  }
@@ -90,7 +456,10 @@ function createDefinition(source, file, name) {
90
456
  }
91
457
  function scanSuffixDefinitions(feature, source) {
92
458
  const definitions = /* @__PURE__ */ new Map();
93
- for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => source.pattern.test(name), { includeHidden: source.includeHidden })) {
459
+ for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => {
460
+ source.pattern.lastIndex = 0;
461
+ return source.pattern.test(name);
462
+ }, { includeHidden: source.includeHidden })) {
94
463
  const name = source.normalizeName(root, file);
95
464
  if (!name) continue;
96
465
  registerDefinition(definitions, createDefinition(source, file, name), feature);
@@ -120,34 +489,46 @@ function createRuntimeRegistryContents(registryFile, definitions) {
120
489
  return [
121
490
  "",
122
491
  "const registry = {",
123
- ...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: async () => ${createImportExpression(registryFile, definition.handler)},`),
492
+ ...definitions.map((definition) => ` [${JSON.stringify(definition.name)}]: async () => ${createImportExpression(registryFile, definition.handler)},`),
124
493
  "}",
125
494
  "",
126
495
  "export default registry",
127
496
  ""
128
497
  ].join("\n");
129
498
  }
130
- function deploymentPresetFromNitro(value) {
131
- const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
132
- if (!normalized) return;
133
- if (normalized.startsWith("cloudflare")) return "cloudflare";
134
- if (normalized.startsWith("deno")) return "deno";
135
- if (normalized.startsWith("netlify")) return "netlify";
136
- if (normalized === "node" || normalized.startsWith("node-")) return "node";
137
- if (normalized.startsWith("vercel")) return "vercel";
499
+ //#endregion
500
+ //#region ../internal/src/durability.ts
501
+ /** The `durability` module next to the Vite plugin module at `importMetaUrl`, in source and in `dist`. */
502
+ function durabilityModuleFile(importMetaUrl) {
503
+ return fileURLToPath(new URL(importMetaUrl.endsWith(".ts") ? "./durability.ts" : "./durability.js", importMetaUrl));
138
504
  }
139
505
  //#endregion
140
506
  //#region ../internal/src/build/vite.ts
141
507
  const projectRootDirectoryMarkers = [
142
508
  ["server", "agents"],
143
509
  ["server", "channels"],
510
+ ["server", "connections"],
144
511
  ["server", "browsers"],
145
512
  ["server", "emails"],
146
513
  ["server", "schedules"],
147
514
  ["server", "workspaces"]
148
515
  ];
149
- const projectRootFileMarkers = [["package.json"]];
516
+ const projectRootFileMarkers = [
517
+ ["package.json"],
518
+ ["nuxt.config.ts"],
519
+ ["nuxt.config.mts"],
520
+ ["nuxt.config.js"],
521
+ ["nuxt.config.mjs"]
522
+ ];
523
+ /**
524
+ * Server directories that ViteHub scans for Definitions. The first entry is the application.
525
+ * Later entries are Nuxt layers in Nuxt priority order.
526
+ */
150
527
  const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
528
+ /** Reports a Vite config hook call for a production build. `nuxt prepare` is not a build: it only writes types. */
529
+ function isProductionBuild(config, environment) {
530
+ return environment?.command === "build" && Reflect.get(config, "__vitehubPrepare") !== true;
531
+ }
151
532
  function resolveViteHubProjectRoot(root, options = {}) {
152
533
  const resolvedRoot = resolve(root);
153
534
  const temporaryRoot = resolve(tmpdir());
@@ -155,7 +536,12 @@ function resolveViteHubProjectRoot(root, options = {}) {
155
536
  if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
156
537
  if (basename(resolvedRoot) === "app") {
157
538
  const parent = dirname(resolvedRoot);
158
- if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
539
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
540
+ "nuxt.config.ts",
541
+ "nuxt.config.mts",
542
+ "nuxt.config.js",
543
+ "nuxt.config.mjs"
544
+ ]))) return parent;
159
545
  }
160
546
  let current = resolvedRoot;
161
547
  while (true) {
@@ -176,18 +562,154 @@ function hasProjectRootDirectoryMarker(root) {
176
562
  }
177
563
  function hasProjectRootMarker(root) {
178
564
  if (hasProjectRootDirectoryMarker(root)) return true;
179
- for (const marker of projectRootFileMarkers) try {
180
- if (statSync(resolve(root, ...marker)).isFile()) return true;
181
- } catch (error) {
182
- if (error.code !== "ENOENT") throw error;
565
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
566
+ }
567
+ function hasProjectRootFileMarker(root, markers) {
568
+ for (const marker of markers) {
569
+ const path = Array.isArray(marker) ? marker : [marker];
570
+ try {
571
+ if (statSync(resolve(root, ...path)).isFile()) return true;
572
+ } catch (error) {
573
+ if (error.code !== "ENOENT") throw error;
574
+ }
183
575
  }
184
576
  return false;
185
577
  }
578
+ /**
579
+ * The path of an app base, without the trailing slash: `/portal/` and `https://cdn.example/portal/` give `/portal`.
580
+ * The root and relative bases (`""`, `"./"`) give `""`. The Console mounts its routes with the same rule.
581
+ */
582
+ function viteHubBasePath(base) {
583
+ if (!base || base === "./") return "";
584
+ let pathname = base;
585
+ if (/^https?:\/\//.test(pathname)) try {
586
+ pathname = new URL(pathname).pathname;
587
+ } catch {
588
+ return "";
589
+ }
590
+ if (!pathname.startsWith("/") || pathname.startsWith("//")) return "";
591
+ return pathname.replace(/\/+$/, "");
592
+ }
593
+ //#endregion
594
+ //#region ../internal/src/build/page-tools.ts
595
+ function readString(value, key) {
596
+ const field = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
597
+ return typeof field === "string" ? field : void 0;
598
+ }
599
+ /**
600
+ * The app base of a Vite configuration. ViteHub's application-base config field or `__VITEHUB_APP_BASE_URL__` constant
601
+ * takes precedence over the Vite `base`; the Nuxt module sets both from `app.baseURL`. Only a root-relative Vite `base`
602
+ * supplies an application path; absolute and protocol-relative URLs are asset CDN bases. The Nitro base is
603
+ * `nitro.baseURL`, else `NITRO_APP_BASE_URL`.
604
+ */
605
+ function viteHubPageToolsBase(config, env = process.env) {
606
+ const defined = readString(config !== null && typeof config === "object" ? Reflect.get(config, "define") : void 0, "__VITEHUB_APP_BASE_URL__");
607
+ const viteBase = readString(config, "base");
608
+ let appBase = viteBase?.startsWith("/") && !viteBase.startsWith("//") ? viteBase : void 0;
609
+ if (defined) try {
610
+ const value = JSON.parse(defined);
611
+ if (typeof value === "string") appBase = value;
612
+ } catch {}
613
+ const base = viteHubBasePath(readString(config, "__vitehubAppBaseURL") ?? appBase);
614
+ const nitroBase = viteHubBasePath(readString(config !== null && typeof config === "object" ? Reflect.get(config, "nitro") : void 0, "baseURL") ?? env.NITRO_APP_BASE_URL);
615
+ return {
616
+ base,
617
+ mount: nitroBase && (base === nitroBase || base.startsWith(`${nitroBase}/`)) ? base.slice(nitroBase.length) : base
618
+ };
619
+ }
620
+ //#endregion
621
+ //#region ../internal/src/nitro-kit.ts
622
+ function cloneArray(value) {
623
+ return Array.isArray(value) ? [...value] : [];
624
+ }
625
+ function sameHandler(left, right) {
626
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
627
+ }
628
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
629
+ function createNitroServerKit(value = {}) {
630
+ const config = isRecordOrFunction(value) ? { ...value } : {};
631
+ const handlers = cloneArray(config.handlers);
632
+ const plugins = cloneArray(config.plugins);
633
+ config.handlers = handlers;
634
+ config.plugins = plugins;
635
+ return {
636
+ config,
637
+ addHandler(handler, position = "end") {
638
+ if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
639
+ if (position === "start") handlers.unshift({ ...handler });
640
+ else handlers.push({ ...handler });
641
+ },
642
+ addPlugin(plugin, position = "end") {
643
+ if (plugins.includes(plugin)) return;
644
+ if (position === "start") plugins.unshift(plugin);
645
+ else plugins.push(plugin);
646
+ }
647
+ };
648
+ }
649
+ /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
650
+ function hostFromNitroPreset(value) {
651
+ const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
652
+ if (!normalized) return;
653
+ if (normalized.startsWith("cloudflare")) return "cloudflare";
654
+ if (normalized.startsWith("deno")) return "deno";
655
+ if (normalized.startsWith("netlify")) return "netlify";
656
+ if (normalized === "node" || normalized.startsWith("node-")) return "node";
657
+ if (normalized.startsWith("vercel")) return "vercel";
658
+ }
186
659
  //#endregion
187
660
  //#region ../internal/src/hosting.ts
661
+ /**
662
+ * Returns the Nitro preset name that this build targets, as the developer wrote it.
663
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOST`.
664
+ * Empty values are skipped.
665
+ */
666
+ function resolveHostPreset(input = {}) {
667
+ const env = input.env ?? (typeof process === "undefined" ? {} : process.env);
668
+ const nitroPreset = input.nitro && typeof input.nitro === "object" ? Reflect.get(input.nitro, "preset") : void 0;
669
+ for (const value of [
670
+ nitroPreset,
671
+ input.hosting,
672
+ env.NITRO_PRESET,
673
+ env.SERVER_PRESET,
674
+ env.VITEHUB_HOST
675
+ ]) if (typeof value === "string" && value.trim()) return value.trim();
676
+ }
677
+ /** Returns the host that this build targets: `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. */
678
+ function resolveHost(input = {}) {
679
+ return hostFromNitroPreset(resolveHostPreset(input));
680
+ }
681
+ /** Narrows a ViteHub host or Nitro preset name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
188
682
  function getHostingProvider(hosting) {
189
- const preset = deploymentPresetFromNitro(hosting);
190
- if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
683
+ const host = hostFromNitroPreset(hosting);
684
+ if (host === "cloudflare" || host === "netlify" || host === "vercel") return host;
685
+ }
686
+ //#endregion
687
+ //#region src/deployment-env.ts
688
+ const owners = ["realtime"];
689
+ function entry(names, required, secret, hasDefault = false) {
690
+ return {
691
+ names,
692
+ required,
693
+ secret,
694
+ hasDefault,
695
+ owners
696
+ };
697
+ }
698
+ /**
699
+ * The variables that Realtime reads on the deployed host. A Node server picks its bus at boot: `REDIS_URL`, then
700
+ * `REALTIME_POSTGRES_URL`, then a Postgres Default Database, else memory. An explicit `redis` or `postgres` driver
701
+ * requires its connection. `REALTIME_NAMESPACE` is optional. Durable Objects on Cloudflare and `memory` read none.
702
+ */
703
+ function realtimeDeploymentEnv(input, context) {
704
+ if (context.host !== "node" || input.driver === "cloudflare" || input.driver === "memory") return [];
705
+ const namespace = entry([realtimeNamespaceVariable], false, false, true);
706
+ if (input.driver === "redis") return [entry(["REDIS_URL"], true, true), namespace];
707
+ const postgres = entry([realtimePostgresUrlVariable], input.driver === "postgres" && !input.postgresDatabase, true, input.postgresDatabase);
708
+ return input.driver === "postgres" ? [postgres, namespace] : [
709
+ entry(["REDIS_URL"], false, true),
710
+ postgres,
711
+ namespace
712
+ ];
191
713
  }
192
714
  //#endregion
193
715
  //#region src/discovery.ts
@@ -202,22 +724,181 @@ function discoverRealtimeDefinitions(rootDir, serverDirs) {
202
724
  })]);
203
725
  }
204
726
  //#endregion
727
+ //#region ../internal/src/inspect.ts
728
+ function relativeDefinitionFile(projectRoot, file) {
729
+ return relative$1(projectRoot, file).replaceAll("\\", "/");
730
+ }
731
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
732
+ new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
733
+ new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
734
+ //#endregion
735
+ //#region src/inspect.ts
736
+ const driverLabels = {
737
+ auto: "auto: Cloudflare Durable Objects on Cloudflare, memory in development, shared rooms on a Node server, build error elsewhere",
738
+ cloudflare: "cloudflare: one Durable Object per document, Yjs state in SQLite",
739
+ memory: "memory: one Node process, rooms lost on restart",
740
+ node: "auto on Node: picked when the server starts. Redis with REDIS_URL, else Postgres on the Default Database or REALTIME_POSTGRES_URL, else memory in one process",
741
+ postgres: "postgres: a room in each Node instance, shared through Postgres LISTEN/NOTIFY on the Default Database or REALTIME_POSTGRES_URL",
742
+ redis: "redis: a room in each Node instance, shared through Redis pub/sub (REDIS_URL)",
743
+ unsupported: "none: this host has no Realtime driver"
744
+ };
745
+ function propertyName(property) {
746
+ if (property.type !== "Property") return;
747
+ const key = property.key;
748
+ if (key.type === "Identifier") return key.name;
749
+ if (key.type === "Literal" && typeof key.value === "string") return key.value;
750
+ }
751
+ function findDefinitionObject(program) {
752
+ for (const statement of program.body) {
753
+ if (statement.type !== "ExportDefaultDeclaration") continue;
754
+ let node = statement.declaration;
755
+ if (node.type === "CallExpression" && node.arguments[0]?.type === "ObjectExpression") node = node.arguments[0];
756
+ if (node.type === "ObjectExpression") return node;
757
+ }
758
+ }
759
+ function properties(object) {
760
+ const values = /* @__PURE__ */ new Map();
761
+ for (const property of object.properties) {
762
+ const name = propertyName(property);
763
+ if (name && property.type === "Property") values.set(name, property.value);
764
+ }
765
+ return values;
766
+ }
767
+ function literal(node) {
768
+ return node?.type === "Literal" ? node.value : void 0;
769
+ }
770
+ function calleeName(node) {
771
+ if (node.type !== "CallExpression") return;
772
+ if (node.callee.type === "Identifier") return node.callee.name;
773
+ if (node.callee.type === "MemberExpression" && node.callee.property.type === "Identifier") return node.callee.property.name;
774
+ }
775
+ function describeDocument(node) {
776
+ if (!node) return "missing";
777
+ if (node.type === "ObjectExpression") {
778
+ const values = properties(node);
779
+ const workspace = literal(values.get("workspace"));
780
+ if (typeof workspace === "string") return `Workspace ${JSON.stringify(workspace)} (Markdown file per path)`;
781
+ if (values.has("load") && values.has("save")) return "custom adapter (inline load/save)";
782
+ }
783
+ const callee = calleeName(node);
784
+ if (callee === "workspaceDocument") {
785
+ const argument = node.type === "CallExpression" ? node.arguments[0] : void 0;
786
+ const name = argument && argument.type !== "SpreadElement" ? literal(argument) : void 0;
787
+ return typeof name === "string" ? `Workspace ${JSON.stringify(name)} (Markdown file per path)` : "Workspace (dynamic name)";
788
+ }
789
+ if (callee) return `custom adapter (${callee}())`;
790
+ if (node.type === "Identifier") return `custom adapter (${node.name})`;
791
+ return "custom adapter";
792
+ }
793
+ function describePersistence(node) {
794
+ if (literal(node) === false) return "explicit saves only";
795
+ let debounce = String(2e3);
796
+ let maxWait = String(1e4);
797
+ if (node?.type === "ObjectExpression") {
798
+ const values = properties(node);
799
+ if (values.has("debounce")) debounce = String(literal(values.get("debounce")) ?? "dynamic");
800
+ if (values.has("maxWait")) maxWait = String(literal(values.get("maxWait")) ?? "dynamic");
801
+ } else if (node) return "dynamic";
802
+ return `idle save after ${debounce} ms (at most ${maxWait} ms) and when the last client leaves`;
803
+ }
804
+ /** Reads the static shape of one Realtime Definition file without executing it. */
805
+ function describeRealtimeDefinitionSource(parse, file, source) {
806
+ let object;
807
+ let builder;
808
+ try {
809
+ const program = parse(file, source).program;
810
+ object = findDefinitionObject(program);
811
+ const exported = program.body.find((statement) => statement.type === "ExportDefaultDeclaration");
812
+ builder = exported?.type === "ExportDefaultDeclaration" ? calleeName(exported.declaration) : void 0;
813
+ } catch {}
814
+ if (!object) return [{
815
+ label: "Document",
816
+ value: builder && builder !== "defineRealtime" ? `built by ${builder}() (not statically inspectable)` : "dynamic definition (not statically inspectable)"
817
+ }];
818
+ const values = properties(object);
819
+ const editor = values.get("editor");
820
+ const auth = literal(values.get("auth")) === true;
821
+ const publicAccess = literal(values.get("access")) === "public";
822
+ const authorization = (rule) => values.has("authorize") ? rule : publicAccess ? "public: anyone may read and write" : auth ? "every identified user" : "missing: the server rejects this definition";
823
+ const perDocument = editor?.type === "ArrowFunctionExpression" || editor?.type === "FunctionExpression";
824
+ const identity = {
825
+ label: "Identity",
826
+ value: values.has("identify") ? `identify()${auth ? ", required" : ""}` : auth ? "ViteHub Auth session, required" : "anonymous; presence names are client-asserted"
827
+ };
828
+ if (literal(values.get("document")) === false) return [
829
+ {
830
+ label: "Document",
831
+ value: "none: presence only, nothing stored"
832
+ },
833
+ identity,
834
+ {
835
+ label: "Authorization",
836
+ value: authorization("authorize() per room, read only")
837
+ }
838
+ ];
839
+ return [
840
+ {
841
+ label: "Document",
842
+ value: describeDocument(values.get("document"))
843
+ },
844
+ {
845
+ label: "Editor",
846
+ value: editor ? perDocument ? "custom codec per document" : `custom codec${editor.type === "Identifier" ? ` (${editor.name})` : ""}` : "built-in Markdown kit"
847
+ },
848
+ identity,
849
+ {
850
+ label: "Authorization",
851
+ value: authorization("authorize() per document and mode")
852
+ },
853
+ {
854
+ label: "Persistence",
855
+ value: describePersistence(values.get("persistence"))
856
+ },
857
+ {
858
+ label: "History",
859
+ value: values.has("history") ? "history.checkpoint() enabled" : "none"
860
+ }
861
+ ];
862
+ }
863
+ async function summarizeRealtimeDefinitions(projectRoot, definitions, driver) {
864
+ const { parseSync } = await import("vite");
865
+ return definitions.map((definition) => {
866
+ let source = "";
867
+ try {
868
+ source = readFileSync(definition.handler, "utf8");
869
+ } catch {}
870
+ return {
871
+ fields: [...describeRealtimeDefinitionSource(parseSync, definition.handler, source), {
872
+ label: "Driver",
873
+ value: driverLabels[driver]
874
+ }],
875
+ file: relativeDefinitionFile(projectRoot, definition.handler),
876
+ name: definition.name,
877
+ source: definition.source
878
+ };
879
+ });
880
+ }
881
+ //#endregion
205
882
  //#region src/vite.ts
206
- function record(value) {
207
- return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
883
+ /**
884
+ * Lists Realtime Definitions with their document adapter, editor codec, identity, authorization,
885
+ * persistence, and driver, read statically from each definition file.
886
+ */
887
+ async function inspectRealtimeDefinitions(options) {
888
+ return await summarizeRealtimeDefinitions(options.projectRoot, [...discoverRealtimeDefinitions(options.projectRoot, options.serverDirs), ...options.contributed ?? []], options.driver ?? "auto");
208
889
  }
209
890
  function configureCloudflareRealtime(nitro) {
210
- nitro.preset = "cloudflare-durable";
211
- const cloudflare = record(nitro.cloudflare);
212
- const wrangler = record(cloudflare.wrangler);
213
- const durableObjects = record(wrangler.durable_objects);
891
+ nitro.preset = "cloudflare-module";
892
+ const cloudflare = cloneRecord(nitro.cloudflare);
893
+ const wrangler = cloneRecord(cloudflare.wrangler);
894
+ const durableObjects = cloneRecord(wrangler.durable_objects);
214
895
  const bindings = Array.isArray(durableObjects.bindings) ? durableObjects.bindings : [];
215
- if (!bindings.some((binding) => record(binding).name === "$DurableObject")) durableObjects.bindings = [...bindings, {
896
+ if (!bindings.some((binding) => cloneRecord(binding).name === "$DurableObject")) durableObjects.bindings = [...bindings, {
216
897
  class_name: "$DurableObject",
217
898
  name: "$DurableObject"
218
899
  }];
219
900
  const migrations = Array.isArray(wrangler.migrations) ? wrangler.migrations : [];
220
- if (!migrations.some((migration) => record(migration).tag === "vitehub-realtime-v1")) wrangler.migrations = [...migrations, {
901
+ if (!migrations.some((migration) => cloneRecord(migration).tag === "vitehub-realtime-v1")) wrangler.migrations = [...migrations, {
221
902
  new_sqlite_classes: ["$DurableObject"],
222
903
  tag: "vitehub-realtime-v1"
223
904
  }];
@@ -225,6 +906,15 @@ function configureCloudflareRealtime(nitro) {
225
906
  cloudflare.wrangler = wrangler;
226
907
  nitro.cloudflare = cloudflare;
227
908
  }
909
+ /** Packages that share the Yjs runtime on the server. They must load as one module graph. */
910
+ const realtimeServerYjsPackages = [
911
+ "yjs",
912
+ "y-protocols",
913
+ "lib0",
914
+ "@tiptap/y-tiptap",
915
+ /^y-protocols\//,
916
+ /^lib0\//
917
+ ];
228
918
  function moduleSpecifier(from, to) {
229
919
  const value = relative(dirname(from), to).replaceAll("\\", "/");
230
920
  return value.startsWith(".") ? value : `./${value}`;
@@ -232,55 +922,240 @@ function moduleSpecifier(from, to) {
232
922
  function applicationBaseURL(base) {
233
923
  return base?.startsWith("/") && !base.startsWith("//") ? base : "/";
234
924
  }
925
+ const databaseVitePluginName = "@vite-hub/database/vite";
926
+ function findDatabasePlugin(plugins) {
927
+ for (const plugin of plugins ?? []) if (Array.isArray(plugin)) {
928
+ const found = findDatabasePlugin(plugin);
929
+ if (found) return found;
930
+ } else if (plugin && typeof plugin === "object" && "name" in plugin && plugin.name === databaseVitePluginName) return plugin;
931
+ }
932
+ /** Whether the Database integration resolved the Default Database on Postgres. The Postgres bus then uses its client. */
933
+ function hasPostgresDefaultDatabase(plugin) {
934
+ return plugin?.api?.getConfig?.()?.databases.default?.dialect === "postgresql";
935
+ }
936
+ /**
937
+ * The handler and the Nitro plugin of a Node build. `database` is the module that exports the app's `databases`, when
938
+ * the Default Database is on Postgres: the bus then borrows the postgres.js client of that Database.
939
+ */
940
+ function renderNodeFiles(input) {
941
+ const { busPlugin, database, handlerFile, importBase, namespace, nodeDriver, registryFile } = input;
942
+ const busOptions = `, { ${database ? `databases: () => import(${JSON.stringify(database)}).then(module => module.databases), ` : ""}namespace: ${JSON.stringify(namespace)} }`;
943
+ const logOptions = `{ ${database ? "database: true, " : ""}namespace: ${JSON.stringify(namespace)} }`;
944
+ const handler = [
945
+ `import registry from ${JSON.stringify(moduleSpecifier(handlerFile, registryFile))}`,
946
+ `import { createRealtimeHandler } from ${JSON.stringify(`${importBase}/server`)}`,
947
+ ...nodeDriver ? [
948
+ `import { useRealtimeBus } from ${JSON.stringify(`${importBase}/bus`)}`,
949
+ "",
950
+ "// Shares rooms with the other instances of this app. The server picks the bus when it starts.",
951
+ `export default createRealtimeHandler(registry, { bus: () => useRealtimeBus(${JSON.stringify(nodeDriver)}${busOptions}) })`
952
+ ] : ["", "export default createRealtimeHandler(registry)"],
953
+ ""
954
+ ].join("\n");
955
+ if (!busPlugin || !nodeDriver) return [[handlerFile, handler]];
956
+ return [[handlerFile, handler], [busPlugin, [
957
+ `import { closeRealtimeBuses, logRealtimeNodeDriver } from ${JSON.stringify(`${importBase}/bus`)}`,
958
+ "",
959
+ "export default (nitroApp) => {",
960
+ " // Prints where the rooms of this server live.",
961
+ ` logRealtimeNodeDriver(${JSON.stringify(nodeDriver)}, ${logOptions})`,
962
+ " // Removes this instance's presence from the other instances, and lets the process exit. A borrowed Database client stays open.",
963
+ " nitroApp.hooks.hook(\"close\", () => closeRealtimeBuses())",
964
+ "}",
965
+ ""
966
+ ].join("\n")]];
967
+ }
968
+ /** The app name: the `name` in the root `package.json`, else the root folder name. */
969
+ function defaultNamespace(root) {
970
+ try {
971
+ const name = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")).name;
972
+ if (typeof name === "string" && name.trim()) return name.trim();
973
+ } catch {}
974
+ return basename(root) || "default";
975
+ }
976
+ const realtimeAvailabilityId = "#vitehub/realtime/availability";
977
+ const resolvedRealtimeAvailabilityId = `\0${realtimeAvailabilityId}`;
235
978
  function hubRealtime(options = {}) {
979
+ if (options.driver === void 0 && Object.hasOwn(options, "authority")) {
980
+ const authority = options.authority;
981
+ throw realtimeErrorDiagnostics.REALTIME_RENAMED_AUTHORITY_KEY({ value: JSON.stringify(authority) ?? String(authority) });
982
+ }
236
983
  const importBase = options.importBase ?? "@vite-hub/realtime";
984
+ let inspectionRoot;
985
+ let inspectionServerDirs;
986
+ let inspectionDriver = options.driver ?? "auto";
987
+ let inspectionContributed = [];
988
+ let hasRoomDriver = false;
989
+ const databaseImport = options.databaseImport ?? "@vite-hub/database/drizzle";
990
+ let databasePlugin;
991
+ let postgresDatabase = false;
992
+ let nodeWrite;
237
993
  return {
238
994
  name: "@vite-hub/realtime/vite",
239
995
  enforce: "pre",
996
+ api: { deploymentEnv: (context) => hasRoomDriver ? realtimeDeploymentEnv({
997
+ driver: options.driver ?? "auto",
998
+ postgresDatabase
999
+ }, context) : [] },
1000
+ vitehub: {
1001
+ durability: () => hasRoomDriver ? [{
1002
+ export: "realtimeDurability",
1003
+ input: { driver: inspectionDriver },
1004
+ module: durabilityModuleFile(import.meta.url),
1005
+ primitive: "realtime"
1006
+ }] : [],
1007
+ inspect: () => ({ definitions: [{
1008
+ kind: "realtime",
1009
+ label: "Realtime",
1010
+ list: () => inspectRealtimeDefinitions({
1011
+ driver: inspectionDriver,
1012
+ projectRoot: inspectionRoot ?? resolveViteHubProjectRoot(process.cwd(), options),
1013
+ serverDirs: inspectionServerDirs,
1014
+ contributed: inspectionContributed
1015
+ })
1016
+ }] })
1017
+ },
240
1018
  async config(config, environment) {
241
1019
  const root = resolveViteHubProjectRoot(resolve(config.root || process.cwd()), options);
242
1020
  const serverDirs = config[VITEHUB_SERVER_DIRS];
243
- const definitions = discoverRealtimeDefinitions(root, serverDirs);
1021
+ inspectionRoot = root;
1022
+ inspectionServerDirs = serverDirs;
1023
+ const discovered = discoverRealtimeDefinitions(root, serverDirs);
1024
+ const nitro = { ...config.nitro };
1025
+ const host = resolveHost({ nitro });
1026
+ const provider = getHostingProvider(host);
1027
+ const driver = options.driver || "auto";
1028
+ const directory = resolve(root, ".vitehub/nitro/realtime");
1029
+ const build = isProductionBuild(config, environment);
1030
+ const node = !host || host === "node";
1031
+ const nodeDriver = !build || !node ? void 0 : driver === "postgres" || driver === "redis" ? driver : driver === "auto" && provider !== "cloudflare" ? "auto" : void 0;
1032
+ const available = driver === "cloudflare" ? !host || host === "cloudflare" ? "cloudflare" : void 0 : driver === "auto" && provider === "cloudflare" ? "cloudflare" : driver !== "auto" ? node ? "memory" : void 0 : !build || nodeDriver ? "memory" : void 0;
1033
+ hasRoomDriver = Boolean(available);
1034
+ const contribution = available && options.contribute ? await options.contribute({
1035
+ driver: available,
1036
+ directory,
1037
+ projectRoot: root,
1038
+ serverDirs
1039
+ }) : void 0;
1040
+ const definitions = [...discovered, ...(contribution?.definitions ?? []).filter((definition) => !discovered.some((entry) => entry.name === definition.name)).map((definition) => ({
1041
+ ...definition,
1042
+ source: "contributed"
1043
+ }))];
1044
+ inspectionContributed = definitions.filter((definition) => definition.source === "contributed");
244
1045
  if (definitions.length === 0) return;
245
1046
  config.resolve = {
246
1047
  ...config.resolve,
247
- dedupe: [...new Set([...config.resolve?.dedupe || [], "yjs"])]
1048
+ dedupe: [.../* @__PURE__ */ new Set([...config.resolve?.dedupe || [], "yjs"])]
248
1049
  };
1050
+ const environments = { ...config.environments };
1051
+ const nitroEnvironment = { ...environments.nitro };
1052
+ const nitroResolve = { ...nitroEnvironment.resolve };
1053
+ const noExternal = nitroResolve.noExternal;
1054
+ if (noExternal !== true) {
1055
+ nitroResolve.noExternal = [...Array.isArray(noExternal) ? noExternal : noExternal ? [noExternal] : [], ...realtimeServerYjsPackages];
1056
+ nitroEnvironment.resolve = nitroResolve;
1057
+ environments.nitro = nitroEnvironment;
1058
+ config.environments = environments;
1059
+ }
249
1060
  config.define = {
250
1061
  __VITEHUB_APP_BASE_URL__: JSON.stringify(applicationBaseURL(config.base)),
251
1062
  ...config.define
252
1063
  };
253
- const directory = resolve(root, ".vitehub/nitro/realtime");
254
1064
  const registryFile = resolve(directory, "registry.mjs");
255
1065
  const handlerFile = resolve(directory, "handler.ts");
1066
+ const busPlugin = nodeDriver ? resolve(directory, "bus.mjs") : void 0;
1067
+ databasePlugin = findDatabasePlugin(config.plugins) ?? databasePlugin;
1068
+ postgresDatabase = !!nodeDriver && hasPostgresDefaultDatabase(databasePlugin);
1069
+ const namespace = options.namespace?.trim() || defaultNamespace(root);
1070
+ const nodeFiles = (files) => renderNodeFiles({
1071
+ ...files,
1072
+ database: postgresDatabase ? databaseImport : void 0,
1073
+ importBase,
1074
+ namespace,
1075
+ nodeDriver
1076
+ });
1077
+ nodeWrite = nodeDriver ? {
1078
+ busPlugin,
1079
+ handlerFile,
1080
+ namespace,
1081
+ nodeDriver,
1082
+ postgres: postgresDatabase,
1083
+ registryFile
1084
+ } : void 0;
256
1085
  await mkdir(directory, { recursive: true });
257
- await Promise.all([writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions)), writeFile(handlerFile, [
258
- `import registry from ${JSON.stringify(moduleSpecifier(handlerFile, registryFile))}`,
259
- `import { createRealtimeHandler } from ${JSON.stringify(`${importBase}/server`)}`,
260
- "",
261
- "export default createRealtimeHandler(registry)",
262
- ""
263
- ].join("\n"))]);
264
- const nitro = { ...config.nitro || {} };
265
- const configuredPreset = nitro.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING;
266
- const deploymentPreset = deploymentPresetFromNitro(configuredPreset);
267
- const provider = getHostingProvider(configuredPreset);
268
- const authority = options.authority || "auto";
269
- if (authority === "cloudflare" && deploymentPreset && deploymentPreset !== "cloudflare") throw new Error(`[vitehub] Realtime authority "cloudflare" conflicts with the ${deploymentPreset} deployment preset.`);
270
- if (authority === "cloudflare" || authority === "auto" && provider === "cloudflare") configureCloudflareRealtime(nitro);
271
- else if (environment?.command === "build" && authority === "auto") throw new Error("[vitehub] Realtime production builds require one room authority. Deploy to Cloudflare Durable Objects or explicitly set realtime.authority to \"memory\" for a single-process server.");
272
- else if (authority === "memory" && deploymentPreset && deploymentPreset !== "node") throw new Error(`[vitehub] Realtime authority "memory" is single-process only and cannot use the ${deploymentPreset} deployment preset.`);
1086
+ await Promise.all([writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions)), ...nodeFiles({
1087
+ busPlugin,
1088
+ handlerFile,
1089
+ registryFile
1090
+ }).map(([file, contents]) => writeFile(file, contents))]);
1091
+ if (driver === "cloudflare" && host && host !== "cloudflare") throw realtimeErrorDiagnostics.REALTIME_DRIVER_CONFLICT({
1092
+ driver: "cloudflare",
1093
+ host
1094
+ });
1095
+ let durablePlugin;
1096
+ if (driver === "cloudflare" || driver === "auto" && provider === "cloudflare") {
1097
+ inspectionDriver = "cloudflare";
1098
+ configureCloudflareRealtime(nitro);
1099
+ durablePlugin = resolve(directory, "durable-object.mjs");
1100
+ await writeFile(durablePlugin, [
1101
+ "export default (nitroApp) => {",
1102
+ " nitroApp.hooks.hook(\"cloudflare:durable:init\", (_durable, { state }) => {",
1103
+ " // Answer the clients' keepalive without waking the Durable Object from hibernation.",
1104
+ ` if (typeof WebSocketRequestResponsePair === "function") state.setWebSocketAutoResponse(new WebSocketRequestResponsePair(${JSON.stringify(realtimeKeepalivePing)}, ${JSON.stringify(realtimeKeepalivePong)}))`,
1105
+ " })",
1106
+ "}",
1107
+ ""
1108
+ ].join("\n"));
1109
+ } else if (build && driver === "auto" && !nodeDriver) throw realtimeErrorDiagnostics.REALTIME_MISSING_DRIVER();
1110
+ else if (driver !== "auto" && !node && host) throw realtimeErrorDiagnostics.REALTIME_DRIVER_CONFLICT({
1111
+ driver,
1112
+ host
1113
+ });
1114
+ if (nodeDriver) inspectionDriver = nodeDriver === "auto" ? "node" : nodeDriver;
1115
+ else if (driver === "memory" || driver === "postgres" || driver === "redis" || driver === "auto" && !build && inspectionDriver !== "cloudflare") inspectionDriver = "memory";
273
1116
  nitro.features = {
274
1117
  ...nitro.features,
275
1118
  websocket: true
276
1119
  };
277
- nitro.handlers = [...nitro.handlers || [], {
1120
+ const kit = createNitroServerKit(nitro);
1121
+ const { mount } = viteHubPageToolsBase(config);
1122
+ kit.addHandler({
278
1123
  handler: handlerFile,
279
- route: "/api/_vitehub/realtime/**"
280
- }];
1124
+ lazy: true,
1125
+ route: `${mount}/api/_vitehub/realtime/**`
1126
+ });
1127
+ if (durablePlugin) kit.addPlugin(durablePlugin);
1128
+ if (busPlugin) kit.addPlugin(busPlugin);
1129
+ for (const plugin of contribution?.plugins ?? []) kit.addPlugin(plugin);
1130
+ Object.assign(nitro, kit.config);
281
1131
  config.nitro = nitro;
1132
+ },
1133
+ async buildStart() {
1134
+ const databaseConfig = databasePlugin?.api?.getConfig?.();
1135
+ if (!databaseConfig || !nodeWrite) return;
1136
+ postgresDatabase = databaseConfig.databases.default?.dialect === "postgresql";
1137
+ if (nodeWrite.postgres === postgresDatabase) return;
1138
+ nodeWrite.postgres = postgresDatabase;
1139
+ const files = renderNodeFiles({
1140
+ ...nodeWrite,
1141
+ database: postgresDatabase ? databaseImport : void 0,
1142
+ importBase
1143
+ });
1144
+ await Promise.all(files.map(([file, contents]) => writeFile(file, contents)));
1145
+ },
1146
+ resolveId: {
1147
+ filter: { id: /^#vitehub\/realtime\/availability$/ },
1148
+ handler(id) {
1149
+ if (id === realtimeAvailabilityId) return resolvedRealtimeAvailabilityId;
1150
+ }
1151
+ },
1152
+ load: {
1153
+ filter: { id: /^\0#vitehub\/realtime\/availability$/ },
1154
+ handler(id) {
1155
+ if (id === resolvedRealtimeAvailabilityId) return hasRoomDriver ? "export default { available: true }\n" : `export default ${JSON.stringify(availability)}\n`;
1156
+ }
282
1157
  }
283
1158
  };
284
1159
  }
285
1160
  //#endregion
286
- export { hubRealtime };
1161
+ export { discoverRealtimeDefinitions, hubRealtime, inspectRealtimeDefinitions };