@vite-hub/comments 0.6.0 → 0.7.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 (52) hide show
  1. package/README.md +23 -6
  2. package/dist/{client-diagnostics-CvfTW5d4.js → client-diagnostics-DoXqdnBd.js} +12 -0
  3. package/dist/client.d.ts +119 -23
  4. package/dist/client.js +708 -209
  5. package/dist/{database-BkPoOdZr.js → database-BuSNVwTx.js} +1 -1
  6. package/dist/database.js +1 -1
  7. package/dist/{define-BCxNaSZv.js → define-BqPcuDhf.js} +1 -1
  8. package/dist/{errors-DFNiJg67.js → errors-CBvIpwbo.js} +1 -1
  9. package/dist/hosted/hosted-comments/frame.js +1 -1
  10. package/dist/hosted/hosted-comments/tools.js +371 -0
  11. package/dist/hosted/hosted-comments.js +1 -9
  12. package/dist/index.js +11 -10
  13. package/dist/{install-NehuMNhG.d.ts → install-9L4ASzUC.d.ts} +10 -1
  14. package/dist/{install-w6CCgGFV.js → install-CqBWFmU7.js} +23 -15
  15. package/dist/{installed-C9SkldMi.js → installed-wUYjqk_k.js} +1 -1
  16. package/dist/{operations-8hqTi0DH.d.ts → operations-DFLer1fR.d.ts} +1 -0
  17. package/dist/{operations-Cic9A9e_.d.ts → operations-Qt8ASQqW.d.ts} +2 -2
  18. package/dist/{operations-B8IMhRmY.js → operations-kMPw-Cyb.js} +10 -11
  19. package/dist/operations.d.ts +2 -2
  20. package/dist/operations.js +2 -2
  21. package/dist/overlay/client-CrnKCZXc.js +4 -0
  22. package/dist/overlay/overlay.js +70 -29
  23. package/dist/page/loader.js +25 -23
  24. package/dist/{page-xzgZ6DGm.js → page-2NzFladc.js} +5 -1
  25. package/dist/{page-tools-shared-fvmJQCrP.js → page-tools-shared-BNw-aWEH.js} +2 -5
  26. package/dist/{plugin-DbCYT7Ac.js → plugin-ChOHe7vq.js} +9 -8
  27. package/dist/realtime.d.ts +12 -1
  28. package/dist/realtime.js +14 -6
  29. package/dist/{request-origin-YPzfE2eh.js → request-origin-B-CPVAVk.js} +6 -1
  30. package/dist/{rpc-BKY7XRlR.js → rpc-kkxzQ3Qy.js} +1 -1
  31. package/dist/rpc.js +1 -1
  32. package/dist/runtime/auth.js +1 -1
  33. package/dist/runtime/console.js +2 -2
  34. package/dist/runtime/index.d.ts +4 -1
  35. package/dist/runtime/index.js +16 -14
  36. package/dist/{server-BGbD7H5s.js → server-8o9u8leM.js} +1 -1
  37. package/dist/server.d.ts +3 -3
  38. package/dist/server.js +6 -6
  39. package/dist/{service-CPiWPoiY.d.ts → service-IvgrI4XM.d.ts} +2 -0
  40. package/dist/{service-DUh2uGd2.js → service-XT2A8YEF.js} +11 -6
  41. package/dist/{session-_1GY5gaG.js → session-DGdFKWDB.js} +8 -7
  42. package/dist/testing.js +1 -1
  43. package/dist/vite.d.ts +2 -1
  44. package/dist/vite.js +31 -11
  45. package/package.json +9 -8
  46. package/dist/hosted/hosted-comments/client-B3dlmmQd.js +0 -4
  47. package/dist/hosted/hosted-comments/dist-DyVmH21U.js +0 -14
  48. package/dist/hosted/hosted-comments/overlay-CFuq5QAH.js +0 -182
  49. package/dist/hosted/hosted-comments/protocol-BHvtQKte.js +0 -1
  50. package/dist/hosted/hosted-comments/rest-transport-D-9_pNqZ.js +0 -1
  51. package/dist/hosted/hosted-comments/tools-Bz--joZw.js +0 -126
  52. package/dist/overlay/client-CerbVjTz.js +0 -4
package/dist/client.js CHANGED
@@ -1,9 +1,9 @@
1
- import { i as commentsUnansweredError, r as commentsClientDiagnostics, t as commentsAnswerError } from "./client-diagnostics-CvfTW5d4.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-DFNiJg67.js";
5
- import { i as commentsRoute } from "./page-xzgZ6DGm.js";
4
+ import { o as commentsRoute } from "./page-2NzFladc.js";
6
5
  import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
6
+ import { t as commentsErrorDiagnostics } from "./errors-CBvIpwbo.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. */
@@ -146,9 +146,9 @@ function requested(request) {
146
146
  request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("The IndexedDB request failed."));
147
147
  });
148
148
  }
