@vite-hub/comments 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +19 -7
  2. package/dist/anchor.d.ts +2 -2
  3. package/dist/client.d.ts +424 -11
  4. package/dist/client.js +405 -5
  5. package/dist/{console-h4KlhIik.d.ts → console-D1lwNMZn.d.ts} +2 -0
  6. package/dist/{migrate-Bpw3xL5e.js → database-6hXRnqDE.js} +47 -2
  7. package/dist/database-CTo7mx6t.d.ts +575 -0
  8. package/dist/database.d.ts +2 -1
  9. package/dist/database.js +2 -2
  10. package/dist/{define-CX_Yr_hz.js → define-BMBSVbD9.js} +1 -1
  11. package/dist/{define-CHTWfHPo.d.ts → define-CmIFU96x.d.ts} +8 -4
  12. package/dist/{errors-4gelGVmK.js → errors-BJTZ9iyv.js} +24 -0
  13. package/dist/{errors-BHsVXlpd.js → errors-Dq4AHjza.js} +16 -0
  14. package/dist/{index-iPGlSAgj.d.ts → index-RiHzmV16.d.ts} +113 -11
  15. package/dist/index.d.ts +6 -7
  16. package/dist/index.js +21 -7
  17. package/dist/{install-96NXWnrw.d.ts → install-BGGQKbQ4.d.ts} +9 -3
  18. package/dist/{install-jRKmuLHK.js → install-DrAse1Fa.js} +844 -38
  19. package/dist/{installed-g6nDr5ac.js → installed-C3EoqJEY.js} +7 -6
  20. package/dist/{operations-D93EV10O.d.ts → operations-BKhUWYkb.d.ts} +9 -5
  21. package/dist/{operations-7ycAhDCw.d.ts → operations-VyyNZusz.d.ts} +8 -2
  22. package/dist/{operations-9tskoLsk.js → operations-lsVKE0GH.js} +294 -212
  23. package/dist/operations.d.ts +2 -2
  24. package/dist/operations.js +2 -2
  25. package/dist/overlay/{client-lZesR40x.js → client-DBmJ4C1M.js} +1 -1
  26. package/dist/overlay/overlay.js +36 -40
  27. package/dist/page/loader.js +39 -47
  28. package/dist/{page-CWwnmF3K.d.ts → page-Bzj0CszG.d.ts} +1 -10
  29. package/dist/{page-tools-shared-NHUjKI8E.js → page-tools-shared-BNnuPK93.js} +6 -3
  30. package/dist/{plugin-BNFd1zGz.js → plugin-DRsNaJaK.js} +14 -9
  31. package/dist/realtime.d.ts +2 -2
  32. package/dist/realtime.js +1 -1
  33. package/dist/request-log-Dj9Vw7qG.js +105 -0
  34. package/dist/request-origin-CFU0TQ7E.js +49 -0
  35. package/dist/{rpc-BZ1QNkCC.d.ts → rpc-CuJ5GLIz.d.ts} +1 -1
  36. package/dist/rpc.d.ts +1 -1
  37. package/dist/runtime/auth.d.ts +2 -2
  38. package/dist/runtime/auth.js +1 -1
  39. package/dist/runtime/console.d.ts +1 -1
  40. package/dist/runtime/console.js +1 -1
  41. package/dist/runtime/index.d.ts +11 -9
  42. package/dist/runtime/index.js +148 -14
  43. package/dist/{server-CqyzrqTI.js → server-Yk610niJ.js} +1 -1
  44. package/dist/server.d.ts +6 -5
  45. package/dist/server.js +5 -5
  46. package/dist/service-Bj-Mg63c.d.ts +73 -0
  47. package/dist/{service-C8ZgFWvy.js → service-DA5BwfPQ.js} +39 -11
  48. package/dist/{session-CKfW6DGE.d.ts → session-DUcEor2W.d.ts} +3 -3
  49. package/dist/{session-ByjMyTak.js → session-X_g9dnU5.js} +26 -29
  50. package/dist/{service-wC9kx9EX.d.ts → store-CsUNfC1w.d.ts} +2 -70
  51. package/dist/{table-names-DfiKUlOV.js → table-names-B9LlRC0B.js} +3 -1
  52. package/dist/testing.d.ts +1 -1
  53. package/dist/testing.js +2 -2
  54. package/dist/{types-C7LzhgRb.d.ts → types-BLaYh0_f.d.ts} +1 -1
  55. package/dist/{types-C1qzObs2.d.ts → types-C35INXIs.d.ts} +79 -4
  56. package/dist/vite.d.ts +22 -5
  57. package/dist/vite.js +140 -65
  58. package/package.json +8 -8
  59. package/dist/errors-BEChnUo7.d.ts +0 -197
