@verbb/comments-core 0.0.0-stage → 4.0.1

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,31 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 4.0.1 - 2026-11-28
6
+
7
+ ### Changed
8
+ - Released alongside Comments 4.0.1 with no changes to this package.
9
+
10
+ ## 4.0.0 - 2026-11-25
11
+
12
+ ### Added
13
+ - Add `@verbb/comments-core`, the data layer for Comments front ends, with no DOM, so it runs in browsers, Node, workers and server components. It's released alongside the Comments plugin at the same version.
14
+ - Add `createCommentsClient()` for the data API (`comments/api/*`), over REST or, through `@verbb/comments-core/graphql`, GraphQL, with the API version check, typed errors whose message is always safe to show a visitor, an `operationId` on every write that's resent once with the same ID after a dropped connection, and `cookieSession()` sign-in for Craft's own domain and for another subdomain of the same site.
15
+ - Add `memberToken({ getToken })` and `guestSession()` for front ends on a different site from Craft. A member's short-lived token goes in `Authorization: Bearer` and is fetched again before it expires or once the server refuses it, and a guest's session token goes in `X-Comments-Session`, kept in memory or, if you choose, `sessionStorage`.
16
+ - Add `createThreadStore()`, which loads a thread and the visitor's own data together, pages roots and replies by cursor without duplicates, places a visitor's pending comments and a moderator's held ones, clears them when the person signs out, fetches a thread again when a cache served one older than the visitor's own data, follows links to comments only the visitor may see, and handles posting, editing, deleting, voting, reporting, following and moderating, running actions on the same comment in the order they were made.
17
+ - Add links to a comment by the number in its permalink: `client.comment({ id })`, `ids` on `viewer` reads, and `store.loadComment()` taking a UID, a number or an answer already fetched. The store asks `viewer` about at most 100 comments a read.
18
+ - Add `createProtectionFlow()`, which keeps a Protect preparation fresh in a page left open, uses each one once, and fetches a new one and retries once when the server says it expired. It imports `@verbb/protect` the first time a preparation arrives, rather than with the thread store, so a front end whose visitors only read never downloads it.
19
+ - Add the `signature_invalid` and `user_not_eligible` error codes, which only a site's own server sees when it asks for member tokens.
20
+ - Add the `blocked` error code for a commenter blocked from a discussion, handled like `forbidden`: never retried, and the thread store shows the refused action, or for `blocked` every action, as unavailable.
21
+ - Add TypeScript types for every response and request, and the JSON Schema generated from them at `@verbb/comments-core/schema/data.json`.
22
+ - Add custom field uploads: `client.upload()` takes an Assets field's `field` with its thread (`ownerId` or `ownerUri`, `siteId`, `parentUid`) or `commentUid`, and a guest's `protection` evidence, answered as `FieldUploadResponse`. Guests' sign-in no longer lists `upload` as unavailable, since guests can upload to the fields they're offered.
23
+ - Add stage M's shapes to the types and schema: `placement`, `accept`, `maxFiles`, `maxSize` and `meta` on field descriptions, `edit`'s `editor.fields` and file values (`EditFileData`), a shown file's `url` being null without public URLs, and the `comment` read's `ownerId` and `siteId`.
24
+ - Add `upload` as a protection flow action (`EvidenceContext`), for a guest's custom field uploads, which each use a preparation of their own.
25
+ - Add `jsonLdScript()`, which writes structured data as text that's safe inside `<script type="application/ld+json">`, with `<`, `>`, `&`, U+2028 and U+2029 escaped, so a comment containing `</script>` can't end the script.
26
+ - Add `ThreadStoreEventMap`, which types each event a thread store emits. `store.on()` takes only those events, and gives each every `detail` key the browser event of the same name has, such as `commentUid`, `commentId` and `vote`, with a few of its own, such as `cursor` and `count`.
27
+ - Add `COMMENTS_SESSION_HEADER`, the name of the header a guest's session token travels in on another site.
28
+ - Add `meta` to a custom field's description, holding anything else its field type gives for a site's own field override.
29
+ - Add `badges` to the viewer's own data, in the same shape as a comment author's, for the "Posting as" line.
30
+ - Add GIFs from GIPHY to the types and schema: `gifWidth` and `gifHeight` beside a comment's `gifUrl`, `editor.gifs` (`GifsData`) on `viewer` and `edit` reads, the `edit` read's `content.gif`, and an optional `gif` on a write's `content`, where an update leaves the comment's GIF alone without it and takes it off with `null`.
31
+ - Add Comments 3's folded comments and author scores to the types and schema: `folded` on every comment (`reports`, `downvotes` or `null`, as `FoldReason`) and `score` on its author.
package/LICENSE.md ADDED
@@ -0,0 +1,40 @@
1
+ Copyright © Verbb
2
+
3
+ Permission is hereby granted to any person obtaining a copy of this software
4
+ (the “Software”) to use, copy, modify, merge, publish and/or distribute copies
5
+ of the Software, and to permit persons to whom the Software is furnished to do
6
+ so, subject to the following conditions:
7
+
8
+ 1. **Don’t plagiarize.** The above copyright notice and this license shall be
9
+ included in all copies or substantial portions of the Software.
10
+
11
+ 2. **Don’t use the same license on more than one project.** Each licensed copy
12
+ of the Software shall be actively installed in no more than one production
13
+ environment at a time.
14
+
15
+ 3. **Don’t mess with the licensing features.** Software features related to
16
+ licensing shall not be altered or circumvented in any way, including (but
17
+ not limited to) license validation, payment prompts, feature restrictions,
18
+ and update eligibility.
19
+
20
+ 4. **Pay up.** Payment shall be made immediately upon receipt of any notice,
21
+ prompt, reminder, or other message indicating that a payment is owed.
22
+
23
+ 5. **Follow the law.** All use of the Software shall not violate any applicable
24
+ law or regulation, nor infringe the rights of any other person or entity.
25
+
26
+ Failure to comply with the foregoing conditions will automatically and
27
+ immediately result in termination of the permission granted hereby. This
28
+ license does not include any right to receive updates to the Software or
29
+ technical support. Licensees bear all risk related to the quality and
30
+ performance of the Software and any modifications made or obtained to it,
31
+ including liability for actual and consequential harm, such as loss or
32
+ corruption of data, and any necessary service, repair, or correction.
33
+
34
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
35
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
36
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
37
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
38
+ LIABILITY, INCLUDING SPECIAL, INCIDENTAL AND CONSEQUENTIAL DAMAGES, WHETHER IN
39
+ AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
40
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,92 @@
1
- # Temporary Holding Version
1
+ # Comments Core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@verbb/comments-core` is the data layer for front ends built on [Comments](https://verbb.io/craft-plugins/comments) for Craft CMS. It reads and writes threads through the Comments data API over REST or GraphQL, keeps a thread's state in a store your own UI can subscribe to, handles signing in, spam protection and retries, and ships TypeScript types and a JSON Schema for every response. It never touches the page, so it runs in browsers, web workers, Node and server components.
4
+
5
+ Most sites don't need it directly. The plugin draws threads with `@verbb/comments-browser`, and the React and Vue packages build on that. Reach for core when you're building your own interface or reading comments on a server.
6
+
7
+ ```js
8
+ import { createCommentsClient, createThreadStore, selectRoots } from '@verbb/comments-core';
9
+
10
+ const client = createCommentsClient({ endpoint: 'https://example.com/actions/comments/api' });
11
+ const store = createThreadStore(client, { ownerUri: 'blog/my-post' });
12
+
13
+ store.subscribe((state) => render(selectRoots(state)));
14
+ await store.load();
15
+ ```
16
+
17
+ ## Events
18
+
19
+ `store.on(name, listener)` tells you as things happen to the thread. The events are the browser events about the thread's data, with the same names, and each `detail` has every key the browser event's has, typed by `ThreadStoreEventMap`, with `apiVersion` on every one. A few add keys the browser events don't have, marked below.
20
+
21
+ | Event | Detail |
22
+ | --- | --- |
23
+ | `comments:request-start`, `comments:request-end` | `reason`, what the request is for, such as `thread` or `vote` |
24
+ | `comments:request-error` | `reason`, `message`, and for a `CommentsRequestError` its `category`, `code`, `fieldErrors` and `recoverable`, plus the `error` itself (store only) |
25
+ | `comments:roots-loaded` | `cursor` the page was loaded from, and its `count` (both store only) |
26
+ | `comments:viewer-loaded` | `viewer`, who's reading and what they may do, as the thread now has it |
27
+ | `comments:sorted` | `sort` |
28
+ | `comments:replies-loaded` | `commentUid`, and `count` (store only) |
29
+ | `comments:comment-created` | `commentUid` and `moderationState`, plus `parentUid` and `replayed` (store only) |
30
+ | `comments:comment-updated`, `comments:comment-deleted` | `commentUid` |
31
+ | `comments:comment-moderated` | `commentUid`, `commentId` and `moderationAction`, plus the comment's `state` afterwards (store only) |
32
+ | `comments:vote-changed` | `commentUid`, `commentId` and `vote`, which is null when a vote was taken back |
33
+ | `comments:report-changed` | `commentUid`, `commentId` and `reported`, which is false after a withdrawal |
34
+ | `comments:follow-changed` | `following` |
35
+
36
+ `commentId` is the number in the comment's permalink, such as `1446` for `#comment-1446`, or null. A `comments:request-error` for something other than a `CommentsRequestError` has a general `message`, where the browser event uses the thread's own translated wording. The page's own events, such as `comments:before-submit` and `comments:editor-opened`, come only from the browser package.
37
+
38
+ ## GraphQL
39
+
40
+ REST is the default. To read and write through Craft's GraphQL API instead, pass the GraphQL transport, which lives in its own entry so sites that don't use it never bundle it. Anything GraphQL has no query for, such as protection and uploads, still goes through REST at `endpoint`.
41
+
42
+ ```js
43
+ import { createCommentsClient } from '@verbb/comments-core';
44
+ import { graphqlTransport } from '@verbb/comments-core/graphql';
45
+
46
+ const client = createCommentsClient({
47
+ endpoint: 'https://example.com/actions/comments/api',
48
+ transport: graphqlTransport({ endpoint: 'https://example.com/api' }),
49
+ });
50
+ ```
51
+
52
+ ## Signing in from another site
53
+
54
+ On Craft's own domain, or another subdomain of the same site, `cookieSession()` (the default) uses Craft's session cookie. A front end on a different site can't send Craft's cookies, so it signs in another way.
55
+
56
+ - **Members** use `memberToken({ getToken })`. Your own server asks Comments for a short-lived token with a signed request, and `getToken()` fetches it from your server and returns `{ token, expiresAt }`. Core sends it as `Authorization: Bearer` on every request that identifies the person, never on public reads, keeps it in memory only, and fetches the next one shortly before it expires or when the server says it has expired or been revoked.
57
+ - **Guests** use `guestSession()`. Their first write starts a guest session through the `session` read, and core sends its token as `X-Comments-Session` from then on, taking the refreshed token each answer carries. Guests can't edit, mention, upload or moderate, so a thread store shows those as unavailable.
58
+
59
+ ```js
60
+ import { createCommentsClient, guestSession, memberToken } from '@verbb/comments-core';
61
+
62
+ const auth = member
63
+ ? memberToken({ getToken: () => fetch('/api/comments-token').then((response) => response.json()) })
64
+ : guestSession({ storage: sessionStorage });
65
+
66
+ const client = createCommentsClient({ endpoint: 'https://cms.example.com/actions/comments/api', auth });
67
+ ```
68
+
69
+ ## Cookies and storage
70
+
71
+ Core stores nothing in a visitor's browser by itself. Craft's session and CSRF cookies, on Craft's own domain or a sibling subdomain, are set by Craft when someone starts writing, voting or following, and never just for reading. A guest on another site keeps their guest session token in memory, so a reload starts a new guest session, unless you pass `guestSession({ storage: sessionStorage })`. That keeps it for the tab under the key `verbb-comments-session:` followed by the API's endpoint, from the guest's first write until the tab closes or `reset()` is called. Member tokens are never stored.
72
+
73
+ ## Caching
74
+
75
+ Structured data from `client.structuredData()` goes into a page as `<script type="application/ld+json">${jsonLdScript(structuredData)}</script>`. Use `jsonLdScript()` rather than `JSON.stringify()`, which would let a comment containing `</script>` end the script early and run the rest of its text as HTML.
76
+
77
+ Public reads (`thread`, `replies`, `comment` and `structured-data`) are cacheable, and the store fetches a thread again when a cache served one older than the visitor's own data. A thread with a comment from the last minute changes its `ETag` every second until that comment is a minute old, because the comment's relative time ("12 seconds ago") is part of it. That's expected, and quieter threads keep the same `ETag` until something changes.
78
+
79
+ ## Requirements
80
+
81
+ - The package is ES modules only, with no CommonJS build. Use `import`, or `await import('@verbb/comments-core')` from CommonJS code.
82
+ - TypeScript projects need `moduleResolution` set to `bundler`, `node16` or `nodenext`. With `node16` or `nodenext`, a CommonJS file can only load the package with a dynamic `import()`.
83
+ - Its types use the standard `fetch` types, so `lib` needs `DOM` or `WebWorker`. Server-only projects can use `WebWorker` with `@types/node`.
84
+ - It needs a global `fetch`, which every supported browser and Node 20 or later has, or one passed as the `fetch` option.
85
+
86
+ ## Documentation
87
+
88
+ The [Comments package docs](https://docs.verbb.io/comments) cover the client, the thread store, signing in across sites, protection and errors.
89
+
90
+ ## Licence
91
+
92
+ Comments Core is released under the Verbb licence in `LICENSE.md`, the same as the Comments plugin.
@@ -0,0 +1,156 @@
1
+ import { type RequestProfile, type SignInProvider } from './sign-in.js';
2
+ import { type CommentsTransport } from './transport.js';
3
+ import type { QueryValue } from './url.js';
4
+ import type { CommentResponse, CreateRequest, CreateResponse, EditResponse, FollowRequest, FollowResponse, ModerateRequest, ModerateResponse, ProtectionEvidenceData, ProtectionResponse, DeleteRequest, DeleteResponse, RepliesResponse, ReportRequest, ReportResponse, SessionResponse, SortOrder, StructuredDataResponse, ThreadResponse, UpdateRequest, UpdateResponse, ViewerResponse, VoteRequest, VoteResponse } from './types.js';
5
+ export type CommentsClientOptions = {
6
+ /** The data API's base URL, such as `https://example.com/actions/comments/api`, or a relative path in a browser. */
7
+ endpoint: string;
8
+ /** The site to read and write, when the endpoint's own site isn't the one wanted. */
9
+ siteId?: number | null;
10
+ /** The request profile, used to choose the default sign-in provider. */
11
+ profile?: RequestProfile;
12
+ /** How the person is identified. Defaults to `cookieSession()` for the profile. */
13
+ auth?: SignInProvider;
14
+ /**
15
+ * REST by default. Pass `graphqlTransport()` from `@verbb/comments-core/graphql`, or a transport
16
+ * of your own; whatever it doesn't `handles()` still goes through REST to `endpoint`.
17
+ */
18
+ transport?: CommentsTransport;
19
+ fetch?: typeof fetch;
20
+ /**
21
+ * Extra headers: `public` ones on the cacheable public reads, `private` ones on everything that
22
+ * identifies the person. Kept apart so a secret meant for private requests can't end up in a
23
+ * shared cache's request or on a CDN.
24
+ */
25
+ headers?: {
26
+ public?: Record<string, string>;
27
+ private?: Record<string, string>;
28
+ };
29
+ /** Milliseconds before a request is abandoned. Defaults to 30 seconds. */
30
+ timeoutMs?: number;
31
+ };
32
+ export type RequestOptions = {
33
+ signal?: AbortSignal;
34
+ /** The fetch cache mode, such as `no-cache` to revalidate what the browser holds. */
35
+ cache?: RequestCache;
36
+ };
37
+ export type WriteOptions = RequestOptions & {
38
+ /** Reuse an `operationId` to retry a write the server may already have made. */
39
+ operationId?: string;
40
+ };
41
+ export type OwnerParams = {
42
+ ownerId?: number;
43
+ /** The owner's URI, for headless sites that route by URI. */
44
+ ownerUri?: string;
45
+ siteId?: number | null;
46
+ };
47
+ export type ThreadParams = OwnerParams & {
48
+ sort?: SortOrder;
49
+ /** Must stay the same while paging: a cursor is only valid at the limit it was made with. */
50
+ limit?: number;
51
+ cursor?: string | null;
52
+ /**
53
+ * The `threadVersion` a `viewer` read gave, sent as `v` to ask past a CDN holding an older
54
+ * thread. The server ignores it; it only makes the URL new.
55
+ */
56
+ threadVersion?: string;
57
+ };
58
+ export type RepliesParams = {
59
+ /** The comment whose replies to load. */
60
+ parentUid: string;
61
+ cursor?: string | null;
62
+ limit?: number;
63
+ };
64
+ export type ViewerParams = ThreadParams & {
65
+ /** Comments outside the window, such as loaded replies, to include permissions for. */
66
+ uids?: string[];
67
+ /** Comments by the number in their permalink (`#comment-1446`), such as from a link. */
68
+ ids?: number[];
69
+ };
70
+ /** A comment by its UID, or by the number in its permalink (`#comment-1446`). */
71
+ export type CommentTarget = string | {
72
+ uid: string;
73
+ } | {
74
+ id: number;
75
+ };
76
+ export type ProtectionParams = {
77
+ ownerId: number;
78
+ siteId?: number | null;
79
+ /** The comment being edited. */
80
+ commentUid?: string | null;
81
+ };
82
+ export type StructuredDataParams = OwnerParams & {
83
+ limit?: number;
84
+ };
85
+ type WithoutOperation<T> = Omit<T, 'operationId'>;
86
+ export type CreateInput = Omit<WithoutOperation<CreateRequest>, 'siteId' | 'parentUid'> & {
87
+ siteId?: number | null;
88
+ parentUid?: string | null;
89
+ };
90
+ export type UpdateInput = WithoutOperation<UpdateRequest>;
91
+ export type DeleteInput = WithoutOperation<DeleteRequest>;
92
+ export type VoteInput = WithoutOperation<VoteRequest>;
93
+ export type ReportInput = WithoutOperation<ReportRequest>;
94
+ export type FollowInput = Omit<WithoutOperation<FollowRequest>, 'siteId'> & {
95
+ siteId?: number | null;
96
+ };
97
+ export type ModerateInput = WithoutOperation<ModerateRequest>;
98
+ export type UploadInput = {
99
+ file: Blob;
100
+ filename?: string;
101
+ /** An Assets field's handle, for a custom field upload. */
102
+ field?: string;
103
+ /** For a field upload on a new comment: its thread, and the comment it replies to. */
104
+ ownerId?: number;
105
+ ownerUri?: string;
106
+ siteId?: number | null;
107
+ parentUid?: string | null;
108
+ /** For a field upload on the asker's own comment. */
109
+ commentUid?: string;
110
+ /** A guest's evidence from a fresh preparation, which the upload uses up. */
111
+ protection?: ProtectionEvidenceData;
112
+ /** Editor's own upload parameters. */
113
+ params?: Record<string, string>;
114
+ };
115
+ export interface CommentsClient {
116
+ readonly endpoint: string;
117
+ readonly siteId: number | null;
118
+ readonly auth: SignInProvider;
119
+ readonly transport: CommentsTransport;
120
+ /** Public: the conversation and a page of approved root comments. */
121
+ thread(params: ThreadParams, options?: RequestOptions): Promise<ThreadResponse>;
122
+ /** Public: a page of approved replies. */
123
+ replies(params: RepliesParams, options?: RequestOptions): Promise<RepliesResponse>;
124
+ /** Public: one approved comment and its ancestors, for deep links. */
125
+ comment(target: CommentTarget, options?: RequestOptions): Promise<CommentResponse>;
126
+ /** Private: everything personal for a window of the thread. */
127
+ viewer(params: ViewerParams, options?: RequestOptions): Promise<ViewerResponse>;
128
+ /** Private: who's signed in, and the CSRF token. */
129
+ session(options?: RequestOptions): Promise<SessionResponse>;
130
+ /** A fresh Protect preparation. */
131
+ protection(params: ProtectionParams, options?: RequestOptions): Promise<ProtectionResponse>;
132
+ /** Public: the JSON-LD object, for server-side rendering. */
133
+ structuredData(params: StructuredDataParams, options?: RequestOptions): Promise<StructuredDataResponse>;
134
+ /** Private: a comment's editable content and field values, for its author. */
135
+ edit(uid: string, options?: RequestOptions): Promise<EditResponse>;
136
+ create(input: CreateInput, options?: WriteOptions): Promise<CreateResponse>;
137
+ update(input: UpdateInput, options?: WriteOptions): Promise<UpdateResponse>;
138
+ /** The asker's own comment. A moderator's removal is `moderate()` with `remove`. */
139
+ delete(input: DeleteInput, options?: WriteOptions): Promise<DeleteResponse>;
140
+ vote(input: VoteInput, options?: WriteOptions): Promise<VoteResponse>;
141
+ report(input: ReportInput, options?: WriteOptions): Promise<ReportResponse>;
142
+ follow(input: FollowInput, options?: WriteOptions): Promise<FollowResponse>;
143
+ moderate(input: ModerateInput, options?: WriteOptions): Promise<ModerateResponse>;
144
+ /** Editor's mention search (`context`, `query` and `scope`), answered in Editor's format. */
145
+ mentions<T = unknown>(params: Record<string, QueryValue | Record<string, unknown>>, options?: RequestOptions): Promise<T>;
146
+ /** An upload for Editor's attachments or an Assets field, answered in Editor's format. */
147
+ upload<T = unknown>(input: UploadInput, options?: RequestOptions): Promise<T>;
148
+ }
149
+ /**
150
+ * The data API client. Public reads go without credentials or sign-in headers, so any cache can
151
+ * hold them; everything else goes through the sign-in provider. Every write gets an
152
+ * `operationId`, and one that loses its connection is sent once more with the same ID, which the
153
+ * server answers from its replay store rather than acting twice.
154
+ */
155
+ export declare function createCommentsClient(options: CommentsClientOptions): CommentsClient;
156
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,218 @@
1
+ import { CommentsRequestError, GENERIC_MESSAGE, normalizeErrorData } from './errors.js';
2
+ import { createOperationId } from './operation.js';
3
+ import { abortable, requestSignal } from './signal.js';
4
+ import { COMMENTS_PROFILE_HEADER, cookieSession } from './sign-in.js';
5
+ import { restTransport } from './transport.js';
6
+ import { COMMENTS_API_VERSION, COMMENTS_API_VERSION_HEADER, assertApiVersion } from './version.js';
7
+ /**
8
+ * The data API client. Public reads go without credentials or sign-in headers, so any cache can
9
+ * hold them; everything else goes through the sign-in provider. Every write gets an
10
+ * `operationId`, and one that loses its connection is sent once more with the same ID, which the
11
+ * server answers from its replay store rather than acting twice.
12
+ */
13
+ export function createCommentsClient(options) {
14
+ const auth = options.auth ?? defaultSignIn(options.profile);
15
+ const rest = restTransport({ endpoint: options.endpoint, fetch: options.fetch });
16
+ const transport = options.transport ?? rest;
17
+ if (typeof transport.send !== 'function') {
18
+ throw new Error('Comments: `transport` takes a transport, such as graphqlTransport() from @verbb/comments-core/graphql.');
19
+ }
20
+ const siteId = options.siteId ?? null;
21
+ const timeoutMs = options.timeoutMs ?? 30000;
22
+ const client = {
23
+ endpoint: options.endpoint,
24
+ siteId,
25
+ auth,
26
+ transport,
27
+ thread: (params, request) => send({ kind: 'public', action: 'thread', query: { ...threadQuery(params), v: params.threadVersion } }, request),
28
+ replies: (params, request) => send({ kind: 'public', action: 'replies', query: { parentUid: params.parentUid, cursor: params.cursor, limit: params.limit } }, request),
29
+ comment: (target, request) => send({ kind: 'public', action: 'comment', query: typeof target === 'string' ? { uid: target } : target }, request),
30
+ viewer: (params, request) => send({ kind: 'private', action: 'viewer', query: { ...threadQuery(params), uids: params.uids?.length ? params.uids : undefined, ids: params.ids?.length ? params.ids : undefined } }, request),
31
+ session: (request) => send({ kind: 'private', action: 'session' }, request),
32
+ protection: (params, request) => send({
33
+ kind: 'private',
34
+ action: 'protection',
35
+ query: { ownerId: params.ownerId, siteId: params.siteId ?? siteId, commentUid: params.commentUid, channel: transport.protectionChannel },
36
+ }, request),
37
+ structuredData: (params, request) => send({
38
+ kind: 'public',
39
+ action: 'structured-data',
40
+ query: { ownerId: params.ownerId, ownerUri: params.ownerUri, siteId: params.siteId ?? siteId, limit: params.limit },
41
+ }, request),
42
+ edit: (uid, request) => send({ kind: 'private', action: 'edit', query: { uid } }, request),
43
+ create: (input, request) => write('create', { ...input, siteId: input.siteId ?? siteId, parentUid: input.parentUid ?? null }, request),
44
+ update: (input, request) => write('update', input, request),
45
+ delete: (input, request) => write('delete', input, request),
46
+ vote: (input, request) => write('vote', input, request),
47
+ report: (input, request) => write('report', input, request),
48
+ follow: (input, request) => write('follow', { ...input, siteId: input.siteId ?? siteId }, request),
49
+ moderate: (input, request) => write('moderate', input, request),
50
+ // Editor's `scope` is an object, which the endpoint takes as a JSON string.
51
+ mentions: (params, request) => send({
52
+ kind: 'private',
53
+ action: 'mentions',
54
+ query: Object.fromEntries(Object.entries(params).map(([name, value]) => [name, isPlainObject(value) ? JSON.stringify(value) : value])),
55
+ editorFormat: true,
56
+ }, request),
57
+ upload: (input, request) => {
58
+ const body = new FormData();
59
+ const { file, filename, params, protection, ...fields } = input;
60
+ for (const [name, value] of Object.entries({ ...params, ...fields, protection: protection && JSON.stringify(protection) })) {
61
+ if (value !== undefined && value !== null)
62
+ body.append(name, String(value));
63
+ }
64
+ body.append('file', file, filename ?? (file.name || 'upload'));
65
+ return send({ kind: 'write', action: 'upload', body, editorFormat: true }, request);
66
+ },
67
+ };
68
+ function threadQuery(params) {
69
+ return {
70
+ ownerId: params.ownerId,
71
+ ownerUri: params.ownerUri,
72
+ siteId: params.siteId ?? siteId,
73
+ sort: params.sort,
74
+ limit: params.limit,
75
+ cursor: params.cursor,
76
+ };
77
+ }
78
+ function write(action, input, request = {}) {
79
+ const operationId = request.operationId ?? createOperationId();
80
+ return send({ kind: 'write', action, body: { operationId, ...input }, operationId }, request);
81
+ }
82
+ async function send(call, request = {}) {
83
+ let resent = false;
84
+ let recovered = false;
85
+ for (;;) {
86
+ try {
87
+ return await attempt(call, request);
88
+ }
89
+ catch (error) {
90
+ if (!(error instanceof CommentsRequestError)) {
91
+ throw error;
92
+ }
93
+ // Only a write with an `operationId` is safe to send again: the server answers a
94
+ // repeat from its replay store. A request the caller cancelled never gets here.
95
+ if (call.operationId && error.code === 'network_error' && !resent) {
96
+ resent = true;
97
+ continue;
98
+ }
99
+ if (call.kind !== 'public' && error.category === 'auth' && !recovered && auth.recover && await auth.recover(error, signInContext(call, request.signal))) {
100
+ recovered = true;
101
+ continue;
102
+ }
103
+ throw error;
104
+ }
105
+ }
106
+ }
107
+ async function attempt(call, request) {
108
+ const identified = call.kind !== 'public';
109
+ const headers = {
110
+ Accept: 'application/json',
111
+ ...(identified ? options.headers?.private : options.headers?.public),
112
+ [COMMENTS_API_VERSION_HEADER]: String(COMMENTS_API_VERSION),
113
+ };
114
+ const timer = requestSignal(request.signal, timeoutMs);
115
+ let response;
116
+ try {
117
+ // Inside the timeout, since a provider may make a request of its own first.
118
+ if (identified) {
119
+ Object.assign(headers, await abortable(auth.headers(signInContext(call, timer.signal)), timer.signal), { [COMMENTS_PROFILE_HEADER]: auth.profile });
120
+ }
121
+ const outgoing = {
122
+ kind: call.kind === 'write' ? 'write' : 'read',
123
+ action: call.action,
124
+ query: call.query,
125
+ body: call.body,
126
+ headers,
127
+ credentials: identified ? auth.credentials : 'omit',
128
+ redirect: identified ? 'manual' : 'follow',
129
+ cache: request.cache,
130
+ signal: timer.signal,
131
+ };
132
+ response = await (transport.handles?.(outgoing) === false ? rest : transport).send(outgoing);
133
+ }
134
+ catch (error) {
135
+ // The caller's own cancellation isn't a failure to report or retry.
136
+ if (request.signal?.aborted) {
137
+ throw error;
138
+ }
139
+ if (error instanceof CommentsRequestError) {
140
+ throw error.withOperation(call.operationId);
141
+ }
142
+ if (timer.timedOut() || isConnectionFailure(error)) {
143
+ const message = timer.timedOut() ? 'The request took too long. Please try again.' : 'Couldn’t reach the server. Check your connection and try again.';
144
+ throw CommentsRequestError.from('network_error', message, { operationId: call.operationId ?? null, recoverable: true, cause: error });
145
+ }
146
+ // A mistake in code, such as a custom transport's, isn't worth sending again.
147
+ throw CommentsRequestError.from('invalid_request', GENERIC_MESSAGE, {
148
+ operationId: call.operationId ?? null,
149
+ cause: error,
150
+ detail: `not sent: ${String(error)}`,
151
+ });
152
+ }
153
+ finally {
154
+ timer.cleanup();
155
+ }
156
+ const payload = response.payload;
157
+ const version = response.headers.get(COMMENTS_API_VERSION_HEADER);
158
+ // An error answer is read before the version check, so the server's own
159
+ // `unsupported_api_version` reaches the caller as itself.
160
+ if (payload && payload.status === 'error' && Array.isArray(payload.errors)) {
161
+ assertApiVersion(payload, version, false);
162
+ const errors = payload.errors.map(normalizeErrorData);
163
+ const retryAfter = retryAfterHeader(response.headers.get('Retry-After'));
164
+ if (errors[0] && errors[0].retryAfter === null && retryAfter !== null) {
165
+ errors[0] = { ...errors[0], retryAfter };
166
+ }
167
+ throw new CommentsRequestError(errors, { status: response.status, operationId: call.operationId ?? null, detail: response.detail ?? null });
168
+ }
169
+ try {
170
+ assertApiVersion(payload, version, !call.editorFormat);
171
+ }
172
+ catch (error) {
173
+ throw error.withOperation(call.operationId);
174
+ }
175
+ if (response.status >= 400) {
176
+ throw CommentsRequestError.from(response.status >= 500 ? 'server_error' : 'invalid_response', GENERIC_MESSAGE, {
177
+ status: response.status,
178
+ operationId: call.operationId ?? null,
179
+ recoverable: response.status >= 500,
180
+ detail: `HTTP ${response.status}`,
181
+ });
182
+ }
183
+ if (identified) {
184
+ auth.observe?.(payload, response.headers);
185
+ }
186
+ return payload;
187
+ }
188
+ function signInContext(call, signal) {
189
+ // The `session` read gets its own timeout rather than this request's signal, so several
190
+ // writes can share it.
191
+ return { write: call.kind === 'write', endpoint: options.endpoint, session: () => client.session(), signal };
192
+ }
193
+ return client;
194
+ }
195
+ function defaultSignIn(profile) {
196
+ if (profile === 'cross-origin-member' || profile === 'cross-origin-public') {
197
+ throw new Error(`Comments: the ${profile} profile needs a sign-in provider passed as \`auth\`.`);
198
+ }
199
+ return cookieSession({ profile });
200
+ }
201
+ function isPlainObject(value) {
202
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
203
+ }
204
+ /** Whether fetch failed to reach the server, rather than code going wrong around it. */
205
+ function isConnectionFailure(error) {
206
+ const name = error?.name;
207
+ return error instanceof TypeError || name === 'AbortError' || name === 'TimeoutError' || name === 'NetworkError';
208
+ }
209
+ /** `Retry-After` in seconds, from a number of seconds or an HTTP date. */
210
+ function retryAfterHeader(value) {
211
+ if (!value)
212
+ return null;
213
+ const seconds = Number(value);
214
+ if (Number.isFinite(seconds))
215
+ return Math.max(0, Math.ceil(seconds));
216
+ const date = Date.parse(value);
217
+ return Number.isNaN(date) ? null : Math.max(0, Math.ceil((date - Date.now()) / 1000));
218
+ }