@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
@@ -1,6 +1,6 @@
1
- import { g as CommentsUser } from "./define-B3TF9zzn.js";
2
- import { s as CommentsRequestEvent } from "./types-BIS0hCEl.js";
3
- import "./index-DNhy69Wt.js";
1
+ import { g as CommentsUser } from "./define-CmIFU96x.js";
2
+ import { f as CommentsRequestEvent } from "./types-C35INXIs.js";
3
+ import "./index-RiHzmV16.js";
4
4
  //#region src/runtime/session.d.ts
5
5
  interface CommentsSessionOptions {
6
6
  /** Reads the ViteHub Auth user only when no custom `identify` is configured. */
@@ -1,5 +1,6 @@
1
- import { o as normalizeCommentPage } from "./page-B41ozN63.js";
2
- import { c as viteHubPageToolsInlineStart, f as viteHubPageToolsWanted, l as viteHubPageToolsLoader, n as viteHubBasePath, o as viteHubPageToolsHintCookie, p as withViteHubBase, r as viteHubPageSessionPath, s as viteHubPageToolsInlineScript, t as readViteHubPageAccount, u as viteHubPageToolsMarker } from "./page-tools-shared-NHUjKI8E.js";
1
+ import { o as normalizeCommentPage } from "./page-DRz_sDY4.js";
2
+ import { r as matchesPublicOrigin, t as forwardedRequestOrigin } from "./request-origin-CFU0TQ7E.js";
3
+ import { c as viteHubPageToolsInlineStart, f as viteHubPageToolsWanted, l as viteHubPageToolsLoader, n as viteHubBasePath, o as viteHubPageToolsHintCookie, p as withViteHubBase, r as viteHubPageSessionPath, s as viteHubPageToolsInlineScript, t as readViteHubPageAccount, u as viteHubPageToolsMarker } from "./page-tools-shared-BNnuPK93.js";
3
4
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
4
5
  //#region ../internal/src/runtime/page-tools-html.ts
5
6
  /** The effective script-element directive is shared by HTTP and HTML meta policies. */
@@ -29,7 +30,7 @@ function isGeneratedCheck(inline) {
29
30
  try {
30
31
  const path = JSON.parse(inline.slice(at + 7, -1));
31
32
  const nonce = tagNonce(inline);
32
- return typeof path === "string" && path.endsWith("/_vitehub/page/assets/loader.js?v=21") && viteHubPageToolsInlineScript(path.slice(0, -36), nonce) === `${inline}<\/script>`;
33
+ return typeof path === "string" && path.endsWith("/_vitehub/page/assets/loader.js?v=22") && viteHubPageToolsInlineScript(path.slice(0, -36), nonce) === `${inline}<\/script>`;
33
34
  } catch {
34
35
  return false;
35
36
  }
@@ -163,28 +164,6 @@ function pageToolsHtmlTransform(loader) {
163
164
  });
164
165
  }
165
166
  //#endregion
166
- //#region ../internal/src/runtime/request-origin.ts
167
- function firstHeaderValue(headers, name) {
168
- return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
169
- }
170
- /**
171
- * The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
172
- * `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
173
- * Without these headers, or with values that are not valid, the result is the origin of `request.url`.
174
- */
175
- function forwardedRequestOrigin(request) {
176
- const url = new URL(request.url);
177
- const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
178
- const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
179
- const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
180
- if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
181
- try {
182
- return new URL(`${protocol}://${host}`).origin;
183
- } catch {
184
- return url.origin;
185
- }
186
- }
187
- //#endregion
188
167
  //#region ../internal/src/runtime/page-tools.ts
189
168
  const stateKey = Symbol.for("vitehub.page-tools");
190
169
  const scope = globalThis;