@@ -0,0 +1,105 @@
1
+ //#region ../internal/src/runtime/request-log.ts
2
+ function isRequestLog(value) {
3
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "set") === "function" && typeof Reflect.get(value, "warn") === "function" && typeof Reflect.get(value, "error") === "function";
4
+ }
5
+ function contextLog(value) {
6
+ const context = value !== null && typeof value === "object" ? Reflect.get(value, "context") : void 0;
7
+ return context !== null && typeof context === "object" ? Reflect.get(context, "log") : void 0;
8
+ }
9
+ /**
10
+ * The evlog request logger of a request, or `undefined` when the app does not register evlog. Pass a Nitro v3 event
11
+ * (evlog sets `event.req.context.log`) or its `Request` (`request.context.log`).
12
+ */
13
+ function requestLog(input) {
14
+ const log = contextLog(input !== null && typeof input === "object" ? Reflect.get(input, "req") : void 0) ?? contextLog(input);
15
+ return isRequestLog(log) ? log : void 0;
16
+ }
17
+ /**
18
+ * The `Symbol.for()` key of the bridge on `globalThis`. Every bundled copy of this module and the Nitro plugin that
19
+ * `vitehub()` generates use the same key.
20
+ */
21
+ const evlogBridgeKey = "vitehub.evlog";
22
+ function isEvlogBridge(value) {
23
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "createLogger") === "function";
24
+ }
25
+ /** The evlog bridge of this process, or `undefined` when the app does not register evlog. */
26
+ function evlogBridge() {
27
+ const bridge = globalThis[Symbol.for(evlogBridgeKey)];
28
+ return isEvlogBridge(bridge) ? bridge : void 0;
29
+ }
30
+ function activeBridge() {
31
+ const bridge = evlogBridge();
32
+ try {
33
+ return bridge && bridge.isEnabled?.() !== false ? bridge : void 0;
34
+ } catch {
35
+ return;
36
+ }
37
+ }
38
+ /**
39
+ * A short name for the cause of a failure, safe to put in a log field: the string `code` of the error, such as
40
+ * `ENOSPC` or a ViteHub diagnostic code, else its class name. Never the message, which can hold paths or values.
41
+ */
42
+ function errorCode(error) {
43
+ if (error === null || typeof error !== "object") return void 0;
44
+ const code = Reflect.get(error, "code");
45
+ if (typeof code === "string" && code) return code;
46
+ const name = Reflect.get(error, "name");
47
+ return typeof name === "string" && name && name !== "Error" ? name : void 0;
48
+ }
49
+ /**
50
+ * Emits one evlog event of its own, outside a request's wide event. The event also reaches the app's `evlog:drain`
51
+ * hooks. Returns `false` when the app does not register evlog or turned it off, and never throws.
52
+ */
53
+ function emitLogEvent(event) {
54
+ const bridge = activeBridge();
55
+ if (!bridge) return false;
56
+ try {
57
+ const log = bridge.createLogger({
58
+ action: event.field,
59
+ message: event.message,
60
+ [event.field]: event.fields
61
+ }, event.waitUntil ? { waitUntil: event.waitUntil } : void 0);
62
+ if (event.level === "error") log.error(event.withError && event.error instanceof Error ? event.error : event.message);
63
+ else log[event.level](event.message);
64
+ const emitted = log.emit();
65
+ if (emitted && bridge.drain) {
66
+ const drained = Promise.resolve().then(() => bridge.drain?.(emitted)).catch((error) => {
67
+ console.error("[evlog] drain failed:", error);
68
+ });
69
+ event.waitUntil?.(drained);
70
+ }
71
+ return true;
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+ /**
77
+ * Logs a failure that the caller survives, with a fixed message and the `code` of the error. With the evlog request
78
+ * logger of `request`, it replaces `[field]` on the request's wide event and adds a warning. Pass `request` only when the
79
+ * request has not answered yet: evlog drops fields after it emits the wide event. Otherwise it emits an event of its
80
+ * own. Without evlog, or with evlog off, it calls `fallback`, which prints to the server console as before. It never
81
+ * throws.
82
+ */
83
+ function logFailure(failure, fallback) {
84
+ const code = errorCode(failure.error);
85
+ const fields = {
86
+ ...failure.fields,
87
+ ...code ? { code } : {}
88
+ };
89
+ const log = failure.request !== void 0 && activeBridge() ? requestLog(failure.request) : void 0;
90
+ if (log) try {
91
+ log.set({ [failure.field]: false });
92
+ log.warn(failure.message, { [failure.field]: fields });
93
+ return;
94
+ } catch {}
95
+ if (emitLogEvent({
96
+ ...failure,
97
+ fields,
98
+ level: failure.level ?? "warn"
99
+ })) return;
100
+ try {
101
+ fallback();
102
+ } catch {}
103
+ }
104
+ //#endregion
105
+ export { logFailure as t };
@@ -0,0 +1,49 @@
1
+ //#region ../internal/src/runtime/request-origin.ts
2
+ function firstHeaderValue(headers, name) {
3
+ return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
4
+ }
5
+ /**
6
+ * The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
7
+ * `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
8
+ * Without these headers, or with values that are not valid, the result is the origin of `request.url`.
9
+ */
10
+ function forwardedRequestOrigin(request) {
11
+ const url = new URL(request.url);
12
+ const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
13
+ const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
14
+ const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
15
+ if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
16
+ try {
17
+ return new URL(`${protocol}://${host}`).origin;
18
+ } catch {
19
+ return url.origin;
20
+ }
21
+ }
22
+ /**
23
+ * Whether a request came in on one of the public `origins` of the app, such as the origin of `vitehub({ publicUrl })`.
24
+ * It compares the host that the client used, so a proxy that does not forward the scheme still matches. A loopback
25
+ * host, such as `localhost:3000` for a preview or a proxy that does not forward the host, also matches: it cannot be a
26
+ * second public hostname. Every request matches when `origins` is empty.
27
+ */
28
+ function matchesPublicOrigin(request, origins) {
29
+ if (origins.length === 0) return true;
30
+ const { host, hostname } = new URL(forwardedRequestOrigin(request));
31
+ return isLoopbackHostname(hostname) || origins.some((origin) => new URL(origin).host === host);
32
+ }
33
+ /** `localhost`, `[::1]`, or an IPv4 address in `127.0.0.0/8`. URL parsing writes IPv4 addresses as four decimal parts. */
34
+ function isLoopbackHostname(hostname) {
35
+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(hostname);
36
+ }
37
+ /**
38
+ * Whether a browser treats `origin` as secure: `https:`, or `http:` on a loopback host (`localhost`, `*.localhost`,
39
+ * `127.0.0.0/8`, or `[::1]`). A route that answers with a secret, or builds a URL that carries one, needs this.
40
+ */
41
+ function isSecureOrigin(origin) {
42
+ if (!URL.canParse(origin)) return false;
43
+ const { protocol, hostname } = new URL(origin);
44
+ if (protocol === "https:") return true;
45
+ if (protocol !== "http:") return false;
46
+ return isLoopbackHostname(hostname) || hostname.endsWith(".localhost");
47
+ }
48
+ //#endregion
49
+ export { isSecureOrigin as n, matchesPublicOrigin as r, forwardedRequestOrigin as t };
@@ -1,4 +1,4 @@
1
- import { k as CommentsTransport } from "./types-C7LzhgRb.js";
1
+ import { k as CommentsTransport } from "./types-BLaYh0_f.js";
2
2
  //#region src/operations-core/rpc.d.ts
3
3
  interface RpcTransportOptions {
4
4
  /** The app origin and mount, such as `https://app.example.com` or `/portal`. Defaults to the page origin. */
package/dist/rpc.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { n as createRpcTransport, t as RpcTransportOptions } from "./rpc-BZ1QNkCC.js";
1
+ import { n as createRpcTransport, t as RpcTransportOptions } from "./rpc-CuJ5GLIz.js";
2
2
  export { RpcTransportOptions, createRpcTransport };
@@ -1,5 +1,5 @@
1
- import { d as CommentsPeople, g as CommentsUser } from "../define-CHTWfHPo.js";
2
- import { s as CommentsRequestEvent } from "../types-C1qzObs2.js";
1
+ import { d as CommentsPeople, g as CommentsUser } from "../define-CmIFU96x.js";
2
+ import { f as CommentsRequestEvent } from "../types-C35INXIs.js";
3
3
  //#region src/runtime/auth.d.ts
4
4
  /** The ViteHub Auth user of a request, or null. Generated Comments files pass it as `session` when the app has Auth. */
5
5
  export declare function commentsAuthSession(event: CommentsRequestEvent): Promise<CommentsUser | null>;
@@ -1,4 +1,4 @@
1
- import { n as createAuthUsers } from "../server-CqyzrqTI.js";
1
+ import { n as createAuthUsers } from "../server-Yk610niJ.js";
2
2
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
3
3
  //#region src/runtime/auth.ts
4
4
  const authServer = () => import("@vite-hub/auth/internal/server");
@@ -1,4 +1,4 @@
1
- import { n as ViteHubConsoleRecord } from "../console-h4KlhIik.js";
1
+ import { n as ViteHubConsoleRecord } from "../console-D1lwNMZn.js";
2
2
  //#region src/runtime/console.d.ts
3
3
  /** The threads of the app as Console records: open threads first, each group newest activity first. It runs on each Console request. */
4
4
  export declare function readCommentsConsoleRecords(): Promise<ViteHubConsoleRecord[]>;
@@ -1,6 +1,6 @@
1
1
  import { n as commentsPageScope } from "../page-DRz_sDY4.js";
2
2
  import { t as describeCommentContext } from "../context-BqIsmYP1.js";
3
- import { n as installedComments } from "../plugin-BNFd1zGz.js";
3
+ import { n as installedComments } from "../plugin-DRsNaJaK.js";
4
4
  //#region src/runtime/console.ts
5
5
  function excerpt(text) {
6
6
  const line = text.replace(/\s+/g, " ").trim();
@@ -1,10 +1,10 @@
1
- import { s as CommentContext } from "../types-C7LzhgRb.js";
2
- import { g as CommentsUser } from "../define-CHTWfHPo.js";
3
- import { s as CommentsRequestEvent } from "../types-C1qzObs2.js";
4
- import { t as Comments } from "../index-iPGlSAgj.js";
5
- import { o as CommentsDatabase } from "../service-wC9kx9EX.js";
6
- import { t as CommentsSessionOptions } from "../session-CKfW6DGE.js";
7
- import { t as InstallCommentsOptions } from "../install-96NXWnrw.js";
1
+ import { s as CommentContext } from "../types-BLaYh0_f.js";
2
+ import { g as CommentsUser } from "../define-CmIFU96x.js";
3
+ import { f as CommentsRequestEvent } from "../types-C35INXIs.js";
4
+ import { t as CommentsDatabase } from "../store-CsUNfC1w.js";
5
+ import { t as Comments } from "../index-RiHzmV16.js";
6
+ import { t as CommentsSessionOptions } from "../session-DUcEor2W.js";
7
+ import { t as InstallCommentsOptions } from "../install-BGGQKbQ4.js";
8
8
  //#region src/runtime/github-login.d.ts
9
9
  /** The Server Env names of the OAuth client that people sign in to Comments with: a GitHub App's, or an OAuth App's. */
10
10
  export declare const githubLoginEnv: {
@@ -133,6 +133,8 @@ interface CommentsPluginOptions extends CommentsSessionOptions {
133
133
  /** The tables of a Postgres Database. Default: the SQLite tables. */
134
134
  tables?: InstallCommentsOptions["tables"];
135
135
  dialect?: InstallCommentsOptions["dialect"];
136
+ /** Loads `@vite-hub/webhooks`, when `defineComments({ send })` is on. */
137
+ webhooks?: InstallCommentsOptions["webhooks"];
136
138
  }
137
139
  /** The Comments definition that the Nitro plugin installed, for the Console reader. */
138
140
  export declare function installedComments(): Comments | undefined;
@@ -287,8 +289,8 @@ export declare function mcpToolResult(result: ViteHubMcpToolResult): {
287
289
  //#endregion
288
290
  //#region ../internal/src/runtime/page-tools.d.ts
289
291
  /**
290
- * The route of `GET /_vitehub/page/session`: a Fetchable (https://fetchable.org). Nitro 3 binds each Request to its
291
- * app in `installViteHubPageTools()`, so the route finds the tools of that app.
292
+ * The route of `GET /_vitehub/page/tools`: a Fetchable (https://fetchable.org). `installViteHubPageTools()` binds
293
+ * each Request to its app in Nitro's `request` hook, so the route finds the tools of that app.
292
294
  */
293
295
  export declare const viteHubPageSessionHandler: {
294
296
  fetch(request: Request): Promise<Response>;
@@ -1,16 +1,17 @@
1
1
  import "../client-files-CJZl5Kc4.js";
2
- import { t as commentsErrorDiagnostics } from "../errors-BHsVXlpd.js";
2
+ import { t as commentsErrorDiagnostics } from "../errors-Dq4AHjza.js";
3
3
  import { i as commentsRoute, n as commentsPageScope, o as normalizeCommentPage } from "../page-DRz_sDY4.js";
4
- import { a as commentThreadSummary, c as hiddenThreadsNote, n as commentAnchorSchema, o as commentThreadsText, r as commentInputSchemas, s as describeCommentThread, t as commentActions } from "../operations-9tskoLsk.js";
4
+ import { a as commentThreadSummary, c as hiddenThreadsNote, n as commentAnchorSchema, o as commentThreadsText, r as commentInputSchemas, s as describeCommentThread, t as commentActions } from "../operations-lsVKE0GH.js";
5
5
  import { t as invariant } from "../invariant-D8_xBqmZ.js";
6
- import { h as readAttachment, i as contextSchema, n as base64, o as deniedError, p as mentionedPeople, r as can } from "../service-C8ZgFWvy.js";
6
+ import { h as readAttachment, i as contextSchema, n as base64, o as deniedError, p as mentionedPeople, r as can } from "../service-DA5BwfPQ.js";
7
7
  import { i as text, n as guestFromHeaders, t as authorOf } from "../identity-CBOzgxSf.js";
8
- import { c as validateCommentsDefinition, o as deniedForMissingPolicy } from "../define-CX_Yr_hz.js";
8
+ import { c as validateCommentsDefinition, o as deniedForMissingPolicy } from "../define-BMBSVbD9.js";
9
9
  import { a as runWithActiveCloudflareEnv, i as getActiveCloudflareBinding, r as rememberGitHubToken, t as forgetGitHubToken } from "../tokens-DSbwkVSy.js";
10
- import { a as runtimeOf, r as resolveCommentsRuntime } from "../installed-g6nDr5ac.js";
11
- import { t as commentsErrors } from "../errors-4gelGVmK.js";
12
- import { a as viteHubPageSessionHandler, n as resolveCommentsPage, o as forwardedRequestOrigin, t as resolveCommentsIdentity } from "../session-ByjMyTak.js";
13
- import { n as installedComments, t as defineCommentsPlugin } from "../plugin-BNFd1zGz.js";
10
+ import { t as forwardedRequestOrigin } from "../request-origin-CFU0TQ7E.js";
11
+ import { t as commentsErrors } from "../errors-BJTZ9iyv.js";
12
+ import { a as runtimeOf, r as resolveCommentsRuntime, t as commentSendOf } from "../installed-C3EoqJEY.js";
13
+ import { a as viteHubPageSessionHandler, n as resolveCommentsPage, t as resolveCommentsIdentity } from "../session-X_g9dnU5.js";
14
+ import { n as installedComments, t as defineCommentsPlugin } from "../plugin-DRsNaJaK.js";
14
15
  import { getStandardContext, installRequestStandardContext } from "@vite-hub/runtime/internal/h3";
15
16
  import * as v from "valibot";
16
17
  import { defineGrant } from "@vite-hub/runtime/internal/grant";
@@ -53,8 +54,14 @@ const fieldBody = v.object({
53
54
  function status(code) {
54
55
  switch (code) {
55
56
  case "COMMENTS_NOT_FOUND":
56
- case "COMMENTS_CONTENT_MISSING": return 404;
57
+ case "COMMENTS_CONTENT_MISSING":
58
+ case "COMMENTS_SEND_OFF": return 404;
59
+ case "COMMENTS_SEND_GRANT_INVALID": return 401;
60
+ case "COMMENTS_SEND_CODE_EXPIRED": return 410;
61
+ case "COMMENTS_SEND_CODE_USED": return 409;
62
+ case "COMMENTS_SEND_CODE_REFUSED": return 422;
57
63
  case "COMMENTS_FORBIDDEN":
64
+ case "COMMENTS_SEND_INSECURE":
58
65
  case "COMMENTS_POLICY_MISSING":
59
66
  case "COMMENTS_FIELD_FORBIDDEN": return 403;
60
67
  case "COMMENTS_RESOLVED":
@@ -274,6 +281,7 @@ function createCommentsHandler(options) {
274
281
  url: `${route}/auth/github`
275
282
  } : void 0;
276
283
  const signOut = user && user.github && github ? `${route}/auth/sign-out` : void 0;
284
+ const send = Boolean(comments.options.send && user && !user.guest && comment && await commentSendOf(comments));
277
285
  return json({ data: {
278
286
  user: user ? authorOf(user) : null,
279
287
  ...user && user.github ? { github: user.github } : {},
@@ -288,6 +296,7 @@ function createCommentsHandler(options) {
288
296
  realtime: options.realtime,
289
297
  ...options.presence === false ? { presence: false } : {},
290
298
  content: Boolean(options.content),
299
+ ...send ? { send: true } : {},
291
300
  ...subject ? { subject } : {},
292
301
  ...revision === void 0 ? {} : { revision }
293
302
  } });
@@ -483,6 +492,77 @@ function createCommentsHandler(options) {
483
492
  const env = request["~standard"].runtime?.cloudflare?.env;
484
493
  return env ? await runWithActiveCloudflareEnv(env, () => handle(request)) : await handle(request);
485
494
  } };
495
+ async function sendRoute(request, url, parts, pageOf) {
496
+ const service = await commentSendOf(comments);
497
+ if (!service) return failure$1(commentsErrors.COMMENTS_SEND_OFF());
498
+ const method = request.method;
499
+ const [, action, code] = parts;
500
+ if (method === "POST" && action === "pair" && !code) {
501
+ const [error, paired] = await service.pair(await readJson(request), forwardedRequestOrigin(request));
502
+ return error ? json({
503
+ error,
504
+ reason: {
505
+ COMMENTS_SEND_CODE_EXPIRED: "expired",
506
+ COMMENTS_SEND_CODE_USED: "used",
507
+ COMMENTS_SEND_CODE_REFUSED: "refused",
508
+ COMMENTS_SEND_INSECURE: "insecure"
509
+ }[error.code] ?? "invalid"
510
+ }, { status: status(error.code) }) : json({ data: paired });
511
+ }
512
+ if (method === "GET" && action && action.startsWith("send_") && !code) {
513
+ const token = /^Bearer\s+(\S+)$/i.exec(request.headers.get("authorization") ?? "")?.[1];
514
+ if (!token) return failure$1(commentsErrors.COMMENTS_SEND_GRANT_INVALID());
515
+ return respond(await service.read(decodeURIComponent(action), token));
516
+ }
517
+ const { user, gate } = await identityOf(request);
518
+ const pathname = url.pathname;
519
+ const caller = async () => {
520
+ const subject = (await pageOf())?.subject;
521
+ if (!subject) return void 0;
522
+ return {
523
+ user,
524
+ gate,
525
+ subject,
526
+ page: normalizeCommentPage(url.searchParams.get("page") ?? "/"),
527
+ origin: forwardedRequestOrigin(request),
528
+ route: pathname.slice(0, pathname.indexOf(commentsRoute) + commentsRoute.length)
529
+ };
530
+ };
531
+ if (action === "pair" && code && !parts[3]) {
532
+ const who = {
533
+ user,
534
+ gate,
535
+ subject: {
536
+ kind: "page",
537
+ id: "/"
538
+ },
539
+ page: "/",
540
+ origin: "",
541
+ route: ""
542
+ };
543
+ if (method === "GET") return json({ data: await service.check(who, decodeURIComponent(code)) });
544
+ if (method === "DELETE") {
545
+ await service.cancel(who, decodeURIComponent(code));
546
+ return json({ data: null });
547
+ }
548
+ }
549
+ const who = await caller();
550
+ if (!who) return failure$1(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "page: Give the page that Send is on." }));
551
+ if (method === "GET" && action === "status" && !code) return json({ data: await service.status(who) });
552
+ if (method === "POST" && action === "start" && !code) return respond(await service.start(who));
553
+ if (method === "POST" && action === "allow" && !code) {
554
+ const body = await readJson(request);
555
+ const given = typeof body === "object" && body !== null ? Reflect.get(body, "code") : void 0;
556
+ if (typeof given !== "string" || !given) return failure$1(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "code: Send the setup code that the agent used." }));
557
+ const selection = typeof body === "object" && body !== null ? Reflect.get(body, "selection") : void 0;
558
+ return respond(await service.allow(who, given, typeof selection === "string" ? selection : ""));
559
+ }
560
+ if (method === "POST" && !action) return respond(await service.send(who));
561
+ return json({ error: {
562
+ code: "COMMENTS_NOT_FOUND",
563
+ why: `No Comments route ${method} ${url.pathname.slice(url.pathname.indexOf(commentsRoute) + commentsRoute.length)}.`
564
+ } }, { status: 404 });
565
+ }
486
566
  async function route(request) {
487
567
  const url = new URL(request.url);
488
568
  const path = url.pathname.slice(url.pathname.indexOf("/_vitehub/comments") + 18).replace(/\/+$/, "") || "/";
@@ -496,10 +576,11 @@ function createCommentsHandler(options) {
496
576
  id: subjectId
497
577
  } } : void 0;
498
578
  const subjectOf = async () => (await pageOf())?.subject;
499
- if (method !== "GET" && !sameOrigin(request)) return json({ error: {
579
+ if (method !== "GET" && !(method === "POST" && path === "/send/pair") && !sameOrigin(request)) return json({ error: {
500
580
  code: "COMMENTS_FORBIDDEN",
501
581
  why: "Comments requests must come from the site's own pages."
502
582
  } }, { status: 403 });
583
+ if (parts[0] === "send") return await sendRoute(request, url, parts, pageOf);
503
584
  if (method === "GET" && path === "/session") {
504
585
  const current = await pageOf();
505
586
  return await session(request, current?.subject, current?.revision);
@@ -549,7 +630,7 @@ function createCommentsHandler(options) {
549
630
  const threadId = decodeURIComponent(parts[1]);
550
631
  const action = parts[2];
551
632
  const messageId = parts[3] ? decodeURIComponent(parts[3]) : void 0;
552
- if (method === "GET" && !action) return await act(request, "read", (who) => commentActions.get({ id: threadId }, who), (thread, who) => threadResponse(who, thread));
633
+ if (method === "GET" && !action) return await act(request, "read", (who) => commentActions.get({ threadId }, who), (thread, who) => threadResponse(who, thread));
553
634
  if (method === "POST" && action === "comments" && !messageId) {
554
635
  const parsed = v.safeParse(replyBody, await readJson(request));
555
636
  if (!parsed.success) return invalid(parsed.issues);
@@ -765,7 +846,7 @@ function commentsMcpTools(comments, options = {}) {
765
846
  })
766
847
  };
767
848
  }
768
- return [
849
+ const tools = [
769
850
  {
770
851
  name: "comments_list_threads",
771
852
  title: "List ViteHub Comments threads",
@@ -903,7 +984,11 @@ function commentsMcpTools(comments, options = {}) {
903
984
  body: {
904
985
  type: "string",
905
986
  description: "Markdown, at most 10,000 characters."
906
- }
987
+ },
988
+ ...comments.options.send ? { send: {
989
+ type: "string",
990
+ description: "The send ID from comments_get_send when answering an ask."
991
+ } } : {}
907
992
  },
908
993
  required: ["id", "body"],
909
994
  additionalProperties: false
@@ -915,10 +1000,23 @@ function commentsMcpTools(comments, options = {}) {
915
1000
  const { thread, grant } = found;
916
1001
  const author = identity.user ? authorOf(identity.user) : guestFor(context);
917
1002
  if (!author) return forbidden("write");
1003
+ const send = text(input.send);
1004
+ if (send) {
1005
+ const service = await commentSendOf(comments);
1006
+ const opened = identity.user && !identity.user.guest && await service?.readOwn(identity.user, send, {
1007
+ gate: identity.gate,
1008
+ console: admitted
1009
+ });
1010
+ if (!opened || !opened.threads.some((entry) => entry.id === thread.id && entry.role === "ask")) return forbidden("write");
1011
+ }
918
1012
  spend(grant, "write", thread.id);
919
1013
  const [error, message] = await comments.reply(thread.id, {
920
1014
  body: text(input.body) ?? "",
921
- author
1015
+ author,
1016
+ ...send ? { actor: {
1017
+ id: "comments-mcp",
1018
+ name: "Comments agent"
1019
+ } } : {}
922
1020
  });
923
1021
  if (error) return failure(error.why);
924
1022
  await comments.flush();
@@ -968,6 +1066,42 @@ function commentsMcpTools(comments, options = {}) {
968
1066
  }
969
1067
  }
970
1068
  ];
1069
+ if (comments.options.send) tools.push({
1070
+ name: "comments_get_send",
1071
+ title: "Read a ViteHub Comments send",
1072
+ description: "ViteHub Comments: read the threads that the signed-in user sent to their agent with Send in the comment pill. Each thread says whether it is an ask, the user's own question, or a quote, what someone else said. Without an id, it reads the user's latest send that no agent read yet. Answer each ask with comments_reply, passing the send ID as `send`.",
1073
+ section: "comments",
1074
+ annotations: { readOnlyHint: true },
1075
+ inputSchema: {
1076
+ type: "object",
1077
+ properties: { id: {
1078
+ type: "string",
1079
+ description: "The send id, such as send_… from the delivery. Default: the latest unread send."
1080
+ } },
1081
+ additionalProperties: false
1082
+ },
1083
+ async call(input, context) {
1084
+ const { user, gate } = await identityFor(context);
1085
+ if (!user || user.guest) return forbidden("read");
1086
+ const service = await commentSendOf(comments);
1087
+ if (!service) return failure(`${commentsErrors.COMMENTS_SEND_OFF().why} ${commentsErrors.COMMENTS_SEND_OFF().fix}`);
1088
+ const id = text(input.id);
1089
+ const opened = await service.readOwn(user, id, {
1090
+ gate,
1091
+ console: admitted
1092
+ });
1093
+ if (!opened) return failure(id ? `No send ${id} of this user.` : "This user has no send that an agent did not read yet.");
1094
+ const { send, threads } = opened;
1095
+ return {
1096
+ text: [`Send ${send.id} from ${send.page}, ${new Date(send.createdAt).toISOString()}: ${threads.length} ${threads.length === 1 ? "thread" : "threads"}.`, ...threads.flatMap((thread) => ["", `${thread.role === "ask" ? "Ask" : "Quote"}: ${describeCommentThread(thread)}`])].join("\n"),
1097
+ structured: {
1098
+ send: { ...send },
1099
+ threads: threads.map((thread) => ({ ...thread }))
1100
+ }
1101
+ };
1102
+ }
1103
+ });
1104
+ return tools;
971
1105
  }
972
1106
  //#endregion
973
1107
  //#region ../internal/src/runtime/mcp-server.ts
@@ -1,4 +1,4 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-BHsVXlpd.js";
1
+ import { t as commentsErrorDiagnostics } from "./errors-Dq4AHjza.js";
2
2
  //#region src/operations-core/server.ts
3
3
  const key = Symbol.for("vitehub.comments.runtime");
4
4
  const scope = globalThis;
package/dist/server.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { d as CommentsPeople, x as validateCommentsDefinition } from "./define-CHTWfHPo.js";
2
- import { a as maximumCommentBodyLength, c as CommentsTables, i as CommentsRuntime, l as createCommentsStore, n as CommentsAttachmentStore, o as CommentsDatabase, r as CommentsForgeHooks, s as CommentsStore } from "./service-wC9kx9EX.js";
3
- import { a as commentsOperations, i as commentInputSchemas, n as commentActions, r as commentAnchorSchema, t as CommentsCaller } from "./operations-D93EV10O.js";
4
- import { n as createRpcTransport, t as RpcTransportOptions } from "./rpc-BZ1QNkCC.js";
5
- import { n as installComments, t as InstallCommentsOptions } from "./install-96NXWnrw.js";
1
+ import { b as validateCommentsDefinition, d as CommentsPeople } from "./define-CmIFU96x.js";
2
+ import { i as createCommentsStore, n as CommentsStore, r as CommentsTables, t as CommentsDatabase } from "./store-CsUNfC1w.js";
3
+ import { a as maximumCommentBodyLength, i as CommentsRuntime, n as CommentsAttachmentStore, r as CommentsForgeHooks } from "./service-Bj-Mg63c.js";
4
+ import { a as commentsOperations, i as commentInputSchemas, n as commentActions, r as commentAnchorSchema, t as CommentsCaller } from "./operations-BKhUWYkb.js";
5
+ import { n as createRpcTransport, t as RpcTransportOptions } from "./rpc-CuJ5GLIz.js";
6
+ import { n as installComments, t as InstallCommentsOptions } from "./install-BGGQKbQ4.js";
6
7
  //#region src/operations-core/server.d.ts
7
8
  /** Where mentions find people. The same shape as `defineComments({ people })`. */
8
9
  export type CommentsUsers = CommentsPeople;
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
1
- import { r as createCommentsStore, t as installComments } from "./install-jRKmuLHK.js";
2
- import { i as commentsOperations, n as commentAnchorSchema, r as commentInputSchemas, t as commentActions } from "./operations-9tskoLsk.js";
1
+ import { r as createCommentsStore, t as installComments } from "./install-DrAse1Fa.js";
2
+ import { i as commentsOperations, n as commentAnchorSchema, r as commentInputSchemas, t as commentActions } from "./operations-lsVKE0GH.js";
3
3
  import { t as createRpcTransport } from "./rpc-BQqYx8kb.js";
4
- import { f as maximumCommentBodyLength } from "./service-C8ZgFWvy.js";
5
- import { c as validateCommentsDefinition } from "./define-CX_Yr_hz.js";
6
- import { i as installCommentsRuntime, n as createAuthUsers, r as hasCommentsRuntime, t as commentsRuntime } from "./server-CqyzrqTI.js";
4
+ import { f as maximumCommentBodyLength } from "./service-DA5BwfPQ.js";
5
+ import { c as validateCommentsDefinition } from "./define-BMBSVbD9.js";
6
+ import { i as installCommentsRuntime, n as createAuthUsers, r as hasCommentsRuntime, t as commentsRuntime } from "./server-Yk610niJ.js";
7
7
  export { commentActions, commentAnchorSchema, commentInputSchemas, commentsOperations, commentsRuntime, createAuthUsers, createCommentsStore, createRpcTransport, hasCommentsRuntime, installComments, installCommentsRuntime, maximumCommentBodyLength, validateCommentsDefinition };
@@ -0,0 +1,73 @@
1
+ import { T as CommentThread } from "./types-BLaYh0_f.js";
2
+ import { d as CommentsPeople, g as CommentsUser, l as CommentsDefinition } from "./define-CmIFU96x.js";
3
+ import { n as CommentsStore } from "./store-CsUNfC1w.js";
4
+ import "valibot";
5
+ //#region ../internal/src/runtime/client-rate-limit.d.ts
6
+ /** The part of `checkRateLimit()` from `vite-hub/rate-limit` that a public write calls. */
7
+ type SharedRateLimit = (request: Request, name: string, options: {
8
+ key: string;
9
+ limit: number;
10
+ window: `${number}${"ms" | "s" | "m" | "h" | "d"}`;
11
+ }) => Promise<[unknown, {
12
+ allowed: boolean;
13
+ reason?: string;
14
+ retryAfter?: number;
15
+ cause?: unknown;
16
+ } | undefined]>;
17
+ //#endregion
18
+ //#region src/operations-core/service.d.ts
19
+ /** Longest message, in characters. */
20
+ declare const maximumCommentBodyLength = 10000;
21
+ /** The parts of a Blob store that attachments use: `blob` of `@vite-hub/blob`. */
22
+ interface CommentsAttachmentStore {
23
+ put: (pathname: string, body: Uint8Array, options: {
24
+ contentType: string;
25
+ }) => Promise<readonly [unknown, unknown]>;
26
+ get?: (pathname: string) => Promise<readonly [unknown, Blob | null | undefined]>;
27
+ }
28
+ /** A file to answer, with the headers that keep a browser from running it. */
29
+ interface CommentsAttachmentBody {
30
+ key: string;
31
+ name: string;
32
+ /** The stored media type when Comments attaches that type, else `application/octet-stream`. */
33
+ type: string;
34
+ size: number;
35
+ /** Whether a browser may show it in the page: images other than SVG. */
36
+ inline: boolean;
37
+ data: Blob;
38
+ }
39
+ /** The pull request sync of `defineComments({ forge })`. */
40
+ interface CommentsForgeHooks {
41
+ /** Starts the sync of a thread after a change. */
42
+ changed: (threadId: string) => void;
43
+ /** The threads with their `forge` link. */
44
+ attach: (threads: CommentThread[]) => Promise<CommentThread[]>;
45
+ }
46
+ /** Everything that the comment operations, the server API, and the overlay API share. */
47
+ interface CommentsRuntime {
48
+ definition: CommentsDefinition;
49
+ /**
50
+ * The app's `identify`, given the server event of a call. With it, the comment operations ask it for the user, as
51
+ * the overlay API does, instead of taking the Console's user.
52
+ */
53
+ identify?: (event: unknown) => Promise<CommentsUser | null>;
54
+ store: CommentsStore;
55
+ /** The Auth adapter. `people` wins over it. Without both, `@` finds the authors that the store knows. */
56
+ users?: CommentsPeople;
57
+ /** Vite's serve command, for the default guest policy. */
58
+ development?: boolean;
59
+ /** The Blob store for attachments, when the app has one and no `storeAttachment`. */
60
+ attachments?: CommentsAttachmentStore;
61
+ forge?: CommentsForgeHooks;
62
+ /**
63
+ * `checkRateLimit` of ViteHub Rate Limit, when it counts in a KV store that every server process shares. Guest writes
64
+ * then count under the Rate Limit name `comments`. Without it, they count in the memory of this process.
65
+ */
66
+ rateLimit?: SharedRateLimit;
67
+ /** Work that runs after the answer, such as `onMention`. `flush()` of the server API waits for it. */
68
+ background?: (task: Promise<unknown>) => void;
69
+ /** Runs after someone opens a thread again. With Send, it puts back the sends that carried the thread. */
70
+ reopened?: (thread: CommentThread) => Promise<unknown>;
71
+ }
72
+ //#endregion
73
+ export { maximumCommentBodyLength as a, CommentsRuntime as i, CommentsAttachmentStore as n, SharedRateLimit as o, CommentsForgeHooks as r, CommentsAttachmentBody as t };