@vite-hub/comments 0.6.1 → 0.8.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 (70) hide show
  1. package/README.md +8 -12
  2. package/dist/anchor.d.ts +1 -1
  3. package/dist/{client-diagnostics-D987sEK7.js → client-diagnostics-DoXqdnBd.js} +8 -0
  4. package/dist/client-request-B1DCz3a9.js +29 -0
  5. package/dist/client.d.ts +48 -223
  6. package/dist/client.js +232 -569
  7. package/dist/database.d.ts +1 -2
  8. package/dist/database.js +1 -1
  9. package/dist/{define-C2tnAtBU.js → define-C-LUOouq.js} +1 -1
  10. package/dist/{errors-C0VwRHiy.js → errors-C5utwZ5H.js} +0 -24
  11. package/dist/{errors-ByCRdInk.js → errors-DeSEHzRf.js} +1 -13
  12. package/dist/hosted/hosted-comments/frame.js +4 -1
  13. package/dist/hosted/hosted-comments/tools.js +362 -0
  14. package/dist/hosted/hosted-comments.js +1 -19
  15. package/dist/{index-D1T7RJ4R.d.ts → index-d6NsDxu9.d.ts} +4 -112
  16. package/dist/index.d.ts +4 -5
  17. package/dist/index.js +6 -20
  18. package/dist/{install-D6hXZaSN.js → install-BueV_fJY.js} +22 -780
  19. package/dist/{install-9L4ASzUC.d.ts → install-F-_O7zDr.d.ts} +5 -11
  20. package/dist/{installed-bPUnazFf.js → installed-BqQKo6WC.js} +2 -7
  21. package/dist/{database-Cguz3hZL.js → migrate-oseJAYbm.js} +2 -46
  22. package/dist/{operations-B1ALn4VS.js → operations-0llC5kKO.js} +49 -51
  23. package/dist/{operations-8hqTi0DH.d.ts → operations-DFLer1fR.d.ts} +1 -0
  24. package/dist/{operations-BkkrI8a3.d.ts → operations-jaihyWw2.d.ts} +36 -4
  25. package/dist/operations.d.ts +3 -3
  26. package/dist/operations.js +2 -2
  27. package/dist/overlay/client-ZBsUybIe.js +4 -0
  28. package/dist/overlay/overlay.js +68 -37
  29. package/dist/page/loader.js +36 -30
  30. package/dist/page-BgvzzsJb.d.ts +32 -0
  31. package/dist/{page-2NzFladc.js → page-CDhmXO-y.js} +24 -1
  32. package/dist/{page-tools-shared-fvmJQCrP.js → page-tools-shared-BCdvqA4S.js} +41 -6
  33. package/dist/{plugin-l4sPt5-n.js → plugin-DGUqlc3C.js} +9 -9
  34. package/dist/realtime.d.ts +10 -9
  35. package/dist/realtime.js +2 -4
  36. package/dist/{rpc-BYmbVkr8.js → rpc-kkxzQ3Qy.js} +1 -1
  37. package/dist/rpc.js +1 -1
  38. package/dist/runtime/auth.d.ts +1 -2
  39. package/dist/runtime/auth.js +1 -1
  40. package/dist/runtime/client-request-plugin.d.ts +2 -0
  41. package/dist/runtime/client-request-plugin.js +21 -0
  42. package/dist/runtime/console.js +2 -2
  43. package/dist/runtime/index.d.ts +6 -8
  44. package/dist/runtime/index.js +25 -153
  45. package/dist/{server-DvSehkPP.js → server-CAMs6viR.js} +1 -1
  46. package/dist/server.d.ts +11 -7
  47. package/dist/server.js +8 -7
  48. package/dist/{store-DvNTDNgn.d.ts → service-CMVA_Ryv.d.ts} +67 -1
  49. package/dist/{service-BIGe1Hpo.js → service-DaMq8TBw.js} +35 -33
  50. package/dist/{session-CCRLR9bf.js → session-B7GDrqsK.js} +207 -41
  51. package/dist/{session-CN4irEqf.d.ts → session-EzQqBeE8.d.ts} +2 -3
  52. package/dist/{table-names-BIHjuEFK.js → table-names-DUmWROM4.js} +1 -3
  53. package/dist/testing.js +1 -1
  54. package/dist/{define-B1jLSPe9.d.ts → types-qzJKgWYS.d.ts} +157 -4
  55. package/dist/vite.d.ts +3 -20
  56. package/dist/vite.js +20 -52
  57. package/package.json +9 -8
  58. package/dist/database-CPua6Q6_.d.ts +0 -573
  59. package/dist/hosted/hosted-comments/client-Czl2zu9P.js +0 -4
  60. package/dist/hosted/hosted-comments/dist-DyVmH21U.js +0 -14
  61. package/dist/hosted/hosted-comments/overlay-DpS0P-nd.js +0 -186
  62. package/dist/hosted/hosted-comments/protocol-DuB0Zhs-.js +0 -1
  63. package/dist/hosted/hosted-comments/rest-transport-CKZG_jZ4.js +0 -1
  64. package/dist/hosted/hosted-comments/tools-D8xg-kDW.js +0 -126
  65. package/dist/overlay/client-C7ftI-CB.js +0 -4
  66. package/dist/overlay/dist-yIZmvSaU.js +0 -1
  67. package/dist/page-DE71P_gQ.d.ts +0 -11
  68. package/dist/request-origin-YPzfE2eh.js +0 -48
  69. package/dist/service-IvgrI4XM.d.ts +0 -71
  70. package/dist/types-l6GOb_yc.d.ts +0 -206
