@vite-hub/comments 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +37 -15
  2. package/dist/anchor.d.ts +2 -2
  3. package/dist/{client-diagnostics-CcFpkbAk.js → client-diagnostics-Bubm7Shd.js} +20 -5
  4. package/dist/client-files-CJZl5Kc4.js +53 -0
  5. package/dist/client.d.ts +567 -13
  6. package/dist/client.js +1209 -34
  7. package/dist/{console-h4KlhIik.d.ts → console-D1lwNMZn.d.ts} +2 -0
  8. package/dist/{migrate-BDQ8xqUs.js → database-6hXRnqDE.js} +47 -2
  9. package/dist/database-CTo7mx6t.d.ts +575 -0
  10. package/dist/database.d.ts +2 -1
  11. package/dist/database.js +2 -2
  12. package/dist/{define-43mMR39K.js → define-BMBSVbD9.js} +1 -1
  13. package/dist/{define-B3TF9zzn.d.ts → define-CmIFU96x.d.ts} +8 -4
  14. package/dist/{errors-4gelGVmK.js → errors-BJTZ9iyv.js} +24 -0
  15. package/dist/{errors-C6qptPoG.js → errors-Dq4AHjza.js} +23 -3
  16. package/dist/index-RiHzmV16.d.ts +194 -0
  17. package/dist/index.d.ts +6 -7
  18. package/dist/index.js +57 -9
  19. package/dist/{install-W9ghhGoh.d.ts → install-BGGQKbQ4.d.ts} +9 -3
  20. package/dist/{install-BcMPgPk_.js → install-DrAse1Fa.js} +912 -60
  21. package/dist/{installed-B-PfERBU.js → installed-C3EoqJEY.js} +7 -6
  22. package/dist/{operations-GLeOqgMt.d.ts → operations-BKhUWYkb.d.ts} +10 -5
  23. package/dist/{operations-D4A1Fcgf.d.ts → operations-VyyNZusz.d.ts} +13 -2
  24. package/dist/{operations-DMMIfYPW.js → operations-lsVKE0GH.js} +312 -219
  25. package/dist/operations.d.ts +2 -2
  26. package/dist/operations.js +2 -2
  27. package/dist/overlay/client-DBmJ4C1M.js +4 -0
  28. package/dist/overlay/overlay.js +41 -65
  29. package/dist/page/loader.js +39 -47
  30. package/dist/{page-DtbMOEMd.d.ts → page-Bzj0CszG.d.ts} +1 -10
  31. package/dist/{page-B41ozN63.js → page-DRz_sDY4.js} +1 -1
  32. package/dist/{page-tools-shared-NHUjKI8E.js → page-tools-shared-BNnuPK93.js} +6 -3
  33. package/dist/{plugin-PS8PMYus.js → plugin-DRsNaJaK.js} +34 -8
  34. package/dist/realtime.d.ts +2 -2
  35. package/dist/realtime.js +2 -2
  36. package/dist/reply-id-P_bSuEng.js +12 -0
  37. package/dist/request-log-Dj9Vw7qG.js +105 -0
  38. package/dist/request-origin-CFU0TQ7E.js +49 -0
  39. package/dist/{rpc-RKPAusHp.js → rpc-BQqYx8kb.js} +23 -7
  40. package/dist/{rpc-HBcWtg0T.d.ts → rpc-CuJ5GLIz.d.ts} +1 -1
  41. package/dist/rpc.d.ts +1 -1
  42. package/dist/rpc.js +1 -1
  43. package/dist/runtime/auth.d.ts +2 -2
  44. package/dist/runtime/auth.js +2 -2
  45. package/dist/runtime/console.d.ts +1 -1
  46. package/dist/runtime/console.js +3 -3
  47. package/dist/runtime/index.d.ts +42 -13
  48. package/dist/runtime/index.js +224 -22
  49. package/dist/{server-D8k-0GXe.js → server-Yk610niJ.js} +1 -1
  50. package/dist/server.d.ts +6 -5
  51. package/dist/server.js +6 -6
  52. package/dist/service-Bj-Mg63c.d.ts +73 -0
  53. package/dist/{service-GHhhyQj4.js → service-DA5BwfPQ.js} +71 -14
  54. package/dist/{session-DVx-1Tym.d.ts → session-DUcEor2W.d.ts} +3 -3
  55. package/dist/{session-EkudzUmm.js → session-X_g9dnU5.js} +27 -30
  56. package/dist/{service-CFVm23k7.d.ts → store-CsUNfC1w.d.ts} +11 -72
  57. package/dist/table-names-B9LlRC0B.js +16 -0
  58. package/dist/testing.d.ts +1 -1
  59. package/dist/testing.js +38 -5
  60. package/dist/{types-CZujrMFd.d.ts → types-BLaYh0_f.d.ts} +48 -4
  61. package/dist/{types-BIS0hCEl.d.ts → types-C35INXIs.d.ts} +88 -4
  62. package/dist/vite.d.ts +24 -7
  63. package/dist/vite.js +322 -173
  64. package/package.json +9 -9
  65. package/dist/errors-CyQyKAvy.d.ts +0 -185
  66. package/dist/index-DNhy69Wt.d.ts +0 -83
  67. package/dist/overlay/client-DmsSMOzi.js +0 -4
