pups-client 0.1.0 → 0.2.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/dist/feed.js ADDED
@@ -0,0 +1,805 @@
1
+ import { isPupsError, PupsError } from './errors.js';
2
+ import { fileTypes } from './file-types.js';
3
+ import { pathFromPublicUrl } from './paths.js';
4
+ import { randomString } from './util.js';
5
+ /** The link relation that registers a feed in `host-meta.json` (RFC-7). A placeholder in RFC-7. */
6
+ export const FEED_REL = 'https://bigwide.net/ns/feed';
7
+ /** The `about` of the `_pups` object: RFC-7. Not its final location; readers must not rely on it. */
8
+ export const PUPS_FEED_SPEC = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-7-Feed-Publishing-with-PUPS.md';
9
+ const RFC1_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-1-Source-for-JSON-Feeds.md';
10
+ const JSON_FEED_VERSION = 'https://jsonfeed.org/version/1.1';
11
+ const FEED_CONTENT_TYPE = 'application/feed+json';
12
+ const maxArchiveNumber = 999_999;
13
+ /** The feed file keeps at least this many items, also when `maxBytes` is exceeded (RFC-7 "Size in bytes"). */
14
+ const minFeedItems = 10;
15
+ const mainComment = `This feed is maintained by apps through a Personal Upload Server (PUPS), following ${PUPS_FEED_SPEC}. It contains the newest items. If it has _pups.archive_url, all items are in the archives, starting with the one there.`;
16
+ const archiveComment = (feedUrl) => `This is an archive of ${feedUrl}, maintained by apps through a Personal Upload Server (PUPS), following ${PUPS_FEED_SPEC}. New items appear in the feed at _pups.updates_url, older ones are in the archive at next_url.`;
17
+ /** Feed names (RFC-7 "Named feeds"): 1 to 40 lowercase letters, digits and `-`, not starting or ending with `-`. */
18
+ const feedNamePattern = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;
19
+ /** The main feed's media directories in `/feed/`, which therefore can't be feed names. */
20
+ const mainMediaFolders = ['images', 'media'];
21
+ /** Top-level fields that are fixed or managed by RFC-7, and can't be set through `create()` or `updateSettings()`. */
22
+ const reservedFields = new Set(['version', 'home_page_url', 'feed_url', 'user_comment', 'next_url', 'items', 'hubs', '_pups', 'icon', 'favicon']);
23
+ /** The scopes an app needs to write a feed: the feed file and the feed directory (RFC-7 "Server requirements"). */
24
+ export function feedScopes(name) {
25
+ const { path, directory } = feedPaths(name);
26
+ return [`write:${path}`, `write:${directory}`];
27
+ }
28
+ function feedPaths(name) {
29
+ if (name === undefined)
30
+ return { path: '/feed.json', directory: '/feed/' };
31
+ if (!feedNamePattern.test(name))
32
+ throw new PupsError('invalid_request', `"${name}" is not a valid feed name: use 1 to 40 lowercase letters, digits and "-", not starting or ending with "-" (RFC-7, Named feeds).`);
33
+ if (mainMediaFolders.includes(name))
34
+ throw new PupsError('invalid_request', `"${name}" can't be a feed name: /feed/${name}/ and its files belong to the main feed (RFC-7, Named feeds).`);
35
+ return { path: `/feed/${name}.json`, directory: `/feed/${name}/` };
36
+ }
37
+ const isObject = (value) => !!value && typeof value == 'object' && !Array.isArray(value);
38
+ const isFeedDocument = (value) => isObject(value) && typeof value.version == 'string' && value.version.startsWith('https://jsonfeed.org/version/1')
39
+ && Array.isArray(value.items) && value.items.every(i => isObject(i) && typeof i.id == 'string');
40
+ const isControlled = (doc) => doc._pups?.pupsControlled === true;
41
+ const notControlled = (path) => new PupsError('not_pups_controlled', `${path} is not maintained by PUPS clients: it has no "_pups": { "pupsControlled": true }. It is never written; the owner can hand it over by adding that marker (RFC-7, The _pups object).`);
42
+ const conflict = (what) => new PupsError('precondition_failed', `${what} changed in the meantime.`);
43
+ const now = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
44
+ const clone = (value) => structuredClone(value);
45
+ const serialize = (doc) => JSON.stringify(doc, null, 2);
46
+ const byteLength = (text) => new TextEncoder().encode(text).length;
47
+ const replaceAt = (array, index, value) => array.map((v, i) => i == index ? value : v);
48
+ /** Adds `incoming` items at the top of `existing`; an item whose id is already there replaces the old copy instead. */
49
+ function mergeItems(existing, incoming) {
50
+ const byId = new Map(incoming.map(item => [item.id, item]));
51
+ const present = new Set(existing.map(item => item.id));
52
+ return [...incoming.filter(item => !present.has(item.id)), ...existing.map(item => byId.get(item.id) ?? item)];
53
+ }
54
+ /** Every string inside `value`, deeply. */
55
+ function* strings(value) {
56
+ if (typeof value == 'string')
57
+ yield value;
58
+ else if (Array.isArray(value))
59
+ for (const v of value)
60
+ yield* strings(v);
61
+ else if (isObject(value))
62
+ for (const v of Object.values(value))
63
+ yield* strings(v);
64
+ }
65
+ /** The file extension for a media type, preferring extensions that are served as exactly that type. */
66
+ function extensionForType(type) {
67
+ const essence = type.split(';')[0].trim().toLowerCase();
68
+ const entries = Object.entries(fileTypes);
69
+ return entries.find(([, t]) => t.served == essence)?.[0] ?? entries.find(([, t]) => t.accepted.includes(essence))?.[0];
70
+ }
71
+ /**
72
+ * A feed on the owner's domain, maintained according to RFC-7: the main feed `/feed.json`, or a named feed
73
+ * `/feed/<name>.json`, each with its feed directory for archives, icons and media: `/feed/`, or `/feed/<name>/`.
74
+ * The main feed keeps its media in `/feed/images/` and `/feed/media/`, since the rest of `/feed/` belongs to the
75
+ * named feeds.
76
+ *
77
+ * Get one from `session.feed()` or `session.feed('photos')`. The session needs the feed's scopes, see
78
+ * {@link feedScopes}. All writes are safe against concurrent changes by other apps and the owner: they are
79
+ * read-modify-write cycles with ETags, repeated when another client wrote in between.
80
+ */
81
+ export class PupsFeed {
82
+ /** The name of a named feed; undefined for the main feed. */
83
+ name;
84
+ /** The feed file, e.g. `/feed.json` or `/feed/photos.json`. */
85
+ path;
86
+ /** The feed directory, e.g. `/feed/` or `/feed/photos/`. */
87
+ directory;
88
+ #session;
89
+ #maxItems;
90
+ #archiveSize;
91
+ #archivesWanted;
92
+ #maxBytes;
93
+ #maxAttempts;
94
+ /** @internal Use `session.feed()`. */
95
+ constructor(session, name, options = {}) {
96
+ const { path, directory } = feedPaths(name);
97
+ this.name = name;
98
+ this.path = path;
99
+ this.directory = directory;
100
+ this.#session = session;
101
+ this.#maxItems = options.maxItems ?? 30;
102
+ this.#archiveSize = options.archiveSize ?? 20;
103
+ this.#archivesWanted = options.startArchives ?? true;
104
+ this.#maxBytes = options.maxBytes;
105
+ this.#maxAttempts = options.maxAttempts ?? 8;
106
+ if (!(this.#archiveSize >= 1 && this.#maxItems >= 1))
107
+ throw new PupsError('invalid_request', 'Feed options: maxItems and archiveSize must be at least 1.');
108
+ }
109
+ /** The public URL of the feed file, its `feed_url`. */
110
+ get url() {
111
+ return this.#session.publicUrl(this.path);
112
+ }
113
+ /** The scopes needed to write this feed. */
114
+ get scopes() {
115
+ return feedScopes(this.name);
116
+ }
117
+ /** Whether the session may write the feed file and the feed directory. */
118
+ get writable() {
119
+ return this.#session.canWrite(this.path) && this.#session.canWrite(this.#archivePath(0));
120
+ }
121
+ /** Reads the feed file and tells whether it exists, and whether PUPS clients may write it. */
122
+ async load(options = {}) {
123
+ try {
124
+ const loaded = await this.#read(this.path, options.signal);
125
+ if (!loaded)
126
+ return { status: 'missing' };
127
+ return isControlled(loaded.doc) ? { status: 'pups', feed: loaded.doc, etag: loaded.etag } : { status: 'foreign', feed: loaded.doc };
128
+ }
129
+ catch (e) {
130
+ if (isPupsError(e, 'invalid_feed'))
131
+ return { status: 'invalid' };
132
+ throw e;
133
+ }
134
+ }
135
+ /**
136
+ * Sets up a new feed (RFC-7 "Setting up a feed"): uploads the icons, writes the feed file with the fixed fields
137
+ * and the `_pups` marker, and registers the feed in `host-meta.json` (unless `register` is false).
138
+ * @returns `registered`: false if the feed couldn't be registered; call `register()` again later, or tell the owner
139
+ * to add the link to `host-meta.json` by hand.
140
+ * @throws {PupsError} `precondition_failed` if the feed file exists already; `insufficient_scope`.
141
+ */
142
+ async create(setup, options = {}) {
143
+ const { icon, favicon, title, ...settings } = setup;
144
+ if (typeof title != 'string' || !title.trim())
145
+ throw new PupsError('invalid_request', 'A feed needs a title.');
146
+ this.#checkSettings(settings);
147
+ this.#checkWritable();
148
+ const uploaded = [];
149
+ try {
150
+ const iconFile = icon && await this.#upload(icon, 'images/icons/icon-', options.signal);
151
+ if (iconFile)
152
+ uploaded.push(iconFile);
153
+ const faviconFile = favicon && await this.#upload(favicon, 'images/icons/favicon-', options.signal);
154
+ if (faviconFile)
155
+ uploaded.push(faviconFile);
156
+ const { description, ...rest } = settings;
157
+ const doc = {
158
+ version: JSON_FEED_VERSION,
159
+ title,
160
+ home_page_url: this.#session.me,
161
+ feed_url: this.url,
162
+ ...description === undefined ? {} : { description },
163
+ user_comment: mainComment,
164
+ ...iconFile ? { icon: iconFile.url } : {},
165
+ ...faviconFile ? { favicon: faviconFile.url } : {},
166
+ ...rest,
167
+ items: [],
168
+ _pups: { about: PUPS_FEED_SPEC, pupsControlled: true },
169
+ };
170
+ await this.#session.create(this.path, serialize(doc), { contentType: FEED_CONTENT_TYPE, signal: options.signal });
171
+ }
172
+ catch (e) {
173
+ await Promise.all(uploaded.map(file => this.#deleteQuietly(file.path)));
174
+ if (isPupsError(e, 'precondition_failed'))
175
+ throw new PupsError('precondition_failed', `${this.path} exists already. Use load() to see whether it can be used.`, { cause: e });
176
+ throw e;
177
+ }
178
+ if (options.register === false)
179
+ return { url: this.url, registered: false };
180
+ try {
181
+ return { url: this.url, registered: await this.register(options) };
182
+ }
183
+ catch (e) {
184
+ // The feed exists now; a failed registration must not look like a failed setup.
185
+ if (isPupsError(e, 'aborted'))
186
+ throw e;
187
+ return { url: this.url, registered: false };
188
+ }
189
+ }
190
+ /**
191
+ * Registers the feed in `host-meta.json` (RFC-7 "Registering feeds"), unless a link with the feed relation and
192
+ * this feed's URL exists already.
193
+ * @returns false if the server has no host-meta endpoint, or doesn't allow the feed relation for this path.
194
+ */
195
+ async register(options = {}) {
196
+ const hostMeta = this.#session.hostMeta;
197
+ if (!hostMeta.available || !hostMeta.allowsRel(FEED_REL, this.path))
198
+ return false;
199
+ const document = await hostMeta.get(options);
200
+ if (document.links?.some(link => link.rel == FEED_REL && link.href == this.url))
201
+ return true;
202
+ await hostMeta.addLink({ rel: FEED_REL, href: this.path, type: FEED_CONTENT_TYPE }, options);
203
+ return true;
204
+ }
205
+ /**
206
+ * Changes the owner's fields of the feed (RFC-7 "Editing a feed"): a value sets a field, `null` removes it.
207
+ * @returns the feed as written.
208
+ */
209
+ async updateSettings(changes, options = {}) {
210
+ this.#checkSettings(changes);
211
+ if (changes.title === null || (changes.title !== undefined && !changes.title.trim()))
212
+ throw new PupsError('invalid_request', 'A feed needs a title.');
213
+ return this.#transaction(async () => {
214
+ const main = await this.#readControlled(this.path, options.signal);
215
+ const doc = { ...main.doc };
216
+ for (const [key, value] of Object.entries(changes))
217
+ if (value === null)
218
+ delete doc[key];
219
+ else if (value !== undefined)
220
+ doc[key] = value;
221
+ return this.#writeMain(doc, main.etag, options.signal);
222
+ });
223
+ }
224
+ /**
225
+ * Uploads a new icon (512 × 512) to `/feed/images/icons/` (`/feed/<name>/images/icons/` for a named feed) and
226
+ * deletes the old one, or removes it with `null`.
227
+ */
228
+ setIcon(media, options = {}) {
229
+ return this.#setImage('icon', media, options.signal);
230
+ }
231
+ /** Uploads a new favicon (64 × 64) to the icons directory, like `setIcon()`, or removes it with `null`. */
232
+ setFavicon(media, options = {}) {
233
+ return this.#setImage('favicon', media, options.signal);
234
+ }
235
+ /**
236
+ * Uploads an image, audio or video file into the feed directory under a new, unique name, by default
237
+ * `images/<year>/…` for images and `media/<year>/…` for everything else. Reference it from a post by its `url`.
238
+ * For the main feed, `folder` must be inside `images/` or `media/`: the rest of `/feed/` belongs to named feeds.
239
+ */
240
+ async uploadMedia(media, options = {}) {
241
+ const { type } = this.#mediaType(media);
242
+ const folder = (options.folder ?? (type.startsWith('image/') ? 'images' : 'media')).replace(/^\/+|\/+$/g, '');
243
+ if (folder == 'images/icons' || folder.startsWith('images/icons/'))
244
+ throw new PupsError('invalid_request', `${this.directory}images/icons/ is reserved for the feed's icons (RFC-7, Icons).`);
245
+ if (this.name === undefined && !mainMediaFolders.includes(folder.split('/')[0]))
246
+ throw new PupsError('invalid_request', `The main feed's media go into /feed/images/ or /feed/media/; the rest of /feed/ belongs to named feeds (RFC-7, Items).`);
247
+ return this.#upload(media, `${folder}/${new Date().getUTCFullYear()}/`, options.signal);
248
+ }
249
+ /**
250
+ * Adds a post (RFC-7 "Posting with archives"): first to the newest archive, or to a new archive once the newest
251
+ * holds `archiveSize` items, then to the top of the feed file, which keeps the newest `maxItems`. A feed without
252
+ * archives gets them now, unless `startArchives` is false; then the post only goes into the feed file. Upload
253
+ * media with `uploadMedia()` before posting.
254
+ * @returns the post, with `url`: its archive's URL plus `#<id>`, which never changes; for a feed without
255
+ * archives, the feed file's URL plus `#<id>`, valid while the post is among the newest.
256
+ */
257
+ async addPost(input, options = {}) {
258
+ const item = this.#newItem(input);
259
+ const signal = options.signal;
260
+ let archiveUrl = '';
261
+ let firstAttempt = true;
262
+ await this.#transaction(async () => {
263
+ const main = await this.#readControlled(this.path, signal);
264
+ // On a retry, the item may be in the feed file already: another client repaired it from the archive.
265
+ if (firstAttempt && main.doc.items.some(i => i.id == item.id))
266
+ throw new PupsError('invalid_request', `The feed already has an item with the id "${item.id}".`);
267
+ firstAttempt = false;
268
+ const doc = { ...main.doc, _pups: { ...main.doc._pups } };
269
+ const hasArchives = this.#archiveNumber(doc._pups.archive_url) !== undefined;
270
+ if (!hasArchives && !this.#archivesWanted) {
271
+ // A feed without archives: the feed file is all there is (RFC-7 "Posting").
272
+ archiveUrl = this.url;
273
+ await this.#writeMain({ ...doc, items: this.#newestItems([item], doc.items, doc) }, main.etag, signal);
274
+ return;
275
+ }
276
+ if (!hasArchives) {
277
+ const started = await this.#startArchives(main, signal);
278
+ if (started)
279
+ doc._pups.archive_url = started;
280
+ }
281
+ const added = await this.#addToArchive(main, doc, item, signal);
282
+ archiveUrl = added.url;
283
+ doc._pups.archive_url = added.url;
284
+ // The old chain of a handed-over feed now continues behind the oldest archive.
285
+ if (!hasArchives)
286
+ delete doc.next_url;
287
+ doc.items = this.#newestItems(added.recent, doc.items, doc);
288
+ await this.#writeMain(doc, main.etag, signal);
289
+ });
290
+ return this.#result(item, archiveUrl);
291
+ }
292
+ /**
293
+ * Finds a post by id in the archives (or, for a handed-over feed without archives yet, in the feed file).
294
+ * @returns undefined if there is no such post.
295
+ */
296
+ async getPost(id, options = {}) {
297
+ const main = await this.#read(this.path, options.signal);
298
+ const found = main && await this.#find(main, id, options.signal);
299
+ return found && this.#result(found.file.doc.items[found.index], this.#session.publicUrl(found.file.path));
300
+ }
301
+ /**
302
+ * All posts, newest first: the archives from `_pups.archive_url` along `next_url` (for a feed without archives,
303
+ * the feed file and its `next_url` chain). Each post is returned once.
304
+ */
305
+ async *posts(options = {}) {
306
+ const main = await this.#read(this.path, options.signal);
307
+ if (!main)
308
+ return;
309
+ const seen = new Set();
310
+ for await (const file of this.#chain(main, options.signal))
311
+ for (const item of file.doc.items)
312
+ if (!seen.has(item.id)) {
313
+ seen.add(item.id);
314
+ yield item;
315
+ }
316
+ }
317
+ /**
318
+ * Edits a post in its archive, and in the feed file if it is among the newest items (RFC-7 "Editing and deleting
319
+ * items"), and sets `date_modified`. `changes` is either an object (a value sets a field, `null` removes it), or
320
+ * a function that gets a copy of the item and returns the new item, or `undefined` to leave it unchanged. The
321
+ * function may run more than once.
322
+ *
323
+ * Apps should edit posts only when the owner asks them to, whichever app created them.
324
+ * @throws {PupsError} `not_found`
325
+ */
326
+ async editPost(id, changes, options = {}) {
327
+ const signal = options.signal;
328
+ return this.#transaction(async () => {
329
+ const { main, file, index } = await this.#findWritable(id, signal);
330
+ const old = file.doc.items[index];
331
+ const fileUrl = this.#session.publicUrl(file.path);
332
+ const changed = typeof changes == 'function' ? await changes(clone(old)) : this.#applyChanges(clone(old), changes);
333
+ if (!changed)
334
+ return this.#result(old, fileUrl);
335
+ const item = { ...changed, id, date_modified: now() };
336
+ if (file != main)
337
+ await this.#writeArchive(file, replaceAt(file.doc.items, index, item), signal);
338
+ const mainIndex = main.doc.items.findIndex(i => i.id == id);
339
+ if (mainIndex >= 0)
340
+ await this.#writeMain({ ...main.doc, items: replaceAt(main.doc.items, mainIndex, item) }, main.etag, signal);
341
+ return this.#result(item, fileUrl);
342
+ });
343
+ }
344
+ /**
345
+ * Deletes a post from its archive and from the feed file, which is then filled up again with the newest items
346
+ * from the archives. With `deleteMedia`, it also deletes the files in the feed directory that the post references
347
+ * and no other post does; this reads all archives.
348
+ * @returns the deleted item, and the public URLs of the deleted media files.
349
+ * @throws {PupsError} `not_found`
350
+ */
351
+ async deletePost(id, options = {}) {
352
+ const signal = options.signal;
353
+ const item = await this.#transaction(async () => {
354
+ const { main, file, index } = await this.#findWritable(id, signal);
355
+ const item = file.doc.items[index];
356
+ if (file != main) {
357
+ await this.#writeArchive(file, file.doc.items.filter(i => i.id != id), signal);
358
+ // Fill the feed file up again from the archives, which no longer contain the item.
359
+ const newest = [];
360
+ for await (const archive of this.#chain(main, signal)) {
361
+ newest.push(...archive.doc.items.filter(i => i.id != id));
362
+ if (newest.length >= this.#maxItems)
363
+ break;
364
+ }
365
+ await this.#writeMain({ ...main.doc, items: this.#newestItems(newest, [], main.doc) }, main.etag, signal);
366
+ }
367
+ else
368
+ await this.#writeMain({ ...main.doc, items: main.doc.items.filter(i => i.id != id) }, main.etag, signal);
369
+ return item;
370
+ });
371
+ const deletedMedia = [];
372
+ if (options.deleteMedia) {
373
+ const candidates = new Set(this.#mediaUrls(item));
374
+ if (candidates.size)
375
+ for await (const other of this.posts(options))
376
+ for (const url of this.#mediaUrls(other))
377
+ candidates.delete(url);
378
+ for (const url of candidates) {
379
+ const path = pathFromPublicUrl(this.#session.server, url);
380
+ if (path && await this.#deleteQuietly(path, signal))
381
+ deletedMedia.push(url);
382
+ }
383
+ }
384
+ return { item, deletedMedia };
385
+ }
386
+ // Reading
387
+ /**
388
+ * Reads a feed file or archive from `storage_base`.
389
+ * @returns undefined if it doesn't exist.
390
+ * @throws {PupsError} `invalid_feed` if it is not a JSON Feed.
391
+ */
392
+ async #read(path, signal) {
393
+ const file = await this.#session.get(path, { signal });
394
+ if (!file)
395
+ return;
396
+ if (!file.etag)
397
+ throw new PupsError('server_error', `The server sends no ETag for ${path}, so it can't be changed safely. It must expose the ETag header to browsers (RFC-6, CORS).`);
398
+ let doc;
399
+ try {
400
+ doc = await file.json();
401
+ }
402
+ catch {
403
+ // Not JSON: handled below.
404
+ }
405
+ if (!isFeedDocument(doc))
406
+ throw new PupsError('invalid_feed', `${path} is not a JSON Feed.`);
407
+ return { path, doc, etag: file.etag };
408
+ }
409
+ /** Reads a file that must exist and carry the `_pups` marker. */
410
+ async #readControlled(path, signal) {
411
+ const loaded = await this.#read(path, signal);
412
+ if (!loaded)
413
+ throw new PupsError('not_found', path == this.path ? `There is no feed at ${path} yet. Set it up with create().` : `${path} doesn't exist.`);
414
+ if (!isControlled(loaded.doc))
415
+ throw notControlled(path);
416
+ return loaded;
417
+ }
418
+ /**
419
+ * The files that hold all items: the archives from `_pups.archive_url` along `next_url`, as far as they are files
420
+ * on this server. A feed without archives yet (handed over, not posted to) holds its items in the feed file and
421
+ * the pages its `next_url` names.
422
+ */
423
+ async *#chain(main, signal) {
424
+ const visited = new Set([main.path]);
425
+ const archive = main.doc._pups?.archive_url;
426
+ let file = main;
427
+ let next = archive && this.#archiveNumber(archive) !== undefined ? archive : undefined;
428
+ if (next)
429
+ file = undefined;
430
+ else
431
+ yield main;
432
+ for (;;) {
433
+ if (file)
434
+ next = file.doc.next_url;
435
+ const path = next && pathFromPublicUrl(this.#session.server, next);
436
+ if (!path || visited.has(path))
437
+ return;
438
+ visited.add(path);
439
+ try {
440
+ file = await this.#read(path, signal);
441
+ }
442
+ catch (e) {
443
+ if (!isPupsError(e, 'invalid_feed', 'invalid_path'))
444
+ throw e;
445
+ return;
446
+ }
447
+ if (!file)
448
+ return;
449
+ yield file;
450
+ }
451
+ }
452
+ async #find(main, id, signal) {
453
+ for await (const file of this.#chain(main, signal)) {
454
+ const index = file.doc.items.findIndex(item => item.id == id);
455
+ if (index >= 0)
456
+ return { main, file, index };
457
+ }
458
+ return;
459
+ }
460
+ async #findWritable(id, signal) {
461
+ const main = await this.#readControlled(this.path, signal);
462
+ const found = await this.#find(main, id, signal);
463
+ if (!found)
464
+ throw new PupsError('not_found', `There is no post with the id "${id}" in ${this.path} or its archives.`);
465
+ if (!isControlled(found.file.doc))
466
+ throw notControlled(found.file.path);
467
+ return found;
468
+ }
469
+ // Writing
470
+ /** Runs `operation` again when another client changed a file in between, up to `maxAttempts` times. */
471
+ async #transaction(operation) {
472
+ for (let attempt = 1;; attempt++)
473
+ try {
474
+ return await operation();
475
+ }
476
+ catch (e) {
477
+ if (!isPupsError(e, 'precondition_failed') || attempt >= this.#maxAttempts)
478
+ throw e;
479
+ }
480
+ }
481
+ /**
482
+ * Writes the feed file. Sets the fixed fields, so that a feed the owner handed over gets them on its first write,
483
+ * and upgrades JSON Feed 1.0 (RFC-7 "Handing over an existing feed"). The optional `next_url` of a feed with
484
+ * archives is kept equal to `archive_url` (RFC-7 "Reading").
485
+ */
486
+ async #writeMain(doc, etag, signal) {
487
+ const { author, ...rest } = doc;
488
+ const fixed = {
489
+ ...rest,
490
+ version: JSON_FEED_VERSION,
491
+ home_page_url: this.#session.me,
492
+ feed_url: this.url,
493
+ user_comment: mainComment,
494
+ };
495
+ if (author !== undefined && fixed.authors === undefined)
496
+ fixed.authors = [author];
497
+ if (fixed.next_url !== undefined && this.#archiveNumber(fixed._pups?.archive_url) !== undefined)
498
+ fixed.next_url = fixed._pups.archive_url;
499
+ await this.#session.replace(this.path, serialize(fixed), etag, { contentType: FEED_CONTENT_TYPE, signal });
500
+ return fixed;
501
+ }
502
+ async #writeArchive(archive, items, signal) {
503
+ await this.#session.replace(archive.path, serialize({ ...archive.doc, items }), archive.etag, { contentType: FEED_CONTENT_TYPE, signal });
504
+ }
505
+ /**
506
+ * The items of the feed file: the newest archive items first (which also repairs items an interrupted post wrote
507
+ * only into the archive), then the other items of the feed file, at most `maxItems`, fewer if `maxBytes` is set
508
+ * and exceeded, but at least 10.
509
+ */
510
+ #newestItems(recent, current, doc) {
511
+ const ids = new Set(recent.map(item => item.id));
512
+ const items = [...recent, ...current.filter(item => !ids.has(item.id))].slice(0, this.#maxItems);
513
+ if (this.#maxBytes)
514
+ while (items.length > minFeedItems && byteLength(serialize({ ...doc, items })) > this.#maxBytes)
515
+ items.pop();
516
+ return items;
517
+ }
518
+ // Archives
519
+ #archivePath(n) {
520
+ return `${this.directory}feed.${String(n).padStart(6, '0')}.json`;
521
+ }
522
+ #archiveUrl(n) {
523
+ return this.#session.publicUrl(this.#archivePath(n));
524
+ }
525
+ /** The number of the archive at `url`, or undefined if `url` is not an archive file of this feed. */
526
+ #archiveNumber(url) {
527
+ const path = url && pathFromPublicUrl(this.#session.server, url);
528
+ if (!path?.startsWith(this.directory))
529
+ return;
530
+ const match = /^feed\.(\d{6})\.json$/.exec(path.slice(this.directory.length));
531
+ return match ? Number(match[1]) : undefined;
532
+ }
533
+ /** A new archive with the feed fields of the feed file (RFC-7 "Archives"). */
534
+ #newArchive(n, main, items, nextUrl) {
535
+ const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, ...fields } = main;
536
+ const { archive_url: _archive, ...marker } = _pups ?? {};
537
+ const podcast = fields._podcast;
538
+ if (isObject(podcast) && 'liveItems' in podcast) {
539
+ const { liveItems: _live, ...rest } = podcast;
540
+ fields._podcast = rest;
541
+ }
542
+ return {
543
+ ...fields,
544
+ version: JSON_FEED_VERSION,
545
+ home_page_url: this.#session.me,
546
+ feed_url: this.#archiveUrl(n),
547
+ user_comment: archiveComment(this.url),
548
+ ...nextUrl ? { next_url: nextUrl } : {},
549
+ items,
550
+ _pups: { about: PUPS_FEED_SPEC, ...marker, pupsControlled: true, updates_url: this.url },
551
+ };
552
+ }
553
+ async #createArchive(n, main, items, nextUrl, signal) {
554
+ await this.#session.create(this.#archivePath(n), serialize(this.#newArchive(n, main, items, nextUrl)), { contentType: FEED_CONTENT_TYPE, signal });
555
+ }
556
+ /**
557
+ * Reads an archive for writing.
558
+ * @returns undefined if it doesn't exist, 'foreign' if it exists but is no PUPS archive.
559
+ */
560
+ async #readArchive(path, signal) {
561
+ try {
562
+ const loaded = await this.#read(path, signal);
563
+ return loaded && !isControlled(loaded.doc) ? 'foreign' : loaded;
564
+ }
565
+ catch (e) {
566
+ if (isPupsError(e, 'invalid_feed'))
567
+ return 'foreign';
568
+ throw e;
569
+ }
570
+ }
571
+ /**
572
+ * Puts the items of a feed without archives into new archives of `archiveSize`, oldest first (RFC-7 "Starting the
573
+ * archives"). The oldest archive continues the feed's `next_url` chain.
574
+ * @returns the URL of the newest archive, or undefined if the feed has no items.
575
+ */
576
+ async #startArchives(main, signal) {
577
+ const oldestFirst = [...main.doc.items].reverse();
578
+ let url;
579
+ for (let n = 0; n * this.#archiveSize < oldestFirst.length; n++) {
580
+ const items = oldestFirst.slice(n * this.#archiveSize, (n + 1) * this.#archiveSize).reverse();
581
+ const nextUrl = n ? this.#archiveUrl(n - 1) : main.doc.next_url;
582
+ try {
583
+ await this.#createArchive(n, main.doc, items, nextUrl, signal);
584
+ }
585
+ catch (e) {
586
+ if (!isPupsError(e, 'precondition_failed'))
587
+ throw e;
588
+ // Left behind by an interrupted start: complete it, as long as it holds only these items.
589
+ const existing = await this.#readArchive(this.#archivePath(n), signal);
590
+ const ids = new Set(items.map(item => item.id));
591
+ if (!existing || existing == 'foreign' || !existing.doc.items.every(item => ids.has(item.id)))
592
+ throw new PupsError('conflict', `${this.#archivePath(n)} exists already, but ${this.path} has no archive_url. Remove the file, or set _pups.archive_url (RFC-7, Starting the archives).`);
593
+ await this.#writeArchive(existing, items, signal);
594
+ }
595
+ url = this.#archiveUrl(n);
596
+ }
597
+ return url;
598
+ }
599
+ /**
600
+ * Adds an item to the newest archive, or to a new archive if the newest holds `archiveSize` items (RFC-7
601
+ * "Posting"). Writes only archives; the caller writes the feed file afterwards.
602
+ * @returns the archive's URL, and the newest items known from the archives, newest first.
603
+ */
604
+ async #addToArchive(main, doc, item, signal) {
605
+ const newest = this.#archiveNumber(doc._pups?.archive_url);
606
+ let previous = [];
607
+ if (newest !== undefined) {
608
+ const existing = await this.#readArchive(this.#archivePath(newest), signal);
609
+ if (!existing) {
610
+ // The owner deleted it: create it again, linked to the next older archive.
611
+ await this.#createArchive(newest, doc, [item], newest ? this.#archiveUrl(newest - 1) : undefined, signal);
612
+ return { url: this.#archiveUrl(newest), recent: [item] };
613
+ }
614
+ if (existing != 'foreign') {
615
+ const merged = mergeItems(existing.doc.items, [item]);
616
+ if (merged.length <= this.#archiveSize) {
617
+ await this.#writeArchive(existing, merged, signal);
618
+ return { url: this.#archiveUrl(newest), recent: merged };
619
+ }
620
+ previous = existing.doc.items;
621
+ }
622
+ }
623
+ // The archive before the new one: the newest, or for a feed without archives the end of its old chain.
624
+ const nextUrl = newest === undefined ? doc.next_url : this.#archiveUrl(newest);
625
+ for (let n = newest === undefined ? 0 : newest + 1; n <= maxArchiveNumber; n++) {
626
+ try {
627
+ await this.#createArchive(n, doc, [item], nextUrl, signal);
628
+ return { url: this.#archiveUrl(n), recent: [item, ...previous] };
629
+ }
630
+ catch (e) {
631
+ if (!isPupsError(e, 'precondition_failed'))
632
+ throw e;
633
+ }
634
+ // The archive exists: left behind by an interrupted client, or created by another client just now.
635
+ const existing = await this.#readArchive(this.#archivePath(n), signal);
636
+ if (existing && existing != 'foreign' && existing.doc.next_url == nextUrl) {
637
+ const merged = mergeItems(existing.doc.items, [item]);
638
+ if (merged.length <= this.#archiveSize) {
639
+ await this.#writeArchive(existing, merged, signal);
640
+ return { url: this.#archiveUrl(n), recent: [...merged, ...previous] };
641
+ }
642
+ }
643
+ const current = await this.#session.get(this.path, { signal });
644
+ if (current?.etag != main.etag)
645
+ throw conflict(this.path);
646
+ }
647
+ throw new PupsError('conflict', `No free archive number in ${this.directory}.`);
648
+ }
649
+ // Items and media
650
+ #newItem(input) {
651
+ const { id, markdown, date_published, ...fields } = input;
652
+ if (id !== undefined && (typeof id != 'string' || !id))
653
+ throw new PupsError('invalid_request', 'A post id must be a non-empty string.');
654
+ const item = {
655
+ id: id ?? randomString(12),
656
+ ...fields,
657
+ date_published: date_published instanceof Date ? date_published.toISOString() : date_published ?? now(),
658
+ };
659
+ if (markdown !== undefined)
660
+ this.#setMarkdown(item, markdown);
661
+ if (item.content_html === undefined && item.content_text === undefined)
662
+ throw new PupsError('invalid_request', 'A post needs content_html, content_text or markdown (JSON Feed requires content).');
663
+ return item;
664
+ }
665
+ #applyChanges(item, changes) {
666
+ for (const [key, value] of Object.entries(changes)) {
667
+ if (key == 'id')
668
+ throw new PupsError('invalid_request', 'The id of a post can\'t be changed.');
669
+ if (value === undefined)
670
+ continue;
671
+ if (key == 'markdown') {
672
+ if (value === null) {
673
+ const source = isObject(item._source) ? { ...item._source } : undefined;
674
+ if (source) {
675
+ delete source.markdown;
676
+ item._source = source;
677
+ }
678
+ }
679
+ else
680
+ this.#setMarkdown(item, value);
681
+ }
682
+ else if (value === null)
683
+ delete item[key];
684
+ else
685
+ item[key] = value instanceof Date ? value.toISOString() : value;
686
+ }
687
+ if (item.content_html === undefined && item.content_text === undefined)
688
+ throw new PupsError('invalid_request', 'A post needs content_html or content_text (JSON Feed requires content).');
689
+ return item;
690
+ }
691
+ /** Stores Markdown in `_source.markdown` (RFC-1), with `content_text` as the fallback JSON Feed requires. */
692
+ #setMarkdown(item, markdown) {
693
+ const source = isObject(item._source) ? item._source : {};
694
+ item._source = { about: RFC1_URL, ...source, markdown };
695
+ if (item.content_html === undefined)
696
+ item.content_text = markdown;
697
+ }
698
+ #result(item, fileUrl) {
699
+ return { id: item.id, item, url: `${fileUrl}#${encodeURIComponent(item.id)}` };
700
+ }
701
+ /**
702
+ * The URLs of this feed's media files (not icons, not archives) that an item references. For the main feed, only
703
+ * `/feed/images/` and `/feed/media/`, so that files of named feeds are never taken for its own.
704
+ */
705
+ #mediaUrls(item) {
706
+ const base = this.#session.publicUrl(this.directory);
707
+ const bases = this.name === undefined ? mainMediaFolders.map(folder => `${base}${folder}/`) : [base];
708
+ const icons = `${base}images/icons/`;
709
+ const urls = new Set();
710
+ for (const text of strings(item))
711
+ for (const [url] of text.matchAll(/https?:\/\/[^\s"'<>()]+/g))
712
+ if (bases.some(b => url.startsWith(b)) && !url.startsWith(icons) && this.#archiveNumber(url) === undefined)
713
+ urls.add(url);
714
+ return [...urls];
715
+ }
716
+ #mediaType(media) {
717
+ const blob = typeof Blob != 'undefined' && media instanceof Blob ? media : undefined;
718
+ const given = blob ? undefined : media;
719
+ const nameExtension = blob?.name?.match(/\.([a-z0-9]+)$/i)?.[1];
720
+ const type = blob?.type || given?.type;
721
+ const extension = (given?.extension ?? nameExtension ?? (type ? extensionForType(type) : undefined))?.toLowerCase().replace(/^\./, '');
722
+ const fileType = extension ? fileTypes[extension] : undefined;
723
+ if (!extension || !fileType)
724
+ throw new PupsError('unsupported_type', `Can't tell the file type of the upload${extension ? ` (".${extension}" is not allowed)` : ''}. Pass a Blob with a type, or { body, type } or { body, extension } (RFC-6, File types).`);
725
+ return { type: fileType.served, extension, body: blob ?? given.body };
726
+ }
727
+ async #upload(media, prefix, signal) {
728
+ const { type, extension, body } = this.#mediaType(media);
729
+ const path = `${this.directory}${prefix}${randomString(9)}.${extension}`;
730
+ const result = await this.#session.create(path, body, { signal });
731
+ const size = typeof body == 'string' ? byteLength(body) : body instanceof Blob ? body.size : body.byteLength;
732
+ return { path, url: result.url, type, size };
733
+ }
734
+ async #setImage(field, media, signal) {
735
+ const uploaded = media ? await this.#upload(media, `images/icons/${field}-`, signal) : undefined;
736
+ let old;
737
+ let doc;
738
+ try {
739
+ doc = await this.#transaction(async () => {
740
+ const main = await this.#readControlled(this.path, signal);
741
+ old = main.doc[field];
742
+ const changed = { ...main.doc };
743
+ if (uploaded)
744
+ changed[field] = uploaded.url;
745
+ else
746
+ delete changed[field];
747
+ return this.#writeMain(changed, main.etag, signal);
748
+ });
749
+ }
750
+ catch (e) {
751
+ if (uploaded)
752
+ await this.#deleteQuietly(uploaded.path);
753
+ throw e;
754
+ }
755
+ const oldPath = typeof old == 'string' && old != uploaded?.url ? pathFromPublicUrl(this.#session.server, old) : undefined;
756
+ if (oldPath?.startsWith(`${this.directory}images/icons/`))
757
+ await this.#deleteQuietly(oldPath, signal);
758
+ return doc;
759
+ }
760
+ /** Deletes a file, ignoring a missing one. @returns whether it was deleted. */
761
+ async #deleteQuietly(path, signal) {
762
+ try {
763
+ await this.#session.delete(path, { signal });
764
+ return true;
765
+ }
766
+ catch (e) {
767
+ if (isPupsError(e, 'not_found'))
768
+ return false;
769
+ throw e;
770
+ }
771
+ }
772
+ #checkSettings(settings) {
773
+ for (const key of Object.keys(settings))
774
+ if (reservedFields.has(key))
775
+ throw new PupsError('invalid_request', key == 'icon' || key == 'favicon'
776
+ ? `Set ${key} with ${key == 'icon' ? 'setIcon' : 'setFavicon'}(), which stores it in images/icons/ (RFC-7, Icons).`
777
+ : `"${key}" is fixed or managed by RFC-7 and can't be set.`);
778
+ else if (!['title', 'description', 'authors', 'language', 'expired'].includes(key) && !key.startsWith('_'))
779
+ throw new PupsError('invalid_request', `"${key}" is not a feed field the owner can set. Use title, description, authors, language, expired or an extension starting with "_".`);
780
+ }
781
+ #checkWritable() {
782
+ if (!this.writable)
783
+ throw new PupsError('insufficient_scope', `Writing ${this.path} needs the scopes ${this.scopes.join(' ')} (RFC-7, Server requirements).`);
784
+ }
785
+ }
786
+ /** The feeds registered in the owner's `host-meta.json` (RFC-7 "Registering feeds"). */
787
+ export async function listFeeds(session, options = {}) {
788
+ const document = await session.hostMeta.get(options);
789
+ const links = (document.links ?? []).filter(link => link.rel == FEED_REL && typeof link.href == 'string');
790
+ return links.map(link => {
791
+ const url = link.href;
792
+ const path = pathFromPublicUrl(session.server, url);
793
+ const name = path == '/feed.json' ? null : /^\/feed\/([^/]+)\.json$/.exec(path ?? '')?.[1];
794
+ let feed;
795
+ if (name !== undefined)
796
+ try {
797
+ feed = new PupsFeed(session, name ?? undefined, options);
798
+ }
799
+ catch {
800
+ // Not a valid feed name, e.g. an archive or a link the owner added.
801
+ }
802
+ return { url, ...typeof link.type == 'string' ? { type: link.type } : {}, ...feed ? { feed } : {} };
803
+ });
804
+ }
805
+ //# sourceMappingURL=feed.js.map