package/dist/client.js CHANGED
@@ -1,9 +1,9 @@
1
- import { i as commentsUnansweredError, r as commentsClientDiagnostics, t as commentsAnswerError } from "./client-diagnostics-D987sEK7.js";
1
+ import { i as commentsUnansweredError, r as commentsClientDiagnostics, t as commentsAnswerError } from "./client-diagnostics-DoXqdnBd.js";
2
2
  import { i as withCommentFiles, n as outboxAccountHeader, r as retryAfterOf, t as failedCommentPreparation } from "./client-files-lC6X7XyS.js";
3
3
  import { t as replyMessageId } from "./reply-id-Cm9FGOBs.js";
4
- import { t as commentsErrorDiagnostics } from "./errors-ByCRdInk.js";
5
- import { o as commentsRoute } from "./page-2NzFladc.js";
4
+ import { s as commentsRoute } from "./page-CDhmXO-y.js";
6
5
  import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
6
+ import { t as commentsErrorDiagnostics } from "./errors-DeSEHzRf.js";
7
7
  import { t as foldName } from "./fold-name-g-xg0mQk.js";
8
8
  // ../internal/src/browser-environment.ts
9
9
  /** The real browser: window events, Web Locks, and a BroadcastChannel, each only when the browser has it. */
@@ -1036,6 +1036,211 @@ function createOutbox(options, host) {
1036
1036
  }
1037
1037
  };
1038
1038
  }
