@vite-hub/comments 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +37 -15
  2. package/dist/anchor.d.ts +2 -2
  3. package/dist/{client-diagnostics-CcFpkbAk.js → client-diagnostics-Bubm7Shd.js} +20 -5
  4. package/dist/client-files-CJZl5Kc4.js +53 -0
  5. package/dist/client.d.ts +567 -13
  6. package/dist/client.js +1209 -34
  7. package/dist/{console-h4KlhIik.d.ts → console-D1lwNMZn.d.ts} +2 -0
  8. package/dist/{migrate-BDQ8xqUs.js → database-6hXRnqDE.js} +47 -2
  9. package/dist/database-CTo7mx6t.d.ts +575 -0
  10. package/dist/database.d.ts +2 -1
  11. package/dist/database.js +2 -2
  12. package/dist/{define-43mMR39K.js → define-BMBSVbD9.js} +1 -1
  13. package/dist/{define-B3TF9zzn.d.ts → define-CmIFU96x.d.ts} +8 -4
  14. package/dist/{errors-4gelGVmK.js → errors-BJTZ9iyv.js} +24 -0
  15. package/dist/{errors-C6qptPoG.js → errors-Dq4AHjza.js} +23 -3
  16. package/dist/index-RiHzmV16.d.ts +194 -0
  17. package/dist/index.d.ts +6 -7
  18. package/dist/index.js +57 -9
  19. package/dist/{install-W9ghhGoh.d.ts → install-BGGQKbQ4.d.ts} +9 -3
  20. package/dist/{install-BcMPgPk_.js → install-DrAse1Fa.js} +912 -60
  21. package/dist/{installed-B-PfERBU.js → installed-C3EoqJEY.js} +7 -6
  22. package/dist/{operations-GLeOqgMt.d.ts → operations-BKhUWYkb.d.ts} +10 -5
  23. package/dist/{operations-D4A1Fcgf.d.ts → operations-VyyNZusz.d.ts} +13 -2
  24. package/dist/{operations-DMMIfYPW.js → operations-lsVKE0GH.js} +312 -219
  25. package/dist/operations.d.ts +2 -2
  26. package/dist/operations.js +2 -2
  27. package/dist/overlay/client-DBmJ4C1M.js +4 -0
  28. package/dist/overlay/overlay.js +41 -65
  29. package/dist/page/loader.js +39 -47
  30. package/dist/{page-DtbMOEMd.d.ts → page-Bzj0CszG.d.ts} +1 -10
  31. package/dist/{page-B41ozN63.js → page-DRz_sDY4.js} +1 -1
  32. package/dist/{page-tools-shared-NHUjKI8E.js → page-tools-shared-BNnuPK93.js} +6 -3
  33. package/dist/{plugin-PS8PMYus.js → plugin-DRsNaJaK.js} +34 -8
  34. package/dist/realtime.d.ts +2 -2
  35. package/dist/realtime.js +2 -2
  36. package/dist/reply-id-P_bSuEng.js +12 -0
  37. package/dist/request-log-Dj9Vw7qG.js +105 -0
  38. package/dist/request-origin-CFU0TQ7E.js +49 -0
  39. package/dist/{rpc-RKPAusHp.js → rpc-BQqYx8kb.js} +23 -7
  40. package/dist/{rpc-HBcWtg0T.d.ts → rpc-CuJ5GLIz.d.ts} +1 -1
  41. package/dist/rpc.d.ts +1 -1
  42. package/dist/rpc.js +1 -1
  43. package/dist/runtime/auth.d.ts +2 -2
  44. package/dist/runtime/auth.js +2 -2
  45. package/dist/runtime/console.d.ts +1 -1
  46. package/dist/runtime/console.js +3 -3
  47. package/dist/runtime/index.d.ts +42 -13
  48. package/dist/runtime/index.js +224 -22
  49. package/dist/{server-D8k-0GXe.js → server-Yk610niJ.js} +1 -1
  50. package/dist/server.d.ts +6 -5
  51. package/dist/server.js +6 -6
  52. package/dist/service-Bj-Mg63c.d.ts +73 -0
  53. package/dist/{service-GHhhyQj4.js → service-DA5BwfPQ.js} +71 -14
  54. package/dist/{session-DVx-1Tym.d.ts → session-DUcEor2W.d.ts} +3 -3
  55. package/dist/{session-EkudzUmm.js → session-X_g9dnU5.js} +27 -30
  56. package/dist/{service-CFVm23k7.d.ts → store-CsUNfC1w.d.ts} +11 -72
  57. package/dist/table-names-B9LlRC0B.js +16 -0
  58. package/dist/testing.d.ts +1 -1
  59. package/dist/testing.js +38 -5
  60. package/dist/{types-CZujrMFd.d.ts → types-BLaYh0_f.d.ts} +48 -4
  61. package/dist/{types-BIS0hCEl.d.ts → types-C35INXIs.d.ts} +88 -4
  62. package/dist/vite.d.ts +24 -7
  63. package/dist/vite.js +322 -173
  64. package/package.json +9 -9
  65. package/dist/errors-CyQyKAvy.d.ts +0 -185
  66. package/dist/index-DNhy69Wt.d.ts +0 -83
  67. package/dist/overlay/client-DmsSMOzi.js +0 -4