@@ -224,6 +203,10 @@ async function readAccount(nitroApp, request) {
224
203
  function viteHubSiteVisitorReader() {
225
204
  return state().siteVisitor;
226
205
  }
206
+ /** Whether the app serves its page tools on the origin of the request. Every origin counts for an app without `origins`. */
207
+ function servesOrigin(nitroApp, request) {
208
+ return matchesPublicOrigin(request, state().origins?.get(nitroApp) ?? []);
209
+ }
227
210
  /** The path of a URL below the app base. A path outside the base stays as it is. */
228
211
  function pathBelow(base, pathname) {
229
212
  return base && (pathname === base || pathname.startsWith(`${base}/`)) ? pathname.slice(base.length) || "/" : pathname;
@@ -241,6 +224,7 @@ function isPagePath(url, base) {
241
224
  function pageAddition(nitroApp, request, base) {
242
225
  const url = new URL(request.url);
243
226
  if ((state().tools.get(nitroApp)?.size ?? 0) === 0 || !isPagePath(url, base)) return void 0;
227
+ if (!request.headers.has("x-nitro-prerender") && !servesOrigin(nitroApp, request)) return void 0;
244
228
  return viteHubPageToolsWanted(url.search, request.headers.get("cookie") ?? "") ? "loader" : "bootstrap";
245
229
  }
246
230
  function loaderTag(base, nonce) {
@@ -258,12 +242,13 @@ function sessionResponse(value, init = {}) {
258
242
  });
259
243
  }
260
244
  /**
261
- * Answers `GET <base>/_vitehub/page/session`: the tools whose `allowed` check passes for this visitor, in registration
245
+ * Answers `GET <base>/_vitehub/page/tools`: the tools whose `allowed` check passes for this visitor, in registration
262
246
  * order. The app base is the part of the request path before the session path, as the Console finds its own base, and
263
247
  * each tool `script` path gets it. When at least one tool is allowed, the answer also has the `account` of a signed-in
264
248
  * visitor, from the reader of `registerViteHubPageAccount()`. An anonymous visitor never gets one. It sets the hint cookie to `1` when at least one tool is allowed, and to `0` when
265
249
  * none is, so a signed-in person without access does not ask again on each page. A tool whose check throws is not
266
- * allowed. Requests from other sites get 403 and run no check.
250
+ * allowed. Requests from other sites get 403 and run no check. An origin that the app does not serve its page tools on
251
+ * gets 404.
267
252
  */
268
253
  async function respondViteHubPageSession(nitroApp, request) {
269
254
  if (request.method !== "GET" && request.method !== "HEAD") return sessionResponse({ error: {
@@ -275,6 +260,10 @@ async function respondViteHubPageSession(nitroApp, request) {
275
260
  code: "VITEHUB_PAGE_TOOLS_CROSS_ORIGIN",
276
261
  why: "The page tools session answers the site's own pages only."
277
262
  } }, { status: 403 });
263
+ if (!servesOrigin(nitroApp, request)) return sessionResponse({ error: {
264
+ code: "VITEHUB_PAGE_TOOLS_ORIGIN",
265
+ why: "The page tools answer only on the public URL of the app."
266
+ } }, { status: 404 });
278
267
  const registered = [...state().tools.get(nitroApp)?.values() ?? []];
279
268
  const checks = await Promise.all(registered.map(async (tool) => {
280
269
  try {
@@ -299,8 +288,8 @@ async function respondViteHubPageSession(nitroApp, request) {
299
288
  } : { tools }, { cookie: viteHubPageToolsHintCookie(tools.length > 0) });
300
289
  }
301
290
  /**
302
- * The route of `GET /_vitehub/page/session`: a Fetchable (https://fetchable.org). Nitro 3 binds each Request to its
303
- * app in `installViteHubPageTools()`, so the route finds the tools of that app.
291
+ * The route of `GET /_vitehub/page/tools`: a Fetchable (https://fetchable.org). `installViteHubPageTools()` binds
292
+ * each Request to its app in Nitro's `request` hook, so the route finds the tools of that app.
304
293
  */
305
294
  const viteHubPageSessionHandler = { async fetch(request) {
306
295
  const nitroApp = state().apps.get(request);
@@ -412,13 +401,21 @@ function transformPage(response, tag, personal) {
412
401
  * static assets, still shows the pill. Call it from each owner's Nitro plugin: it installs once per app, whatever the
413
402
  * number of calls. It reads that app's registry and configured base on each request, so plugin order does not matter.
414
403
  * It wraps `nitroApp.fetch`, the Web entry that every preset and the prerenderer call. The tag uses `options.base`.
404
+ * It binds each request to the app in Nitro's `request` hook too, since another wrapper of `fetch` may pass a copy of
405
+ * the request inward, such as the `security` policy of `vite-hub` on Node.js.
415
406
  */
416
407
  function installViteHubPageTools(nitroApp, options = {}) {
417
408
  if (nitroApp === null || typeof nitroApp !== "object") return;
418
409
  const { installed, bases } = state();
419
410
  if (options.base !== void 0) bases.set(nitroApp, viteHubBasePath(options.base));
411
+ if (options.origins !== void 0) (state().origins ??= /* @__PURE__ */ new WeakMap()).set(nitroApp, options.origins);
420
412
  if (installed.has(nitroApp)) return;
421
413
  installed.add(nitroApp);
414
+ const hooks = Reflect.get(nitroApp, "hooks");
415
+ const hook = hooks && typeof hooks === "object" ? Reflect.get(hooks, "hook") : void 0;
416
+ if (hook instanceof Function) Reflect.apply(hook, hooks, ["request", (event) => {
417
+ if (event?.req instanceof Request) state().apps.set(event.req, nitroApp);
418
+ }]);
422
419
  const fetch = Reflect.get(nitroApp, "fetch");
423
420
  if (fetch instanceof Function) {
424
421
  Reflect.set(nitroApp, "fetch", async (request, ...rest) => {
@@ -500,4 +497,4 @@ async function resolveCommentsPage(comments, event, request, path) {
500
497
  };
501
498
  }
502
499
  //#endregion
503
- export { viteHubPageSessionHandler as a, registerViteHubPageTool as i, resolveCommentsPage as n, forwardedRequestOrigin as o, installViteHubPageTools as r, resolveCommentsIdentity as t };
500
+ export { viteHubPageSessionHandler as a, registerViteHubPageTool as i, resolveCommentsPage as n, installViteHubPageTools as r, resolveCommentsIdentity as t };
@@ -1,21 +1,6 @@
1
- import { S as CommentThread, _ as CommentMetadata, h as CommentListQuery, n as CommentActor, r as CommentAnchor, s as CommentContext, w as CommentUser, x as CommentSubject, y as CommentStatus } from "./types-CZujrMFd.js";
2
- import { d as CommentsPeople, g as CommentsUser, l as CommentsDefinition } from "./define-B3TF9zzn.js";
1
+ import { D as CommentUser, S as CommentStatus, T as CommentThread, b as CommentMetadata, n as CommentActor, r as CommentAnchor, s as CommentContext, v as CommentListQuery, w as CommentSubject } from "./types-BLaYh0_f.js";
3
2
  import { i as commentThreads, r as commentMessages, t as commentCounters } from "./database-CA1aHKN7.js";
4
- import "valibot";
5
3
  import { LibSQLDatabase } from "drizzle-orm/libsql";
6
- //#region ../internal/src/runtime/client-rate-limit.d.ts
7
- /** The part of `checkRateLimit()` from `vite-hub/rate-limit` that a public write calls. */
8
- type SharedRateLimit = (request: Request, name: string, options: {
9
- key: string;
10
- limit: number;
11
- window: `${number}${"ms" | "s" | "m" | "h" | "d"}`;
12
- }) => Promise<[unknown, {
13
- allowed: boolean;
14
- reason?: string;
15
- retryAfter?: number;
16
- cause?: unknown;
17
- } | undefined]>;
18
- //#endregion
19
4
  //#region src/operations-core/store.d.ts
20
5
  /**
21
6
  * The Drizzle database that the store uses. The store calls `select`, `insert`, `update`, and `delete` (with
@@ -77,7 +62,7 @@ interface CommentsStore {
77
62
  createThread: (input: NewThread) => Promise<CommentThread>;
78
63
  /**
79
64
  * Adds a message. A resolved thread takes it only with `allowResolved`; otherwise it fails with `COMMENTS_R0016`,
80
- * checked in the same statement as the insert.
65
+ * checked in the same statement as the insert. A message id that is already stored fails with `COMMENTS_R0022`.
81
66
  */
82
67
  addMessage: (threadId: string, input: NewMessage, options?: {
83
68
  allowResolved?: boolean;
@@ -90,9 +75,16 @@ interface CommentsStore {
90
75
  deleteMessage: (threadId: string, messageId: string, now: number) => Promise<CommentThread>;
91
76
  /** With `ownerId`, delete only if every message still belongs to that owner at mutation time. */
92
77
  deleteThread: (threadId: string, ownerId?: string) => Promise<boolean>;
93
- setStatus: (threadId: string, status: CommentStatus, by: CommentUser, now: number) => Promise<CommentThread>;
78
+ /** `actor`: the agent that resolves it for `by`. Reopening clears both. */
79
+ setStatus: (threadId: string, status: CommentStatus, by: CommentUser, now: number, actor?: CommentActor) => Promise<CommentThread>;
94
80
  /** Deletes every thread of a scope with its messages, and returns their ids. Numbers of the scope are never reused. */
95
81
  deleteScope: (scope: string) => Promise<string[]>;
82
+ /**
83
+ * Deletes the messages of one person. A thread with no message left goes too. A thread that they started keeps the
84
+ * replies of other people, without the person's name and image, and a thread that they resolved forgets who resolved
85
+ * it. Returns the ids of the threads that changed or went.
86
+ */
87
+ deleteUser: (userId: string) => Promise<string[]>;
96
88
  /**
97
89
  * The people that wrote in a thread, for a store without an Auth adapter. Only authors of threads that `canRead`
98
90
  * accepts count, and a message without a thread never shows.
@@ -102,57 +94,4 @@ interface CommentsStore {
102
94
  }
103
95
  declare function createCommentsStore(database: CommentsDatabase, tables?: CommentsTables): CommentsStore;
104
96
  //#endregion
105
- //#region src/operations-core/service.d.ts
106
- /** Longest message, in characters. */
107
- declare const maximumCommentBodyLength = 10000;
108
- /** The parts of a Blob store that attachments use: `blob` of `@vite-hub/blob`. */
109
- interface CommentsAttachmentStore {
110
- put: (pathname: string, body: Uint8Array, options: {
111
- contentType: string;
112
- }) => Promise<readonly [unknown, unknown]>;
113
- get?: (pathname: string) => Promise<readonly [unknown, Blob | null | undefined]>;
114
- }
115
- /** A file to answer, with the headers that keep a browser from running it. */
116
- interface CommentsAttachmentBody {
117
- key: string;
118
- name: string;
119
- /** The stored media type when Comments attaches that type, else `application/octet-stream`. */
120
- type: string;
121
- size: number;
122
- /** Whether a browser may show it in the page: images other than SVG. */
123
- inline: boolean;
124
- data: Blob;
125
- }
126
- /** The pull request sync of `defineComments({ forge })`. */
127
- interface CommentsForgeHooks {
128
- /** Starts the sync of a thread after a change. */
129
- changed: (threadId: string) => void;
130
- /** The threads with their `forge` link. */
131
- attach: (threads: CommentThread[]) => Promise<CommentThread[]>;
132
- }
133
- /** Everything that the comment operations, the server API, and the overlay API share. */
134
- interface CommentsRuntime {
135
- definition: CommentsDefinition;
136
- /**
137
- * The app's `identify`, given the server event of a call. With it, the comment operations ask it for the user, as
138
- * the overlay API does, instead of taking the Console's user.
139
- */
140
- identify?: (event: unknown) => Promise<CommentsUser | null>;
141
- store: CommentsStore;
142
- /** The Auth adapter. `people` wins over it. Without both, `@` finds the authors that the store knows. */
143
- users?: CommentsPeople;
144
- /** Vite's serve command, for the default guest policy. */
145
- development?: boolean;
146
- /** The Blob store for attachments, when the app has one and no `storeAttachment`. */
147
- attachments?: CommentsAttachmentStore;
148
- forge?: CommentsForgeHooks;
149
- /**
150
- * `checkRateLimit` of ViteHub Rate Limit, when it counts in a KV store that every server process shares. Guest writes
151
- * then count under the Rate Limit name `comments`. Without it, they count in the memory of this process.
152
- */
153
- rateLimit?: SharedRateLimit;
154
- /** Work that runs after the answer, such as `onMention`. `flush()` of the server API waits for it. */
155
- background?: (task: Promise<unknown>) => void;
156
- }
157
- //#endregion
158
- export { maximumCommentBodyLength as a, CommentsTables as c, CommentsRuntime as i, createCommentsStore as l, CommentsAttachmentStore as n, CommentsDatabase as o, CommentsForgeHooks as r, CommentsStore as s, CommentsAttachmentBody as t, SharedRateLimit as u };
97
+ export { createCommentsStore as i, CommentsStore as n, CommentsTables as r, CommentsDatabase as t };
@@ -0,0 +1,16 @@
1
+ //#region src/table-names.ts
2
+ /**
3
+ * The tables of `commentsSchema` and `commentsPostgresSchema`: each schema key and its SQL name. The Comments
4
+ * contribution gives them to the Database, so resolving the Vite config loads neither the schema nor drizzle-orm. A
5
+ * test keeps them equal to both schemas.
6
+ */
7
+ const commentsTableNames = {
8
+ vitehubCommentThreads: "vitehub_comment_threads",
9
+ vitehubCommentMessages: "vitehub_comment_messages",
10
+ vitehubCommentCounters: "vitehub_comment_counters",
11
+ vitehubCommentForge: "vitehub_comment_forge"
12
+ };
13
+ /** The tables of `commentSendsSchema`: each schema key and its SQL name. Comments adds them when `send` is on. */
14
+ const commentSendsTableNames = { commentSends: "vitehub_comment_sends" };
15
+ //#endregion
16
+ export { commentsTableNames as n, commentSendsTableNames as t };
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { E as CommentsTransport, S as CommentThread, w as CommentUser, x as CommentSubject } from "./types-CZujrMFd.js";
1
+ import { D as CommentUser, T as CommentThread, k as CommentsTransport, w as CommentSubject } from "./types-BLaYh0_f.js";
2
2
  //#region src/operations-core/testing.d.ts
3
3
  export interface MemoryTransportOptions {
4
4
  /** The signed-in user. Every call acts as this user. */
package/dist/testing.js CHANGED
@@ -1,8 +1,17 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
1
+ import { t as replyMessageId } from "./reply-id-P_bSuEng.js";
2
+ import { t as commentsErrorDiagnostics } from "./errors-Dq4AHjza.js";
2
3
  //#region src/operations-core/testing.ts
4
+ function checkOutboxAccount(input, user) {
5
+ if (input.outbox && input.outbox.account !== user.id) throw Object.assign(commentsErrorDiagnostics.COMMENTS_OUTBOX_ACCOUNT_CHANGED(), { status: 401 });
6
+ }
3
7
  function copy(value) {
4
8
  return JSON.parse(JSON.stringify(value));
5
9
  }
10
+ /** The attachment keys of a message: the keys that it names, then one made-up key for each file that it brings. */
11
+ function attachmentsOf(input) {
12
+ const files = (input.files ?? []).map((file) => `memory/${crypto.randomUUID()}/${file instanceof File ? file.name : "file"}`);
13
+ return [...input.attachments ?? [], ...files];
14
+ }
6
15
  function sameSubject(a, b) {
7
16
  return a.kind === b.kind && a.id === b.id;
8
17
  }
@@ -39,7 +48,7 @@ function message(store, user, input) {
39
48
  const body = input.body.trim();
40
49
  if (!body && !input.attachments?.length) throw commentsErrorDiagnostics.COMMENTS_R0005();
41
50
  return {
42
- id: `message-${crypto.randomUUID()}`,
51
+ id: input.id ?? `message-${crypto.randomUUID()}`,
43
52
  threadId: input.threadId,
44
53
  body,
45
54
  author: copy(user),
@@ -89,10 +98,11 @@ function view(store, user) {
89
98
  return threads.sort((a, b) => a.n - b.n).map(copy);
90
99
  },
91
100
  async get(input) {
92
- const found = "id" in input ? store.threads.get(input.id) : [...store.threads.values()].find((item) => item.n === input.n && item.scope === input.scope);
101
+ const found = "threadId" in input ? store.threads.get(input.threadId) : [...store.threads.values()].find((item) => item.n === input.n && item.scope === input.scope);
93
102
  return found ? copy(found) : null;
94
103
  },
95
104
  async create(input) {
105
+ checkOutboxAccount(input, user);
96
106
  const scope = store.scope(input.subject);
97
107
  const request = input.requestId === void 0 ? void 0 : JSON.stringify([scope, input.requestId]);
98
108
  const earlier = request === void 0 ? void 0 : store.threads.get(store.requests.get(request) ?? "");
@@ -104,6 +114,7 @@ function view(store, user) {
104
114
  const id = `thread-${crypto.randomUUID()}`;
105
115
  const first = message(store, user, {
106
116
  ...input,
117
+ attachments: attachmentsOf(input),
107
118
  threadId: id
108
119
  });
109
120
  store.counters.set(scope, n);
@@ -115,6 +126,7 @@ function view(store, user) {
115
126
  subject: copy(input.subject),
116
127
  ...input.metadata === void 0 ? {} : { metadata: copy(input.metadata) },
117
128
  ...input.revision === void 0 ? {} : { revision: input.revision },
129
+ ...input.requestId === void 0 ? {} : { requestId: input.requestId },
118
130
  anchor: copy(input.anchor),
119
131
  status: "open",
120
132
  author: copy(user),
@@ -123,9 +135,28 @@ function view(store, user) {
123
135
  updatedAt: first.createdAt
124
136
  });
125
137
  },
126
- async reply(input) {
138
+ async reply(draft) {
139
+ checkOutboxAccount(draft, user);
140
+ const id = draft.requestId === void 0 ? void 0 : await replyMessageId(draft.threadId, draft.requestId);
141
+ const input = {
142
+ ...draft,
143
+ id,
144
+ attachments: attachmentsOf(draft)
145
+ };
127
146
  const found = copy(thread(store, input.threadId));
128
- found.messages.push(message(store, user, input));
147
+ const request = input.requestId === void 0 ? void 0 : JSON.stringify([
148
+ "reply",
149
+ input.threadId,
150
+ input.requestId
151
+ ]);
152
+ const earlier = request === void 0 ? void 0 : found.messages.find((entry) => entry.id === store.requests.get(request));
153
+ if (earlier) {
154
+ if (earlier.author.id !== user.id) throw commentsErrorDiagnostics.COMMENTS_R0022();
155
+ return found;
156
+ }
157
+ const added = message(store, user, input);
158
+ if (request !== void 0) store.requests.set(request, added.id);
159
+ found.messages.push(added);
129
160
  return save(found);
130
161
  },
131
162
  async edit(input) {
@@ -161,6 +192,7 @@ function view(store, user) {
161
192
  const found = copy(thread(store, input.threadId));
162
193
  found.status = "resolved";
163
194
  found.resolvedBy = copy(user);
195
+ delete found.resolvedActor;
164
196
  found.resolvedAt = store.now();
165
197
  return save(found);
166
198
  },
@@ -168,6 +200,7 @@ function view(store, user) {
168
200
  const found = copy(thread(store, input.threadId));
169
201
  found.status = "open";
170
202
  delete found.resolvedBy;
203
+ delete found.resolvedActor;
171
204
  delete found.resolvedAt;
172
205
  return save(found);
173
206
  },
@@ -168,6 +168,8 @@ interface CommentMessage {
168
168
  /** Milliseconds since the epoch. */
169
169
  createdAt: number;
170
170
  editedAt?: number;
171
+ /** Set only by the client's outbox: the message has a local `id` and is not on the server yet. */
172
+ delivery?: CommentDelivery;
171
173
  }
172
174
  interface CommentThread {
173
175
  id: string;
@@ -179,6 +181,8 @@ interface CommentThread {
179
181
  anchor: CommentAnchor;
180
182
  status: CommentStatus;
181
183
  resolvedBy?: CommentUser;
184
+ /** The agent that resolved it for `resolvedBy`, such as through an MCP client. Like `actor` for the author. */
185
+ resolvedActor?: CommentActor;
182
186
  resolvedAt?: number;
183
187
  author: CommentUser;
184
188
  actor?: CommentActor;
@@ -194,6 +198,29 @@ interface CommentThread {
194
198
  forge?: CommentForgeLink | null;
195
199
  createdAt: number;
196
200
  updatedAt: number;
201
+ /** The retry key of the `create` that started it, when it had one. The client matches its own waiting comment by it. */
202
+ requestId?: string;
203
+ /** Set only by the client's outbox: the thread has a local `id` and its `n` is 0. */
204
+ delivery?: CommentDelivery;
205
+ }
206
+ /** A comment or reply that the outbox of the client holds. */
207
+ interface CommentDelivery {
208
+ /** `pending` while it waits or goes out, `failed` when the server refused it. */
209
+ status: "pending" | "failed";
210
+ requestId: string;
211
+ /** The files that go with it, to show before the server stores them. */
212
+ files: Blob[];
213
+ /** Why the last try did not go out. A `pending` message with an error waits to try again. */
214
+ error?: CommentDeliveryError;
215
+ }
216
+ /** A failure that the outbox keeps with the entry. Plain data, so it is stored with the entry. */
217
+ interface CommentDeliveryError {
218
+ /** Such as `COMMENTS_R0013`. Absent when the error had no code. */
219
+ code?: string;
220
+ why: string;
221
+ fix?: string;
222
+ /** The HTTP status. 0 when the request got no answer. */
223
+ status: number;
197
224
  }
198
225
  interface CommentListQuery {
199
226
  subject?: CommentSubject;
@@ -222,7 +249,7 @@ interface CommentListCursor {
222
249
  }
223
250
  /** By id, or by number inside its scope, as `?comment=<n>` names it. */
224
251
  type CommentGetInput = {
225
- id: string;
252
+ threadId: string;
226
253
  } | {
227
254
  scope: string;
228
255
  n: number;
@@ -247,6 +274,11 @@ interface CommentReplyInput {
247
274
  body: string;
248
275
  mentions?: string[];
249
276
  attachments?: string[];
277
+ /**
278
+ * A retry key, such as `crypto.randomUUID()`, kept for one draft. A second reply with the same key in the same
279
+ * thread returns the thread with the first message and adds nothing.
280
+ */
281
+ requestId?: string;
250
282
  }
251
283
  interface CommentEditInput {
252
284
  threadId: string;
@@ -301,13 +333,25 @@ type CommentEvent = {
301
333
  * The seam between the browser and the server. Each method has the name and the input of one `comments.*` operation.
302
334
  * A mutation returns the thread as it is afterwards, and `delete` returns `null` when the thread is gone.
303
335
  */
336
+ interface CommentFiles {
337
+ /** Files that the transport stores and adds to `attachments` before sending the message. */
338
+ files?: Blob[];
339
+ /** The subject of the thread for reply file uploads. */
340
+ subject?: CommentSubject;
341
+ /** For queued writes, check the authenticated author on every write and save each completed upload before the next request. */
342
+ outbox?: {
343
+ account: string;
344
+ uploaded: (key: string) => Promise<void>;
345
+ };
346
+ }
304
347
  interface CommentsTransport {
305
348
  /** Whether the server accepts attachment keys. Defaults to true for custom transports. */
306
349
  supportsAttachments?: boolean;
307
350
  list: (query: CommentListQuery) => Promise<CommentThread[]>;
308
351
  get: (input: CommentGetInput) => Promise<CommentThread | null>;
309
- create: (input: CommentCreateInput) => Promise<CommentThread>;
310
- reply: (input: CommentReplyInput) => Promise<CommentThread>;
352
+ /** Gets the client's `requestId` and the files of the comment, which it stores first. */
353
+ create: (input: CommentCreateInput & CommentFiles) => Promise<CommentThread>;
354
+ reply: (input: CommentReplyInput & CommentFiles) => Promise<CommentThread>;
311
355
  edit: (input: CommentEditInput) => Promise<CommentThread>;
312
356
  delete: (input: CommentDeleteInput) => Promise<CommentThread | null>;
313
357
  resolve: (input: CommentStatusInput) => Promise<CommentThread>;
@@ -319,4 +363,4 @@ interface CommentsTransport {
319
363
  subscribe?: (listener: (event: CommentEvent) => void) => () => void;
320
364
  }
321
365
  //#endregion
322
- export { TextAnchor as A, CommentUploadInput as C, ElementAnchor as D, CommentsTransport as E, ImageAnchor as O, CommentThread as S, CommentUsersInput as T, CommentMetadata as _, CommentBuild as a, CommentStatusInput as b, CommentCreateInput as c, CommentEvent as d, CommentForgeLink as f, CommentMessage as g, CommentListQuery as h, CommentAttachment as i, PageAnchor as k, CommentDeleteInput as l, CommentListCursor as m, CommentActor as n, CommentComponent as o, CommentGetInput as p, CommentAnchor as r, CommentContext as s, AreaAnchor as t, CommentEditInput as u, CommentReplyInput as v, CommentUser as w, CommentSubject as x, CommentStatus as y };
366
+ export { ElementAnchor as A, CommentStatusInput as C, CommentUser as D, CommentUploadInput as E, PageAnchor as M, TextAnchor as N, CommentUsersInput as O, CommentStatus as S, CommentThread as T, CommentListCursor as _, CommentBuild as a, CommentMetadata as b, CommentCreateInput as c, CommentDeliveryError as d, CommentEditInput as f, CommentGetInput as g, CommentForgeLink as h, CommentAttachment as i, ImageAnchor as j, CommentsTransport as k, CommentDeleteInput as l, CommentFiles as m, CommentActor as n, CommentComponent as o, CommentEvent as p, CommentAnchor as r, CommentContext as s, AreaAnchor as t, CommentDelivery as u, CommentListQuery as v, CommentSubject as w, CommentReplyInput as x, CommentMessage as y };
@@ -1,5 +1,5 @@
1
- import { S as CommentThread, _ as CommentMetadata, m as CommentListCursor, r as CommentAnchor, s as CommentContext, w as CommentUser, x as CommentSubject, y as CommentStatus } from "./types-CZujrMFd.js";
2
- import { g as CommentsUser, l as CommentsDefinition } from "./define-B3TF9zzn.js";
1
+ import { D as CommentUser, S as CommentStatus, T as CommentThread, _ as CommentListCursor, b as CommentMetadata, n as CommentActor, r as CommentAnchor, s as CommentContext, w as CommentSubject } from "./types-BLaYh0_f.js";
2
+ import { g as CommentsUser, l as CommentsDefinition } from "./define-CmIFU96x.js";
3
3
  import { ViteHubContext } from "@vite-hub/runtime";
4
4
  //#region src/types.d.ts
5
5
  interface CommentsForgeTarget {
@@ -52,7 +52,80 @@ interface CommentsPageContext {
52
52
  interface CommentsPageSubject extends CommentSubject {
53
53
  revision?: number;
54
54
  }
55
+ /** What `send.address` gets: the member who presses Send, and the subject of their page. */
56
+ interface CommentSendAddressContext {
57
+ user: CommentsUser;
58
+ subject: CommentSubject;
59
+ }
60
+ /** What `send.payload` gets: one send, before Comments delivers it. */
61
+ interface CommentSendPayloadContext {
62
+ /** The id of the send, as `send` of the delivered body. */
63
+ send: string;
64
+ /** The member who pressed Send. */
65
+ user: CommentsUser;
66
+ /** The subject of the page that the member sent from. */
67
+ subject: CommentSubject;
68
+ /** The threads of the send. `asks` and `quotes` split their ids. */
69
+ threads: readonly CommentThread[];
70
+ asks: readonly string[];
71
+ quotes: readonly string[];
72
+ }
73
+ /** What `send.prompt` gets: the values of one setup code, and the default prompt. */
74
+ interface CommentSendPromptContext {
75
+ /** The member who pressed Send. */
76
+ user: CommentsUser;
77
+ /** The subject of the page that the member pairs from. */
78
+ subject: CommentSubject;
79
+ /** The public origin of the app, such as `https://joyandmaxi.com`. */
80
+ origin: string;
81
+ /** The URL that the agent posts the code to: `{ code, url, thread }` for a T3 task, or `{ code, inbox }` for an inbox. */
82
+ pairUrl: string;
83
+ /** The setup code. It works once, for 10 minutes. */
84
+ code: string;
85
+ /** The secret that signs each delivery to a T3 webhook task. */
86
+ secret: string;
87
+ /** Whether each send carries a read token. `false` when `grant` is `false`. */
88
+ grant: boolean;
89
+ /** The default prompt: the steps that connect a T3 Code thread. */
90
+ prompt: string;
91
+ }
92
+ /** A JSON value, as the delivered body holds it. */
93
+ type CommentSendData = string | number | boolean | null | CommentSendData[] | {
94
+ [key: string]: CommentSendData;
95
+ };
96
+ /**
97
+ * Send: a member hands the threads that wait for an answer to their own agent, such as a T3 Code thread. Each member
98
+ * pairs their agent once, in the comment pill.
99
+ */
100
+ interface CommentSendOptions {
101
+ /** Adds `data` to the delivered body, such as the id of a document that your own MCP reads. Default: `null`. */
102
+ payload?: (context: CommentSendPayloadContext) => CommentSendData | Promise<CommentSendData>;
103
+ /**
104
+ * The address of the agent that should get a send from this subject, such as the T3 thread link that wrote the
105
+ * document. A member who paired an agent from that thread sends there; otherwise to the agent they paired last.
106
+ * Default: none, so every send goes to the agent the member paired last.
107
+ */
108
+ address?: (context: CommentSendAddressContext) => string | null | undefined | Promise<string | null | undefined>;
109
+ /**
110
+ * `false` sends no read token: the agent reads the threads through your own MCP server, as the member. Default: each
111
+ * send carries a token that reads its threads, as the member, for 24 hours.
112
+ */
113
+ grant?: false;
114
+ /** The hosts that a paired agent URL may use. Default: `["relay.t3.codes"]`, the T3 Code relay. */
115
+ hosts?: readonly string[];
116
+ /**
117
+ * The setup prompt that Send copies, such as to add the steps of a Claude Code or Codex inbox, or to name the tools of
118
+ * your own MCP server. Default: `context.prompt`, the steps that connect a T3 Code thread.
119
+ */
120
+ prompt?: (context: CommentSendPromptContext) => string | Promise<string>;
121
+ }
55
122
  interface DefineCommentsOptions extends CommentsDefinition {
123
+ /**
124
+ * `true` turns on **Send** in the comment pill, for signed-in people who may write. It needs Webhooks and a SQLite
125
+ * Database: ViteHub adds the `vitehub_comment_sends` tables and the member endpoints of Webhooks. See
126
+ * https://vitehub.dev/docs/comments/send
127
+ */
128
+ send?: boolean | CommentSendOptions;
56
129
  /** Resolves the user of a request. Without it, Comments reads the ViteHub Auth session. Return `null` for anonymous. */
57
130
  identify?: (context: CommentsIdentifyContext) => CommentsUser | null | undefined | Promise<CommentsUser | null | undefined>;
58
131
  /** Name of the Database that stores comments. Defaults to the `default` Database, or the only one. */
@@ -111,14 +184,25 @@ interface EditCommentInput {
111
184
  interface ReplyInput {
112
185
  body: string;
113
186
  author: CommentUser;
187
+ /** The agent replying on behalf of the author. */
188
+ actor?: CommentActor;
114
189
  mentions?: string[];
115
190
  attachments?: string[];
191
+ /** A retry key. A second reply with the same key and author in the same thread returns the first message. */
192
+ requestId?: string;
193
+ }
194
+ interface FindCommentThreadInput {
195
+ /** The subject that the create named. Or set `page`. */
196
+ subject?: CommentSubject;
197
+ /** An app path, for a thread on a page. */
198
+ page?: string;
199
+ requestId: string;
116
200
  }
117
201
  interface ReplyOptions {
118
202
  /** Reply to a resolved thread, and keep it resolved. Default `false`: the reply fails with `COMMENTS_RESOLVED`. */
119
203
  allowResolved?: boolean;
120
204
  }
121
205
  /** Codes of the errors that Comments methods return in the `[error, data]` tuple. */
122
- type CommentsErrorCode = "COMMENTS_NOT_INSTALLED" | "COMMENTS_NOT_FOUND" | "COMMENTS_INVALID_INPUT" | "COMMENTS_FORBIDDEN" | "COMMENTS_POLICY_MISSING" | "COMMENTS_RESOLVED" | "COMMENTS_CONTENT_MISSING" | "COMMENTS_FIELD_INVALID" | "COMMENTS_FIELD_NOT_EDITABLE" | "COMMENTS_FIELD_FORBIDDEN" | "COMMENTS_FIELD_CONFLICT" | "COMMENTS_FIELD_LOCKED";
206
+ type CommentsErrorCode = "COMMENTS_NOT_INSTALLED" | "COMMENTS_NOT_FOUND" | "COMMENTS_INVALID_INPUT" | "COMMENTS_FORBIDDEN" | "COMMENTS_POLICY_MISSING" | "COMMENTS_RESOLVED" | "COMMENTS_CONTENT_MISSING" | "COMMENTS_FIELD_INVALID" | "COMMENTS_FIELD_NOT_EDITABLE" | "COMMENTS_FIELD_FORBIDDEN" | "COMMENTS_FIELD_CONFLICT" | "COMMENTS_FIELD_LOCKED" | "COMMENTS_SEND_OFF";
123
207
  //#endregion
124
- export { CommentsPageContext as a, CreateCommentThreadInput as c, ListCommentThreadsOptions as d, ReplyInput as f, CommentsIdentifyContext as i, DefineCommentsOptions as l, CommentsForgeOptions as n, CommentsPageSubject as o, ReplyOptions as p, CommentsForgeTarget as r, CommentsRequestEvent as s, CommentsErrorCode as t, EditCommentInput as u };
208
+ export { ListCommentThreadsOptions as _, CommentSendPromptContext as a, CommentsForgeTarget as c, CommentsPageSubject as d, CommentsRequestEvent as f, FindCommentThreadInput as g, EditCommentInput as h, CommentSendPayloadContext as i, CommentsIdentifyContext as l, DefineCommentsOptions as m, CommentSendData as n, CommentsErrorCode as o, CreateCommentThreadInput as p, CommentSendOptions as r, CommentsForgeOptions as s, CommentSendAddressContext as t, CommentsPageContext as u, ReplyInput as v, ReplyOptions as y };