1039
+ // src/api-can.ts
1040
+ /**
1041
+ * Whether the Comments API lets `user` do `action`, from the permissions of the page session and the ones that the API
1042
+ * sent with the thread. A guest never edits or deletes, because the server does not take a guest id as proof. The
1043
+ * server still decides.
1044
+ */
1045
+ function commentsApiCan(user, page, action, { thread, message }) {
1046
+ if (!user) return false;
1047
+ const allowed = thread.can ?? {
1048
+ comment: Boolean(page?.comment),
1049
+ resolve: Boolean(page?.resolve),
1050
+ delete: Boolean(page?.delete)
1051
+ };
1052
+ if (action === "reply") return thread.status === "open" && allowed.comment;
1053
+ if (action === "resolve") return allowed.resolve;
1054
+ const own = (entry) => !user.guest && !entry.author.guest && entry.author.id === user.id;
1055
+ if (!message || page?.change === false) return false;
1056
+ if (action === "edit") return own(message);
1057
+ return (thread.messages[0]?.id === message.id ? thread.messages.every(own) : own(message)) ? allowed.comment : allowed.delete === true && !user.guest;
1058
+ }
1059
+ /** The app base, such as `/portal`, that Vite `base` or Nuxt `app.baseURL` sets. The Comments API of the app runs below it. */
1060
+ function appCommentsBase() {
1061
+ const base = typeof __VITEHUB_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_APP_BASE_URL__;
1062
+ return base.startsWith("/") && !base.startsWith("//") ? base.replace(/\/+$/, "") : "";
1063
+ }
1064
+ // src/guest.ts
1065
+ const guestKey = "vitehub-comments-guest";
1066
+ /** The guest name and id that this browser saved, the same one that the overlay uses. */
1067
+ function readCommentsGuest() {
1068
+ try {
1069
+ const value = JSON.parse(localStorage.getItem(guestKey) ?? "null");
1070
+ if (value && typeof value === "object" && "id" in value && "name" in value && typeof value.id === "string" && typeof value.name === "string") return {
1071
+ id: value.id,
1072
+ name: value.name
1073
+ };
1074
+ } catch {}
1075
+ }
1076
+ const savedListeners = /* @__PURE__ */ new Set();
1077
+ /** Saves the name that a guest typed. The id stays when the guest saved a name before. */
1078
+ function saveCommentsGuest(name) {
1079
+ const guest = {
1080
+ id: readCommentsGuest()?.id ?? crypto.randomUUID(),
1081
+ name
1082
+ };
1083
+ localStorage.setItem(guestKey, JSON.stringify(guest));
1084
+ for (const listener of savedListeners) listener(guest);
1085
+ return guest;
1086
+ }
1087
+ /** Calls `listener` each time `saveCommentsGuest()` saves a guest on this page. Returns a function that stops it. */
1088
+ function onCommentsGuestSaved(listener) {
1089
+ savedListeners.add(listener);
1090
+ return () => savedListeners.delete(listener);
1091
+ }
1092
+ function commentsGuestUser(guest) {
1093
+ return {
1094
+ id: `guest:${guest.id}`,
1095
+ name: guest.name,
1096
+ guest: true
1097
+ };
1098
+ }
1099
+ // src/rest-transport.ts
1100
+ /** The URL of an attachment key below the Comments API, such as `/_vitehub/comments/attachments/comments/<id>/shot.png`. */
1101
+ function commentAttachmentUrl(key, base = "") {
1102
+ return `${base.replace(/\/+$/, "")}${commentsRoute}/attachments/${key.split("/").map((part) => encodeURIComponent(part)).join("/")}`;
1103
+ }
1104
+ /**
1105
+ * Requests to the Comments API at `<base>/_vitehub/comments`, with the guest headers and the session cookie. A
1106
+ * failure throws a diagnostic with the `code`, `why`, and `fix` of the error object of the answer, and its `status`.
1107
+ */
1108
+ function createCommentsRestRequest(options = {}) {
1109
+ const route = options.route ?? `${(options.base ?? "").replace(/\/+$/, "")}/_vitehub/comments`;
1110
+ return async (path, init = {}) => {
1111
+ const send = options.fetch ?? globalThis.fetch;
1112
+ const headers = new Headers(typeof options.headers === "function" ? await options.headers() : options.headers);
1113
+ for (const [name, value] of new Headers(init.headers)) headers.set(name, value);
1114
+ if (init.body !== void 0 && !headers.has("content-type")) headers.set("content-type", "application/json");
1115
+ const guest = typeof options.guest === "function" ? options.guest() : options.guest;
1116
+ if (guest) {
1117
+ headers.set("x-vitehub-comments-guest-id", guest.id);
1118
+ headers.set("x-vitehub-comments-guest-name", encodeURIComponent(guest.name));
1119
+ }
1120
+ let response;
1121
+ try {
1122
+ response = await send(`${route}${path}`, {
1123
+ ...init,
1124
+ headers,
1125
+ credentials: options.credentials ?? "same-origin",
1126
+ cache: "no-store"
1127
+ });
1128
+ } catch (cause) {
1129
+ throw commentsUnansweredError(0, cause);
1130
+ }
1131
+ const value = await response.json().catch(() => void 0);
1132
+ const retryAfter = retryAfterOf(response);
1133
+ if (isRecordOrFunction(value) && isRecordOrFunction(value.error)) {
1134
+ const { code, why, fix } = value.error;
1135
+ if (typeof code !== "string" || typeof why !== "string") throw commentsUnansweredError(response.status, void 0, retryAfter);
1136
+ throw commentsAnswerError({
1137
+ code,
1138
+ why,
1139
+ ...typeof fix === "string" ? { fix } : {},
1140
+ ...retryAfter === void 0 ? {} : { retryAfter },
1141
+ status: response.status
1142
+ });
1143
+ }
1144
+ if (isRecordOrFunction(value) && "data" in value) {
1145
+ const answer = {
1146
+ data: value.data,
1147
+ people: Array.isArray(value.people) ? value.people : [],
1148
+ ...isRecordOrFunction(value.thread) ? { thread: value.thread } : {}
1149
+ };
1150
+ options.onAnswer?.(answer);
1151
+ return answer;
1152
+ }
1153
+ throw commentsUnansweredError(response.status, void 0, retryAfter);
1154
+ };
1155
+ }
1156
+ function listSearch(query) {
1157
+ const params = new URLSearchParams();
1158
+ if (query.page !== void 0) params.set("page", query.page);
1159
+ if (query.subject) {
1160
+ params.set("subjectKind", query.subject.kind);
1161
+ params.set("subjectId", query.subject.id);
1162
+ } else if (query.subjectKind) params.set("subjectKind", query.subjectKind);
1163
+ if (query.status) params.set("status", query.status);
1164
+ if (query.mine !== void 0) params.set("mine", String(query.mine));
1165
+ if (query.mentions !== void 0) params.set("mentions", String(query.mentions));
1166
+ if (query.revision) params.set("revision", String(query.revision.lte));
1167
+ if (query.limit !== void 0) params.set("limit", String(query.limit));
1168
+ if (query.before) {
1169
+ params.set("beforeId", query.before.id);
1170
+ params.set("beforeUpdatedAt", String(query.before.updatedAt));
1171
+ }
1172
+ return params;
1173
+ }
1174
+ const thread = (id) => `/threads/${encodeURIComponent(id)}`;
1175
+ const post = (body, account) => ({
1176
+ method: "POST",
1177
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
1178
+ ...account === void 0 ? {} : { headers: { [outboxAccountHeader]: encodeURIComponent(account) } }
1179
+ });
1180
+ /**
1181
+ * A transport over the Comments API at `<base>/_vitehub/comments`: the routes that the overlay uses. The server
1182
+ * runs the `authorize` policy of `server/comments.ts` for the user of the request: the app session, or a guest that
1183
+ * `guest` names. Guests and share-link readers can use it. It has no
1184
+ * `subscribe`: the client refreshes when the window gets focus.
1185
+ */
1186
+ function createRestTransport(options = {}) {
1187
+ const request = createCommentsRestRequest(options);
1188
+ const base = (options.base ?? "").replace(/\/+$/, "");
1189
+ const upload = async (input, account) => (await request("/attachments", post(input, account))).data;
1190
+ return {
1191
+ async list(query) {
1192
+ return (await request(`/threads?${listSearch(query)}`)).data;
1193
+ },
1194
+ async get(input) {
1195
+ const path = "threadId" in input ? thread(input.threadId) : `/scopes/${encodeURIComponent(input.scope)}/threads/${input.n}`;
1196
+ return (await request(path)).data;
1197
+ },
1198
+ async create({ files, outbox, ...input }) {
1199
+ const body = await withCommentFiles(input, {
1200
+ files,
1201
+ outbox
1202
+ }, input.subject, (data) => upload(data, outbox?.account));
1203
+ return (await request("/threads", post(body, outbox?.account))).data;
1204
+ },
1205
+ async reply({ threadId, subject, files, outbox, ...input }) {
1206
+ const body = await withCommentFiles(input, {
1207
+ files,
1208
+ outbox
1209
+ }, subject, (data) => upload(data, outbox?.account));
1210
+ const answer = await request(`${thread(threadId)}/comments`, post(body, outbox?.account));
1211
+ if (!answer.thread) throw commentsUnansweredError(200);
1212
+ return answer.thread;
1213
+ },
1214
+ async edit({ threadId, messageId, ...input }) {
1215
+ return (await request(`${thread(threadId)}/comments/${encodeURIComponent(messageId)}`, {
1216
+ method: "PATCH",
1217
+ body: JSON.stringify(input)
1218
+ })).data;
1219
+ },
1220
+ async delete({ threadId, messageId }) {
1221
+ const path = messageId === void 0 ? thread(threadId) : `${thread(threadId)}/comments/${encodeURIComponent(messageId)}`;
1222
+ return (await request(path, { method: "DELETE" })).data;
1223
+ },
1224
+ async resolve({ threadId }) {
1225
+ return (await request(`${thread(threadId)}/resolve`, post())).data;
1226
+ },
1227
+ async reopen({ threadId }) {
1228
+ return (await request(`${thread(threadId)}/reopen`, post())).data;
1229
+ },
1230
+ async users({ query, limit, threadId, subject }) {
1231
+ const params = new URLSearchParams({ q: query });
1232
+ if (limit !== void 0) params.set("limit", String(limit));
1233
+ if (threadId !== void 0) params.set("thread", threadId);
1234
+ else if (subject) {
1235
+ params.set("subjectKind", subject.kind);
1236
+ params.set("subjectId", subject.id);
1237
+ }
1238
+ return (await request(`/people?${params}`)).data;
1239
+ },
1240
+ upload: (input) => upload(input),
1241
+ attachmentUrl: (key) => commentAttachmentUrl(key, base)
1242
+ };
1243
+ }
1039
1244
  // src/agent-prompt.ts
