pups-client 0.4.0 → 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.
package/src/index.ts CHANGED
@@ -18,6 +18,8 @@ export { PupsSession } from './session.js'
18
18
  export type { Body, JsonBody, SessionChangeEvent, StoredFile, WriteOptions, WriteResult } from './session.js'
19
19
  export { FEED_REL, POST_URL_TEMPLATE, PUPS_FEED_SPEC, PupsFeed, feedScopes, itemIndex } from './feed.js'
20
20
  export type {
21
+ CommentPolicy,
22
+ CommentsState,
21
23
  FeedAttachment,
22
24
  FeedAuthor,
23
25
  FeedDocument,
@@ -29,6 +31,7 @@ export type {
29
31
  FeedSetup,
30
32
  FeedState,
31
33
  ItemMarker,
34
+ MentionChoice,
32
35
  MediaInput,
33
36
  MediaResult,
34
37
  PostChanges,
@@ -37,6 +40,10 @@ export type {
37
40
  PupsMarker,
38
41
  } from './feed.js'
39
42
  export { HostMetaEditor } from './host-meta.js'
43
+ export { MENTION_REL, Mentions } from './mentions.js'
44
+ export type { Delivery, DeliveryStatus, FoundItem, MentionReport, MentionSource, MentionsOptions, PlannedMention, PostChange, PostMentions, Submission, SubmissionStatus } from './mentions.js'
45
+ export { accountHost, findHandles, handleText, itemHandles, visibleText } from './handles.js'
46
+ export type { HandleSource } from './handles.js'
40
47
  export type { HostMetaDocument, HostMetaLink } from './host-meta.js'
41
48
  export { PupsError, isPupsError } from './errors.js'
42
49
  export type { PupsErrorCode } from './errors.js'
@@ -0,0 +1,443 @@
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
+ /**
155
+ * Sends webmentions: RFC-11 mentions to the domains a post names or answers, found through their `host-meta.json`,
156
+ * and RFC-4 submissions to the endpoint a target feed names in `_submissions`. Plain Webmention, form-encoded.
157
+ *
158
+ * Use `session.mentions`, which shares the discovery cache of the session, or create one for use without a session.
159
+ * In a browser, it can only read feeds and `host-meta.json` files that allow CORS, as RFC-4 and RFC-6 require;
160
+ * domains whose `host-meta.json` doesn't count as having no endpoint (RFC-11 "CORS").
161
+ */
162
+ export class Mentions {
163
+ readonly #fetch: typeof fetch
164
+ readonly #retryDelays: number[]
165
+ readonly #visibilityDelays: number[]
166
+ readonly #timeoutMs: number
167
+ readonly #endpoints = new Map<string, { endpoint?: string; until: number }>()
168
+ readonly #me?: string
169
+
170
+ constructor(options: MentionsOptions = {}) {
171
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init))
172
+ this.#retryDelays = options.retryDelays ?? [10_000, 60_000, 300_000]
173
+ this.#visibilityDelays = options.visibilityDelays ?? [1000, 2000, 4000, 8000, 15_000]
174
+ this.#timeoutMs = options.timeoutMs ?? 15_000
175
+ this.#me = options.me
176
+ }
177
+
178
+ /**
179
+ * The mention endpoint of a domain (RFC-11 "Discovery"): the first link with the relation `MENTION_REL` in its
180
+ * `host-meta.json`, if it is an https URL. Undefined if the domain has none, or its `host-meta.json` can't be
181
+ * read. Cached for 24 hours (less if the file's `max-age` says so), failures for an hour.
182
+ * @param domain `tim.example.com`, `@tim.example.com` or `https://tim.example.com/`.
183
+ */
184
+ async discover(domain: string, options: { signal?: AbortSignal } = {}): Promise<string | undefined> {
185
+ const host = asciiHost(domain.replace(/^@/, '').replace(/^https:\/\//i, '').replace(/\/$/, ''))
186
+ if (!host) return undefined
187
+ const cached = this.#endpoints.get(host)
188
+ if (cached && cached.until > Date.now()) return cached.endpoint
189
+ const url = `https://${host}/.well-known/host-meta.json`
190
+ let endpoint: string | undefined
191
+ let maxAge = DAY_MS
192
+ try {
193
+ const response = await fetchWithTimeout(this.#fetch, url, { credentials: 'omit', headers: { Accept: 'application/json' } }, this.#timeoutMs, options.signal)
194
+ // Only host-meta.json on the domain itself counts (RFC-11 "Discovery").
195
+ if (response.ok && (!response.url || new URL(response.url).host == host)) {
196
+ const doc: unknown = await response.json()
197
+ const link = isObject(doc) && Array.isArray(doc.links) ? doc.links.find(l => isObject(l) && l.rel == MENTION_REL) : undefined
198
+ endpoint = isHttps(link?.href) ? link.href : undefined
199
+ const age = /max-age=(\d+)/.exec(response.headers.get('Cache-Control') ?? '')
200
+ if (age) maxAge = Math.min(maxAge, Number(age[1]) * 1000)
201
+ }
202
+ } catch (e) {
203
+ if (isPupsError(e, 'aborted')) throw e
204
+ }
205
+ this.#endpoints.set(host, { endpoint, until: Date.now() + (endpoint ? maxAge : Math.max(maxAge, HOUR_MS)) })
206
+ return endpoint
207
+ }
208
+
209
+ /**
210
+ * Sends a webmention: a form-encoded `POST` with `source` and `target`. Retries after network errors, `5xx` and
211
+ * `429` with the `retryDelays` (unless `retry` is false), never after other answers. Never throws, except
212
+ * `aborted`.
213
+ */
214
+ async send(endpoint: string, source: string, target: string, options: { signal?: AbortSignal; retry?: boolean } = {}): Promise<Delivery> {
215
+ return (await this.#sendWithBody(endpoint, source, target, options)).delivery
216
+ }
217
+
218
+ async #sendWithBody(endpoint: string, source: string, target: string, options: { signal?: AbortSignal; retry?: boolean }) {
219
+ const delays = options.retry === false ? [] : this.#retryDelays
220
+ for (let attempt = 0; ; attempt++) {
221
+ const answer = await this.#post(endpoint, source, target, options.signal)
222
+ if (answer.delivery.status != 'failed' || attempt >= delays.length) return answer
223
+ await sleep(Math.max(delays[attempt]!, Math.min(answer.retryAfterMs, 600_000)), options.signal)
224
+ }
225
+ }
226
+
227
+ async #post(endpoint: string, source: string, target: string, signal?: AbortSignal): Promise<{ delivery: Delivery; json?: unknown; retryAfterMs: number }> {
228
+ const body = () => new URLSearchParams({ source, target })
229
+ let response: Response
230
+ try {
231
+ response = await fetchWithTimeout(this.#fetch, endpoint, { method: 'POST', body: body(), credentials: 'omit' }, this.#timeoutMs, signal)
232
+ } catch (e) {
233
+ if (isPupsError(e, 'aborted')) throw e
234
+ // A browser hides the answer of an endpoint without CORS headers, but a form-encoded POST is a simple request
235
+ // and reaches it anyway: send it without reading the answer.
236
+ try {
237
+ await fetchWithTimeout(this.#fetch, endpoint, { method: 'POST', body: body(), credentials: 'omit', mode: 'no-cors' }, this.#timeoutMs, signal)
238
+ return { delivery: { status: 'unknown', message: 'Sent, but the endpoint doesn\'t let a browser read its answer.' }, retryAfterMs: 0 }
239
+ } catch (again) {
240
+ if (isPupsError(again, 'aborted')) throw again
241
+ return { delivery: { status: 'failed', message: e instanceof Error ? e.message : String(e) }, retryAfterMs: 0 }
242
+ }
243
+ }
244
+ const location = response.headers.get('Location')
245
+ const json: unknown = await response.json().catch(() => undefined)
246
+ const delivery: Delivery = {
247
+ status: response.ok ? 'accepted' : retryable(response.status) ? 'failed' : 'rejected',
248
+ httpStatus: response.status,
249
+ ...location ? { location: new URL(location, endpoint).href } : {},
250
+ ...!response.ok && isObject(json) && typeof json.message == 'string' ? { message: json.message } : {},
251
+ ...!response.ok && isObject(json) && typeof json.error == 'string' ? { code: json.error } : {},
252
+ }
253
+ return { delivery, json, retryAfterMs: (Number(response.headers.get('Retry-After')) || 0) * 1000 }
254
+ }
255
+
256
+ /**
257
+ * Tells a domain that `source` names it (RFC-11 "Mentions by name"), or answers its item `target`. Discovers
258
+ * the endpoint and sends the webmention.
259
+ * @param account `@tim.example.com` (or the bare host).
260
+ * @param target Default: the domain's root URL, `https://tim.example.com/`.
261
+ */
262
+ async notify(source: string, account: string, options: { target?: string; signal?: AbortSignal; retry?: boolean } = {}): Promise<MentionReport> {
263
+ const host = asciiHost(account.replace(/^@/, '')) ?? account.replace(/^@/, '')
264
+ const planned: PlannedMention = { account: `@${host}`, kind: options.target ? 'reply' : 'mention', target: options.target ?? `https://${host}/` }
265
+ return (await this.sendPlanned(source, [planned], options))[0]!
266
+ }
267
+
268
+ /**
269
+ * Tells the author of the item `target` (a feed URL plus `#<id>`) that `source` answers it (RFC-11 "Replies").
270
+ * @returns undefined if the item has no author to notify, can't be read, or its feed takes RFC-4 submissions:
271
+ * then the answer is a submission, and the RFC-4 server sends the mentions.
272
+ */
273
+ async reply(source: string, target: string, options: { signal?: AbortSignal; retry?: boolean } = {}): Promise<MentionReport | undefined> {
274
+ const found = await this.findItem(target, options).catch(e => {
275
+ if (isPupsError(e, 'aborted')) throw e
276
+ return undefined
277
+ })
278
+ return found?.author && !found.submissions ? this.notify(source, found.author, { ...options, target }) : undefined
279
+ }
280
+
281
+ /**
282
+ * Submits a comment or post to an RFC-4 feed (RFC-4 "Submitting"): `source` is the item in the author feed,
283
+ * `target` the answered item (feed URL plus `#<id>`), or the group feed for a new post. The endpoint is the
284
+ * target feed's `_submissions.url`, unless given. The app must have shown the target's terms of service and what
285
+ * `republish` means before the first submission (RFC-4 "Republishing").
286
+ * @throws {PupsError} `unsupported` if the target feed takes no submissions.
287
+ */
288
+ async submit(source: string, target: string, options: { endpoint?: string; signal?: AbortSignal } = {}): Promise<Submission> {
289
+ let endpoint = options.endpoint
290
+ if (!endpoint) {
291
+ const submissions = (await this.findItem(target, { ...options, item: false })).submissions
292
+ if (!isHttpUrl(submissions?.url))
293
+ throw new PupsError('unsupported', `${splitRef(target)[0]} takes no submissions: it has no _submissions with a url (RFC-4).`)
294
+ endpoint = submissions!.url as string
295
+ }
296
+ const { delivery, json } = await this.#sendWithBody(endpoint, source, target, { signal: options.signal, retry: false })
297
+ const statusUrl = delivery.location ?? (isObject(json) && typeof json.statusUrl == 'string' ? json.statusUrl : undefined)
298
+ const guid = isObject(json) && typeof json.guid == 'string' ? json.guid : undefined
299
+ return { ...delivery, endpoint, ...statusUrl ? { statusUrl } : {}, ...guid ? { guid } : {} }
300
+ }
301
+
302
+ /** Reads an RFC-4 status page. */
303
+ async submissionStatus(statusUrl: string, options: { signal?: AbortSignal } = {}): Promise<SubmissionStatus> {
304
+ const response = await fetchWithTimeout(this.#fetch, statusUrl, { credentials: 'omit', cache: 'no-store', headers: { Accept: 'application/json' } }, this.#timeoutMs, options.signal)
305
+ const json: unknown = await response.json().catch(() => undefined)
306
+ if (!isObject(json) || typeof json.status != 'string')
307
+ throw new PupsError('invalid_request', `${statusUrl} is not an RFC-4 status page (HTTP ${response.status}).`)
308
+ return json as SubmissionStatus
309
+ }
310
+
311
+ /**
312
+ * The accounts a post that is added, changed or deleted would notify (RFC-11 "Who is mentioned"), without sending
313
+ * anything, e.g. to list them in a confirmation dialog before posting: every domain its title and text name
314
+ * (RFC-11 "Handles"), and the author of the item it answers, with a reply. After an edit or delete, every account
315
+ * the old or the new version mentions. Each account once, replies first, never `me`, at most 20.
316
+ *
317
+ * Empty if the post answers an item of a feed with RFC-4 `_submissions`: such a post is a submission, and the
318
+ * RFC-4 server sends the mentions once it republishes it (RFC-11 "Who sends").
319
+ *
320
+ * Finding the author of an answered item reads its feed. With `discover`, it also looks up each domain's endpoint,
321
+ * and leaves out the domains that don't accept mentions; that tells them that a post names them, before the post
322
+ * is published (RFC-11 "Privacy considerations").
323
+ */
324
+ async plan(post: PostChange, options: { signal?: AbortSignal; discover?: boolean } = {}): Promise<PlannedMention[]> {
325
+ const me = post.me ?? this.#me
326
+ const own = me ? asciiHost(new URL(me).hostname) : undefined
327
+ const replies = new Map<string, string>()
328
+ for (const target of new Set([inReplyTo(post.item), inReplyTo(post.previous)].filter((t): t is string => !!t?.includes('#')))) {
329
+ const found = await this.findItem(target, options).catch(e => {
330
+ if (isPupsError(e, 'aborted')) throw e
331
+ return undefined
332
+ })
333
+ if (found?.submissions) return []
334
+ if (found?.author && found.author != own && !replies.has(found.author)) replies.set(found.author, target)
335
+ }
336
+ const names = [...new Set([...post.item ? itemHandles(post.item) : [], ...post.previous ? itemHandles(post.previous) : []])]
337
+ .filter(host => host != own && !replies.has(host))
338
+ const planned: PlannedMention[] = [
339
+ ...[...replies].map(([host, target]) => ({ account: `@${host}`, kind: 'reply' as const, target })),
340
+ ...names.map(host => ({ account: `@${host}`, kind: 'mention' as const, target: `https://${host}/` })),
341
+ ].slice(0, MAX_ACCOUNTS)
342
+ if (!options.discover) return planned
343
+ const endpoints = await Promise.all(planned.map(p => this.discover(p.account, options)))
344
+ return planned.flatMap((p, i) => endpoints[i] ? [{ ...p, endpoint: endpoints[i] }] : [])
345
+ }
346
+
347
+ /**
348
+ * Sends mentions as `plan()` returned them, e.g. those the author confirmed, with `source` as the post: the
349
+ * post's feed or archive URL plus `#<id>`, once it is published.
350
+ */
351
+ sendPlanned(source: string, planned: PlannedMention[], options: { signal?: AbortSignal; retry?: boolean } = {}): Promise<MentionReport[]> {
352
+ return Promise.all(planned.map(async p => {
353
+ const endpoint = p.endpoint ?? await this.discover(p.account, options)
354
+ if (!endpoint) return { ...p, status: 'no-endpoint' as const }
355
+ const { status, httpStatus, message } = await this.send(endpoint, source, p.target, options)
356
+ return { ...p, endpoint, status, ...httpStatus ? { httpStatus } : {}, ...message ? { message } : {} }
357
+ }))
358
+ }
359
+
360
+ /** `plan()` and `sendPlanned()` in one: sends the RFC-11 mentions of a post that was added, changed or deleted. */
361
+ async notifyAll(post: PostMentions, options: { signal?: AbortSignal } = {}): Promise<MentionReport[]> {
362
+ return this.sendPlanned(post.source, await this.plan(post, options), options)
363
+ }
364
+
365
+ /**
366
+ * Finds an item, given as feed URL plus `#<id>`, as RFC-4 does: in the feed, then along `next_url` (or RFC-7's
367
+ * `_pups.archive_url`) on the same host, at most 10 pages. JSON Feed only.
368
+ * @throws {PupsError} `network`, `not_found` or `invalid_feed` if the first feed can't be read.
369
+ */
370
+ async findItem(ref: string, options: { signal?: AbortSignal; item?: boolean } = {}): Promise<FoundItem> {
371
+ const [url, id] = splitRef(ref)
372
+ const first = await this.#readFeed(url, options.signal)
373
+ // An RFC-7 archive takes its _submissions from its feed file (RFC-7 "Receiving comments").
374
+ let owner = first
375
+ const updates = isObject(first.doc._pups) ? first.doc._pups.updates_url : undefined
376
+ if (typeof updates == 'string') {
377
+ const feedUrl = new URL(updates, first.url)
378
+ owner = feedUrl.host == new URL(first.url).host ? await this.#readFeed(feedUrl.href, options.signal).catch(() => ({ url: feedUrl.href, doc: {} })) : { url: feedUrl.href, doc: {} }
379
+ }
380
+ const submissions = isObject(owner.doc._submissions) ? owner.doc._submissions : undefined
381
+ const result: FoundItem = { feedUrl: first.url, ...submissions ? { submissions } : {} }
382
+ if (options.item === false || id === undefined) return result
383
+ const seen = new Set<string>()
384
+ let feed: Feed | undefined = first
385
+ for (let page = 0; feed && page < MAX_PAGES; page++) {
386
+ seen.add(feed.url)
387
+ const items: unknown[] = Array.isArray(feed.doc.items) ? feed.doc.items : []
388
+ const item = items.find((i): i is FeedItem => isObject(i) && i.id == id)
389
+ if (item) {
390
+ const author = accountHost(socialspec(item)) ?? (submissions ? undefined : accountHost(socialspec(owner.doc)))
391
+ return { ...result, item, ...author ? { author } : {} }
392
+ }
393
+ const next: unknown = feed.doc.next_url ?? (isObject(feed.doc._pups) ? feed.doc._pups.archive_url : undefined)
394
+ if (typeof next != 'string') break
395
+ const nextUrl: URL = new URL(next, feed.url)
396
+ if (nextUrl.host != new URL(url).host || seen.has(nextUrl.href)) break
397
+ feed = await this.#readFeed(nextUrl.href, options.signal).catch(e => {
398
+ if (isPupsError(e, 'aborted')) throw e
399
+ return undefined
400
+ })
401
+ }
402
+ return result
403
+ }
404
+
405
+ async #readFeed(url: string, signal?: AbortSignal): Promise<Feed> {
406
+ const response = await fetchWithTimeout(this.#fetch, url, { credentials: 'omit', headers: { Accept: 'application/feed+json, application/json' } }, this.#timeoutMs, signal)
407
+ if (!response.ok) throw new PupsError('not_found', `${url} answered HTTP ${response.status}.`)
408
+ const text = await response.text()
409
+ if (text.length > MAX_FEED_BYTES) throw new PupsError('invalid_feed', `${url} is too large.`)
410
+ let doc: unknown
411
+ try {
412
+ doc = JSON.parse(text)
413
+ } catch {
414
+ doc = undefined
415
+ }
416
+ if (!isObject(doc) || typeof doc.version != 'string' || !doc.version.startsWith('https://jsonfeed.org/version/'))
417
+ throw new PupsError('invalid_feed', `${url} is not a JSON Feed.`)
418
+ return { url, doc }
419
+ }
420
+
421
+ /**
422
+ * Waits until the item `id` at the public URL `feedUrl` is in the state `ready` wants, e.g. present after a post,
423
+ * so that a receiver that fetches it right away doesn't get an older copy from a cache (RFC-11 "When"). Gives up
424
+ * after the `visibilityDelays`, or at once if the feed can't be read.
425
+ */
426
+ async waitForItem(feedUrl: string, id: string, ready: (item: FeedItem | undefined) => boolean, options: { signal?: AbortSignal } = {}): Promise<boolean> {
427
+ for (let attempt = 0; ; attempt++) {
428
+ let doc: Record<string, unknown>
429
+ try {
430
+ const response = await fetchWithTimeout(this.#fetch, feedUrl, { credentials: 'omit', cache: 'no-store' }, this.#timeoutMs, options.signal)
431
+ if (!response.ok) return false
432
+ doc = await response.json()
433
+ } catch (e) {
434
+ if (isPupsError(e, 'aborted')) throw e
435
+ return false
436
+ }
437
+ const items: unknown[] = Array.isArray(doc?.items) ? doc.items : []
438
+ if (ready(items.find((i): i is FeedItem => isObject(i) && i.id == id))) return true
439
+ if (attempt >= this.#visibilityDelays.length) return false
440
+ await sleep(this.#visibilityDelays[attempt]!, options.signal)
441
+ }
442
+ }
443
+ }
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.5.0'