package/dist/vite.js CHANGED
@@ -1,10 +1,12 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
2
- import { a as mountedCommentsRoute, i as commentsRoute, r as commentsRealtimeDefinition } from "./page-B41ozN63.js";
1
+ import { t as commentsErrorDiagnostics } from "./errors-Dq4AHjza.js";
2
+ import { a as mountedCommentsRoute, i as commentsRoute, r as commentsRealtimeDefinition } from "./page-DRz_sDY4.js";
3
3
  import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
4
4
  import { t as invariant } from "./invariant-D8_xBqmZ.js";
5
- import { c as validateCommentsDefinition } from "./define-43mMR39K.js";
6
- import { a as viteHubPageToolsCookie, d as viteHubPageToolsQuery, i as viteHubPageToolsAssets, n as viteHubBasePath, r as viteHubPageSessionPath, s as viteHubPageToolsInlineScript } from "./page-tools-shared-NHUjKI8E.js";
7
- import { existsSync, statSync } from "node:fs";
5
+ import { c as validateCommentsDefinition } from "./define-BMBSVbD9.js";
6
+ import { a as viteHubPageToolsCookie, d as viteHubPageToolsQuery, i as viteHubPageToolsAssets, n as viteHubBasePath, r as viteHubPageSessionPath, s as viteHubPageToolsInlineScript } from "./page-tools-shared-BNnuPK93.js";
7
+ import { n as commentsTableNames, t as commentSendsTableNames } from "./table-names-B9LlRC0B.js";
8
+ import { formatDiagnostic } from "nostics";
9
+ import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
8
10
  import { tmpdir } from "node:os";
9
11
  import { basename, dirname, join, parse, relative, resolve, sep } from "node:path";
10
12
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -14,88 +16,6 @@ import { nitro } from "nitro/vite";
14
16
  import { parseDatabaseLocation } from "@vite-hub/database/config";
15
17
  import { githubRepository, readForgeBuild } from "@vite-hub/forge/build/node";
16
18
  import { parseJSONC, parseTOML } from "confbox";
17
- //#region ../internal/src/build/vite.ts
18
- const projectRootDirectoryMarkers = [
19
- ["server", "agents"],
20
- ["server", "channels"],
21
- ["server", "connections"],
22
- ["server", "browsers"],
23
- ["server", "emails"],
24
- ["server", "schedules"],
25
- ["server", "workspaces"]
26
- ];
27
- const projectRootFileMarkers = [
28
- ["package.json"],
29
- ["nuxt.config.ts"],
30
- ["nuxt.config.mts"],
31
- ["nuxt.config.js"],
32
- ["nuxt.config.mjs"]
33
- ];
34
- function isServerEnvironment(name, config) {
35
- return name === "ssr" || config.consumer === "server";
36
- }
37
- /** Nitro RC externalizes dependencies by default; explicit inlining still needs CommonJS pre-bundling in workerd. */
38
- function workerdDependencyConfig(name, config, env) {
39
- if (env.command !== "serve" || !isServerEnvironment(name, config) || config.resolve?.noExternal !== true) return;
40
- if (!config.resolve.conditions?.some((condition) => condition === "workerd" || condition === "worker")) return;
41
- return { optimizeDeps: {
42
- noDiscovery: config.optimizeDeps?.noDiscovery ?? false,
43
- exclude: ["nitro"]
44
- } };
45
- }
46
- const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
47
- /**
48
- * Server directories that ViteHub scans for Definitions. The first entry is the application.
49
- * Later entries are Nuxt layers in Nuxt priority order.
50
- */
51
- const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
52
- function resolveViteHubProjectRoot(root, options = {}) {
53
- const resolvedRoot = resolve(root);
54
- const temporaryRoot = resolve(tmpdir());
55
- const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
56
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
57
- if (basename(resolvedRoot) === "app") {
58
- const parent = dirname(resolvedRoot);
59
- if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
60
- "nuxt.config.ts",
61
- "nuxt.config.mts",
62
- "nuxt.config.js",
63
- "nuxt.config.mjs"
64
- ]))) return parent;
65
- }
66
- let current = resolvedRoot;
67
- while (true) {
68
- if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
69
- if (hasProjectRootMarker(current)) return current;
70
- const parent = dirname(current);
71
- if (parent === current) return resolvedRoot;
72
- current = parent;
73
- }
74
- }
75
- function hasProjectRootDirectoryMarker(root) {
76
- for (const marker of projectRootDirectoryMarkers) try {
77
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
78
- } catch (error) {
79
- if (error.code !== "ENOENT") throw error;
80
- }
81
- return false;
82
- }
83
- function hasProjectRootMarker(root) {
84
- if (hasProjectRootDirectoryMarker(root)) return true;
85
- return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
86
- }
87
- function hasProjectRootFileMarker(root, markers) {
88
- for (const marker of markers) {
89
- const path = Array.isArray(marker) ? marker : [marker];
90
- try {
91
- if (statSync(resolve(root, ...path)).isFile()) return true;
92
- } catch (error) {
93
- if (error.code !== "ENOENT") throw error;
94
- }
95
- }
96
- return false;
97
- }
98
- //#endregion
99
19
  //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