1040
1245
  /** The longest link that `commentsT3CodeLink()` makes. */
1041
1246
  const t3CodeLinkLimit = 8e3;
@@ -1126,6 +1331,24 @@ function commentsT3CodeLink(input, repository) {
1126
1331
  if (href.length <= 8e3) return href;
1127
1332
  }
1128
1333
  }
1334
+ /**
1335
+ * The prompt of **Copy prompt** in the pill, for the open threads of one page. With `agent`, it is three lines: the page,
1336
+ * the app in the Console to read the threads from, and what to do with them. Without it, the agent cannot read the
1337
+ * threads, so the prompt is `commentsAgentPrompt()` with their text.
1338
+ */
1339
+ function commentsPagePrompt(input) {
1340
+ const { agent, threads, url } = input;
1341
+ if (!agent) return commentsAgentPrompt(input);
1342
+ const page = new URL(url);
1343
+ const count = threads.length === 1 ? "a comment" : `${threads.length} comments`;
1344
+ const app = agent.project.name ? `"${agent.project.name}" (${new URL(agent.project.url).host})` : new URL(agent.project.url).host;
1345
+ const ids = threads.map((thread) => thread.id);
1346
+ return [
1347
+ `I left ${count} on ${page.href}`,
1348
+ `In the ViteHub Console, open app ${app} through the ViteHub MCP (${agent.mcp}): find it with list_apps (id: ${agent.project.id}, team ${agent.project.teamId}; if it is missing, ask me to switch team), then call read_operation with the app id, operation "comments.get", and input { threadId } for each ID in ${JSON.stringify(ids)}.`,
1349
+ agent.resolve ? "Fix each comment, then resolve it with run_operation, the app id, operation \"comments.resolve\", and input { threadId, reply }. Say what you changed in the reply." : "Fix each comment and tell me what you changed."
1350
+ ].join("\n");
1351
+ }
1129
1352
  // src/client-anchor.ts
1130
1353
  const defaultContext = 32;
1131
1354
  const clamp = (value) => Math.min(1e3, Math.max(0, value));
@@ -1528,569 +1751,6 @@ function resolveAnchor(anchor, root = document) {
1528
1751
  element
1529
1752
  };
1530
1753
  }