package/README.md CHANGED
@@ -22,7 +22,7 @@ A production build connects to `DATABASE_URL`, `TURSO_DATABASE_URL`, or a Cloudf
22
22
 
23
23
  ### Sign in with GitHub
24
24
 
25
- Create a GitHub App, install it on the repository, and list `https://<site>/api/_vitehub/comments/auth/callback/github` as its callback URL. Then set `VITEHUB_GITHUB_CLIENT_ID`, `VITEHUB_GITHUB_CLIENT_SECRET`, and `VITEHUB_SECRET` on the server. People who can push to the repository may comment. The session is an encrypted cookie, so the server stores no users.
25
+ Create a GitHub App, install it on the repository, and list `https://<site>/_vitehub/comments/auth/callback/github` as its callback URL. Then set `VITEHUB_GITHUB_CLIENT_ID`, `VITEHUB_GITHUB_CLIENT_SECRET`, and `VITEHUB_SECRET` on the server. People who can push to the repository may comment. The session is an encrypted cookie, so the server stores no users.
26
26
 
27
27
  ### In a ViteHub app
28
28
 
@@ -41,13 +41,13 @@ export const comments = defineComments({
41
41
 
42
42
  Without the file, `vitehub({ comments: true })` turns Comments on with `defineComments()`, and so does an object such as `{ database: "team" }`. The Console does not turn it on. `comments: false` turns it off. Docs sites of `@vite-hub/docs` on `vite-hub/nuxt` set it by default; `docs: { comments: false }` turns it off.
43
43
 
44
- ViteHub then adds the `vitehub_comment_threads`, `vitehub_comment_messages`, `vitehub_comment_counters`, and `vitehub_comment_forge` tables to the default Database (or the only one, or `defineComments({ database: "name" })`; without a Database Definition, the implicit `default` Database of `@vite-hub/database`), serves `/api/_vitehub/comments/**`, and adds a Comments section to the Console. Apply the tables with `vitehub database generate` and `vitehub database migrate`.
44
+ ViteHub then adds the `vitehub_comment_threads`, `vitehub_comment_messages`, `vitehub_comment_counters`, and `vitehub_comment_forge` tables to the default Database (or the only one, or `defineComments({ database: "name" })`; without a Database Definition, the implicit `default` Database of `@vite-hub/database`), serves `/_vitehub/comments/**`, and adds a Comments section to the Console. Apply the tables with `vitehub database generate` and `vitehub database migrate`. A production build fails with `DATABASE_CONTRIBUTED_TABLES_NOT_GENERATED` while the migrations lack a Comments table or column, such as one that a new version of Comments added.
45
45
 
46
46
  A ViteHub Database with the tables of the earlier live-site model must move them once in a migration: see [Upgrade to one model](https://vitehub.dev/docs/comments/configure#upgrade-to-one-model). Until then every Comments request fails with `COMMENTS_R0019`, whose `fix` names `commentsMigrationSql({ from: "live" })`. `migrateComments(db)` from `@vite-hub/comments/database` moves them in place and keeps the old tables as a backup.
47
47
 
48
- Comments is a ViteHub page tool. Open any page with `?vitehub`, or `?vitehub=comments`. The server adds the page tools loader to that page. The loader calls `GET /_vitehub/page/session`, which allows Comments when `authorize` allows `read` or offers GitHub sign-in or account switching, and sets the `vitehub-tools` cookie so later pages open in comment mode too. The loader then draws the ViteHub tools pill at the bottom of the page and imports the overlay. The overlay draws its toolbar in its segment of the pill, and its pins, cursors, and cards in `<vitehub-comments>`. The pill's **×** button turns the page tools off, so the toolbar has no close button of its own. A small ViteHub hexagon then stays at the pill's place, on every page, and pressing it turns them on again. The cookie is a hint, never a credential: every Comments route checks `authorize` again. A request without the hint gets the page with a short inline bootstrap that loads the loader in the browser only when the hint is there, so prerendered pages that a host serves as static files work too. Opening the Console calls the same session route, so the Console's people see the toolbar on the app's pages. The session route and the loader do not need the Console.
48
+ Comments is a ViteHub page tool. Open any page with `?vitehub`, or `?vitehub=comments`. The server adds the page tools loader to that page. The loader calls `GET /_vitehub/page/tools`, which allows Comments when `authorize` allows `read` or offers GitHub sign-in or account switching, and sets the `vitehub-tools` cookie so later pages open in comment mode too. The loader then draws the ViteHub tools pill at the bottom of the page and imports the overlay. The overlay draws its toolbar in its segment of the pill, and its pins, cursors, and cards in `<vitehub-comments>`. The pill's **×** button turns the page tools off, so the toolbar has no close button of its own. A small ViteHub hexagon then stays at the pill's place, on every page, and pressing it turns them on again. The cookie is a hint, never a credential: every Comments route checks `authorize` again. A request without the hint gets the page with a short inline bootstrap that loads the loader in the browser only when the hint is there, so prerendered pages that a host serves as static files work too. Opening the Console calls the same session route, so the Console's people see the toolbar on the app's pages. The session route and the loader do not need the Console.
49
49
 
50
- A single page app whose `index.html` Vite serves or builds gets a short inline check in that file. It imports the loader in the browser when the page has the query or the cookie, so a built `index.html` that a host serves as a static file also gets the tools. When the app has a Vite `base` or a Nuxt `app.baseURL`, such as `/docs/`, every path follows it: `/docs/_vitehub/page/session`, `/docs/_vitehub/page/assets/loader.js`, and `/docs/api/_vitehub/comments/**`. The loader and the overlay find the base from their own URL, including the overlay's Realtime presence and live update connections.
50
+ A single page app whose `index.html` Vite serves or builds gets a short inline check in that file. It imports the loader in the browser when the page has the query or the cookie, so a built `index.html` that a host serves as a static file also gets the tools. When the app has a Vite `base` or a Nuxt `app.baseURL`, such as `/docs/`, every path follows it: `/docs/_vitehub/page/tools`, `/docs/_vitehub/page/assets/loader.js`, and `/docs/_vitehub/comments/**`. The loader and the overlay find the base from their own URL, including the overlay's Realtime presence and live update connections.
51
51
 
52
52
  Custom `identify` names the user of every surface, and `authorize` decides; Comments then reads neither the Auth session nor the Console's access. Without `identify`, when the app has the Console, its Comments section controls access, and opening the Console enables the toolbar on the app's pages. Otherwise Comments reads the Auth session.
53
53
 
@@ -108,12 +108,20 @@ await comments.resolve(threadId, { by: { id: "agent", name: "Docs Agent" } })
108
108
 
109
109
  On a preview, `forge: { provider: "github" }` posts each thread to the pull request that the build previews: one summary comment that lists every thread, then one comment per comment, with the page, the element, the components, and the browser. Resolving a thread hides its comment. It posts with the GitHub App of `VITEHUB_GITHUB_APP_ID` and `VITEHUB_GITHUB_PRIVATE_KEY`, or as each person: people who signed in with GitHub post as themselves, and `token(author)` returns the token for any other sign-in. Each thread's `forge` field says whether it posted.
110
110
 
111
+ ## Failures in logs
112
+
113
+ A failure in `onComment`, `onMention`, or the pull request sync never fails the comment. With the evlog Nitro module registered, Comments logs it with `comments: { hook, step?, thread, code }`: a failed `onComment` on the wide event of the request, the others as their own evlog events. Without evlog, they go to the console. See [Limits and errors](https://vitehub.dev/docs/comments/limits-and-errors#see-hook-and-sync-failures-in-logs).
114
+
115
+ ## Send to an agent
116
+
117
+ `defineComments({ send: true })` adds **Send N** to the comment pill: one click hands the open threads of the page that wait for an answer to the person's own agent, such as a T3 Code thread. The first press copies a setup prompt; the agent creates a T3 webhook task and pairs it with the one-use code, and the pill asks once to allow it. Each send is a signed `POST` with the thread ids and a read token for 24 hours, through the member endpoints of `@vite-hub/webhooks`. `send: { grant: false }` leaves the token out, for an app that reads through its own MCP server, and `payload` adds fields, and `prompt` changes the setup prompt. Each member has their own count, and Allow sends only the threads the member saw. The `comments_get_send` MCP tool reads a send, and `comments.listSends(user)` and `comments.readSend(user, id)` read sends on the server. Reopening a thread can restore a done inbox send or let the member send it to a webhook agent again. Send needs a ViteHub app with a SQLite Database. See [Send comments to your agent](https://vitehub.dev/docs/comments/send).
118
+
111
119
  ## Deployment and security boundaries
112
120
 
113
121
  - Threads live only in the Database. Presence rooms hold no document, and connections are read-only. The server binds each person's presence to the user that `identify` or the Auth session resolves.
114
122
  - Pins anchor to the Content field first, then a CSS path checked against the element text, then the text alone, then the page point. A pin whose element is gone shows dashed.
115
123
  - A thread change tells the other tabs of the page through the Realtime events room, and they read the threads again. Changes from the server API reach open pages when they refetch: on focus and every 30 seconds.
116
- - Without a Realtime authority, such as on Vercel, comments work without presence or cursors.
124
+ - Without a Realtime driver, such as on Vercel, comments work without presence or cursors.
117
125
  - Write routes compare `Origin` with the request origin, and honour `X-Forwarded-Proto` and `X-Forwarded-Host` from a proxy that ends TLS.
118
126
  - Page context stores only the URL origin and pathname, validated against the request origin and thread page. Query parameters, URL credentials, and fragments are discarded. Nuxt component files come from its resolved component registry.
119
127
  - Guests can comment only when `authorize` allows `user: null`. They name themselves in the browser, and their names and IDs are display data only. Guests cannot delete comments or threads. `defineComments({ rateLimit: { limit: 5, window: "1m" } })` limits the writes of each guest address.
@@ -124,34 +132,34 @@ On a preview, `forge: { provider: "github" }` posts each thread to the pull requ
124
132
  | Import | Purpose |
125
133
  | --- | --- |
126
134
  | `@vite-hub/comments` | `defineComments()` and types. `installComments()` is in `@vite-hub/comments/server`. |
127
- | `@vite-hub/comments/client` | Framework-free client, transport types, `createAnchor()`, and `resolveAnchor()`. |
135
+ | `@vite-hub/comments/client` | Framework-free client, transport types, `createAnchor()`, `resolveAnchor()`, and `createCommentSend()`, the state of the Send segment that hands a member's waiting comments to their agent. |
128
136
  | `@vite-hub/comments/testing` | In-memory client transport for tests and examples. |
129
137
  | `@vite-hub/comments/anchor` | DOM anchoring: `createAnchor()`, `placeAnchor()`, `selectorOf()`, `labelOf()`. |
130
138
  | `@vite-hub/comments/database` | `commentsSchema`, the Drizzle tables, and `commentsTables`, the statements that create them. |
131
139
  | `@vite-hub/comments/realtime` | `commentsRealtime()`, the presence room Realtime Definition. |
132
- | `@vite-hub/comments/runtime` | `createCommentsHandler()` and `defineCommentsPlugin()` for a manual Nitro setup; `commentsMcpTools()` for an app's own MCP server. |
140
+ | `@vite-hub/comments/runtime` | `createCommentsHandler()` and `defineCommentsPlugin()` for a manual Nitro setup; `commentsMcpTools()` and `mcpToolResult()` for an app's own MCP server. |
133
141
  | `@vite-hub/comments/vite` | `comments()`, the plugin for apps without `vite-hub`, and `hubComments()`, the integration that `vitehub()` adds. |
134
142
  | `@vite-hub/comments/runtime/connect` | `connectDatabase()` of `@vite-hub/database/connect`, for the files that `comments()` generates. `/node` also opens SQLite files. |
135
143
 
136
144
  Generated files under `.vitehub/nitro/comments` are inspectable build output, not application imports.
137
145
 
138
- `createCommentsHandler(options)` returns a Fetchable, `{ fetch(request) }`. Mount it as a Nitro or H3 route at `/api/_vitehub/comments/**`, or call `handler.fetch(request)` yourself. Every outcome is a `Response`, also the errors. The handler gives the Request to `identify` as `event`, and reads cookies, the Cloudflare bindings, and `waitUntil` from its Standard Context, `request["~standard"]`. In a ViteHub app, Nitro sets it. For a Request from elsewhere, the handler sets it.
146
+ `createCommentsHandler(options)` returns a Fetchable, `{ fetch(request) }`. Mount it as a Nitro or H3 route at `/_vitehub/comments/**`, or call `handler.fetch(request)` yourself. Every outcome is a `Response`, also the errors. The handler gives the Request to `identify` as `event`, and reads cookies, the Cloudflare bindings, and `waitUntil` from its Standard Context, `request["~standard"]`. In a ViteHub app, Nitro sets it. For a Request from elsewhere, the handler sets it.
139
147
 
140
148
  ```ts
141
149
  import { createCommentsHandler } from "@vite-hub/comments/runtime";
142
150
  import { comments } from "./server/comments";
143
151
 
144
152
  const handler = createCommentsHandler({ comments, realtime: false });
145
- const response = await handler.fetch(new Request("https://site.test/api/_vitehub/comments/threads?page=/"));
153
+ const response = await handler.fetch(new Request("https://site.test/_vitehub/comments/threads?page=/"));
146
154
  ```
147
155
 
148
- `commentsMcpTools(comments)` returns tools with `call(input, { user })`, where your server authenticates `user` or passes `null` for an anonymous caller. With a request `event`, such as the Request or an H3 event, a configured Comments `identify` or session reader takes precedence over `user`. The `page` filter of `comments_list_threads` and of `comments.threads` takes a path such as `/pricing` or a full URL of the page. When `authorize` hides threads from the caller, the list says how many and why, and its structured output has a `hidden` count. See [Fix comments with an Agent](https://vitehub.dev/docs/comments/configure#fix-comments-with-an-agent).
156
+ `commentsMcpTools(comments)` returns tools with `call(input, { user })`, where your server authenticates `user` or passes `null` for an anonymous caller. A call returns `{ text, images, structured, isError }`: `comments_get_thread` puts the image attachments of the thread in `images`, up to 4 MB. `mcpToolResult(result)` turns it into the MCP tool result, with one `image` block for each image. With a request `event`, such as the Request or an H3 event, a configured Comments `identify` or session reader takes precedence over `user`. The `page` filter of `comments_list_threads` and of `comments.threads` takes a path such as `/pricing` or a full URL of the page. When `authorize` hides threads from the caller, the list says how many and why, and its structured output has a `hidden` count. See [Fix comments with an Agent](https://vitehub.dev/docs/comments/configure#fix-comments-with-an-agent).
149
157
 
150
158
  ## Learn more
151
159
 
152
160
  - [Comments](https://vitehub.dev/docs/comments) covers access, guests, mentions, hosts, and errors.
153
161
  - [Content](https://vitehub.dev/docs/content) covers collections, drafts, and publishing.
154
- - [Realtime](https://vitehub.dev/docs/realtime) covers room authorities.
162
+ - [Realtime](https://vitehub.dev/docs/realtime) covers room drivers.
155
163
 
156
164
  ### Floating window
157
165
 
@@ -235,8 +243,16 @@ client.onChange(() => console.log(`${client.threads.length} threads`));
235
243
 
236
244
  To retry a create safely, give it a `requestId`, such as `crypto.randomUUID()`, and keep it for that draft. A second create with the same `requestId` in the same scope returns the first thread and creates no new thread. Only the author of the first thread gets it back, for the same subject, and only when that author may still read it. Anything else fails: the Operations and `POST /threads` answer `409` with `COMMENTS_R0022`, and the server API `comments.create()` returns `COMMENTS_INVALID_INPUT` with the reason. Make a new `requestId` for each new comment.
237
245
 
246
+ A reply takes a `requestId` too. A second reply with the same `requestId` in the same thread returns the thread with the first message, adds nothing, and runs no hooks. Another author with that key gets the same `409`.
247
+
238
248
  `start()` listens to the transport's `subscribe`, such as Realtime. Without `subscribe` it refreshes when the window gets focus. A list that comes back late never undoes a thread that was created, changed, or deleted while it was on its way, and an event that is older than the stored thread is ignored. A transport that lost its connection sends `{ type: "reconnected" }` when it has it again, and the client lists the threads once more.
239
249
 
250
+ ### Outbox
251
+
252
+ `createCommentsClient({ ..., outbox: { account } })` saves each new comment and reply in IndexedDB before it sends. Drafts show with `delivery: { status: "pending" }` and survive a reload. The outbox checks the author on each write and stores progress so another tab can resume. See [Write comments offline](https://vitehub.dev/docs/comments/offline).
253
+
254
+ If a comment write gets no answer, retry it to recover the server copy. A later refusal does not make the draft safe to edit or dismiss. A lost upload or thread lookup answer does not lock the draft on its own.
255
+
240
256
  Without an explicit query `limit`, refresh loads every page. Multi-page refreshes require two matching scans before replacing the cache. If three scans cannot agree because the list keeps changing, refresh raises `COMMENTS_R0015` and preserves the previous cache; refresh again to retry. An explicit `limit` makes one request.
241
257
 
242
258
  ### Transport
@@ -244,14 +260,14 @@ Without an explicit query `limit`, refresh loads every page. Multi-page refreshe
244
260
  A transport is the seam to the server. Each method has the name and the input of one `comments.*` operation.
245
261
 
246
262
  ```ts
247
- import type { CommentCreateInput, CommentDeleteInput, CommentEditInput, CommentEvent, CommentGetInput, CommentListQuery, CommentReplyInput, CommentStatusInput, CommentThread, CommentUser, CommentUsersInput } from "@vite-hub/comments"
263
+ import type { CommentCreateInput, CommentDeleteInput, CommentEditInput, CommentEvent, CommentFiles, CommentGetInput, CommentListQuery, CommentReplyInput, CommentStatusInput, CommentThread, CommentUser, CommentUsersInput } from "@vite-hub/comments"
248
264
 
249
265
  interface CommentsTransport {
250
266
  supportsAttachments?: boolean; // Defaults to true for custom transports.
251
267
  list(query: CommentListQuery): Promise<CommentThread[]>;
252
- get(input: CommentGetInput): Promise<CommentThread | null>; // { id } or { scope, n }
253
- create(input: CommentCreateInput): Promise<CommentThread>;
254
- reply(input: CommentReplyInput): Promise<CommentThread>;
268
+ get(input: CommentGetInput): Promise<CommentThread | null>; // { threadId } or { scope, n }
269
+ create(input: CommentCreateInput & CommentFiles): Promise<CommentThread>; // `files` to store before the comment
270
+ reply(input: CommentReplyInput & CommentFiles): Promise<CommentThread>; // and `subject` of the thread, for the upload
255
271
  edit(input: CommentEditInput): Promise<CommentThread>;
256
272
  delete(input: CommentDeleteInput): Promise<CommentThread | null>;
257
273
  resolve(input: CommentStatusInput): Promise<CommentThread>;
@@ -263,6 +279,8 @@ interface CommentsTransport {
263
279
 
264
280
  A mutation returns the thread as it is afterwards. `delete` returns `null` when the thread is gone.
265
281
 
282
+ Queued `create` and `reply` get `requestId`, the remaining `files`, and `outbox`. Check `outbox.account` against the current author on every server write, including file uploads. Await `outbox.uploaded(key)` for each stored file, add the keys to `attachments`, and return the first thread for a repeated `requestId` on the same target. `createRestTransport()` and `createRpcTransport()` do this. A thrown error with `status` tells the outbox whether to wait, and `retryAfter` in milliseconds tells it how long.
283
+
266
284
  Transports accept attachment keys by default, including the shipped `createRpcTransport()`. Custom transports that reject attachment keys should set `supportsAttachments: false` to disable file controls in comment surfaces.
267
285
 
268
286
  `createMemoryTransport()` keeps threads in memory. Use it in tests and docs examples:
@@ -278,6 +296,10 @@ const client = createCommentsClient({ transport, user: ana });
278
296
 
279
297
  `transport.as(user)` gives another person on the same store, and `transport.reconnect()` sends `reconnected` to the listeners.
280
298
 
299
+ ### Send
300
+
301
+ `createCommentSend(transport)` is the state of the **Send** segment of a comment pill, without a framework. Its states are `idle`, `pairing`, `confirm`, `sending`, `sent`, `working`, `failed`, and `limited`. `send.state` holds the state and its data, and `send.onChange()` reports each change. The transport has `status()`, `startPairing()`, `pollPairing(code)`, `allow(code, selection)`, `cancel(code)`, `send()`, and an optional `subscribe()`. `CommentSend` of `@vite-hub/ui` renders it. `createCommentSendTransport({ page })` is the transport over the Send routes of `send: true`. See [Send to an agent](https://vitehub.dev/docs/ui/comments#send-to-an-agent).
302
+
281
303
  ## Errors
282
304
 
283
305
  Errors have a stable code, a `why`, and a `fix`.
package/dist/anchor.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { D as ElementAnchor } from "./types-CZujrMFd.js";
2
- import "./types-BIS0hCEl.js";
1
+ import { A as ElementAnchor } from "./types-BLaYh0_f.js";
2
+ import "./types-C35INXIs.js";
3
3
  //#region src/anchor.d.ts
4
4
  /** The anchor of a pin that the overlay drops: an element anchor with every hint that `placeAnchor()` uses. */
5
5
  export type PinAnchor = ElementAnchor & Required<Pick<ElementAnchor, "label" | "page" | "viewport">>;
@@ -1,6 +1,14 @@
1
1
  import { Diagnostic, defineDiagnostics } from "nostics";
2
2
  //#region src/client-diagnostics.ts
3
3
  const commentsClientCodes = {
4
+ COMMENTS_OUTBOX_ACCOUNT_CHANGED: {
5
+ why: "The current author is not the author of this queued comment.",
6
+ fix: "Sign in as the original author and retry the outbox."
7
+ },
8
+ COMMENTS_OUTBOX_SENDING: {
9
+ why: "The server may already have this comment, so the draft cannot change.",
10
+ fix: "Wait for delivery to finish, then edit or delete the server copy."
11
+ },
4
12
  COMMENTS_R0001: {
5
13
  why: ({ target }) => `createAnchor() found nothing to anchor to for ${target}.`,
6
14
  fix: "Pass an element, a non-empty selection, or a point that is over an element of the page."
@@ -18,9 +26,12 @@ const commentsClientDiagnostics = /*#__PURE__*/ defineDiagnostics({
18
26
  docsBase: "https://vitehub.dev/docs/comments/diagnostics",
19
27
  codes: commentsClientCodes
20
28
  });
21
- /** A failure that the server answered: a diagnostic with its code, why, and fix, and the HTTP status of the answer. */
29
+ /**
30
+ * A failure that the server answered: a diagnostic with its code, why, and fix, the HTTP status of the answer, and the
31
+ * wait that its `Retry-After` asks for, in milliseconds.
32
+ */
22
33
  function commentsAnswerError(failure) {
23
- const { code, details, fix, status, why } = failure;
34
+ const { code, details, fix, retryAfter, status, why } = failure;
24
35
  const docs = code.startsWith("COMMENTS_") ? `https://vitehub.dev/docs/comments/diagnostics/${code.toLowerCase()}` : void 0;
25
36
  return Object.assign(new Diagnostic({
26
37
  code,
@@ -29,12 +40,16 @@ function commentsAnswerError(failure) {
29
40
  ...docs ? { docs } : {}
30
41
  }), {
31
42
  status,
32
- ...details ? { details } : {}
43
+ ...details ? { details } : {},
44
+ ...retryAfter === void 0 ? {} : { retryAfter }
33
45
  });
34
46
  }
35
47
  /** `COMMENTS_R0013`: the request got no usable answer. `status` is 0 when it got no answer at all. */
36
- function commentsUnansweredError(status, cause) {
37
- return Object.assign(commentsClientDiagnostics.COMMENTS_R0013(cause === void 0 ? {} : { cause }), { status });
48
+ function commentsUnansweredError(status, cause, retryAfter) {
49
+ return Object.assign(commentsClientDiagnostics.COMMENTS_R0013(cause === void 0 ? {} : { cause }), {
50
+ status,
51
+ ...retryAfter === void 0 ? {} : { retryAfter }
52
+ });
38
53
  }
39
54
  //#endregion
40
55
  export { commentsUnansweredError as i, commentsClientCodes as n, commentsClientDiagnostics as r, commentsAnswerError as t };
@@ -0,0 +1,53 @@
1
+ //#region src/client-files.ts
2
+ const outboxAccountHeader = "x-vitehub-comments-outbox-account";
3
+ const failedCommentPreparation = /* @__PURE__ */ new WeakMap();
4
+ /** The file as Base64, the form that `comments.upload` takes. */
5
+ async function base64(file) {
6
+ const bytes = new Uint8Array(await file.arrayBuffer());
7
+ let binary = "";
8
+ for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
9
+ return btoa(binary);
10
+ }
11
+ /** A `File` keeps its name. A plain `Blob` gets `file` and the extension of its media type, such as `file.png`. */
12
+ function fileName(file) {
13
+ if (file instanceof File && file.name) return file.name;
14
+ const extension = /^[a-z]+\/([a-z0-9]+)/i.exec(file.type)?.[1];
15
+ return extension ? `file.${extension}` : "file";
16
+ }
17
+ /** Stores each file with `upload`, in order, and returns the keys for `attachments`. */
18
+ async function uploadFiles(files, subject, upload, uploaded) {
19
+ const keys = [];
20
+ for (const file of files) {
21
+ const stored = await upload({
22
+ name: fileName(file),
23
+ type: file.type || "application/octet-stream",
24
+ data: await base64(file),
25
+ ...subject ? { subject } : {}
26
+ });
27
+ await uploaded?.(stored.key);
28
+ keys.push(stored.key);
29
+ }
30
+ return keys;
31
+ }
32
+ async function withCommentFiles(input, { files, outbox }, subject, upload) {
33
+ if (!files?.length) return input;
34
+ try {
35
+ return {
36
+ ...input,
37
+ attachments: [...input.attachments ?? [], ...await uploadFiles(files, subject, upload, outbox?.uploaded)]
38
+ };
39
+ } catch (cause) {
40
+ if (outbox) failedCommentPreparation.set(outbox, { cause });
41
+ throw cause;
42
+ }
43
+ }
44
+ /** The `Retry-After` of an answer in milliseconds: seconds, or an HTTP date. */
45
+ function retryAfterOf(response, now = Date.now()) {
46
+ const value = response.headers.get("retry-after")?.trim();
47
+ if (!value) return void 0;
48
+ if (/^\d+$/.test(value)) return Number(value) * 1e3;
49
+ const date = Date.parse(value);
50
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - now);
51
+ }
52
+ //#endregion
53
+ export { withCommentFiles as i, outboxAccountHeader as n, retryAfterOf as r, failedCommentPreparation as t };