100
20
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
101
21
  function normalizeWindowsPath(input = "") {
@@ -202,6 +122,92 @@ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|pr
202
122
  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");
203
123
  new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
204
124
  //#endregion
125
+ //#region ../internal/src/build/vite.ts
126
+ const projectRootDirectoryMarkers = [
127
+ ["server", "agents"],
128
+ ["server", "channels"],
129
+ ["server", "connections"],
130
+ ["server", "browsers"],
131
+ ["server", "emails"],
132
+ ["server", "schedules"],
133
+ ["server", "workspaces"]
134
+ ];
135
+ const projectRootFileMarkers = [
136
+ ["package.json"],
137
+ ["nuxt.config.ts"],
138
+ ["nuxt.config.mts"],
139
+ ["nuxt.config.js"],
140
+ ["nuxt.config.mjs"]
141
+ ];
142
+ function isServerEnvironment(name, config) {
143
+ return name === "ssr" || config.consumer === "server";
144
+ }
145
+ /** Nitro RC externalizes dependencies by default; explicit inlining still needs CommonJS pre-bundling in workerd. */
146
+ function workerdDependencyConfig(name, config, env) {
147
+ if (env.command !== "serve" || !isServerEnvironment(name, config) || config.resolve?.noExternal !== true) return;
148
+ if (!config.resolve.conditions?.some((condition) => condition === "workerd" || condition === "worker")) return;
149
+ return { optimizeDeps: {
150
+ noDiscovery: config.optimizeDeps?.noDiscovery ?? false,
151
+ exclude: ["nitro"]
152
+ } };
153
+ }
154
+ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
155
+ /**
156
+ * Server directories that ViteHub scans for Definitions. The first entry is the application.
157
+ * Later entries are Nuxt layers in Nuxt priority order.
158
+ */
159
+ const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
160
+ function resolveViteHubProjectRoot(root, options = {}) {
161
+ const resolvedRoot = resolve(root);
162
+ const temporaryRoot = resolve(tmpdir());
163
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
164
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
165
+ if (basename(resolvedRoot) === "app") {
166
+ const parent = dirname(resolvedRoot);
167
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
168
+ "nuxt.config.ts",
169
+ "nuxt.config.mts",
170
+ "nuxt.config.js",
171
+ "nuxt.config.mjs"
172
+ ]))) return parent;
173
+ }
174
+ let current = resolvedRoot;
175
+ while (true) {
176
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
177
+ if (hasProjectRootMarker(current)) return current;
178
+ const parent = dirname(current);
179
+ if (parent === current) return resolvedRoot;
180
+ current = parent;
181
+ }
182
+ }
183
+ function hasProjectRootDirectoryMarker(root) {
184
+ for (const marker of projectRootDirectoryMarkers) try {
185
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
186
+ } catch (error) {
187
+ if (!isMissingProjectMarker(error)) throw error;
188
+ }
189
+ return false;
190
+ }
191
+ function hasProjectRootMarker(root) {
192
+ if (hasProjectRootDirectoryMarker(root)) return true;
193
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
194
+ }
195
+ function hasProjectRootFileMarker(root, markers) {
196
+ for (const marker of markers) {
197
+ const path = Array.isArray(marker) ? marker : [marker];
198
+ try {
199
+ if (statSync(resolve(root, ...path)).isFile()) return true;
200
+ } catch (error) {
201
+ if (!isMissingProjectMarker(error)) throw error;
202
+ }
203
+ }
204
+ return false;
205
+ }
206
+ function isMissingProjectMarker(error) {
207
+ const code = error.code;
208
+ return code === "ENOENT" || code === "ENOTDIR";
209
+ }
210
+ //#endregion
205
211
  //#region ../internal/src/build/paths.ts
206
212
  function resolveRuntimeModule(packageDir, modulePath) {
207
213
  const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
@@ -251,10 +257,46 @@ function findContentEntry(projectRoot, serverDirs) {
251
257
  if (existsSync(file)) return file;
252
258
  }
253
259
  }
260
+ Object.freeze({ vitehubAuthAccess: "handler" });
261
+ /**
262
+ * The route meta of a generated handler that checks access on every request, even when the app adds no rule: a required
263
+ * `authorize` policy, an explicit `access` rule, a required access token, or a signature. Auth access routes still apply
264
+ * to it, so an app rule stays in force. `checksOwnAccess(event)` of `vite-hub/auth` reads it, so app middleware can skip
265
+ * the route. A route that can run without a check, such as a browser error sink, an optional `authorize`, or a webhook
266
+ * with `secret: false`, must not use it.
267
+ */
268
+ const ownAccessRouteMeta = Object.freeze({ vitehubOwnAccess: true });
269
+ function cloneArray(value) {
270
+ return Array.isArray(value) ? [...value] : [];
271
+ }
272
+ function sameHandler(left, right) {
273
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
274
+ }
275
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
276
+ function createNitroServerKit(value = {}) {
277
+ const config = isRecordOrFunction(value) ? { ...value } : {};
278
+ const handlers = cloneArray(config.handlers);
279
+ const plugins = cloneArray(config.plugins);
280
+ config.handlers = handlers;
281
+ config.plugins = plugins;
282
+ return {
283
+ config,
284
+ addHandler(handler, position = "end") {
285
+ if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
286
+ if (position === "start") handlers.unshift({ ...handler });
287
+ else handlers.push({ ...handler });
288
+ },
289
+ addPlugin(plugin, position = "end") {
290
+ if (plugins.includes(plugin)) return;
291
+ if (position === "start") plugins.unshift(plugin);
292
+ else plugins.push(plugin);
293
+ }
294
+ };
295
+ }
254
296
  //#endregion
255
297
  //#region ../internal/src/build/page-tools.ts