1531
- // src/client-send.ts
1532
- const reasonOf = (error) => error instanceof Error ? error.message : String(error);
1533
- /**
1534
- * The Send segment of a comment pill, without a framework: it hands the member's waiting threads to their agent, and
1535
- * pairs one in place first when there is none. `CommentSend` of `@vite-hub/ui` renders it.
1536
- */
1537
- function createCommentSend(transport, options = {}) {
1538
- const pairingInterval = options.pairingInterval ?? 1500;
1539
- const statusInterval = options.statusInterval ?? 5e3;
1540
- const sentFor = options.sentFor ?? 2e3;
1541
- const listeners = /* @__PURE__ */ new Set();
1542
- let state = {
1543
- status: "idle",
1544
- count: 0,
1545
- inbox: false
1546
- };
1547
- let agent;
1548
- let count = 0;
1549
- let countRevision = 0;
1550
- let selection = "";
1551
- let selections = 0;
1552
- let code;
1553
- let fetching = false;
1554
- let sendId;
1555
- let thread;
1556
- let sentInbox = false;
1557
- let pushed;
1558
- let step = 0;
1559
- let sentUntil = 0;
1560
- let timer;
1561
- let run = 0;
1562
- let lastStep = "send";
1563
- const notify = () => {
1564
- for (const listener of listeners) listener();
1565
- };
1566
- const set = (next) => {
1567
- step++;
1568
- clearTimeout(timer);
1569
- timer = void 0;
1570
- state = next;
1571
- notify();
1572
- };
1573
- const later = (ms, then) => {
1574
- const at = step;
1575
- clearTimeout(timer);
1576
- timer = setTimeout(() => at === step && then(), ms);
1577
- };
1578
- const inbox = () => Boolean(agent && !agent.host);
1579
- const needsStatus = () => state.status === "failed" && lastStep === "allow";
1580
- const idleState = () => ({
1581
- status: "idle",
1582
- count,
1583
- inbox: inbox(),
1584
- ...agent && count > 0 ? { canPairAnother: true } : {}
1585
- });
1586
- const idle = () => set(idleState());
1587
- const sentState = () => ({
1588
- status: "sent",
1589
- count,
1590
- inbox: sentInbox,
1591
- ...agent ? { agent } : {}
1592
- });
1593
- const finish = () => {
1594
- sendId = void 0;
1595
- thread = void 0;
1596
- idle();
1597
- };
1598
- const working = () => {
1599
- set({
1600
- status: "working",
1601
- count,
1602
- ...agent ? { agent } : {},
1603
- ...thread ? { thread } : {}
1604
- });
1605
- if (!transport.subscribe) later(statusInterval, () => void refresh(working));
1606
- };
1607
- const sent = () => {
1608
- set(sentState());
1609
- if (!transport.subscribe) later(statusInterval, () => void refresh(sent));
1610
- };
1611
- const holdingSent = () => state.status === "sent" && Date.now() < sentUntil;
1612
- const limited = (retryAt) => {
1613
- set({
1614
- status: "limited",
1615
- count,
1616
- retryAt
1617
- });
1618
- later(Math.max(0, retryAt - Date.now()), () => void refresh(idle));
1619
- };
1620
- const pending = () => {
1621
- set({
1622
- status: "sending",
1623
- count
1624
- });
1625
- later(statusInterval, () => void refresh(pending, true));
1626
- };
1627
- const apply = (status) => {
1628
- agent = status.agent;
1629
- if (status.pending) return pending();
1630
- const last = status.working ?? status.sent;
1631
- if (last) {
1632
- if (status.sent) sentInbox = status.sent.inbox ?? inbox();
1633
- const hold = holdingSent() && sendId === last.id;
1634
- sendId = last.id;
1635
- thread = hold ? thread ?? last.thread : last.thread;
1636
- if (hold) {
1637
- state = sentState();
1638
- return notify();
1639
- }
1640
- return status.working ? working() : sent();
1641
- }
1642
- sendId = void 0;
1643
- thread = void 0;
1644
- if (status.retryAt !== void 0 && status.retryAt > Date.now()) return limited(status.retryAt);
1645
- idle();
1646
- };
1647
- const refresh = async (onError, deliveryPending = false) => {
1648
- const at = step;
1649
- const canApply = () => at === step && !fetching && state.status !== "pairing" && state.status !== "confirm" && (state.status !== "sending" || deliveryPending);
1650
- if (!canApply()) return;
1651
- const revision = countRevision;
1652
- try {
1653
- const status = await transport.status();
1654
- if (!canApply()) return;
1655
- if (revision === countRevision) count = status.count;
1656
- selection = status.selection ?? "";
1657
- apply(status);
1658
- } catch (error) {
1659
- if (!onError) throw error;
1660
- if (canApply()) onError();
1661
- }
1662
- };
1663
- const settle = (result, revision, paired) => {
1664
- const updates = pushed;
1665
- pushed = void 0;
1666
- if (result.status === "changed") {
1667
- count = result.count;
1668
- selection = result.selection;
1669
- if (!paired) return set({
1670
- status: "failed",
1671
- count,
1672
- reason: "The waiting comments changed."
1673
- });
1674
- code = paired.code;
1675
- return set({
1676
- status: "confirm",
1677
- count,
1678
- agent: paired.agent
1679
- });
1680
- }
1681
- if (result.status === "failed") return set({
1682
- status: "failed",
1683
- count,
1684
- reason: result.reason
1685
- });
1686
- if (paired) agent = paired.agent;
1687
- if (result.status === "limited") return limited(result.retryAt);
1688
- if (result.status === "pending") return pending();
1689
- sendId = result.id;
1690
- const update = updates?.get(result.id);
1691
- thread = update?.thread ?? result.thread;
1692
- if (revision === countRevision) count = 0;
1693
- sentInbox = result.inbox ?? inbox();
1694
- set(sentState());
1695
- sentUntil = Date.now() + sentFor;
1696
- later(sentFor, update?.done ? finish : update ? working : () => void refresh(sent));
1697
- };
1698
- const drop = (dropped) => void transport.cancel(dropped).catch(() => void 0);
1699
- const deliver = async (request, paired) => {
1700
- const revision = countRevision;
1701
- pushed = transport.subscribe ? /* @__PURE__ */ new Map() : void 0;
1702
- set({
1703
- status: "sending",
1704
- count
1705
- });
1706
- const at = step;
1707
- let result;
1708
- try {
1709
- result = await request();
1710
- } catch (error) {
1711
- result = {
1712
- status: "failed",
1713
- reason: reasonOf(error)
1714
- };
1715
- }
1716
- const current = at === step;
1717
- if (current) settle(result, revision, paired);
1718
- if (paired && (result.status === "failed" || result.status === "limited" || !current && result.status === "changed")) drop(paired.code);
1719
- };
1720
- const poll = () => {
1721
- later(pairingInterval, async () => {
1722
- if (state.status !== "pairing" || !code) return;
1723
- if (Date.now() >= state.expiresAt) return set({
1724
- ...state,
1725
- reason: "expired"
1726
- });
1727
- const at = step;
1728
- const check = await transport.pollPairing(code).catch(() => ({ status: "waiting" }));
1729
- if (at !== step || state.status !== "pairing") return;
1730
- if (check.status === "waiting") return poll();
1731
- if (check.status === "paired") return set({
1732
- status: "confirm",
1733
- count,
1734
- agent: check.agent
1735
- });
1736
- set({
1737
- ...state,
1738
- reason: check.status
1739
- });
1740
- });
1741
- };
1742
- const pair = async (copy) => {
1743
- if (fetching) return;
1744
- fetching = true;
1745
- lastStep = "pair";
1746
- const at = ++step;
1747
- try {
1748
- const pairing = transport.startPairing();
1749
- const prompt = pairing.then((next) => next.prompt);
1750
- prompt.catch(() => void 0);
1751
- const copied = (async () => copy ? copy(prompt) : true)().then((ok) => ({ ok }), (error) => ({
1752
- ok: false,
1753
- error
1754
- }));
1755
- const next = await pairing;
1756
- const outcome = await copied;
1757
- if (at !== step) return drop(next.code);
1758
- fetching = false;
1759
- if (!outcome.ok) {
1760
- drop(next.code);
1761
- const reason = "error" in outcome ? reasonOf(outcome.error) : "The browser did not let the page copy the setup prompt.";
1762
- return set({
1763
- status: "failed",
1764
- count,
1765
- reason
1766
- });
1767
- }
1768
- if (code) drop(code);
1769
- code = next.code;
1770
- count = next.count;
1771
- selection = next.selection;
1772
- set({
1773
- status: "pairing",
1774
- count,
1775
- prompt: next.prompt,
1776
- expiresAt: next.expiresAt,
1777
- agent: next.agent
1778
- });
1779
- poll();
1780
- } catch (error) {
1781
- if (at === step) {
1782
- fetching = false;
1783
- set({
1784
- status: "failed",
1785
- count,
1786
- reason: reasonOf(error)
1787
- });
1788
- }
1789
- }
1790
- };
1791
- const reselect = async () => {
1792
- const at = ++selections;
1793
- const pairing = code;
1794
- const status = await transport.status().catch(() => void 0);
1795
- if (!status || at !== selections || !pairing || pairing !== code || state.status !== "pairing" && state.status !== "confirm") return;
1796
- count = status.count;
1797
- selection = status.selection ?? "";
1798
- state = {
1799
- ...state,
1800
- count
1801
- };
1802
- notify();
1803
- };
1804
- return {
1805
- get state() {
1806
- return state;
1807
- },
1808
- onChange(listener) {
1809
- listeners.add(listener);
1810
- return () => {
1811
- listeners.delete(listener);
1812
- };
1813
- },
1814
- start() {
1815
- const current = ++run;
1816
- const stop = transport.subscribe?.((event) => {
1817
- if (current !== run) return;
1818
- if (event.type === "count") {
1819
- countRevision++;
1820
- if (state.status === "pairing" || state.status === "confirm") return void reselect();
1821
- count = event.count;
1822
- if (state.status !== "sending") {
1823
- state = state.status === "idle" ? idleState() : {
1824
- ...state,
1825
- count
1826
- };
1827
- notify();
1828
- }
1829
- return;
1830
- }
1831
- if (state.status === "sending") {
1832
- const update = pushed?.get(event.id);
1833
- pushed?.set(event.id, event.type === "done" ? {
1834
- ...update,
1835
- done: true
1836
- } : {
1837
- ...update,
1838
- thread: event.thread ?? update?.thread
1839
- });
1840
- return;
1841
- }
1842
- if (fetching || state.status === "pairing" || state.status === "confirm" || needsStatus()) return;
1843
- if ((state.status === "working" || state.status === "sent") && sendId !== event.id) return;
1844
- if (event.type === "working") {
1845
- thread = event.thread ?? (event.id === sendId ? thread : void 0);
1846
- sendId = event.id;
1847
- if (holdingSent()) later(sentUntil - Date.now(), working);
1848
- else working();
1849
- return;
1850
- }
1851
- if (event.id === sendId) finish();
1852
- });
1853
- refresh(() => void 0);
1854
- return () => {
1855
- stop?.();
1856
- if (current !== run) return;
1857
- run++;
1858
- if (code) drop(code);
1859
- code = void 0;
1860
- fetching = false;
1861
- pushed = void 0;
1862
- agent = void 0;
1863
- count = 0;
1864
- finish();
1865
- };
1866
- },
1867
- refresh: () => refresh(),
1868
- async send(copy) {
1869
- if (fetching || state.status !== "idle" && state.status !== "failed" && state.status !== "sent" && state.status !== "working") return;
1870
- if (state.status !== "failed" && count === 0) return;
1871
- if (state.status === "failed" && lastStep === "pair") return pair(copy);
1872
- if (needsStatus()) return refresh(() => void 0);
1873
- if (!agent) return pair(copy);
1874
- lastStep = "send";
1875
- return deliver(() => transport.send());
1876
- },
1877
- async pairAnother(copy) {
1878
- if (state.status !== "idle" || !state.canPairAnother) return;
1879
- return pair(copy);
1880
- },
1881
- async allow() {
1882
- if (state.status !== "confirm" || !code) return;
1883
- const used = code;
1884
- code = void 0;
1885
- lastStep = "allow";
1886
- return deliver(() => transport.allow(used, selection), {
1887
- code: used,
1888
- agent: state.agent
1889
- });
1890
- },
1891
- async copyAgain(copy) {
1892
- if (state.status !== "pairing" || !state.reason) return;
1893
- return pair(copy);
1894
- },
1895
- cancel() {
1896
- if (state.status !== "pairing" && state.status !== "confirm") return;
1897
- if (code) drop(code);
1898
- code = void 0;
1899
- fetching = false;
1900
- idle();
1901
- }
1902
- };
1903
- }
1904
- // src/rest-transport.ts
1905
- /** The URL of an attachment key below the Comments API, such as `/_vitehub/comments/attachments/comments/<id>/shot.png`. */
1906
- function commentAttachmentUrl(key, base = "") {
1907
- return `${base.replace(/\/+$/, "")}${commentsRoute}/attachments/${key.split("/").map((part) => encodeURIComponent(part)).join("/")}`;
1908
- }
1909
- /**
1910
- * Requests to the Comments API at `<base>/_vitehub/comments`, with the guest headers and the session cookie. A
1911
- * failure throws a diagnostic with the `code`, `why`, and `fix` of the error object of the answer, and its `status`.
1912
- */
1913
- function createCommentsRestRequest(options = {}) {
1914
- const route = options.route ?? `${(options.base ?? "").replace(/\/+$/, "")}/_vitehub/comments`;
1915
- return async (path, init = {}) => {
1916
- const send = options.fetch ?? globalThis.fetch;
1917
- const headers = new Headers(typeof options.headers === "function" ? await options.headers() : options.headers);
1918
- for (const [name, value] of new Headers(init.headers)) headers.set(name, value);
1919
- if (init.body !== void 0 && !headers.has("content-type")) headers.set("content-type", "application/json");
1920
- const guest = typeof options.guest === "function" ? options.guest() : options.guest;
1921
- if (guest) {
1922
- headers.set("x-vitehub-comments-guest-id", guest.id);
1923
- headers.set("x-vitehub-comments-guest-name", encodeURIComponent(guest.name));
1924
- }
1925
- let response;
1926
- try {
1927
- response = await send(`${route}${path}`, {
1928
- ...init,
1929
- headers,
1930
- credentials: options.credentials ?? "same-origin",
1931
- cache: "no-store"
1932
- });
1933
- } catch (cause) {
1934
- throw commentsUnansweredError(0, cause);
1935
- }
1936
- const value = await response.json().catch(() => void 0);
1937
- const retryAfter = retryAfterOf(response);
1938
- if (isRecordOrFunction(value) && isRecordOrFunction(value.error)) {
1939
- const { code, why, fix } = value.error;
1940
- if (typeof code !== "string" || typeof why !== "string") throw commentsUnansweredError(response.status, void 0, retryAfter);
1941
- throw commentsAnswerError({
1942
- code,
1943
- why,
1944
- ...typeof fix === "string" ? { fix } : {},
1945
- ...retryAfter === void 0 ? {} : { retryAfter },
1946
- status: response.status
1947
- });
1948
- }
1949
- if (isRecordOrFunction(value) && "data" in value) {
1950
- const answer = {
1951
- data: value.data,
1952
- people: Array.isArray(value.people) ? value.people : [],
1953
- ...isRecordOrFunction(value.thread) ? { thread: value.thread } : {}
1954
- };
1955
- options.onAnswer?.(answer);
1956
- return answer;
1957
- }
1958
- throw commentsUnansweredError(response.status, void 0, retryAfter);
1959
- };
1960
- }
1961
- function listSearch(query) {
1962
- const params = new URLSearchParams();
1963
- if (query.page !== void 0) params.set("page", query.page);
1964
- if (query.subject) {
1965
- params.set("subjectKind", query.subject.kind);
1966
- params.set("subjectId", query.subject.id);
1967
- } else if (query.subjectKind) params.set("subjectKind", query.subjectKind);
1968
- if (query.status) params.set("status", query.status);
1969
- if (query.mine !== void 0) params.set("mine", String(query.mine));
1970
- if (query.mentions !== void 0) params.set("mentions", String(query.mentions));
1971
- if (query.revision) params.set("revision", String(query.revision.lte));
1972
- if (query.limit !== void 0) params.set("limit", String(query.limit));
1973
- if (query.before) {
1974
- params.set("beforeId", query.before.id);
1975
- params.set("beforeUpdatedAt", String(query.before.updatedAt));
1976
- }
1977
- return params;
1978
- }
1979
- const thread = (id) => `/threads/${encodeURIComponent(id)}`;
1980
- const post = (body, account) => ({
1981
- method: "POST",
1982
- ...body === void 0 ? {} : { body: JSON.stringify(body) },
1983
- ...account === void 0 ? {} : { headers: { [outboxAccountHeader]: encodeURIComponent(account) } }
1984
- });
1985
- /**
1986
- * A transport over the Comments API at `<base>/_vitehub/comments`: the routes that the overlay uses. The server
1987
- * runs the `authorize` policy of `server/comments.ts` for the user of the request: the app session, or a guest that
1988
- * `guest` names. Guests and share-link readers can use it. It has no
1989
- * `subscribe`: the client refreshes when the window gets focus.
1990
- */
1991
- function createRestTransport(options = {}) {
1992
- const request = createCommentsRestRequest(options);
1993
- const base = (options.base ?? "").replace(/\/+$/, "");
1994
- const upload = async (input, account) => (await request("/attachments", post(input, account))).data;
1995
- return {
1996
- async list(query) {
1997
- return (await request(`/threads?${listSearch(query)}`)).data;
1998
- },
1999
- async get(input) {
2000
- const path = "threadId" in input ? thread(input.threadId) : `/scopes/${encodeURIComponent(input.scope)}/threads/${input.n}`;
2001
- return (await request(path)).data;
2002
- },
2003
- async create({ files, outbox, ...input }) {
2004
- const body = await withCommentFiles(input, {
2005
- files,
2006
- outbox
2007
- }, input.subject, (data) => upload(data, outbox?.account));
2008
- return (await request("/threads", post(body, outbox?.account))).data;
2009
- },
2010
- async reply({ threadId, subject, files, outbox, ...input }) {
2011
- const body = await withCommentFiles(input, {
2012
- files,
2013
- outbox
2014
- }, subject, (data) => upload(data, outbox?.account));
2015
- const answer = await request(`${thread(threadId)}/comments`, post(body, outbox?.account));
2016
- if (!answer.thread) throw commentsUnansweredError(200);
2017
- return answer.thread;
2018
- },
2019
- async edit({ threadId, messageId, ...input }) {
2020
- return (await request(`${thread(threadId)}/comments/${encodeURIComponent(messageId)}`, {
2021
- method: "PATCH",
2022
- body: JSON.stringify(input)
2023
- })).data;
2024
- },
2025
- async delete({ threadId, messageId }) {
2026
- const path = messageId === void 0 ? thread(threadId) : `${thread(threadId)}/comments/${encodeURIComponent(messageId)}`;
2027
- return (await request(path, { method: "DELETE" })).data;
2028
- },
2029
- async resolve({ threadId }) {
2030
- return (await request(`${thread(threadId)}/resolve`, post())).data;
2031
- },
2032
- async reopen({ threadId }) {
2033
- return (await request(`${thread(threadId)}/reopen`, post())).data;
2034
- },
2035
- async users({ query, limit, threadId, subject }) {
2036
- const params = new URLSearchParams({ q: query });
2037
- if (limit !== void 0) params.set("limit", String(limit));
2038
- if (threadId !== void 0) params.set("thread", threadId);
2039
- else if (subject) {
2040
- params.set("subjectKind", subject.kind);
2041
- params.set("subjectId", subject.id);
2042
- }
2043
- return (await request(`/people?${params}`)).data;
2044
- },
2045
- upload: (input) => upload(input),
2046
- attachmentUrl: (key) => commentAttachmentUrl(key, base)
2047
- };
2048
- }
2049
- // src/send-transport.ts
2050
- /**
2051
- * The transport of `createCommentSend()` over the Send routes of Comments, `<base>/_vitehub/comments/send/**`. The
2052
- * ViteHub pill uses it, and an app renders `CommentSend` of `@vite-hub/ui` with it in its own pill:
2053
- *
2054
- * ```ts
2055
- * import { createCommentSend, createCommentSendTransport } from "@vite-hub/comments/client"
2056
- *
2057
- * const send = createCommentSend(createCommentSendTransport({ page: () => location.pathname }))
2058
- * ```
2059
- */
2060
- function createCommentSendTransport(options = {}) {
2061
- const request = createCommentsRestRequest(options);
2062
- const page = () => encodeURIComponent(typeof options.page === "function" ? options.page() : options.page ?? location.pathname);
2063
- const post = (body) => ({
2064
- method: "POST",
2065
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
2066
- });
2067
- const code = (value) => encodeURIComponent(value);
2068
- const pairingPages = /* @__PURE__ */ new Map();
2069
- return {
2070
- status: async () => (await request(`/send/status?page=${page()}`)).data,
2071
- startPairing: async () => {
2072
- const path = page();
2073
- const pairing = (await request(`/send/start?page=${path}`, post())).data;
2074
- pairingPages.set(pairing.code, path);
2075
- return pairing;
2076
- },
2077
- pollPairing: async (value) => (await request(`/send/pair/${code(value)}`)).data,
2078
- allow: async (value, selection) => {
2079
- const path = pairingPages.get(value) ?? page();
2080
- const result = (await request(`/send/allow?page=${path}`, post({
2081
- code: value,
2082
- selection
2083
- }))).data;
2084
- if (result.status !== "changed") pairingPages.delete(value);
2085
- return result;
2086
- },
2087
- cancel: async (value) => {
2088
- pairingPages.delete(value);
2089
- await request(`/send/pair/${code(value)}`, { method: "DELETE" });
2090
- },
2091
- send: async () => (await request(`/send?page=${page()}`, post())).data
2092
- };
2093
- }
2094
1754
  // src/client.ts
