pups-client 0.4.0 → 0.6.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.
package/src/handles.ts ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Handles in text (bigwide.net RFC-11 "Handles"): `@` followed by a host name with at least two labels, e.g.
3
+ * `@tim.example.com`. Not e-mail addresses (`tim@tim.example.com`), fediverse addresses (`@tim@social.example`),
4
+ * names without a dot (`@foobar`) or paths (`@x.example/path`). A `/` directly between handles separates them:
5
+ * `@a.example/@b.example` names both.
6
+ */
7
+
8
+ const LABEL = '[\\p{L}\\p{N}](?:[\\p{L}\\p{M}\\p{N}-]*[\\p{L}\\p{M}\\p{N}])?'
9
+ const HOST = `(?:${LABEL}\\.)+\\p{L}(?:[\\p{L}\\p{M}\\p{N}-]*[\\p{L}\\p{M}\\p{N}])?`
10
+ /** A handle, or several separated by `/`, with RFC-11's rules for the characters before and after. */
11
+ const HANDLES_RE = new RegExp(
12
+ `(?:^|(?<=[\\s\\p{P}\\p{S}]))(?<![._\\-+/@])@${HOST}(?:/@${HOST})*(?![\\p{L}\\p{M}\\p{N}_\\-/@]|\\.[\\p{L}\\p{N}])`, 'gu')
13
+
14
+ /** Elements whose content is never shown. */
15
+ const HIDDEN_TAGS = new Set(['script', 'style', 'template', 'noscript', 'iframe', 'object', 'embed', 'svg', 'math', 'head', 'title', 'select', 'textarea', 'button'])
16
+ /** Elements whose content doesn't count for handles. */
17
+ const CODE_TAGS = new Set(['code', 'pre'])
18
+ const BLOCK_TAGS = new Set(['address', 'article', 'aside', 'blockquote', 'br', 'dd', 'div', 'dl', 'dt', 'figcaption', 'figure', 'footer',
19
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'li', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'td', 'th', 'tr', 'ul'])
20
+ const VOID_TAGS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr'])
21
+ const ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: '\'', nbsp: ' ', commat: '@', sol: '/', period: '.' }
22
+
23
+ /** A host name as handles are compared: lowercase ASCII (IDNA). Undefined if it isn't a valid host. */
24
+ export function asciiHost(host: string): string | undefined {
25
+ try {
26
+ const url = new URL(`https://${host}/`)
27
+ return url.hostname && url.pathname == '/' && !url.port ? url.hostname.toLowerCase() : undefined
28
+ } catch {
29
+ return undefined
30
+ }
31
+ }
32
+
33
+ /** The host of an account like `@alice.example.com`, in comparable form, or undefined. */
34
+ export function accountHost(account: unknown): string | undefined {
35
+ const match = typeof account == 'string' ? /^@([^@\s/]+)$/u.exec(account.trim()) : null
36
+ return match ? asciiHost(match[1]!) : undefined
37
+ }
38
+
39
+ /** The hosts of all handles in a plain text, in comparable form and in order, each once. */
40
+ export function findHandles(text: string): string[] {
41
+ const hosts = [...text.matchAll(HANDLES_RE)].flatMap(m => m[0].split('/').map(h => asciiHost(h.slice(1))))
42
+ return [...new Set(hosts.filter((h): h is string => !!h))]
43
+ }
44
+
45
+ const decode = (text: string) => text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, name: string) => {
46
+ if (name[0] != '#') return ENTITIES[name.toLowerCase()] ?? entity
47
+ const code = name[1] == 'x' || name[1] == 'X' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10)
48
+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : entity
49
+ })
50
+
51
+ /**
52
+ * The visible text of an HTML fragment, with whitespace collapsed: without attribute values, comments and the
53
+ * content of elements that are never shown. With `skipCode`, the content of `code` and `pre` is left out as well.
54
+ * A small tokenizer, so that it works without a DOM; good enough for finding handles, not a sanitizer.
55
+ */
56
+ export function visibleText(html: string, skipCode = false): string {
57
+ let out = ''
58
+ const hidden: string[] = []
59
+ const tokens = /<!--[\s\S]*?(?:-->|$)|<!\[CDATA\[[\s\S]*?(?:\]\]>|$)|<[!?][^>]*>?|<\/?([a-zA-Z][a-zA-Z0-9-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>|[^<]+|</g
60
+ for (const [token, rawTag, attributes] of html.matchAll(tokens)) {
61
+ if (!rawTag) {
62
+ if (token[0] != '<' || token == '<') {
63
+ if (!hidden.length) out += decode(token)
64
+ }
65
+ continue
66
+ }
67
+ const tag = rawTag.toLowerCase()
68
+ const closing = token[1] == '/'
69
+ if (BLOCK_TAGS.has(tag)) out += ' '
70
+ const hides = HIDDEN_TAGS.has(tag) || (skipCode && CODE_TAGS.has(tag))
71
+ if (!hides) continue
72
+ if (closing) {
73
+ const at = hidden.lastIndexOf(tag)
74
+ if (at >= 0) hidden.length = at
75
+ out += ' '
76
+ } else if (!VOID_TAGS.has(tag) && !attributes?.trimEnd().endsWith('/')) hidden.push(tag)
77
+ }
78
+ return out.replace(/\s+/g, ' ').trim()
79
+ }
80
+
81
+ /** The parts of a JSON Feed item in which RFC-11 finds handles. */
82
+ export interface HandleSource {
83
+ title?: unknown
84
+ content_html?: unknown
85
+ content_text?: unknown
86
+ /** The Markdown of a `PostInput`, which becomes `content_text` if there is no other content. */
87
+ markdown?: unknown
88
+ }
89
+
90
+ /**
91
+ * The text of an item in which handles are found: the title, and the visible text of its HTML without code, or its
92
+ * plain text (for a `PostInput`, its Markdown).
93
+ */
94
+ export function handleText(item: HandleSource): string {
95
+ const text = typeof item.content_text == 'string' ? item.content_text : typeof item.markdown == 'string' ? item.markdown : undefined
96
+ const body = typeof item.content_html == 'string' ? visibleText(item.content_html, true) : text?.replace(/\s+/g, ' ').trim() ?? ''
97
+ return `${typeof item.title == 'string' ? item.title : ''} ${body}`.trim()
98
+ }
99
+
100
+ /** The hosts of the handles in an item (RFC-11 "Finding handles in text"). */
101
+ export const itemHandles = (item: HandleSource) => findHandles(handleText(item))
package/src/index.ts CHANGED
@@ -16,8 +16,11 @@ export type {
16
16
  } from './client.js'
17
17
  export { PupsSession } from './session.js'
18
18
  export type { Body, JsonBody, SessionChangeEvent, StoredFile, WriteOptions, WriteResult } from './session.js'
19
- export { FEED_REL, POST_URL_TEMPLATE, PUPS_FEED_SPEC, PupsFeed, feedScopes, itemIndex } from './feed.js'
19
+ export { ARCHIVE_SPEC, FEED_REL, POST_URL_TEMPLATE, PUPS_FEED_SPEC, PupsFeed, feedScopes, itemIndex } from './feed.js'
20
20
  export type {
21
+ ArchiveFields,
22
+ CommentPolicy,
23
+ CommentsState,
21
24
  FeedAttachment,
22
25
  FeedAuthor,
23
26
  FeedDocument,
@@ -28,7 +31,9 @@ export type {
28
31
  FeedSettingsChanges,
29
32
  FeedSetup,
30
33
  FeedState,
34
+ ItemArchive,
31
35
  ItemMarker,
36
+ MentionChoice,
32
37
  MediaInput,
33
38
  MediaResult,
34
39
  PostChanges,
@@ -37,6 +42,10 @@ export type {
37
42
  PupsMarker,
38
43
  } from './feed.js'
39
44
  export { HostMetaEditor } from './host-meta.js'
45
+ export { MENTION_REL, Mentions } from './mentions.js'
46
+ export type { Delivery, DeliveryStatus, FoundItem, MentionReport, MentionSource, MentionsOptions, PlannedMention, PostChange, PostMentions, Submission, SubmissionStatus } from './mentions.js'
47
+ export { accountHost, findHandles, handleText, itemHandles, visibleText } from './handles.js'
48
+ export type { HandleSource } from './handles.js'
40
49
  export type { HostMetaDocument, HostMetaLink } from './host-meta.js'
41
50
  export { PupsError, isPupsError } from './errors.js'
42
51
  export type { PupsErrorCode } from './errors.js'
@@ -0,0 +1,447 @@
1
+ import type { FeedItem } from './feed.js'
2
+ import { accountHost, asciiHost, itemHandles, type HandleSource } from './handles.js'
3
+ import { isPupsError, PupsError } from './errors.js'
4
+ import { fetchWithTimeout, isObject, sleep } from './util.js'
5
+
6
+ /** The link relation of the mention endpoint in `host-meta.json` (RFC-11 "Discovery"). A placeholder in RFC-11. */
7
+ export const MENTION_REL = 'https://bigwide.net/ns/mention'
8
+
9
+ /** RFC-11: senders should notify at most this many accounts per post. */
10
+ const MAX_ACCOUNTS = 20
11
+ /** RFC-4 "Archived items": servers follow at least 10 pages; so does the sender looking for an item. */
12
+ const MAX_PAGES = 10
13
+ const DAY_MS = 24 * 3600_000
14
+ const HOUR_MS = 3600_000
15
+ const MAX_FEED_BYTES = 2_000_000
16
+
17
+ export interface MentionsOptions {
18
+ fetch?: typeof fetch
19
+ /**
20
+ * The waits before the retries of a webmention after a network error, a `5xx` or a `429` (RFC-11 "When").
21
+ * A longer `Retry-After` is respected, up to 10 minutes. Default: 10 seconds, 1 minute, 5 minutes.
22
+ */
23
+ retryDelays?: number[]
24
+ /**
25
+ * The waits between the checks whether a new or changed post is visible at its public URL, before the mentions
26
+ * are sent (RFC-11 "When"). Default: 1, 2, 4, 8 and 15 seconds, so about half a minute.
27
+ */
28
+ visibilityDelays?: number[]
29
+ /** Timeout of each request, in milliseconds. Default 15 seconds. */
30
+ timeoutMs?: number
31
+ /** The publisher's identity, e.g. `https://tim.example.com/`: never notified. `session.mentions` sets it. */
32
+ me?: string
33
+ }
34
+
35
+ /**
36
+ * The result of sending a webmention:
37
+ * - `accepted`: the endpoint answered `2xx`.
38
+ * - `unknown`: sent, but the endpoint doesn't allow a browser to read its answer (no CORS headers).
39
+ * - `rejected`: the endpoint answered `4xx` (other than `429`); not retried.
40
+ * - `failed`: a network error, `5xx` or `429`, also after the retries.
41
+ */
42
+ export type DeliveryStatus = 'accepted' | 'unknown' | 'rejected' | 'failed'
43
+
44
+ export interface Delivery {
45
+ status: DeliveryStatus
46
+ /** The HTTP status, if there was a readable answer. */
47
+ httpStatus?: number
48
+ /** The `message` of a JSON error body, or what went wrong. */
49
+ message?: string
50
+ /** The `error` of a JSON error body, e.g. an RFC-4 failure code such as `comments-disabled`. */
51
+ code?: string
52
+ /** The `Location` header of the answer, e.g. an RFC-4 status page. */
53
+ location?: string
54
+ }
55
+
56
+ /** An account a post would notify, from `plan()`: e.g. to ask the author before anything is sent. */
57
+ export interface PlannedMention {
58
+ /** The account, e.g. `@tim.example.com`. */
59
+ account: string
60
+ /** `reply` if the post answers an item of the account, `mention` if it names it. */
61
+ kind: 'mention' | 'reply'
62
+ /** The webmention's target: the domain's root URL, or the answered item. */
63
+ target: string
64
+ /** The mention endpoint; set by `plan()` with `discover`, and on reports of accounts that have one. */
65
+ endpoint?: string
66
+ }
67
+
68
+ /** One account notified by `notifyAll()` or `sendPlanned()`, or skipped because its domain doesn't accept mentions. */
69
+ export interface MentionReport extends PlannedMention {
70
+ /** `no-endpoint` if the domain doesn't accept mentions (no link in `host-meta.json`, or it can't be read). */
71
+ status: DeliveryStatus | 'no-endpoint'
72
+ httpStatus?: number
73
+ message?: string
74
+ }
75
+
76
+ /** The answer to an RFC-4 submission. */
77
+ export interface Submission extends Delivery {
78
+ /** The endpoint from the target feed's `_submissions.url`. */
79
+ endpoint: string
80
+ /** The status page (RFC-4 "Response and status"), from `Location`; poll it with `submissionStatus()`. */
81
+ statusUrl?: string
82
+ /** The guid the item will have when it is republished. */
83
+ guid?: string
84
+ }
85
+
86
+ /** An RFC-4 status page. */
87
+ export type SubmissionStatus =
88
+ | { status: 'waiting' }
89
+ | { status: 'success'; pubDate?: string; pubUrl?: string }
90
+ | { status: 'deleted' }
91
+ | { status: 'failure'; code?: string; text?: string }
92
+
93
+ /** An item found in a feed, with what decides about mentions and submissions. */
94
+ export interface FoundItem {
95
+ /** The URL of the feed or archive that was fetched first. */
96
+ feedUrl: string
97
+ /** The RFC-4 `_submissions` that apply: the feed's, or for an RFC-7 archive, those of its feed file. */
98
+ submissions?: Record<string, unknown>
99
+ /** The item, if it was found. */
100
+ item?: FeedItem
101
+ /** The host of the item's author (RFC-11 "Replies"): its own socialspec account, else the feed's if the feed has no `_submissions`. */
102
+ author?: string
103
+ }
104
+
105
+ interface Feed {
106
+ url: string
107
+ doc: Record<string, unknown>
108
+ }
109
+
110
+ /** What decides about the mentions of a post: its title, content and `_source.inReplyTo`. A `FeedItem` or a `PostInput`. */
111
+ export type MentionSource = HandleSource & { _source?: unknown }
112
+
113
+ /** The input of `plan()`: a post to be added (`item`), changed (`item` and `previous`) or deleted (`previous`). */
114
+ export interface PostChange {
115
+ /** The post as it will be published; undefined for a delete. */
116
+ item?: MentionSource
117
+ /** The post before an edit or delete. */
118
+ previous?: MentionSource
119
+ /** The publisher's identity; never notified. Default: the `me` of the options. */
120
+ me?: string
121
+ }
122
+
123
+ /** The input of `notifyAll()`: a post that was added, changed or deleted, and its `source`. */
124
+ export interface PostMentions extends PostChange {
125
+ /** The post's `source`: its feed or archive URL plus `#<id>`. */
126
+ source: string
127
+ }
128
+
129
+ const protocolOf = (url: unknown) => {
130
+ try {
131
+ return typeof url == 'string' ? new URL(url).protocol : undefined
132
+ } catch {
133
+ return undefined
134
+ }
135
+ }
136
+ const isHttps = (url: unknown): url is string => protocolOf(url) == 'https:'
137
+ const isHttpUrl = (url: unknown): url is string => isHttps(url) || protocolOf(url) == 'http:'
138
+
139
+ const inReplyTo = (item?: MentionSource) => isObject(item?._source) && typeof item._source.inReplyTo == 'string' ? item._source.inReplyTo : undefined
140
+ const socialspec = (o: unknown) => isObject(o) && isObject(o._source) && isObject(o._source.accounts) ? o._source.accounts.socialspec : undefined
141
+ const retryable = (status: number) => status == 429 || status >= 500
142
+
143
+ /** Splits `https://x.example/feed.json#p-1` into the feed URL and the decoded id. */
144
+ function splitRef(ref: string): [string, string | undefined] {
145
+ const at = ref.indexOf('#')
146
+ if (at < 0) return [ref, undefined]
147
+ let id = ref.slice(at + 1)
148
+ try {
149
+ id = decodeURIComponent(id)
150
+ } catch { /* keep it as it is */ }
151
+ return [ref.slice(0, at), id]
152
+ }
153
+
154
+ /** A field of a feed's RFC-13 `_archive`, or of `_pups` in feeds of earlier drafts (RFC-13 "Earlier drafts"). */
155
+ const archiveField = (doc: Record<string, unknown>, key: string): unknown =>
156
+ (isObject(doc._archive) ? doc._archive[key] : undefined) ?? (isObject(doc._pups) ? doc._pups[key] : undefined)
157
+
158
+ /**
159
+ * Sends webmentions: RFC-11 mentions to the domains a post names or answers, found through their `host-meta.json`,
160
+ * and RFC-4 submissions to the endpoint a target feed names in `_submissions`. Plain Webmention, form-encoded.
161
+ *
162
+ * Use `session.mentions`, which shares the discovery cache of the session, or create one for use without a session.
163
+ * In a browser, it can only read feeds and `host-meta.json` files that allow CORS, as RFC-4 and RFC-6 require;
164
+ * domains whose `host-meta.json` doesn't count as having no endpoint (RFC-11 "CORS").
165
+ */
166
+ export class Mentions {
167
+ readonly #fetch: typeof fetch
168
+ readonly #retryDelays: number[]
169
+ readonly #visibilityDelays: number[]
170
+ readonly #timeoutMs: number
171
+ readonly #endpoints = new Map<string, { endpoint?: string; until: number }>()
172
+ readonly #me?: string
173
+
174
+ constructor(options: MentionsOptions = {}) {
175
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init))
176
+ this.#retryDelays = options.retryDelays ?? [10_000, 60_000, 300_000]
177
+ this.#visibilityDelays = options.visibilityDelays ?? [1000, 2000, 4000, 8000, 15_000]
178
+ this.#timeoutMs = options.timeoutMs ?? 15_000
179
+ this.#me = options.me
180
+ }
181
+
182
+ /**
183
+ * The mention endpoint of a domain (RFC-11 "Discovery"): the first link with the relation `MENTION_REL` in its
184
+ * `host-meta.json`, if it is an https URL. Undefined if the domain has none, or its `host-meta.json` can't be
185
+ * read. Cached for 24 hours (less if the file's `max-age` says so), failures for an hour.
186
+ * @param domain `tim.example.com`, `@tim.example.com` or `https://tim.example.com/`.
187
+ */
188
+ async discover(domain: string, options: { signal?: AbortSignal } = {}): Promise<string | undefined> {
189
+ const host = asciiHost(domain.replace(/^@/, '').replace(/^https:\/\//i, '').replace(/\/$/, ''))
190
+ if (!host) return undefined
191
+ const cached = this.#endpoints.get(host)
192
+ if (cached && cached.until > Date.now()) return cached.endpoint
193
+ const url = `https://${host}/.well-known/host-meta.json`
194
+ let endpoint: string | undefined
195
+ let maxAge = DAY_MS
196
+ try {
197
+ const response = await fetchWithTimeout(this.#fetch, url, { credentials: 'omit', headers: { Accept: 'application/json' } }, this.#timeoutMs, options.signal)
198
+ // Only host-meta.json on the domain itself counts (RFC-11 "Discovery").
199
+ if (response.ok && (!response.url || new URL(response.url).host == host)) {
200
+ const doc: unknown = await response.json()
201
+ const link = isObject(doc) && Array.isArray(doc.links) ? doc.links.find(l => isObject(l) && l.rel == MENTION_REL) : undefined
202
+ endpoint = isHttps(link?.href) ? link.href : undefined
203
+ const age = /max-age=(\d+)/.exec(response.headers.get('Cache-Control') ?? '')
204
+ if (age) maxAge = Math.min(maxAge, Number(age[1]) * 1000)
205
+ }
206
+ } catch (e) {
207
+ if (isPupsError(e, 'aborted')) throw e
208
+ }
209
+ this.#endpoints.set(host, { endpoint, until: Date.now() + (endpoint ? maxAge : Math.max(maxAge, HOUR_MS)) })
210
+ return endpoint
211
+ }
212
+
213
+ /**
214
+ * Sends a webmention: a form-encoded `POST` with `source` and `target`. Retries after network errors, `5xx` and
215
+ * `429` with the `retryDelays` (unless `retry` is false), never after other answers. Never throws, except
216
+ * `aborted`.
217
+ */
218
+ async send(endpoint: string, source: string, target: string, options: { signal?: AbortSignal; retry?: boolean } = {}): Promise<Delivery> {
219
+ return (await this.#sendWithBody(endpoint, source, target, options)).delivery
220
+ }
221
+
222
+ async #sendWithBody(endpoint: string, source: string, target: string, options: { signal?: AbortSignal; retry?: boolean }) {
223
+ const delays = options.retry === false ? [] : this.#retryDelays
224
+ for (let attempt = 0; ; attempt++) {
225
+ const answer = await this.#post(endpoint, source, target, options.signal)
226
+ if (answer.delivery.status != 'failed' || attempt >= delays.length) return answer
227
+ await sleep(Math.max(delays[attempt]!, Math.min(answer.retryAfterMs, 600_000)), options.signal)
228
+ }
229
+ }
230
+
231
+ async #post(endpoint: string, source: string, target: string, signal?: AbortSignal): Promise<{ delivery: Delivery; json?: unknown; retryAfterMs: number }> {
232
+ const body = () => new URLSearchParams({ source, target })
233
+ let response: Response
234
+ try {
235
+ response = await fetchWithTimeout(this.#fetch, endpoint, { method: 'POST', body: body(), credentials: 'omit' }, this.#timeoutMs, signal)
236
+ } catch (e) {
237
+ if (isPupsError(e, 'aborted')) throw e
238
+ // A browser hides the answer of an endpoint without CORS headers, but a form-encoded POST is a simple request
239
+ // and reaches it anyway: send it without reading the answer.
240
+ try {
241
+ await fetchWithTimeout(this.#fetch, endpoint, { method: 'POST', body: body(), credentials: 'omit', mode: 'no-cors' }, this.#timeoutMs, signal)
242
+ return { delivery: { status: 'unknown', message: 'Sent, but the endpoint doesn\'t let a browser read its answer.' }, retryAfterMs: 0 }
243
+ } catch (again) {
244
+ if (isPupsError(again, 'aborted')) throw again
245
+ return { delivery: { status: 'failed', message: e instanceof Error ? e.message : String(e) }, retryAfterMs: 0 }
246
+ }
247
+ }
248
+ const location = response.headers.get('Location')
249
+ const json: unknown = await response.json().catch(() => undefined)
250
+ const delivery: Delivery = {
251
+ status: response.ok ? 'accepted' : retryable(response.status) ? 'failed' : 'rejected',
252
+ httpStatus: response.status,
253
+ ...location ? { location: new URL(location, endpoint).href } : {},
254
+ ...!response.ok && isObject(json) && typeof json.message == 'string' ? { message: json.message } : {},
255
+ ...!response.ok && isObject(json) && typeof json.error == 'string' ? { code: json.error } : {},
256
+ }
257
+ return { delivery, json, retryAfterMs: (Number(response.headers.get('Retry-After')) || 0) * 1000 }
258
+ }
259
+
260
+ /**
261
+ * Tells a domain that `source` names it (RFC-11 "Mentions by name"), or answers its item `target`. Discovers
262
+ * the endpoint and sends the webmention.
263
+ * @param account `@tim.example.com` (or the bare host).
264
+ * @param target Default: the domain's root URL, `https://tim.example.com/`.
265
+ */
266
+ async notify(source: string, account: string, options: { target?: string; signal?: AbortSignal; retry?: boolean } = {}): Promise<MentionReport> {
267
+ const host = asciiHost(account.replace(/^@/, '')) ?? account.replace(/^@/, '')
268
+ const planned: PlannedMention = { account: `@${host}`, kind: options.target ? 'reply' : 'mention', target: options.target ?? `https://${host}/` }
269
+ return (await this.sendPlanned(source, [planned], options))[0]!
270
+ }
271
+
272
+ /**
273
+ * Tells the author of the item `target` (a feed URL plus `#<id>`) that `source` answers it (RFC-11 "Replies").
274
+ * @returns undefined if the item has no author to notify, can't be read, or its feed takes RFC-4 submissions:
275
+ * then the answer is a submission, and the RFC-4 server sends the mentions.
276
+ */
277
+ async reply(source: string, target: string, options: { signal?: AbortSignal; retry?: boolean } = {}): Promise<MentionReport | undefined> {
278
+ const found = await this.findItem(target, options).catch(e => {
279
+ if (isPupsError(e, 'aborted')) throw e
280
+ return undefined
281
+ })
282
+ return found?.author && !found.submissions ? this.notify(source, found.author, { ...options, target }) : undefined
283
+ }
284
+
285
+ /**
286
+ * Submits a comment or post to an RFC-4 feed (RFC-4 "Submitting"): `source` is the item in the author feed,
287
+ * `target` the answered item (feed URL plus `#<id>`), or the group feed for a new post. The endpoint is the
288
+ * target feed's `_submissions.url`, unless given. The app must have shown the target's terms of service and what
289
+ * `republish` means before the first submission (RFC-4 "Republishing").
290
+ * @throws {PupsError} `unsupported` if the target feed takes no submissions.
291
+ */
292
+ async submit(source: string, target: string, options: { endpoint?: string; signal?: AbortSignal } = {}): Promise<Submission> {
293
+ let endpoint = options.endpoint
294
+ if (!endpoint) {
295
+ const submissions = (await this.findItem(target, { ...options, item: false })).submissions
296
+ if (!isHttpUrl(submissions?.url))
297
+ throw new PupsError('unsupported', `${splitRef(target)[0]} takes no submissions: it has no _submissions with a url (RFC-4).`)
298
+ endpoint = submissions!.url as string
299
+ }
300
+ const { delivery, json } = await this.#sendWithBody(endpoint, source, target, { signal: options.signal, retry: false })
301
+ const statusUrl = delivery.location ?? (isObject(json) && typeof json.statusUrl == 'string' ? json.statusUrl : undefined)
302
+ const guid = isObject(json) && typeof json.guid == 'string' ? json.guid : undefined
303
+ return { ...delivery, endpoint, ...statusUrl ? { statusUrl } : {}, ...guid ? { guid } : {} }
304
+ }
305
+
306
+ /** Reads an RFC-4 status page. */
307
+ async submissionStatus(statusUrl: string, options: { signal?: AbortSignal } = {}): Promise<SubmissionStatus> {
308
+ const response = await fetchWithTimeout(this.#fetch, statusUrl, { credentials: 'omit', cache: 'no-store', headers: { Accept: 'application/json' } }, this.#timeoutMs, options.signal)
309
+ const json: unknown = await response.json().catch(() => undefined)
310
+ if (!isObject(json) || typeof json.status != 'string')
311
+ throw new PupsError('invalid_request', `${statusUrl} is not an RFC-4 status page (HTTP ${response.status}).`)
312
+ return json as SubmissionStatus
313
+ }
314
+
315
+ /**
316
+ * The accounts a post that is added, changed or deleted would notify (RFC-11 "Who is mentioned"), without sending
317
+ * anything, e.g. to list them in a confirmation dialog before posting: every domain its title and text name
318
+ * (RFC-11 "Handles"), and the author of the item it answers, with a reply. After an edit or delete, every account
319
+ * the old or the new version mentions. Each account once, replies first, never `me`, at most 20.
320
+ *
321
+ * Empty if the post answers an item of a feed with RFC-4 `_submissions`: such a post is a submission, and the
322
+ * RFC-4 server sends the mentions once it republishes it (RFC-11 "Who sends").
323
+ *
324
+ * Finding the author of an answered item reads its feed. With `discover`, it also looks up each domain's endpoint,
325
+ * and leaves out the domains that don't accept mentions; that tells them that a post names them, before the post
326
+ * is published (RFC-11 "Privacy considerations").
327
+ */
328
+ async plan(post: PostChange, options: { signal?: AbortSignal; discover?: boolean } = {}): Promise<PlannedMention[]> {
329
+ const me = post.me ?? this.#me
330
+ const own = me ? asciiHost(new URL(me).hostname) : undefined
331
+ const replies = new Map<string, string>()
332
+ for (const target of new Set([inReplyTo(post.item), inReplyTo(post.previous)].filter((t): t is string => !!t?.includes('#')))) {
333
+ const found = await this.findItem(target, options).catch(e => {
334
+ if (isPupsError(e, 'aborted')) throw e
335
+ return undefined
336
+ })
337
+ if (found?.submissions) return []
338
+ if (found?.author && found.author != own && !replies.has(found.author)) replies.set(found.author, target)
339
+ }
340
+ const names = [...new Set([...post.item ? itemHandles(post.item) : [], ...post.previous ? itemHandles(post.previous) : []])]
341
+ .filter(host => host != own && !replies.has(host))
342
+ const planned: PlannedMention[] = [
343
+ ...[...replies].map(([host, target]) => ({ account: `@${host}`, kind: 'reply' as const, target })),
344
+ ...names.map(host => ({ account: `@${host}`, kind: 'mention' as const, target: `https://${host}/` })),
345
+ ].slice(0, MAX_ACCOUNTS)
346
+ if (!options.discover) return planned
347
+ const endpoints = await Promise.all(planned.map(p => this.discover(p.account, options)))
348
+ return planned.flatMap((p, i) => endpoints[i] ? [{ ...p, endpoint: endpoints[i] }] : [])
349
+ }
350
+
351
+ /**
352
+ * Sends mentions as `plan()` returned them, e.g. those the author confirmed, with `source` as the post: the
353
+ * post's feed or archive URL plus `#<id>`, once it is published.
354
+ */
355
+ sendPlanned(source: string, planned: PlannedMention[], options: { signal?: AbortSignal; retry?: boolean } = {}): Promise<MentionReport[]> {
356
+ return Promise.all(planned.map(async p => {
357
+ const endpoint = p.endpoint ?? await this.discover(p.account, options)
358
+ if (!endpoint) return { ...p, status: 'no-endpoint' as const }
359
+ const { status, httpStatus, message } = await this.send(endpoint, source, p.target, options)
360
+ return { ...p, endpoint, status, ...httpStatus ? { httpStatus } : {}, ...message ? { message } : {} }
361
+ }))
362
+ }
363
+
364
+ /** `plan()` and `sendPlanned()` in one: sends the RFC-11 mentions of a post that was added, changed or deleted. */
365
+ async notifyAll(post: PostMentions, options: { signal?: AbortSignal } = {}): Promise<MentionReport[]> {
366
+ return this.sendPlanned(post.source, await this.plan(post, options), options)
367
+ }
368
+
369
+ /**
370
+ * Finds an item, given as feed URL plus `#<id>`, as RFC-4 does: in the feed, then along `next_url` (or RFC-13's
371
+ * `_archive.archive_url`) on the same host, at most 10 pages. JSON Feed only.
372
+ * @throws {PupsError} `network`, `not_found` or `invalid_feed` if the first feed can't be read.
373
+ */
374
+ async findItem(ref: string, options: { signal?: AbortSignal; item?: boolean } = {}): Promise<FoundItem> {
375
+ const [url, id] = splitRef(ref)
376
+ const first = await this.#readFeed(url, options.signal)
377
+ // An RFC-13 archive takes its _submissions from its feed file (RFC-7 "Receiving comments").
378
+ let owner = first
379
+ const updates = archiveField(first.doc, 'updates_url')
380
+ if (typeof updates == 'string') {
381
+ const feedUrl = new URL(updates, first.url)
382
+ owner = feedUrl.host == new URL(first.url).host ? await this.#readFeed(feedUrl.href, options.signal).catch(() => ({ url: feedUrl.href, doc: {} })) : { url: feedUrl.href, doc: {} }
383
+ }
384
+ const submissions = isObject(owner.doc._submissions) ? owner.doc._submissions : undefined
385
+ const result: FoundItem = { feedUrl: first.url, ...submissions ? { submissions } : {} }
386
+ if (options.item === false || id === undefined) return result
387
+ const seen = new Set<string>()
388
+ let feed: Feed | undefined = first
389
+ for (let page = 0; feed && page < MAX_PAGES; page++) {
390
+ seen.add(feed.url)
391
+ const items: unknown[] = Array.isArray(feed.doc.items) ? feed.doc.items : []
392
+ const item = items.find((i): i is FeedItem => isObject(i) && i.id == id)
393
+ if (item) {
394
+ const author = accountHost(socialspec(item)) ?? (submissions ? undefined : accountHost(socialspec(owner.doc)))
395
+ return { ...result, item, ...author ? { author } : {} }
396
+ }
397
+ const next: unknown = feed.doc.next_url ?? archiveField(feed.doc, 'archive_url')
398
+ if (typeof next != 'string') break
399
+ const nextUrl: URL = new URL(next, feed.url)
400
+ if (nextUrl.host != new URL(url).host || seen.has(nextUrl.href)) break
401
+ feed = await this.#readFeed(nextUrl.href, options.signal).catch(e => {
402
+ if (isPupsError(e, 'aborted')) throw e
403
+ return undefined
404
+ })
405
+ }
406
+ return result
407
+ }
408
+
409
+ async #readFeed(url: string, signal?: AbortSignal): Promise<Feed> {
410
+ const response = await fetchWithTimeout(this.#fetch, url, { credentials: 'omit', headers: { Accept: 'application/feed+json, application/json' } }, this.#timeoutMs, signal)
411
+ if (!response.ok) throw new PupsError('not_found', `${url} answered HTTP ${response.status}.`)
412
+ const text = await response.text()
413
+ if (text.length > MAX_FEED_BYTES) throw new PupsError('invalid_feed', `${url} is too large.`)
414
+ let doc: unknown
415
+ try {
416
+ doc = JSON.parse(text)
417
+ } catch {
418
+ doc = undefined
419
+ }
420
+ if (!isObject(doc) || typeof doc.version != 'string' || !doc.version.startsWith('https://jsonfeed.org/version/'))
421
+ throw new PupsError('invalid_feed', `${url} is not a JSON Feed.`)
422
+ return { url, doc }
423
+ }
424
+
425
+ /**
426
+ * Waits until the item `id` at the public URL `feedUrl` is in the state `ready` wants, e.g. present after a post,
427
+ * so that a receiver that fetches it right away doesn't get an older copy from a cache (RFC-11 "When"). Gives up
428
+ * after the `visibilityDelays`, or at once if the feed can't be read.
429
+ */
430
+ async waitForItem(feedUrl: string, id: string, ready: (item: FeedItem | undefined) => boolean, options: { signal?: AbortSignal } = {}): Promise<boolean> {
431
+ for (let attempt = 0; ; attempt++) {
432
+ let doc: Record<string, unknown>
433
+ try {
434
+ const response = await fetchWithTimeout(this.#fetch, feedUrl, { credentials: 'omit', cache: 'no-store' }, this.#timeoutMs, options.signal)
435
+ if (!response.ok) return false
436
+ doc = await response.json()
437
+ } catch (e) {
438
+ if (isPupsError(e, 'aborted')) throw e
439
+ return false
440
+ }
441
+ const items: unknown[] = Array.isArray(doc?.items) ? doc.items : []
442
+ if (ready(items.find((i): i is FeedItem => isObject(i) && i.id == id))) return true
443
+ if (attempt >= this.#visibilityDelays.length) return false
444
+ await sleep(this.#visibilityDelays[attempt]!, options.signal)
445
+ }
446
+ }
447
+ }
package/src/session.ts CHANGED
@@ -3,6 +3,7 @@ import { errorFromResponse, isPupsError, PupsError } from './errors.js'
3
3
  import { listFeeds, PupsFeed, type FeedLink, type FeedOptions } from './feed.js'
4
4
  import { fileTypeOf, uploadContentType } from './file-types.js'
5
5
  import { HostMetaEditor } from './host-meta.js'
6
+ import { Mentions } from './mentions.js'
6
7
  import { revokeToken } from './oauth.js'
7
8
  import { isPrivate, publicUrl, resolvePath, scopeCovers, storageUrl, validatePath } from './paths.js'
8
9
  import {
@@ -98,6 +99,7 @@ export class PupsSession {
98
99
  readonly privatePath: string
99
100
  /** Edits `host-meta.json` through the server's host-meta endpoint. */
100
101
  readonly hostMeta: HostMetaEditor
102
+ #mentions?: Mentions
101
103
  /** @internal */
102
104
  readonly _tokens: TokenManager
103
105
  readonly #ctx: SessionContext
@@ -119,6 +121,14 @@ export class PupsSession {
119
121
  this.hostMeta = new HostMetaEditor(this, ctx.fetch)
120
122
  }
121
123
 
124
+ /**
125
+ * Sends webmentions: RFC-11 mentions to domains, RFC-4 submissions to feeds. Shared by the session's feeds, so
126
+ * that they share the discovery cache.
127
+ */
128
+ get mentions(): Mentions {
129
+ return this.#mentions ??= new Mentions({ fetch: this.#ctx.fetch, me: this.me })
130
+ }
131
+
122
132
  /** The server configuration, pinned at login. */
123
133
  get server(): PupsServer {
124
134
  return this._tokens.record.server
package/src/util.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  import { PupsError } from './errors.js'
2
2
 
3
+ /** Whether `value` is a plain object, not an array or null. */
4
+ export const isObject = (value: unknown): value is Record<string, unknown> =>
5
+ !!value && typeof value == 'object' && !Array.isArray(value)
6
+
3
7
  /** Base64url without padding (RFC 4648 §5), as PKCE requires. */
4
8
  export function base64url(bytes: Uint8Array): string {
5
9
  let binary = ''
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.4.0'
1
+ export const VERSION = '0.6.0'