256
298
  /**
257
- * Adds the session route `GET <mount>/_vitehub/page/session` and the loader script at
299
+ * Adds the session route `GET <mount>/_vitehub/page/tools` and the loader script at
258
300
  * `<mount>/_vitehub/page/assets/loader.js` to a Nitro configuration. Each owner package of a page tool calls it from its
259
301
  * Vite plugin, so the routes exist without the Console. The first owner wins: a later call keeps the route and the asset
260
302
  * that are already there, because the page tools registry is shared by every copy of this package.
@@ -265,6 +307,7 @@ function addViteHubPageToolRoutes(kit, options) {
265
307
  const assetsBase = `${mount}${viteHubPageToolsAssets}`;
266
308
  if (!(Array.isArray(kit.config.handlers) ? kit.config.handlers : []).some((handler) => Object(handler) === handler && Reflect.get(Object(handler), "route") === route)) kit.addHandler({
267
309
  handler: options.handler,
310
+ meta: { ...ownAccessRouteMeta },
268
311
  route
269
312
  });
270
313
  const assets = Array.isArray(kit.config.publicAssets) ? [...kit.config.publicAssets] : [];
@@ -315,6 +358,15 @@ function viteHubPageToolsIndexHtml(html, base) {
315
358
  return index === -1 ? `${html}${script}` : `${html.slice(0, index)}${script}${html.slice(index)}`;
316
359
  }
317
360
  //#endregion
361
+ //#region ../internal/src/build/ast-walk.ts
362
+ /** The oxc parser grammar for a file, from its extension. Defaults to TypeScript. */
363
+ function moduleLanguage(file) {
364
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
365
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
366
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
367
+ return "ts";
368
+ }
369
+ //#endregion
318
370
  //#region ../internal/src/build/scan-module.ts
319
371
  /**
320
372
  * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
@@ -323,16 +375,10 @@ function viteHubPageToolsIndexHtml(html, base) {
323
375
  */
324
376
  /** The value of an expression that the scanner cannot read without running the module. */
325
377
  const dynamic = Symbol("dynamic");
326
- function languageOf(file) {
327
- if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
328
- if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
329
- if (/\.(?:c|m)?js$/i.test(file)) return "js";
330
- return "ts";
331
- }
332
378
  /** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
333
379
  function scanModule(source, file = "module.ts") {
334
380
  const result = parseSync(file, source, {
335
- lang: languageOf(file),
381
+ lang: moduleLanguage(file),
336
382
  preserveParens: false,
337
383
  sourceType: "module"
338
384
  });
@@ -442,6 +488,85 @@ function staticValue(node) {
442
488
  }
443
489
  }
444
490
  //#endregion
491
+ //#region ../internal/src/hints.ts
492
+ /**
493
+ * The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
494
+ * about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
495
+ * the file instead of the terminal.
496
+ */
497
+ const viteHubHintsFile = ".vitehub/hints.json";
498
+ const VITEHUB_NUXT_HINTS = "__vitehubNuxtHints";
499
+ const runsKey = Symbol.for("vitehub.hints.runs");
500
+ const shared = globalThis;
501
+ const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
502
+ const startedKey = Symbol.for("vitehub.hints.started");
503
+ const startedShared = globalThis;
504
+ const started = startedShared[startedKey] ??= /* @__PURE__ */ new WeakSet();
505
+ /**
506
+ * The report of the ViteHub project root, where the other generated files go. A Nuxt app with `srcDir: "app"` has its
507
+ * Vite root in `app/`, one folder below.
508
+ */
509
+ function hintsFile(config) {
510
+ const projectRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
511
+ return resolve(typeof projectRoot === "string" ? projectRoot : resolveViteHubProjectRoot(config.root), viteHubHintsFile);
512
+ }
513
+ function startRun(config) {
514
+ const file = hintsFile(config);
515
+ const run = {
516
+ file,
517
+ report: {
518
+ version: 1,
519
+ command: config.command,
520
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
521
+ hints: []
522
+ },
523
+ keys: /* @__PURE__ */ new Set()
524
+ };
525
+ runs.set(file, run);
526
+ return run;
527
+ }
528
+ function write(run) {
529
+ mkdirSync(dirname(run.file), { recursive: true });
530
+ writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
531
+ }
532
+ /**
533
+ * Reports a hint from a Vite plugin hook, or from a Nitro or Nuxt hook of the same build: prints it once with its fix and docs link, and adds it to
534
+ * {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
535
+ */
536
+ function reportViteHubHint(config, diagnostic) {
537
+ if (skipHints(config)) return;
538
+ const nuxt = config[VITEHUB_NUXT_HINTS];
539
+ if (typeof nuxt === "function") return nuxt(diagnostic);
540
+ const run = runs.get(hintsFile(config)) ?? startRun(config);
541
+ const hint = {
542
+ code: diagnostic.code,
543
+ why: diagnostic.why,
544
+ ...diagnostic.fix ? { fix: diagnostic.fix } : {},
545
+ ...diagnostic.docs ? { docs: diagnostic.docs } : {},
546
+ ...diagnostic.sources?.length ? { sources: diagnostic.sources } : {}
547
+ };
548
+ const key = JSON.stringify([hint.code, hint.sources ?? []]);
549
+ if (run.keys.has(key)) return;
550
+ run.keys.add(key);
551
+ run.report.hints.push(hint);
552
+ write(run);
553
+ (config.logger ?? console).warn(formatDiagnostic(diagnostic));
554
+ }
555
+ function skipHints(config) {
556
+ return !config.command || Reflect.get(config, "__vitehubPrepare") === true || Reflect.get(config, "vitehubCliDiscovery") === true;
557
+ }
558
+ /**
559
+ * Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
560
+ * leave the hints of an earlier run in place. Every plugin that reports hints calls it from `configResolved`, so a
561
+ * package used without `vitehub()` starts its own run. Nuxt uses the app instance as owner so its Vite builds and
562
+ * separate Nitro build share one report; replay, prepare and discovery never reset it.
563
+ */
564
+ function startViteHubHints(config, owner = config) {
565
+ if (skipHints(config) || config["__vitehubNuxtHints"] || started.has(owner)) return;
566
+ started.add(owner);
567
+ write(startRun(config));
568
+ }
569
+ //#endregion
445
570
  //#region ../internal/src/build/included-nitro-registry.ts