2095
1755
  function observed(input) {
2096
1756
  for (const files of [input.files, input.deferredFiles]) if (files && !Array.isArray(files)) files.catch(() => {});
@@ -2106,8 +1766,11 @@ async function filesArrived({ files, deferredFiles, ...input }) {
2106
1766
  ...files ? { files: await files } : {}
2107
1767
  };
2108
1768
  }
2109
- function createCommentsClient(options) {
2110
- const { transport } = options;
1769
+ function createCommentsClient(options = {}) {
1770
+ const transport = options.transport ?? createRestTransport({
1771
+ base: appCommentsBase(),
1772
+ guest: readCommentsGuest
1773
+ });
2111
1774
  const listeners = /* @__PURE__ */ new Set();
2112
1775
  const byId = /* @__PURE__ */ new Map();
2113
1776
  let listed = /* @__PURE__ */ new Set();
@@ -2349,4 +2012,4 @@ function createCommentsClient(options) {
2349
2012
  }
2350
2013
  };
2351
2014
  }
2352
- export { anchorRange, commentAttachmentUrl, commentsAgentPrompt, commentsErrorDiagnostics, commentsT3CodeLink, createAnchor, createCommentSend, createCommentSendTransport, createCommentsClient, createCommentsRestRequest, createIndexedDBOutboxStore, createMemoryOutboxStore, createRestTransport, foldName, replyMessageId, resolveAnchor, selectorFor, t3CodeLinkLimit };
2015
+ export { anchorRange, appCommentsBase, commentAttachmentUrl, commentsAgentPrompt, commentsApiCan, commentsErrorDiagnostics, commentsGuestUser, commentsPagePrompt, commentsT3CodeLink, createAnchor, createCommentsClient, createCommentsRestRequest, createIndexedDBOutboxStore, createMemoryOutboxStore, createRestTransport, foldName, onCommentsGuestSaved, readCommentsGuest, replyMessageId, resolveAnchor, saveCommentsGuest, selectorFor, t3CodeLinkLimit };