pups-client 0.6.0 → 0.8.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.
@@ -0,0 +1,247 @@
1
+ import { isPupsError, PupsError } from './errors.js'
2
+ import type { FeedAttachment, FeedAuthor, FeedDocument, FeedItem } from './feed.js'
3
+ import type { Submission } from './mentions.js'
4
+ import { pathFromPublicUrl } from './paths.js'
5
+ import type { PupsSession } from './session.js'
6
+ import { isObject, randomString } from './util.js'
7
+
8
+ const RFC1_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-1-Source-for-JSON-Feeds.md'
9
+ const JSON_FEED = 'https://jsonfeed.org/version/1.1'
10
+
11
+ type Signal = { signal?: AbortSignal }
12
+
13
+ /** A comment, or a post to a discussion group: what an RFC-4 submission publishes. */
14
+ export interface CommentInput {
15
+ /** The answered item, as feed URL plus `#<id>`; for a new post in a group, the group feed's URL. */
16
+ target: string
17
+ title?: string
18
+ content_html?: string
19
+ content_text?: string
20
+ /** The text as Markdown, stored in `_source.markdown` (RFC-1), and as `content_text` if neither content is given. */
21
+ markdown?: string
22
+ url?: string
23
+ authors?: FeedAuthor[]
24
+ language?: string
25
+ attachments?: FeedAttachment[]
26
+ [extension: `_${string}`]: unknown
27
+ }
28
+
29
+ /** Changes to a comment: a value sets the field, `null` removes it, `undefined` leaves it unchanged. */
30
+ export type CommentChanges = { [K in Exclude<keyof CommentInput, 'target'>]?: CommentInput[K] | null }
31
+
32
+ export interface CommentResult {
33
+ /** The comment's `source`: the public URL of its comment feed plus `#<id>`. It never changes. */
34
+ source: string
35
+ /** The comment feed, below `/appdata/<client-host>/comments/`. */
36
+ path: string
37
+ /** The item as stored; for a deleted comment, as it was. */
38
+ item: FeedItem
39
+ /** The RFC-4 submission; missing with `submit: false`. */
40
+ submission?: Submission
41
+ }
42
+
43
+ type SubmitOption = Signal & {
44
+ /** Submit to the target after writing (default `true`). Show the target's terms of service before the first one. */
45
+ submit?: boolean
46
+ }
47
+
48
+ const now = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
49
+
50
+ async function sha256Hex(text: string): Promise<string> {
51
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))
52
+ return [...digest].map(b => b.toString(16).padStart(2, '0')).join('')
53
+ }
54
+
55
+ /**
56
+ * The comment feed for a comment on `target` published at `date`, relative to the comments directory, in the layout
57
+ * RFC-7 recommends ("Comment feeds"): `<hash3>/<hash>.json`, where `<hash>` is the first 16 hex characters of the
58
+ * SHA-256 of `<target host> <yyyymmddhh>`, with the hour in UTC, and `<hash3>` its last three characters.
59
+ * @throws {PupsError} `invalid_request` if `target` is not an http(s) URL or `date` is invalid.
60
+ */
61
+ export async function commentFeedPath(target: string, date: Date | string): Promise<string> {
62
+ let host: string
63
+ try {
64
+ const url = new URL(target)
65
+ if (url.protocol != 'https:' && url.protocol != 'http:') throw new Error()
66
+ host = url.hostname
67
+ } catch {
68
+ throw new PupsError('invalid_request', `"${target}" is not an http(s) URL, so it can't be the target of a comment (RFC-4).`)
69
+ }
70
+ const time = new Date(date)
71
+ if (isNaN(+time)) throw new PupsError('invalid_request', `"${date}" is not a valid date.`)
72
+ const hour = time.toISOString().slice(0, 13).replace(/[-T]/g, '')
73
+ const hash = (await sha256Hex(`${host} ${hour}`)).slice(0, 16)
74
+ return `${hash.slice(-3)}/${hash}.json`
75
+ }
76
+
77
+ const isFeed = (doc: unknown): doc is FeedDocument =>
78
+ isObject(doc) && typeof doc.version == 'string' && doc.version.startsWith('https://jsonfeed.org/version/') && Array.isArray(doc.items)
79
+
80
+ const inReplyTo = (item: FeedItem) => isObject(item._source) && typeof item._source.inReplyTo == 'string' ? item._source.inReplyTo : undefined
81
+
82
+ /** Stores Markdown in `_source.markdown` (RFC-1), with `content_text` as the fallback JSON Feed requires. */
83
+ function setMarkdown(item: FeedItem, markdown: string | null) {
84
+ const { markdown: _old, ...source } = isObject(item._source) ? item._source : {}
85
+ item._source = markdown === null ? source : { about: RFC1_URL, ...source, markdown }
86
+ if (markdown !== null && item.content_html === undefined) item.content_text = markdown
87
+ }
88
+
89
+ function checkContent(item: FeedItem) {
90
+ if (item.content_html === undefined && item.content_text === undefined)
91
+ throw new PupsError('invalid_request', 'A comment needs content_html, content_text or markdown (JSON Feed requires content).')
92
+ }
93
+
94
+ /**
95
+ * The owner's RFC-4 submissions (comments, and posts to discussion groups), kept in comment feeds in the app's own
96
+ * directory, never in the owner's main feed (RFC-7 "Comment feeds"): one file per target site and hour,
97
+ * `/appdata/<client-host>/comments/<hash3>/<hash>.json`. Needs the `appdata` scope. Use `session.comments`.
98
+ *
99
+ * ```ts
100
+ * const { source, submission } = await session.comments.post({ target: 'https://rm.example.org/groups/twowaves/posts.json#a8Kd03XpQz', markdown: 'Agreed!' })
101
+ * const status = await session.mentions.submissionStatus(submission!.statusUrl!)
102
+ * ```
103
+ */
104
+ export class PupsComments {
105
+ readonly #session: PupsSession
106
+
107
+ constructor(session: PupsSession) {
108
+ this.#session = session
109
+ }
110
+
111
+ /** The path of the comment feed for a comment on `target` published at `date`. */
112
+ async pathFor(target: string, date: Date | string): Promise<string> {
113
+ return `${this.#session.appDataPath}comments/${await commentFeedPath(target, date)}`
114
+ }
115
+
116
+ /**
117
+ * Publishes a comment: adds it at the top of its comment feed, which is created if needed, and submits it to the
118
+ * target, once it is visible at its public URL.
119
+ * @throws {PupsError} `invalid_request` for a bad target or missing content; `invalid_feed` if the file holds
120
+ * something else; the errors of writing.
121
+ */
122
+ async post(input: CommentInput, options: SubmitOption = {}): Promise<CommentResult> {
123
+ const { target, markdown, ...fields } = input
124
+ const item: FeedItem = { id: randomString(12), ...fields, date_published: now() }
125
+ item._source = { about: RFC1_URL, ...isObject(item._source) ? item._source : {}, inReplyTo: target }
126
+ if (markdown !== undefined) setMarkdown(item, markdown)
127
+ checkContent(item)
128
+ const path = await this.pathFor(target, item.date_published!)
129
+ const feedUrl = this.#session.publicUrl(path)
130
+ await this.#session.update(path, async file => {
131
+ const doc = file ? await this.#feed(file.json(), path) : this.#newFeed(feedUrl)
132
+ return { ...doc, items: [item, ...doc.items] }
133
+ }, { contentType: 'application/feed+json', signal: options.signal })
134
+ return this.#result(feedUrl, path, item, options)
135
+ }
136
+
137
+ /** A comment, given by its `source`; undefined if its feed or the item doesn't exist. */
138
+ async get(source: string, options: Signal = {}): Promise<CommentResult | undefined> {
139
+ const { path, id } = this.#parse(source)
140
+ const file = await this.#session.get(path, options)
141
+ const item = file ? (await this.#feed(file.json(), path)).items.find(i => i.id == id) : undefined
142
+ return item && { source, path, item }
143
+ }
144
+
145
+ /**
146
+ * Changes a comment in its comment feed, keeping `id`, `date_published` and the target, sets `date_modified`, and
147
+ * submits it again with the same `source`. RFC-4 servers apply it only if the target allows edits.
148
+ * @throws {PupsError} `not_found` if the comment doesn't exist.
149
+ */
150
+ async edit(source: string, changes: CommentChanges | ((item: FeedItem) => FeedItem), options: SubmitOption = {}): Promise<CommentResult> {
151
+ const { path, id } = this.#parse(source)
152
+ let changed: FeedItem | undefined
153
+ await this.#session.update(path, async file => {
154
+ const doc = file ? await this.#feed(file.json(), path) : undefined
155
+ const current = doc?.items.find(i => i.id == id)
156
+ if (!doc || !current) throw new PupsError('not_found', `There is no comment ${source}.`)
157
+ changed = this.#change(structuredClone(current), changes)
158
+ return { ...doc, items: doc.items.map(i => i.id == id ? changed! : i) }
159
+ }, { contentType: 'application/feed+json', signal: options.signal })
160
+ return this.#result(source.slice(0, source.indexOf('#')), path, changed!, options)
161
+ }
162
+
163
+ /**
164
+ * Removes a comment from its comment feed, deletes the file once it is empty, and submits again with the same
165
+ * `source`, so that the RFC-4 server deletes the republished comment if the target allows it.
166
+ * @throws {PupsError} `not_found` if the comment doesn't exist.
167
+ */
168
+ async delete(source: string, options: SubmitOption = {}): Promise<CommentResult> {
169
+ const { path, id } = this.#parse(source)
170
+ for (let attempt = 1; ; attempt++) {
171
+ const file = await this.#session.get(path, options)
172
+ const doc = file ? await this.#feed(file.json(), path) : undefined
173
+ const item = doc?.items.find(i => i.id == id)
174
+ if (!file || !doc || !item) throw new PupsError('not_found', `There is no comment ${source}.`)
175
+ const items = doc.items.filter(i => i.id != id)
176
+ try {
177
+ if (items.length) await this.#session.replace(path, { ...doc, items }, file.etag, { contentType: 'application/feed+json', signal: options.signal })
178
+ else await this.#session.delete(path, { ifMatch: file.etag, signal: options.signal })
179
+ } catch (e) {
180
+ if (isPupsError(e, 'precondition_failed') && attempt < 5) continue
181
+ throw e
182
+ }
183
+ return this.#result(source.slice(0, source.indexOf('#')), path, item, options, true)
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Submits a comment to its target (RFC-4 "Submitting"), e.g. again after a failure. Waits until its feed shows the
189
+ * comment as it is now, or no longer shows it after a delete, so that the server doesn't fetch an older copy.
190
+ */
191
+ async submit(source: string, target: string, options: Signal & { deleted?: boolean } = {}): Promise<Submission> {
192
+ const mentions = this.#session.mentions
193
+ const { id } = this.#parse(source)
194
+ await mentions.waitForItem(source.slice(0, source.indexOf('#')), id, item => options.deleted ? !item : !!item, options)
195
+ return mentions.submit(source, target, options)
196
+ }
197
+
198
+ async #result(feedUrl: string, path: string, item: FeedItem, options: SubmitOption, deleted = false): Promise<CommentResult> {
199
+ const source = `${feedUrl}#${encodeURIComponent(item.id)}`
200
+ const target = inReplyTo(item)
201
+ const submission = options.submit ?? true
202
+ ? target && await this.submit(source, target, { signal: options.signal, deleted })
203
+ : undefined
204
+ return { source, path, item, ...submission ? { submission } : {} }
205
+ }
206
+
207
+ #newFeed(feedUrl: string): FeedDocument {
208
+ const host = new URL(this.#session.me).hostname
209
+ return {
210
+ version: JSON_FEED,
211
+ title: `Comments by ${host}`,
212
+ home_page_url: `https://${host}/`,
213
+ feed_url: feedUrl,
214
+ _source: { about: RFC1_URL, accounts: { socialspec: `@${host}` } },
215
+ items: [],
216
+ }
217
+ }
218
+
219
+ async #feed(json: Promise<unknown>, path: string): Promise<FeedDocument> {
220
+ const doc = await json.catch(() => undefined)
221
+ if (!isFeed(doc)) throw new PupsError('invalid_feed', `${path} is not a JSON Feed.`)
222
+ return doc
223
+ }
224
+
225
+ #change(item: FeedItem, changes: CommentChanges | ((item: FeedItem) => FeedItem)): FeedItem {
226
+ const { id, date_published } = item
227
+ const target = inReplyTo(item)
228
+ if (typeof changes == 'function') item = changes(item)
229
+ else for (const [key, value] of Object.entries(changes)) {
230
+ if (key == 'markdown') value !== undefined && setMarkdown(item, value as string | null)
231
+ else if (value === null) delete (item as Record<string, unknown>)[key]
232
+ else if (value !== undefined) (item as Record<string, unknown>)[key] = value
233
+ }
234
+ checkContent(item)
235
+ // The comment stays the same submission: same id, date, target and therefore file.
236
+ const source = isObject(item._source) ? item._source : {}
237
+ return { ...item, id, date_published, _source: { ...source, inReplyTo: target }, date_modified: now() }
238
+ }
239
+
240
+ #parse(source: string): { path: string; id: string } {
241
+ const at = source.indexOf('#')
242
+ const path = at > 0 ? pathFromPublicUrl(this.#session.server, source.slice(0, at)) : undefined
243
+ if (!path || !path.startsWith(`${this.#session.appDataPath}comments/`))
244
+ throw new PupsError('invalid_request', `${source} is not a comment in this app's comment feeds.`)
245
+ return { path, id: decodeURIComponent(source.slice(at + 1)) }
246
+ }
247
+ }
package/src/discovery.ts CHANGED
@@ -48,6 +48,11 @@ export interface PupsServer {
48
48
  * (RFC-6 "Built-in receiver"). Feeds opt in with `feed.enableComments()`.
49
49
  */
50
50
  commentEndpoint?: string
51
+ /**
52
+ * Whether the server keeps feeds with the RFC-7 marker (`kept_feeds`): it writes their archives, and takes single
53
+ * items by POST. `PupsFeed` needs it to post.
54
+ */
55
+ keptFeeds: boolean
51
56
  maxUploadBytes: number
52
57
  specVersion: string
53
58
  /** The configuration document as fetched, including fields this library doesn't know. */
@@ -181,6 +186,7 @@ export function parseConfig(json: unknown, domain: string, identityHosts: string
181
186
  ...hostMetaEndpoint ? { hostMetaEndpoint } : {},
182
187
  ...postEndpoint ? { postEndpoint } : {},
183
188
  ...commentEndpoint ? { commentEndpoint } : {},
189
+ keptFeeds: raw.kept_feeds === true,
184
190
  maxUploadBytes: maxUploadBytes as number,
185
191
  specVersion,
186
192
  raw,
package/src/errors.ts CHANGED
@@ -126,7 +126,7 @@ export async function errorFromResponse(response: Response, what: string): Promi
126
126
  const serverMessage = typeof body.message == 'string' ? body.message : undefined
127
127
  const code: PupsErrorCode = status == 400
128
128
  ? serverError == 'invalid_path' ? 'invalid_path' : 'invalid_request'
129
- : statusCodes[status] ?? 'server_error'
129
+ : serverError == 'not_pups_controlled' ? serverError : statusCodes[status] ?? 'server_error'
130
130
  const retryAfterHeader = Number(response.headers.get('Retry-After'))
131
131
  return new PupsError(code, `${what} failed with HTTP ${status}${serverMessage ? `: ${serverMessage}` : ''}`, {
132
132
  status,