446
571
  const includedKey = Symbol.for("vitehub.included-nitro");
447
572
  const scope = globalThis;
@@ -486,35 +611,6 @@ function includedNitro(options = {}) {
486
611
  return plugins;
487
612
  }
488
613
  //#endregion
489
- //#region ../internal/src/nitro-kit.ts
490
- function cloneArray(value) {
491
- return Array.isArray(value) ? [...value] : [];
492
- }
493
- function sameHandler(left, right) {
494
- return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
495
- }
496
- /** Create a Nitro 3 configuration builder for generated ViteHub output. */
497
- function createNitroServerKit(value = {}) {
498
- const config = isRecordOrFunction(value) ? { ...value } : {};
499
- const handlers = cloneArray(config.handlers);
500
- const plugins = cloneArray(config.plugins);
501
- config.handlers = handlers;
502
- config.plugins = plugins;
503
- return {
504
- config,
505
- addHandler(handler, position = "end") {
506
- if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
507
- if (position === "start") handlers.unshift({ ...handler });
508
- else handlers.push({ ...handler });
509
- },
510
- addPlugin(plugin, position = "end") {
511
- if (plugins.includes(plugin)) return;
512
- if (position === "start") plugins.unshift(plugin);
513
- else plugins.push(plugin);
514
- }
515
- };
516
- }
517
- //#endregion
518
614
  //#region src/deployment-env.ts
519
615
  const owners = ["comments"];
520
616
  const githubLoginNames = {
@@ -640,19 +736,6 @@ const commentsConsoleSection = {
640
736
  }
641
737
  };
642
738
  //#endregion
643
- //#region src/table-names.ts
644
- /**
645
- * The tables of `commentsSchema` and `commentsPostgresSchema`: each schema key and its SQL name. The Comments
646
- * contribution gives them to the Database, so resolving the Vite config loads neither the schema nor drizzle-orm. A
647
- * test keeps them equal to both schemas.
648
- */
649
- const commentsTableNames = {
650
- vitehubCommentThreads: "vitehub_comment_threads",
651
- vitehubCommentMessages: "vitehub_comment_messages",
652
- vitehubCommentCounters: "vitehub_comment_counters",
653
- vitehubCommentForge: "vitehub_comment_forge"
654
- };
655
- //#endregion
656
739
  //#region src/live-vite.ts