149
- function openDatabase() {
149
+ function openDatabase(name) {
150
150
  return new Promise((resolve, reject) => {
151
- const request = indexedDB.open(databaseName, format);
151
+ const request = indexedDB.open(name, format);
152
152
  request.onupgradeneeded = (event) => {
153
153
  const drafts = request.result.createObjectStore("drafts", { keyPath: ["account", "id"] });
154
154
  drafts.createIndex("account", "account");
@@ -184,9 +184,12 @@ function openDatabase() {
184
184
  * does not open, as in some private windows, it keeps the entries in memory and `persisted` is `false`.
185
185
  */
186
186
  function createIndexedDBOutboxStore() {
187
+ return indexedDBOutboxStore(databaseName);
188
+ }
189
+ function indexedDBOutboxStore(name) {
187
190
  let backend;
188
191
  let persisted = typeof indexedDB !== "undefined";
189
- const open = () => backend ??= (persisted ? openDatabase() : Promise.reject(/* @__PURE__ */ new Error("No IndexedDB."))).then((database) => ({ database }), () => {
192
+ const open = () => backend ??= (persisted ? openDatabase(name) : Promise.reject(/* @__PURE__ */ new Error("No IndexedDB."))).then((database) => ({ database }), () => {
190
193
  persisted = false;
191
194
  return { memory: createMemoryOutboxStore() };
192
195
  });
@@ -226,7 +229,6 @@ function createIndexedDBOutboxStore() {
226
229
  })
227
230
  };
228
231
  }
229
- /** The error of a try, as plain data that the store keeps. */
230
232
  function deliveryError(error) {
231
233
  const field = (name) => error && typeof error === "object" ? Reflect.get(error, name) : void 0;
232
234
  const status = field("status");
@@ -242,7 +244,6 @@ function deliveryError(error) {
242
244
  ...typeof retryAfter === "number" && retryAfter >= 0 ? { retryAfter } : {}
243
245
  };
244
246
  }
245
- /** `wait`: try again later. `hold`: wait for `retry()`, such as after a sign-in or a plan upgrade. `fail`: the server refused this entry. */
246
247
  function outcomeOf(status) {
247
248
  if (status === 401 || status === 402) return "hold";
248
249
  if (status === 408 || status === 429) return "wait";
@@ -250,14 +251,32 @@ function outcomeOf(status) {
250
251
  }
251
252
  /** The outbox of one client. */
252
253
  function createOutbox(options, host) {
253
- const { account } = options;
254
- const store = options.store ?? createIndexedDBOutboxStore();
254
+ const { account, namespace } = options;
255
+ const scopedChannel = namespace === void 0 ? channel : `${channel}:${JSON.stringify(namespace)}`;
256
+ const hasLocks = Boolean(options.environment || globalThis.navigator?.locks);
257
+ const stageFiles = Boolean(options.store && !hasLocks);
258
+ const store = options.store ?? (hasLocks ? indexedDBOutboxStore(scopedChannel) : createMemoryOutboxStore());
255
259
  const environment = options.environment ?? createBrowserEnvironment({
256
- channel,
260
+ channel: scopedChannel,
257
261
  isMessage: isOutboxMessage
258
262
  });
259
- const lockName = `vitehub-comments-outbox:${account}`;
263
+ const queue = namespace === void 0 ? account : JSON.stringify([namespace, account]);
264
+ const storeKey = options.store ? queue : account;
265
+ const lockName = `vitehub-comments-outbox:${queue}`;
266
+ const filesLock = (id) => `vitehub-comments-files:${queue}:${id}`;
260
267
  let entries = [];
268
+ let stored = [];
269
+ const unsaved = /* @__PURE__ */ new Map();
270
+ const arriving = /* @__PURE__ */ new Map();
271
+ const blockedFiles = /* @__PURE__ */ new Map();
272
+ const aliases = /* @__PURE__ */ new Map();
273
+ const entryId = (id) => aliases.get(id) ?? id;
274
+ const queueListeners = /* @__PURE__ */ new Set();
275
+ const queueChanged = () => {
276
+ for (const listener of queueListeners) listener();
277
+ };
278
+ const written = /* @__PURE__ */ new Set();
279
+ let lastOrder = 0;
261
280
  const sent = /* @__PURE__ */ new Map();
262
281
  const receipts = /* @__PURE__ */ new Map();
263
282
  const keyOf = (entry) => entry.kind === "create" ? JSON.stringify([
@@ -275,10 +294,12 @@ function createOutbox(options, host) {
275
294
  let loading = Promise.resolve();
276
295
  let leading;
277
296
  let again = false;
297
+ let stopped = false;
278
298
  let cancelWait;
279
299
  const post = (message) => environment.post(message);
280
300
  const reload = () => loading = loading.catch(() => void 0).then(async () => {
281
- const pending = await store.list(account);
301
+ const landed = [...unsaved].flatMap(([id, local]) => local.saved ? [id] : []);
302
+ const pending = await store.list(storeKey);
282
303
  const ids = /* @__PURE__ */ new Map();
283
304
  if (globalThis.crypto?.subtle) await Promise.all(pending.map(async (entry) => {
284
305
  if (entry.kind !== "reply") return;
@@ -287,22 +308,49 @@ function createOutbox(options, host) {
287
308
  ids.set(key, replyIds.get(key) ?? await replyMessageId(threadId, entry.requestId));
288
309
  }));
289
310
  replyIds = ids;
290
- entries = pending;
291
- host.changed();
311
+ stored = pending;
312
+ for (const id of landed) unsaved.delete(id);
313
+ merge();
292
314
  });
315
+ const merge = () => {
316
+ const ids = new Set(stored.map((entry) => entry.id));
317
+ entries = sortEntries([...stored, ...[...unsaved.values()].flatMap((local) => ids.has(local.entry.id) || local.duplicate ? [] : [local.entry])]).map((entry) => {
318
+ const blocked = blockedFiles.get(entry.id);
319
+ return blocked ? {
320
+ ...entry,
321
+ status: "failed",
322
+ files: [...entry.files, ...blocked.files],
323
+ error: blocked.error
324
+ } : entry;
325
+ });
326
+ guardUnload(!store.persisted && entries.length > 0 || blockedFiles.size > 0 || [...unsaved.values()].some((local) => !local.saved));
327
+ host.changed();
328
+ queueChanged();
329
+ };
330
+ let guarded = false;
331
+ const holdPage = (event) => {
332
+ event.preventDefault();
333
+ Reflect.set(event, "returnValue", "");
334
+ };
335
+ const guardUnload = (on) => {
336
+ if (on === guarded || typeof globalThis.addEventListener !== "function") return;
337
+ guarded = on;
338
+ if (on) globalThis.addEventListener("beforeunload", holdPage);
339
+ else globalThis.removeEventListener("beforeunload", holdPage);
340
+ };
293
341
  const changed = async () => {
294
342
  await reload();
295
343
  post({
296
344
  type: "change",
297
- account
345
+ account: queue
298
346
  });
299
347
  };
300
348
  const serverThread = (id) => {
301
349
  for (const thread of host.threads()) if (thread.id === id) return thread;
302
350
  };
303
- /** The server id of a thread that the client may still name by its local id. */
304
351
  const realId = (threadId) => {
305
- return sent.get(threadId)?.id ?? threadId;
352
+ const id = entryId(threadId);
353
+ return sent.get(id)?.id ?? id;
306
354
  };
307
355
  const delivery = (entry) => ({
308
356
  status: entry.status === "failed" ? "failed" : "pending",
@@ -372,11 +420,15 @@ function createOutbox(options, host) {
372
420
  delivery: delivery(entry)
373
421
  };
374
422
  };
375
- /** The first entry that may go out now. A reply waits while its comment has not gone out. */
376
423
  const next = (list) => {
377
- const waiting = new Set(list.flatMap((entry) => entry.kind === "create" ? [entry.id] : []));
424
+ const waiting = new Set([...list, ...[...unsaved.values()].map((local) => local.entry)].flatMap((entry) => entry.kind === "create" ? [entry.id] : []));
378
425
  return list.find((entry) => entry.status !== "failed" && !(entry.kind === "reply" && waiting.has(entry.input.threadId)));
379
426
  };
427
+ const saving = (order) => [...unsaved.values()].some((local) => !local.saved && !local.parked && local.entry.status !== "failed" && local.entry.order < order);
428
+ const aborted = (signal) => new Promise((resolve) => {
429
+ if (signal.aborted) resolve();
430
+ else signal.addEventListener("abort", () => resolve(), { once: true });
431
+ });
380
432
  const wait = (ms) => {
381
433
  cancelWait?.();
382
434
  cancelWait = environment.schedule(() => {
@@ -384,7 +436,7 @@ function createOutbox(options, host) {
384
436
  kick();
385
437
  }, ms);
386
438
  };
387
- const update = (change) => store.update(account, change);
439
+ const update = (change) => store.update(storeKey, change);
388
440
  const send = async (entry) => {
389
441
  const withClaim = (change) => update((drafts) => {
390
442
  const current = drafts.get(entry.id);
@@ -469,7 +521,7 @@ function createOutbox(options, host) {
469
521
  await reload();
470
522
  post({
471
523
  type: "sent",
472
- account,
524
+ account: queue,
473
525
  id: entry.id,
474
526
  kind: entry.kind,
475
527
  key,
@@ -484,7 +536,8 @@ function createOutbox(options, host) {
484
536
  const selected = await update((drafts) => {
485
537
  if (signal.aborted) return;
486
538
  const entry = next(sortEntries([...drafts.values()]));
487
- if (!entry || entry.held) return;
539
+ if (!entry || entry.held || saving(entry.order)) return;
540
+ if (entry.awaitingFiles) return { files: entry.id };
488
541
  const delay = (entry.retryAt ?? 0) - Date.now();
489
542
  if (delay > 0) return { delay };
490
543
  const claimed = {
@@ -497,16 +550,30 @@ function createOutbox(options, host) {
497
550
  return { claimed };
498
551
  });
499
552
  if (!selected) return;
500
- if (selected.delay !== void 0) {
553
+ if ("delay" in selected) {
501
554
  wait(selected.delay);
502
555
  return;
503
556
  }
557
+ if ("files" in selected) {
558
+ if (stageFiles || arriving.has(selected.files)) return;
559
+ await Promise.race([environment.lock(filesLock(selected.files), async () => void 0), aborted(signal)]);
560
+ if (signal.aborted) return;
561
+ await update((drafts) => {
562
+ const current = drafts.get(selected.files);
563
+ if (current?.awaitingFiles && !arriving.has(current.id)) drafts.set(current.id, {
564
+ ...current,
565
+ awaitingFiles: false
566
+ });
567
+ });
568
+ await changed();
569
+ continue;
570
+ }
504
571
  await reload();
505
572
  await send(selected.claimed);
506
573
  }
507
574
  };
508
- /** Sends what waits, in the tab that holds the lock. */
509
575
  function kick() {
576
+ if (stopped) return;
510
577
  if (leading) {
511
578
  again = true;
512
579
  return;
@@ -524,22 +591,181 @@ function createOutbox(options, host) {
524
591
  }
525
592
  });
526
593
  }
527
- const enqueue = async (entry) => {
528
- const saved = await update((drafts) => {
529
- const key = keyOf(entry);
530
- const existing = [...drafts.values()].find((draft) => keyOf(draft) === key);
531
- if (existing) return existing;
532
- let order = entry.createdAt;
533
- for (const draft of drafts.values()) order = Math.max(order, draft.order + 1);
534
- const ordered = {
594
+ const save = (id) => {
595
+ const local = unsaved.get(id);
596
+ if (!local) return Promise.resolve();
597
+ const run = async () => {
598
+ local.parked = false;
599
+ let group = [local];
600
+ try {
601
+ if (await update((drafts) => {
602
+ if (unsaved.get(id) !== local) return false;
603
+ if (local.entry.kind === "reply") local.entry = {
604
+ ...local.entry,
605
+ input: {
606
+ ...local.entry.input,
607
+ threadId: realId(local.entry.input.threadId)
608
+ }
609
+ };
610
+ const parent = local.entry.kind === "reply" ? unsaved.get(local.entry.input.threadId) : void 0;
611
+ if (parent && !parent.saved && !drafts.has(parent.entry.id)) return true;
612
+ let order = local.entry.order;
613
+ for (const draft of drafts.values()) if (!written.has(draft.id)) order = Math.max(order, draft.order + 1);
614
+ const later = [...unsaved.values()].filter((other) => other !== local && !drafts.has(other.entry.id) && other.entry.order > local.entry.order);
615
+ let previous = order;
616
+ for (const other of later.sort((a, b) => a.entry.order - b.entry.order)) {
617
+ previous = Math.max(other.entry.order, previous + 1);
618
+ other.entry = {
619
+ ...other.entry,
620
+ order: previous
621
+ };
622
+ }
623
+ lastOrder = Math.max(lastOrder, previous);
624
+ local.entry = {
625
+ ...local.entry,
626
+ order
627
+ };
628
+ group = [local, ...[...unsaved.values()].filter((other) => other.parked && other.entry.kind === "reply" && other.entry.input.threadId === id)];
629
+ for (const member of group) member.write ??= write;
630
+ const keys = new Map([...drafts.values()].map((draft) => [keyOf(draft), draft]));
631
+ for (const member of group) {
632
+ if (member.entry.kind === "reply") member.entry = {
633
+ ...member.entry,
634
+ input: {
635
+ ...member.entry.input,
636
+ threadId: realId(member.entry.input.threadId)
637
+ }
638
+ };
639
+ const key = keyOf(member.entry);
640
+ const duplicate = keys.get(key);
641
+ if (duplicate) {
642
+ member.duplicate = duplicate;
643
+ aliases.set(member.entry.id, duplicate.id);
644
+ } else {
645
+ drafts.set(member.entry.id, member.entry);
646
+ keys.set(key, member.entry);
647
+ }
648
+ }
649
+ return false;
650
+ })) {
651
+ local.parked = true;
652
+ return;
653
+ }
654
+ } catch (cause) {
655
+ local.entry = {
656
+ ...local.entry,
657
+ status: "failed",
658
+ error: deliveryError(cause)
659
+ };
660
+ merge();
661
+ kick();
662
+ return;
663
+ } finally {
664
+ for (const member of group) if (member.write === write) member.write = void 0;
665
+ }
666
+ for (const member of group) Object.assign(member, {
667
+ saved: true,
668
+ parked: false
669
+ });
670
+ await changed().catch(() => void 0);
671
+ kick();
672
+ };
673
+ const write = Promise.resolve().then(run);
674
+ local.write = write;
675
+ return write;
676
+ };
677
+ const flushStaged = () => {
678
+ const locals = [...unsaved.values()];
679
+ if (locals.some((local) => local.write)) return;
680
+ const next = locals.find((local) => !local.saved && !local.parked && local.entry.status === "pending");
681
+ if (next && !next.entry.awaitingFiles) save(next.entry.id).then(flushStaged);
682
+ };
683
+ const queueSave = (local) => {
684
+ if (!stageFiles) return save(local.entry.id);
685
+ local.parked = false;
686
+ flushStaged();
687
+ return local.write ?? Promise.resolve();
688
+ };
689
+ const add = (entry, files) => {
690
+ const later = files !== void 0 && !Array.isArray(files);
691
+ const order = Math.max(Date.now(), lastOrder + 1, ...entries.map((other) => other.order + 1));
692
+ lastOrder = order;
693
+ written.add(entry.id);
694
+ const local = {
695
+ entry: copyEntry({
535
696
  ...entry,
536
- order
537
- };
538
- drafts.set(entry.id, ordered);
539
- return ordered;
697
+ order,
698
+ ...later ? { awaitingFiles: true } : {}
699
+ }),
700
+ saved: false
701
+ };
702
+ unsaved.set(entry.id, local);
703
+ if (later) arrive(entry.id, Promise.resolve(files));
704
+ merge();
705
+ return {
706
+ local,
707
+ write: queueSave(local)
708
+ };
709
+ };
710
+ const queueEntry = (entry, files) => {
711
+ const existing = entries.find((draft) => keyOf(draft) === keyOf(entry));
712
+ if (!existing) return {
713
+ entry,
714
+ ...add(entry, files)
715
+ };
716
+ const local = unsaved.get(existing.id);
717
+ return {
718
+ entry: existing,
719
+ local,
720
+ write: local?.write
721
+ };
722
+ };
723
+ const arrive = (id, files) => {
724
+ const arrival = environment.lock(filesLock(id), async () => {
725
+ const arrived = await files.then((list) => [...list], () => []);
726
+ const local = unsaved.get(id);
727
+ await local?.write;
728
+ const settled = (entry) => ({
729
+ ...entry,
730
+ files: [...entry.files, ...arrived],
731
+ awaitingFiles: false
732
+ });
733
+ if (local && !local.saved) {
734
+ local.entry = settled(local.entry);
735
+ merge();
736
+ if (stageFiles) flushStaged();
737
+ return;
738
+ }
739
+ while (arriving.has(id)) try {
740
+ await update((drafts) => {
741
+ const current = drafts.get(id);
742
+ if (current?.awaitingFiles) drafts.set(id, settled(current));
743
+ });
744
+ break;
745
+ } catch (cause) {
746
+ if (!arriving.has(id)) break;
747
+ const retry = new Promise((resume) => {
748
+ blockedFiles.set(id, {
749
+ files: arrived,
750
+ error: deliveryError(cause),
751
+ resume
752
+ });
753
+ });
754
+ merge();
755
+ await retry;
756
+ }
757
+ }).catch(() => void 0).then(async () => {
758
+ arriving.delete(id);
759
+ blockedFiles.delete(id);
760
+ await changed().catch(() => void 0);
761
+ kick();
540
762
  });
541
- await changed();
542
- return saved;
763
+ arriving.set(id, arrival);
764
+ };
765
+ const unsavedEntry = async (id) => {
766
+ await unsaved.get(id)?.write;
767
+ const local = unsaved.get(id);
768
+ return local && !local.saved ? local : void 0;
543
769
  };
544
770
  const fields = (requestId, files) => {
545
771
  const now = Date.now();
@@ -548,7 +774,7 @@ function createOutbox(options, host) {
548
774
  id,
549
775
  requestId: requestId ?? id,
550
776
  account,
551
- files: [...files ?? []],
777
+ files: Array.isArray(files) ? [...files] : [],
552
778
  createdAt: now,
553
779
  order: now,
554
780
  status: "pending"
@@ -569,8 +795,24 @@ function createOutbox(options, host) {
569
795
  return store.persisted;
570
796
  },
571
797
  overlay,
572
- owns: (threadId, messageId) => entries.some((entry) => entry.id === (messageId ?? threadId)),
573
- async create({ files, requestId, ...input }) {
798
+ owns: (threadId, messageId) => entries.some((entry) => entry.id === entryId(messageId ?? threadId)),
799
+ async beforeResolve(threadId) {
800
+ await reload();
801
+ while (true) {
802
+ const id = realId(threadId);
803
+ const pending = entries.filter((entry) => entry.id === id || entry.kind === "reply" && realId(entry.input.threadId) === id);
804
+ if (!pending.length) return id;
805
+ if (stopped || !environment.isOnline() || pending.some((entry) => entry.held || entry.status === "failed" || entry.retryAt !== void 0) || entries.some((entry) => entry.held)) return;
806
+ await new Promise((resolve) => {
807
+ const wake = () => {
808
+ queueListeners.delete(wake);
809
+ resolve();
810
+ };
811
+ queueListeners.add(wake);
812
+ });
813
+ }
814
+ },
815
+ async create({ files, deferredFiles, requestId, ...input }) {
574
816
  const entry = {
575
817
  ...fields(requestId, files),
576
818
  kind: "create",
@@ -579,11 +821,16 @@ function createOutbox(options, host) {
579
821
  const receipt = () => receipts.get(keyOf(entry)) ?? [...host.threads()].find((thread) => matchesCreate(entry, thread));
580
822
  const earlier = receipt();
581
823
  if (earlier) return earlier;
582
- const saved = await enqueue(entry);
583
- kick();
584
- return receipt() ?? localThread(saved.kind === "create" ? saved : entry);
824
+ const queued = queueEntry(entry, deferredFiles ?? files);
825
+ if (requestId !== void 0) {
826
+ await queued.write;
827
+ const confirmed = receipt();
828
+ if (confirmed) return confirmed;
829
+ }
830
+ const saved = queued.local?.duplicate ?? entries.find((draft) => draft.id === queued.entry.id) ?? queued.entry;
831
+ return localThread(saved.kind === "create" ? saved : entry);
585
832
  },
586
- async reply({ files, requestId, subject, ...input }) {
833
+ async reply({ files, deferredFiles, requestId, subject, ...input }) {
587
834
  const threadId = realId(input.threadId);
588
835
  const parent = entries.find((entry) => entry.kind === "create" && entry.id === threadId);
589
836
  const cached = serverThread(threadId);
@@ -599,14 +846,18 @@ function createOutbox(options, host) {
599
846
  };
600
847
  const earlier = receipts.get(keyOf(entry));
601
848
  if (earlier) return serverThread(earlier.id) ?? earlier;
602
- const saved = await enqueue(entry);
603
- kick();
604
- const thread = serverThread(realId(threadId)) ?? cached;
849
+ const queued = queueEntry(entry, deferredFiles ?? files);
850
+ if (requestId !== void 0) await queued.write;
851
+ const saved = queued.local?.duplicate ?? queued.local?.entry ?? queued.entry;
852
+ const confirmed = receipts.get(keyOf(saved));
853
+ if (confirmed) return serverThread(confirmed.id) ?? confirmed;
854
+ const resolvedId = realId(threadId);
855
+ const thread = serverThread(resolvedId) ?? cached;
605
856
  if (thread) return overlay([thread]).server[0] ?? thread;
606
- const local = overlay([]).local.find((local) => local.id === threadId);
857
+ const local = overlay([]).local.find((local) => local.id === resolvedId);
607
858
  if (local) return local;
608
859
  return {
609
- id: threadId,
860
+ id: resolvedId,
610
861
  scope: "",
611
862
  n: 0,
612
863
  subject: target ?? {
@@ -616,12 +867,31 @@ function createOutbox(options, host) {
616
867
  anchor: { kind: "page" },
617
868
  status: "open",
618
869
  author: author(),
619
- messages: [localMessage(saved, threadId)],
870
+ messages: [localMessage(saved, resolvedId)],
620
871
  createdAt: entry.createdAt,
621
872
  updatedAt: entry.createdAt
622
873
  };
623
874
  },
624
875
  async retry(id) {
876
+ if (id !== void 0) {
877
+ id = entryId(id);
878
+ const blocked = blockedFiles.get(id);
879
+ if (blocked) {
880
+ blocked.resume();
881
+ return;
882
+ }
883
+ }
884
+ const local = id === void 0 ? void 0 : await unsavedEntry(id);
885
+ if (local) {
886
+ local.entry = {
887
+ ...local.entry,
888
+ status: "pending",
889
+ error: void 0
890
+ };
891
+ merge();
892
+ await queueSave(local);
893
+ return;
894
+ }
625
895
  await update((drafts) => {
626
896
  for (const entry of drafts.values()) {
627
897
  if (entry.status === "sending" || id !== void 0 && entry.id !== id) continue;
@@ -640,6 +910,17 @@ function createOutbox(options, host) {
640
910
  kick();
641
911
  },
642
912
  async dismiss(id) {
913
+ id = entryId(id);
914
+ if (await unsavedEntry(id)) {
915
+ for (const [other, local] of unsaved) if (other === id || local.entry.kind === "reply" && local.entry.input.threadId === id) unsaved.delete(other);
916
+ await update((drafts) => {
917
+ for (const reply of drafts.values()) if (reply.kind === "reply" && reply.input.threadId === id) drafts.delete(reply.id);
918
+ });
919
+ await changed();
920
+ if (stageFiles) flushStaged();
921
+ kick();
922
+ return true;
923
+ }
643
924
  const removed = await update((drafts) => {
644
925
  const entry = drafts.get(id);
645
926
  if (!entry || !changeable(entry)) return false;
@@ -649,12 +930,32 @@ function createOutbox(options, host) {
649
930
  return drafts.delete(id);
650
931
  });
651
932
  if (removed) {
933
+ arriving.delete(id);
934
+ blockedFiles.get(id)?.resume();
652
935
  await changed();
653
936
  kick();
654
937
  }
655
938
  return removed;
656
939
  },
657
940
  async edit(id, body, mentions) {
941
+ id = entryId(id);
942
+ const local = await unsavedEntry(id);
943
+ if (local) {
944
+ const input = {
945
+ ...local.entry.input,
946
+ body,
947
+ ...mentions ? { mentions } : {}
948
+ };
949
+ local.entry = {
950
+ ...local.entry,
951
+ input,
952
+ status: "pending",
953
+ error: void 0
954
+ };
955
+ merge();
956
+ await queueSave(local);
957
+ return true;
958
+ }
658
959
  const edited = await update((drafts) => {
659
960
  const entry = drafts.get(id);
660
961
  if (!entry || !changeable(entry)) return false;
@@ -691,13 +992,20 @@ function createOutbox(options, host) {
691
992
  async clear() {
692
993
  cancelWait?.();
693
994
  cancelWait = void 0;
995
+ unsaved.clear();
694
996
  await update((drafts) => drafts.clear());
997
+ arriving.clear();
998
+ for (const blocked of blockedFiles.values()) blocked.resume();
999
+ blockedFiles.clear();
1000
+ aliases.clear();
695
1001
  sent.clear();
696
1002
  receipts.clear();
697
1003
  await changed();
698
1004
  },
699
1005
  start() {
1006
+ stopped = false;
700
1007
  const stops = [environment.listen((event) => {
1008
+ if (event === "offline") queueChanged();
701
1009
  if (event !== "online" && event !== "visible") return;
702
1010
  update((drafts) => {
703
1011
  for (const entry of drafts.values()) if (entry.status === "pending" && entry.retryAt !== void 0) drafts.set(entry.id, {
@@ -706,7 +1014,7 @@ function createOutbox(options, host) {
706
1014
  });
707
1015
  }).then(changed).then(kick);
708
1016
  }), environment.receive((message) => {
709
- if (message.account !== account) return;
1017
+ if (message.account !== queue) return;
710
1018
  if (message.type === "sent") {
711
1019
  if (message.kind === "create") sent.set(message.id, message.thread);
712
1020
  receipts.set(message.key, message.thread);
@@ -718,6 +1026,8 @@ function createOutbox(options, host) {
718
1026
  kick();
719
1027
  return () => {
720
1028
  for (const stop of stops.splice(0)) stop();
1029
+ stopped = true;
1030
+ queueChanged();
721
1031
  cancelWait?.();
722
1032
  cancelWait = void 0;
723
1033
  leading?.giveUp();
@@ -726,12 +1036,317 @@ function createOutbox(options, host) {
726
1036
  }
727
1037
  };
728
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
+ }
729
1244
  // src/agent-prompt.ts
730
- function commentsAgentPrompt({ mcp, project, resolve, threadIds, url }) {
1245
+ /** The longest link that `commentsT3CodeLink()` makes. */
1246
+ const t3CodeLinkLimit = 8e3;
1247
+ const t3CodeNewThread = "https://app.t3.codes/new";
1248
+ const githubRepository = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/(?!\.+$)[A-Za-z0-9._-]{1,100}$/;
1249
+ const shortest = 40;
1250
+ /** `value` when it names a GitHub repository as `owner/name`. */
1251
+ function gitHubRepositoryOf(value) {
1252
+ return value && githubRepository.test(value) ? value : void 0;
1253
+ }
1254
+ function cut(text, length) {
1255
+ return text.length > length ? `${text.slice(0, length).trimEnd()}…` : text;
1256
+ }
1257
+ function where(anchor, length) {
1258
+ if (anchor.kind === "page") return "on the whole page";
1259
+ if (anchor.kind === "text") return `on the text "${cut(anchor.exact, length)}" in ${cut(anchor.selector, length)}`;
1260
+ return `on ${cut(anchor.selector, length)}`;
1261
+ }
1262
+ function threadLines(thread, length) {
1263
+ const [comment, ...replies] = thread.messages;
1264
+ const version = thread.revision === void 0 ? "" : ` (version ${thread.revision})`;
731
1265
  return [
732
- `Fix ${threadIds.length === 1 ? "the open ViteHub comment" : `the ${threadIds.length} open ViteHub comments`} on ${new URL(url).href}`,
733
- `In the ViteHub MCP (${mcp}), use list_apps to verify team ${project.teamId} and app ${project.url} (id: ${project.id}). If the team is different, ask me to switch to that team in the Console; if the app is missing, ask me to check the link. Only after both match, call read_operation with the app id, operation "comments.get", and input { threadId } for each ID in ${JSON.stringify(threadIds)}.`,
734
- resolve ? "After each fix, use run_operation with the app id, operation \"comments.resolve\", and input { threadId, reply }. In the reply, say what changed." : "Report the fixes to me without resolving the threads."
1266
+ `"${cut(comment?.body ?? "", length)}" — ${comment?.author ?? "Someone"}, ${where(thread.anchor, length)}${version}`,
1267
+ ...replies.map((reply) => `Reply: "${cut(reply.body, length)}" — ${reply.author}`),
1268
+ ...thread.files?.length ? [`Files: ${thread.files.join(" ")}`] : []
1269
+ ];
1270
+ }
1271
+ function steps(agent, ids) {
1272
+ if (!agent) return ["When you are done, tell me what you changed."];
1273
+ const { mcp, project, resolve } = agent;
1274
+ const read = `operation "comments.get", and input { threadId } for ${ids.length === 1 ? `thread ${ids[0]}` : `each ID in ${JSON.stringify(ids)}`}`;
1275
+ return [`In the ViteHub MCP (${mcp}), use list_apps to verify team ${project.teamId} and app ${project.url} (id: ${project.id}). If the team is different, ask me to switch to that team in the Console; if the app is missing, ask me to check the link. Only after both match, call read_operation with the app id, ${read}.`, resolve ? "When the fix is live, use run_operation with the app id, operation \"comments.resolve\", and input { threadId, reply }. In the reply, say what you changed." : "Report the fixes to me without resolving the threads."];
1276
+ }
1277
+ function title(thread) {
1278
+ return `${thread.id}: "${cut(thread.messages[0]?.body ?? "", shortest)}"`;
1279
+ }
1280
+ function render({ agent, threads, url }, detail) {
1281
+ const page = new URL(url).href;
1282
+ const one = threads.length === 1;
1283
+ const instructions = steps(agent, threads.map((thread) => thread.id));
1284
+ const heading = one ? `Fix this comment on ${page}` : `Fix these ${threads.length} comments on ${page}`;
1285
+ if (detail === "ids") return [heading, ...instructions].join("\n\n");
1286
+ if (detail === "titles") return [
1287
+ heading,
1288
+ threads.map((thread, index) => one ? title(thread) : `${index + 1}. ${title(thread)}`).join("\n"),
1289
+ ...instructions
1290
+ ].join("\n\n");
1291
+ if (one) return [
1292
+ heading,
1293
+ ...threadLines(threads[0], detail),
1294
+ ...instructions
1295
+ ].join("\n");
1296
+ return [
1297
+ heading,
1298
+ ...threads.map((thread, index) => threadLines(thread, detail).map((line, at) => at === 0 ? `${index + 1}. ${line}` : ` ${line}`).join("\n")),
1299
+ instructions.join("\n")
1300
+ ].join("\n\n");
1301
+ }
1302
+ /**
1303
+ * The prompt that sends an agent to fix comments: the text of each thread, where it is, and its files. With `agent`, it
1304
+ * also tells the agent to read the threads, and to resolve them when the member may, through the ViteHub MCP.
1305
+ */
1306
+ function commentsAgentPrompt(input) {
1307
+ return render(input, Number.POSITIVE_INFINITY);
1308
+ }
1309
+ /**
1310
+ * A link that opens a new T3 Code thread with the prompt of `commentsAgentPrompt()`, in `repository` (`owner/name`)
1311
+ * when it is a GitHub repository. The link is at most `t3CodeLinkLimit` characters. A long prompt always keeps its steps:
1312
+ * first its messages and anchors get shorter, then each thread keeps only its ID and a short title. For an MCP prompt,
1313
+ * the last option is the thread IDs and instructions. Returns `undefined` if none of these fit.
1314
+ */
1315
+ function commentsT3CodeLink(input, repository) {
1316
+ const repo = gitHubRepositoryOf(repository);
1317
+ const link = (detail) => {
1318
+ const url = new URL(t3CodeNewThread);
1319
+ url.searchParams.set("prompt", render(input, detail));
1320
+ if (repo) url.searchParams.set("repo", repo);
1321
+ return url.href;
1322
+ };
1323
+ const lengths = [Number.POSITIVE_INFINITY];
1324
+ for (let length = 2e3; length >= shortest; length = Math.floor(length / 2)) lengths.push(length);
1325
+ for (const detail of [
1326
+ ...lengths,
1327
+ "titles",
1328
+ ...input.agent ? ["ids"] : []
1329
+ ]) {
1330
+ const href = link(detail);
1331
+ if (href.length <= 8e3) return href;
1332
+ }
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."
735
1350
  ].join("\n");
736
1351
  }
737
1352
  // src/client-anchor.ts
@@ -1509,151 +2124,6 @@ function createCommentSend(transport, options = {}) {
1509
2124
  }
1510
2125
  };
1511
2126
  }
1512
- // src/rest-transport.ts
1513
- /** The URL of an attachment key below the Comments API, such as `/_vitehub/comments/attachments/comments/<id>/shot.png`. */
1514
- function commentAttachmentUrl(key, base = "") {
1515
- return `${base.replace(/\/+$/, "")}${commentsRoute}/attachments/${key.split("/").map((part) => encodeURIComponent(part)).join("/")}`;
1516
- }
1517
- /**
1518
- * Requests to the Comments API at `<base>/_vitehub/comments`, with the guest headers and the session cookie. A
1519
- * failure throws a diagnostic with the `code`, `why`, and `fix` of the error object of the answer, and its `status`.
1520
- */
1521
- function createCommentsRestRequest(options = {}) {
1522
- const route = options.route ?? `${(options.base ?? "").replace(/\/+$/, "")}/_vitehub/comments`;
1523
- return async (path, init = {}) => {
1524
- const send = options.fetch ?? globalThis.fetch;
1525
- const headers = new Headers(typeof options.headers === "function" ? await options.headers() : options.headers);
1526
- for (const [name, value] of new Headers(init.headers)) headers.set(name, value);
1527
- if (init.body !== void 0 && !headers.has("content-type")) headers.set("content-type", "application/json");
1528
- const guest = typeof options.guest === "function" ? options.guest() : options.guest;
1529
- if (guest) {
1530
- headers.set("x-vitehub-comments-guest-id", guest.id);
1531
- headers.set("x-vitehub-comments-guest-name", encodeURIComponent(guest.name));
1532
- }
1533
- let response;
1534
- try {
1535
- response = await send(`${route}${path}`, {
1536
- ...init,
1537
- headers,
1538
- credentials: options.credentials ?? "same-origin",
1539
- cache: "no-store"
1540
- });
1541
- } catch (cause) {
1542
- throw commentsUnansweredError(0, cause);
1543
- }
1544
- const value = await response.json().catch(() => void 0);
1545
- const retryAfter = retryAfterOf(response);
1546
- if (isRecordOrFunction(value) && isRecordOrFunction(value.error)) {
1547
- const { code, why, fix } = value.error;
1548
- if (typeof code !== "string" || typeof why !== "string") throw commentsUnansweredError(response.status, void 0, retryAfter);
1549
- throw commentsAnswerError({
1550
- code,
1551
- why,
1552
- ...typeof fix === "string" ? { fix } : {},
1553
- ...retryAfter === void 0 ? {} : { retryAfter },
1554
- status: response.status
1555
- });
1556
- }
1557
- if (isRecordOrFunction(value) && "data" in value) {
1558
- const answer = {
1559
- data: value.data,
1560
- people: Array.isArray(value.people) ? value.people : [],
1561
- ...isRecordOrFunction(value.thread) ? { thread: value.thread } : {}
1562
- };
1563
- options.onAnswer?.(answer);
1564
- return answer;
1565
- }
1566
- throw commentsUnansweredError(response.status, void 0, retryAfter);
1567
- };
1568
- }
1569
- function listSearch(query) {
1570
- const params = new URLSearchParams();
1571
- if (query.page !== void 0) params.set("page", query.page);
1572
- if (query.subject) {
1573
- params.set("subjectKind", query.subject.kind);
1574
- params.set("subjectId", query.subject.id);
1575
- } else if (query.subjectKind) params.set("subjectKind", query.subjectKind);
1576
- if (query.status) params.set("status", query.status);
1577
- if (query.mine !== void 0) params.set("mine", String(query.mine));
1578
- if (query.mentions !== void 0) params.set("mentions", String(query.mentions));
1579
- if (query.revision) params.set("revision", String(query.revision.lte));
1580
- if (query.limit !== void 0) params.set("limit", String(query.limit));
1581
- if (query.before) {
1582
- params.set("beforeId", query.before.id);
1583
- params.set("beforeUpdatedAt", String(query.before.updatedAt));
1584
- }
1585
- return params;
1586
- }
1587
- const thread = (id) => `/threads/${encodeURIComponent(id)}`;
1588
- const post = (body, account) => ({
1589
- method: "POST",
1590
- ...body === void 0 ? {} : { body: JSON.stringify(body) },
1591
- ...account === void 0 ? {} : { headers: { [outboxAccountHeader]: encodeURIComponent(account) } }
1592
- });
1593
- /**
1594
- * A transport over the Comments API at `<base>/_vitehub/comments`: the routes that the overlay uses. The server
1595
- * runs the `authorize` policy of `server/comments.ts` for the user of the request: the app session, or a guest that
1596
- * `guest` names. Guests and share-link readers can use it. It has no
1597
- * `subscribe`: the client refreshes when the window gets focus.
1598
- */
1599
- function createRestTransport(options = {}) {
1600
- const request = createCommentsRestRequest(options);
1601
- const base = (options.base ?? "").replace(/\/+$/, "");
1602
- const upload = async (input, account) => (await request("/attachments", post(input, account))).data;
1603
- return {
1604
- async list(query) {
1605
- return (await request(`/threads?${listSearch(query)}`)).data;
1606
- },
1607
- async get(input) {
1608
- const path = "threadId" in input ? thread(input.threadId) : `/scopes/${encodeURIComponent(input.scope)}/threads/${input.n}`;
1609
- return (await request(path)).data;
1610
- },
1611
- async create({ files, outbox, ...input }) {
1612
- const body = await withCommentFiles(input, {
1613
- files,
1614
- outbox
1615
- }, input.subject, (data) => upload(data, outbox?.account));
1616
- return (await request("/threads", post(body, outbox?.account))).data;
1617
- },
1618
- async reply({ threadId, subject, files, outbox, ...input }) {
1619
- const body = await withCommentFiles(input, {
1620
- files,
1621
- outbox
1622
- }, subject, (data) => upload(data, outbox?.account));
1623
- const answer = await request(`${thread(threadId)}/comments`, post(body, outbox?.account));
1624
- if (!answer.thread) throw commentsUnansweredError(200);
1625
- return answer.thread;
1626
- },
1627
- async edit({ threadId, messageId, ...input }) {
1628
- return (await request(`${thread(threadId)}/comments/${encodeURIComponent(messageId)}`, {
1629
- method: "PATCH",
1630
- body: JSON.stringify(input)
1631
- })).data;
1632
- },
1633
- async delete({ threadId, messageId }) {
1634
- const path = messageId === void 0 ? thread(threadId) : `${thread(threadId)}/comments/${encodeURIComponent(messageId)}`;
1635
- return (await request(path, { method: "DELETE" })).data;
1636
- },
1637
- async resolve({ threadId }) {
1638
- return (await request(`${thread(threadId)}/resolve`, post())).data;
1639
- },
1640
- async reopen({ threadId }) {
1641
- return (await request(`${thread(threadId)}/reopen`, post())).data;
1642
- },
1643
- async users({ query, limit, threadId, subject }) {
1644
- const params = new URLSearchParams({ q: query });
1645
- if (limit !== void 0) params.set("limit", String(limit));
1646
- if (threadId !== void 0) params.set("thread", threadId);
1647
- else if (subject) {
1648
- params.set("subjectKind", subject.kind);
1649
- params.set("subjectId", subject.id);
1650
- }
1651
- return (await request(`/people?${params}`)).data;
1652
- },
1653
- upload: (input) => upload(input),
1654
- attachmentUrl: (key) => commentAttachmentUrl(key, base)
1655
- };
1656
- }
1657
2127
  // src/send-transport.ts
1658
2128
  /**
1659
2129
  * The transport of `createCommentSend()` over the Send routes of Comments, `<base>/_vitehub/comments/send/**`. The
@@ -1700,8 +2170,25 @@ function createCommentSendTransport(options = {}) {
1700
2170
  };
1701
2171
  }
1702
2172
  // src/client.ts
1703
- function createCommentsClient(options) {
1704
- const { transport } = options;
2173
+ function observed(input) {
2174
+ for (const files of [input.files, input.deferredFiles]) if (files && !Array.isArray(files)) files.catch(() => {});
2175
+ return input;
2176
+ }
2177
+ async function filesArrived({ files, deferredFiles, ...input }) {
2178
+ if (deferredFiles) return {
2179
+ ...input,
2180
+ files: [...files ?? [], ...await deferredFiles]
2181
+ };
2182
+ return {
2183
+ ...input,
2184
+ ...files ? { files: await files } : {}
2185
+ };
2186
+ }
2187
+ function createCommentsClient(options = {}) {
2188
+ const transport = options.transport ?? createRestTransport({
2189
+ base: appCommentsBase(),
2190
+ guest: readCommentsGuest
2191
+ });
1705
2192
  const listeners = /* @__PURE__ */ new Set();
1706
2193
  const byId = /* @__PURE__ */ new Map();
1707
2194
  let listed = /* @__PURE__ */ new Set();
@@ -1830,7 +2317,6 @@ function createCommentsClient(options) {
1830
2317
  }
1831
2318
  return threads;
1832
2319
  };
1833
- /** The thread as the client shows it, with what waits in the outbox, also when the query leaves it out. */
1834
2320
  const shown = (threadId) => {
1835
2321
  const stored = byId.get(threadId);
1836
2322
  const { server, local } = outbox ? outbox.overlay(stored ? [stored] : []) : {
@@ -1885,8 +2371,14 @@ function createCommentsClient(options) {
1885
2371
  upsert(thread);
1886
2372
  return shown(thread.id) ?? thread;
1887
2373
  },
1888
- create: async (input) => outbox ? outbox.create(input) : upsert(await transport.create(input)),
1889
- reply: (input) => outbox ? outbox.reply(input) : mutate(input.threadId, async () => upsert(await transport.reply(input))),
2374
+ create: async (input) => {
2375
+ observed(input);
2376
+ return outbox ? outbox.create(input) : upsert(await transport.create(await filesArrived(input)));
2377
+ },
2378
+ reply: (input) => {
2379
+ observed(input);
2380
+ return outbox ? outbox.reply(input) : mutate(input.threadId, async () => upsert(await transport.reply(await filesArrived(input))));
2381
+ },
1890
2382
  edit: async (input) => {
1891
2383
  if (outbox?.owns(input.threadId, input.messageId)) {
1892
2384
  if (!await outbox.edit(input.messageId, input.body, input.mentions)) throw commentsClientDiagnostics.COMMENTS_OUTBOX_SENDING();
@@ -1906,7 +2398,14 @@ function createCommentsClient(options) {
1906
2398
  return next;
1907
2399
  });
1908
2400
  },
1909
- resolve: (input) => mutate(input.threadId, async () => upsert(await transport.resolve(input))),
2401
+ resolve: (input) => mutate(input.threadId, async () => {
2402
+ const threadId = outbox ? await outbox.beforeResolve(input.threadId) : input.threadId;
2403
+ if (threadId === void 0) throw commentsClientDiagnostics.COMMENTS_OUTBOX_RESOLVE_BLOCKED();
2404
+ return upsert(await transport.resolve({
2405
+ ...input,
2406
+ threadId
2407
+ }));
2408
+ }),
1910
2409
  reopen: (input) => mutate(input.threadId, async () => upsert(await transport.reopen(input))),
1911
2410
  users: (input) => transport.users(input),
1912
2411
  outbox,
@@ -1931,4 +2430,4 @@ function createCommentsClient(options) {
1931
2430
  }
1932
2431
  };
1933
2432
  }
1934
- export { anchorRange, commentAttachmentUrl, commentsAgentPrompt, commentsErrorDiagnostics, createAnchor, createCommentSend, createCommentSendTransport, createCommentsClient, createCommentsRestRequest, createIndexedDBOutboxStore, createMemoryOutboxStore, createRestTransport, foldName, replyMessageId, resolveAnchor, selectorFor };
2433
+ export { anchorRange, appCommentsBase, commentAttachmentUrl, commentsAgentPrompt, commentsApiCan, commentsErrorDiagnostics, commentsGuestUser, commentsPagePrompt, commentsT3CodeLink, createAnchor, createCommentSend, createCommentSendTransport, createCommentsClient, createCommentsRestRequest, createIndexedDBOutboxStore, createMemoryOutboxStore, createRestTransport, foldName, onCommentsGuestSaved, readCommentsGuest, replyMessageId, resolveAnchor, saveCommentsGuest, selectorFor, t3CodeLinkLimit };