657
740
  const defaultImports = {
658
741
  runtime: "@vite-hub/comments/runtime",
@@ -663,57 +746,94 @@ const defaultImports = {
663
746
  contentClient: "@vite-hub/content/client",
664
747
  connect: "@vite-hub/comments/runtime/connect",
665
748
  blob: "@vite-hub/blob",
666
- rateLimit: "@vite-hub/rate-limit"
749
+ rateLimit: "@vite-hub/rate-limit",
750
+ webhooks: "@vite-hub/webhooks"
667
751
  };
668
- /**
669
- * The Database name in `defineComments({ database: "name" })`, read without running the file. Undefined means the
670
- * default or only Database.
671
- */
672
- async function readCommentsDatabase(file) {
752
+ function literalProperties(options) {
753
+ return objectProperties(options).flatMap((property) => {
754
+ if (property.node.type !== "SpreadElement") return [property];
755
+ const spread = unwrapExpression(property.node.argument);
756
+ return spread.type === "ObjectExpression" ? literalProperties(spread) : [property];
757
+ });
758
+ }
759
+ async function readDefinitionProperties(file) {
673
760
  const module = scanModule(await readFile(file, "utf8").catch(() => ""), file);
674
761
  if (module.errors.length) return;
675
762
  const bindings = /* @__PURE__ */ new Set();
676
763
  const factories = /* @__PURE__ */ new Set(["defineComments"]);
677
764
  let defaultCall;
765
+ let hasNamedExport = false;
678
766
  for (const statement of module.program.body) {
679
767
  if (statement.type === "ImportDeclaration" && statement.importKind !== "type" && ["vite-hub/comments", "@vite-hub/comments"].includes(statement.source.value)) for (const specifier of statement.specifiers) {
680
768
  if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") continue;
681
769
  if ((specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value) === "defineComments") factories.add(specifier.local.name);
682
770
  }
683
771
  if (statement.type === "ExportDefaultDeclaration") {
684
- const value = unwrapExpression(statement.declaration);
685
- if (value.type === "Identifier") bindings.add(value.name);
686
- else if (value.type === "CallExpression" && value.callee.type === "Identifier") defaultCall = value;
772
+ defaultCall = unwrapExpression(statement.declaration);
687
773
  continue;
688
774
  }
689
- if (statement.type !== "ExportNamedDeclaration" || statement.source) continue;
775
+ if (statement.type !== "ExportNamedDeclaration" || statement.exportKind === "type") continue;
690
776
  if (statement.declaration?.type === "VariableDeclaration") {
691
- for (const declaration of statement.declaration.declarations) if (declaration.id.type === "Identifier" && declaration.id.name === "comments") bindings.add(declaration.id.name);
777
+ for (const declaration of statement.declaration.declarations) if (declaration.id.type === "Identifier" && declaration.id.name === "comments") {
778
+ hasNamedExport = true;
779
+ bindings.add(declaration.id.name);
780
+ }
781
+ }
782
+ for (const specifier of statement.specifiers) if ((specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === "comments" && specifier.exportKind !== "type") {
783
+ hasNamedExport = true;
784
+ if (!statement.source && specifier.local.type === "Identifier") bindings.add(specifier.local.name);
692
785
  }
693
- for (const specifier of statement.specifiers) if ((specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === "comments" && specifier.local.type === "Identifier") bindings.add(specifier.local.name);
694
786
  }
695
- const databaseOf = (call) => {
787
+ const propertiesOf = (call) => {
696
788
  if (call.type !== "CallExpression" || call.callee.type !== "Identifier" || !factories.has(call.callee.name)) return;
789
+ if (call.arguments.length === 0) return [];
697
790
  const options = argumentExpression(call.arguments[0]);
698
- if (options?.type !== "ObjectExpression") return;
699
- const properties = objectProperties(options);
700
- const last = properties.findLastIndex((property) => property.key === "database");
701
- if (last === -1) return;
702
- const property = properties[last];
703
- const name = property.node.type === "Property" && property.node.kind === "init" && !property.node.method && property.value ? staticValue(property.value) : null;
704
- if (properties.slice(last + 1).some((later) => later.key === void 0) || name !== void 0 && typeof name !== "string") throw commentsErrorDiagnostics.COMMENTS_B0004({ file });
705
- return name;
791
+ return options?.type === "ObjectExpression" ? literalProperties(options) : void 0;
706
792
  };
707
- if (defaultCall) return databaseOf(defaultCall);
793
+ if (!hasNamedExport && defaultCall) {
794
+ if (defaultCall.type !== "Identifier") return propertiesOf(defaultCall);
795
+ bindings.add(defaultCall.name);
796
+ }
708
797
  for (const statement of module.program.body) {
709
798
  const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
710
799
  if (declaration?.type !== "VariableDeclaration") continue;
711
800
  for (const binding of declaration.declarations) {
712
801
  if (binding.id.type !== "Identifier" || !bindings.has(binding.id.name) || !binding.init) continue;
713
- return databaseOf(unwrapExpression(binding.init));
802
+ return propertiesOf(unwrapExpression(binding.init));
714
803
  }
715
804
  }
716
805
  }
806
+ function lastProperty(properties, key) {
807
+ const last = properties.findLastIndex((property) => property.key === key);
808
+ if (last === -1) return void 0;
809
+ const property = properties[last];
810
+ if (properties.slice(last + 1).some((later) => later.key === void 0)) return null;
811
+ if (property.node.type !== "Property" || property.node.kind !== "init" || property.node.method || !property.value) return null;
812
+ return { value: staticValue(property.value) };
813
+ }
814
+ /**
815
+ * The Database name in `defineComments({ database: "name" })`, read without running the file. Undefined means the
816
+ * default or only Database.
817
+ */
818
+ async function readCommentsDatabase(file) {
819
+ const properties = await readDefinitionProperties(file);
820
+ if (!properties) return;
821
+ const found = lastProperty(properties, "database");
822
+ if (found === void 0) return;
823
+ if (found === null || found.value !== void 0 && typeof found.value !== "string") throw commentsErrorDiagnostics.COMMENTS_B0004({ file });
824
+ return typeof found.value === "string" ? found.value : void 0;
825
+ }
826
+ /**
827
+ * Whether `defineComments({ send })` turns Send on, read without running the file: Send is on unless `send` is missing
828
+ * or `false`. A value known only at runtime counts as on, so the build adds the tables and the member endpoints.
829
+ */
830
+ async function readCommentsSend(file) {
831
+ const properties = await readDefinitionProperties(file);
832
+ if (!properties) return true;
833
+ const found = lastProperty(properties, "send");
834
+ if (found === void 0) return properties.some((property) => property.key === void 0);
835
+ return found === null || found.value !== false && found.value !== void 0 && found.value !== null;
836
+ }
717
837
  /** A directory of prebuilt browser scripts in this package. */
718
838
  function builtDirectory(name) {
719
839
  const here = dirname(fileURLToPath(import.meta.url));
@@ -812,7 +932,7 @@ function sessionWithGitHubLines(options, imports, repository, base) {
812
932
  return {
813
933
  imports: [`import { createCommentsGitHubLogin } from ${JSON.stringify(imports.runtime)}`, `const githubLogin = createCommentsGitHubLogin(${JSON.stringify({
814
934
  ...repository ? { repository } : {},
815
- ...route !== "/api/_vitehub/comments" ? { basePath: `${route}/auth` } : {}
935
+ ...route !== "/_vitehub/comments" ? { basePath: `${route}/auth` } : {}
816
936
  })})`],
817
937
  value: "undefined",
818
938
  githubLogin: true
@@ -834,7 +954,7 @@ function renderCommentsHandler(input) {
834
954
  ` session: ${session.value},`,
835
955
  ...githubLogin ? [` githubLogin: createCommentsGitHubLogin(${JSON.stringify({
836
956
  ...input.build?.repository ? { repository: input.build.repository } : {},
837
- ...route !== "/api/_vitehub/comments" ? { basePath: `${route}/auth` } : {}
957
+ ...route !== "/_vitehub/comments" ? { basePath: `${route}/auth` } : {}
838
958
  })}),`] : [],
839
959
  ...input.content ? [" content: contentModule.default ? { runtime: contentModule.default, parseField: parseContentField } : undefined,"] : [],
840
960
  ` realtime: ${input.realtime},`,
@@ -884,6 +1004,7 @@ function renderCommentsPlugin(input) {
884
1004
  ...input.session?.blob ? ["attachments: blob"] : [],
885
1005
  ...input.session?.rateLimit ? ["rateLimit: checkRateLimit"] : [],
886
1006
  ...postgres ? ["dialect: \"postgresql\"", "tables: { commentCounters: schema.vitehubCommentCounters, commentMessages: schema.vitehubCommentMessages, commentThreads: schema.vitehubCommentThreads, commentForge: schema.vitehubCommentForge }"] : [],
1007
+ ...input.send ? [`webhooks: () => import(${JSON.stringify(input.imports.webhooks)})`] : [],
887
1008
  `development: ${input.development === true}`,
888
1009
  `overlay: ${overlay}`,
889
1010
  `base: ${JSON.stringify(input.base ?? "")}`
@@ -917,7 +1038,6 @@ async function writeDefaultDefinition(directory, imports) {
917
1038
  async function standaloneDatabase(projectRoot, options, command, workerd) {
918
1039
  const where = options.database || void 0;
919
1040
  const location = parseDatabaseLocation(where, "comments", { node: command !== "serve" || !workerd });
920
- if (where && /[?&]authToken=/.test(where)) console.warn("[vitehub] The token in `comments({ database })` ends up in the build. Use `env:` with a variable instead.");
921
1041
  if (command !== "serve") return {
922
1042
  ...where ? { where } : {},
923
1043
  node: location.kind === "file"
@@ -1003,7 +1123,7 @@ function comments(options = {}) {
1003
1123
  }
1004
1124
  /**
1005
1125
  * Comments build integration. When the app has `server/comments.ts`, it serves the Comments API at
1006
- * `/api/_vitehub/comments/**`, installs the runtime with its Database, adds the tables to that Database, serves the
1126
+ * `/_vitehub/comments/**`, installs the runtime with its Database, adds the tables to that Database, serves the
1007
1127
  * overlay script, and adds it to pages in comment mode. `enabled: true` does the same without the file, with the default
1008
1128
  * `defineComments()`. Other apps without the file are unaffected.
1009
1129
  */
@@ -1036,6 +1156,10 @@ function hubComments$1(options = {}) {
1036
1156
  order: "post",
1037
1157
  handler: workerdDependencyConfig
1038
1158
  } : void 0,
1159
+ configResolved: options.standalone ? (config) => {
1160
+ startViteHubHints(config);
1161
+ if (/[?&]authToken=/.test(options.standalone?.database ?? "")) reportViteHubHint(config, commentsErrorDiagnostics.COMMENTS_DATABASE_TOKEN_IN_BUILD());
1162
+ } : void 0,
1039
1163
  nitro: options.standalone ? { async setup(nitro) {
1040
1164
  if (!projectRoot || !options.standalone) return;
1041
1165
  const runner = nitro.options.devServer.runner || process.env.NITRO_DEV_RUNNER || "node-worker";
@@ -1121,6 +1245,7 @@ function hubComments$1(options = {}) {
1121
1245
  if (!definition && !options.enabled) return [];
1122
1246
  const database = options.database ?? (definition ? await readCommentsDatabase(definition) : void 0);
1123
1247
  const postgres = options.dialect === "postgresql";
1248
+ const send = !postgres && definition !== void 0 && await readCommentsSend(definition);
1124
1249
  return [{
1125
1250
  ...database ? { database } : {},
1126
1251
  definition: postgres ? {
@@ -1134,7 +1259,25 @@ function hubComments$1(options = {}) {
1134
1259
  tables: commentsTableNames,
1135
1260
  name: "comments",
1136
1261
  reason: definition ? "Stores the comment threads of `server/comments.ts`." : "Stores the comment threads of `vitehub({ comments })`."
1137
- }];
1262
+ }, ...send ? [{
1263
+ ...database ? { database } : {},
1264
+ definition: {
1265
+ export: "commentSendsSchema",
1266
+ module: imports.database
1267
+ },
1268
+ dialect: "sqlite",
1269
+ tables: commentSendsTableNames,
1270
+ name: "comment-sends",
1271
+ reason: "Keeps the sends and setup codes of `defineComments({ send })`."
1272
+ }] : []];
1273
+ },
1274
+ async webhooks(context) {
1275
+ if (options.standalone) return void 0;
1276
+ const definition = findCommentsEntry$2(projectRoot ?? context.projectRoot ?? context.root ?? process.cwd(), serverDirs ?? context.serverDirs?.slice());
1277
+ return definition && await readCommentsSend(definition) ? {
1278
+ memberEndpoints: true,
1279
+ reason: "Send hands each member's waiting comments to their own agent."
1280
+ } : void 0;
1138
1281
  }
1139
1282
  },
1140
1283
  enforce: "pre",
@@ -1159,7 +1302,7 @@ function hubComments$1(options = {}) {
1159
1302
  const definition = discover() ?? await writeDefaultDefinition(directory, imports);
1160
1303
  const handler = join(directory, "handler.mjs");
1161
1304
  const plugin = join(directory, "plugin.mjs");
1162
- const pageSession = join(directory, "page-session.mjs");
1305
+ const pageToolsRoute = join(directory, "page-tools-route.mjs");
1163
1306
  componentsFile = join(directory, "components.mjs");
1164
1307
  const build = await readCommentsBuild(projectRoot);
1165
1308
  const pluginInput = {
@@ -1169,7 +1312,8 @@ function hubComments$1(options = {}) {
1169
1312
  imports,
1170
1313
  build,
1171
1314
  base,
1172
- development
1315
+ development,
1316
+ send: !options.standalone && await readCommentsSend(definition)
1173
1317
  };
1174
1318
  await Promise.all([
1175
1319
  writeFile(handler, renderCommentsHandler({
@@ -1183,17 +1327,18 @@ function hubComments$1(options = {}) {
1183
1327
  })),
1184
1328
  writeComponents(),
1185
1329
  options.standalone ? void 0 : writeFile(plugin, renderCommentsPlugin(pluginInput)),
1186
- writeFile(pageSession, `export { viteHubPageSessionHandler as default } from ${JSON.stringify(imports.runtime)}\n`)
1330
+ writeFile(pageToolsRoute, `export { viteHubPageSessionHandler as default } from ${JSON.stringify(imports.runtime)}\n`)
1187
1331
  ]);
1188
1332
  const kit = createNitroServerKit(Reflect.get(config, "nitro"));
1189
1333
  kit.addHandler({
1190
1334
  handler,
1191
1335
  lazy: true,
1336
+ meta: { ...ownAccessRouteMeta },
1192
1337
  route: `${mount}${commentsRoute}/**`
1193
1338
  });
1194
1339
  kit.addPlugin(plugin);
1195
1340
  addViteHubPageToolRoutes(kit, {
1196
- handler: pageSession,
1341
+ handler: pageToolsRoute,
1197
1342
  loader: builtDirectory("page"),
1198
1343
  mount
1199
1344
  });
@@ -1338,8 +1483,8 @@ function usesComments(options) {
1338
1483
  }
1339
1484
  //#endregion
1340
1485
  //#region src/overlay.ts
1341
- /** Where the loader and overlay are served, below the app mount. */
1342
- const overlayRoute = "/_vitehub/comments";
1486
+ /** Where the loader and overlay are served, below the app mount: the assets folder of the Comments API route. */
1487
+ const overlayRoute = "/_vitehub/comments/assets";
1343
1488
  /** The path the app is mounted at: `""` for the root, `"/portal"` below it. A relative or empty Vite base is the root. */
1344
1489
  function mountPath(base) {
1345
1490
  if (!base || base === "./") return "";
@@ -1448,7 +1593,7 @@ function createHtmlScanner() {
1448
1593
  else if (element?.[1] === "") {
1449
1594
  if (!templates && name === "script") {
1450
1595
  const src = htmlAttributes(tag).find((attribute) => attribute.name === "src")?.value;
1451
- if (src && /\/_vitehub\/comments\/loader\.[\w-]+\.js(?:[?#]|$)/i.test(src)) return {
1596
+ if (src && /\/_vitehub\/comments\/assets\/loader\.[\w-]+\.js(?:[?#]|$)/i.test(src)) return {
1452
1597
  loaded: {
1453
1598
  start: position,
1454
1599
  end: position + tag.length
@@ -1642,6 +1787,10 @@ function hubComments(options = {}) {
1642
1787
  logLevel: "silent"
1643
1788
  });
1644
1789
  validateCommentsDefinition(module.comments ?? module.default, display);
1790
+ if (await readCommentsSend(entry)) {
1791
+ if (liveOptions.dialect === "postgresql") throw commentsErrorDiagnostics.COMMENTS_SEND_POSTGRES();
1792
+ if (!resolved.plugins.some((plugin) => plugin.name === "@vite-hub/webhooks/vite")) throw commentsErrorDiagnostics.COMMENTS_SEND_WEBHOOKS_OFF({ file: display });
1793
+ }
1645
1794
  },
1646
1795
  vitehub: {
1647
1796
  ...live.vitehub,
@@ -1657,4 +1806,4 @@ function hubComments(options = {}) {
1657
1806
  };
1658
1807
  }
1659
1808
  //#endregion
1660
- export { COMMENTS_VITE_PLUGIN_NAME, comments, comments as default, commentsConsoleSection, commentsConsoleSection$1 as commentsOperationsConsoleSection, commentsOverlayDirectory, componentNames, findCommentsEntry, githubRepository, hubComments, injectLoader, loaderTag, loaderUrl, mountPath, mountedCommentsRoute, overlayRoute, readCommentsBuild, readCommentsComponents, readCommentsDatabase, renderCommentsHandler, renderCommentsPlugin, renderOverlayMiddleware, scriptNonce, usesComments };
1809
+ export { COMMENTS_VITE_PLUGIN_NAME, comments, comments as default, commentsConsoleSection, commentsConsoleSection$1 as commentsOperationsConsoleSection, commentsOverlayDirectory, componentNames, findCommentsEntry, githubRepository, hubComments, injectLoader, loaderTag, loaderUrl, mountPath, mountedCommentsRoute, overlayRoute, readCommentsBuild, readCommentsComponents, readCommentsDatabase, readCommentsSend, renderCommentsHandler, renderCommentsPlugin, renderOverlayMiddleware, scriptNonce, usesComments };