pups-client 0.7.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.
- package/README.md +5 -5
- package/dist/discovery.d.ts +5 -0
- package/dist/discovery.d.ts.map +1 -1
- package/dist/discovery.js +1 -0
- package/dist/discovery.js.map +1 -1
- package/dist/errors.js +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/feed.d.ts +38 -70
- package/dist/feed.d.ts.map +1 -1
- package/dist/feed.js +123 -566
- package/dist/feed.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mentions.d.ts.map +1 -1
- package/dist/mentions.js +2 -2
- package/dist/mentions.js.map +1 -1
- package/dist/session.d.ts +11 -0
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +13 -0
- package/dist/session.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/src/discovery.ts +6 -0
- package/src/errors.ts +1 -1
- package/src/feed.ts +128 -598
- package/src/index.ts +0 -1
- package/src/mentions.ts +2 -3
- package/src/session.ts +15 -1
- package/src/version.ts +1 -1
package/dist/feed.js
CHANGED
|
@@ -7,7 +7,7 @@ import { isObject, randomString } from './util.js';
|
|
|
7
7
|
export const FEED_REL = 'https://bigwide.net/ns/feed';
|
|
8
8
|
/**
|
|
9
9
|
* The site property in `host-meta.json` with the URL template of the pages that show single posts, e.g.
|
|
10
|
-
* `https://tim.example/p/{feed}/post/{index}` (RFC-6 "Post URLs"
|
|
10
|
+
* `https://tim.example/p/{feed}/post/{index}` (RFC-6 "Post URLs"). The server fills it into new posts.
|
|
11
11
|
*/
|
|
12
12
|
export const POST_URL_TEMPLATE = 'https://bigwide.net/ns/post-url-template';
|
|
13
13
|
/** The `about` of the `_pups` object: RFC-7. Not its final location; readers must not rely on it. */
|
|
@@ -18,11 +18,6 @@ const RFC1_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-1-Source-for
|
|
|
18
18
|
const RFC4_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-4-Feed-Submissions.md';
|
|
19
19
|
const JSON_FEED_VERSION = 'https://jsonfeed.org/version/1.1';
|
|
20
20
|
const FEED_CONTENT_TYPE = 'application/feed+json';
|
|
21
|
-
const maxArchiveNumber = 999_999;
|
|
22
|
-
/** The feed file keeps at least this many items, also when `maxBytes` is exceeded (RFC-7 "Size in bytes"). */
|
|
23
|
-
const minFeedItems = 10;
|
|
24
|
-
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 _archive.archive_url, all items are in the archives, starting with the one there.`;
|
|
25
|
-
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 _archive.updates_url, older ones are in the archive at next_url.`;
|
|
26
21
|
/** Feed names (RFC-7 "Named feeds"): 1 to 40 lowercase letters, digits and `-`, not starting or ending with `-`. */
|
|
27
22
|
const feedNamePattern = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;
|
|
28
23
|
/** The main feed's media directories in `/feed/`, which therefore can't be feed names. */
|
|
@@ -46,88 +41,16 @@ function feedPaths(name) {
|
|
|
46
41
|
const isFeedDocument = (value) => isObject(value) && typeof value.version == 'string' && value.version.startsWith('https://jsonfeed.org/version/1')
|
|
47
42
|
&& Array.isArray(value.items) && value.items.every(i => isObject(i) && typeof i.id == 'string');
|
|
48
43
|
const isControlled = (doc) => doc._pups?.pupsControlled === true;
|
|
49
|
-
const notControlled = (path) => new PupsError('not_pups_controlled', `${path} is not
|
|
50
|
-
const conflict = (what) => new PupsError('precondition_failed', `${what} changed in the meantime.`);
|
|
44
|
+
const notControlled = (path) => new PupsError('not_pups_controlled', `${path} is not kept by PUPS: 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).`);
|
|
51
45
|
const now = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
52
46
|
const clone = (value) => structuredClone(value);
|
|
53
47
|
const serialize = (doc) => JSON.stringify(doc, null, 2);
|
|
54
48
|
const byteLength = (text) => new TextEncoder().encode(text).length;
|
|
55
|
-
|
|
56
|
-
/** Adds `incoming` items at the top of `existing`; an item whose id is already there replaces the old copy instead. */
|
|
57
|
-
function mergeItems(existing, incoming) {
|
|
58
|
-
const byId = new Map(incoming.map(item => [item.id, item]));
|
|
59
|
-
const present = new Set(existing.map(item => item.id));
|
|
60
|
-
return [...incoming.filter(item => !present.has(item.id)), ...existing.map(item => byId.get(item.id) ?? item)];
|
|
61
|
-
}
|
|
62
|
-
/** The index of an item (RFC-13 "Indexes"), also from `_pups` of earlier drafts, or undefined if it has none. */
|
|
49
|
+
/** The index of an item (RFC-13 "Indexes"), or undefined if it has none. */
|
|
63
50
|
export function itemIndex(item) {
|
|
64
|
-
const index = isObject(item._archive)
|
|
51
|
+
const index = isObject(item._archive) ? item._archive.index : undefined;
|
|
65
52
|
return typeof index == 'number' && Number.isSafeInteger(index) && index >= 0 ? index : undefined;
|
|
66
53
|
}
|
|
67
|
-
const withIndex = (item, index) => ({ ...item, _archive: { ...isObject(item._archive) ? item._archive : {}, index } });
|
|
68
|
-
/** The fields of RFC-13 that earlier drafts of RFC-7 kept in `_pups`. */
|
|
69
|
-
const legacyArchiveFields = ['archive_url', 'updates_url', 'next_index'];
|
|
70
|
-
/**
|
|
71
|
-
* Moves the fields that earlier drafts kept in `_pups` into `_archive` (RFC-13 "Earlier drafts"), in the file and its
|
|
72
|
-
* items, where `_archive` doesn't have them already. Changes `doc`.
|
|
73
|
-
*/
|
|
74
|
-
function upgradeArchiveFields(doc) {
|
|
75
|
-
const move = (from, to, keys) => {
|
|
76
|
-
for (const key of keys)
|
|
77
|
-
if (key in from) {
|
|
78
|
-
if (to[key] === undefined)
|
|
79
|
-
to[key] = from[key];
|
|
80
|
-
delete from[key];
|
|
81
|
-
}
|
|
82
|
-
};
|
|
83
|
-
if (isObject(doc._pups) && legacyArchiveFields.some(key => key in doc._pups)) {
|
|
84
|
-
const archive = { about: ARCHIVE_SPEC, ...isObject(doc._archive) ? doc._archive : {} };
|
|
85
|
-
move(doc._pups, archive, legacyArchiveFields);
|
|
86
|
-
doc._archive = archive;
|
|
87
|
-
}
|
|
88
|
-
for (const item of doc.items)
|
|
89
|
-
if (isObject(item._pups) && 'index' in item._pups) {
|
|
90
|
-
const archive = isObject(item._archive) ? item._archive : {};
|
|
91
|
-
move(item._pups, archive, ['index']);
|
|
92
|
-
item._archive = archive;
|
|
93
|
-
if (!Object.keys(item._pups).length)
|
|
94
|
-
delete item._pups;
|
|
95
|
-
}
|
|
96
|
-
return doc;
|
|
97
|
-
}
|
|
98
|
-
/** A post URL template (RFC-6 "Post URLs"): an https URL with `{index}` or `{id}`. */
|
|
99
|
-
function validTemplate(template) {
|
|
100
|
-
if (typeof template != 'string' || !/\{(index|id)\}/.test(template))
|
|
101
|
-
return false;
|
|
102
|
-
try {
|
|
103
|
-
return new URL(template.replace(/\{(feed|index|id)\}/g, 'x')).protocol == 'https:';
|
|
104
|
-
}
|
|
105
|
-
catch {
|
|
106
|
-
return false;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
/** The counter `_archive.next_index` of a file, if it has a valid one. */
|
|
110
|
-
function counterOf(doc) {
|
|
111
|
-
const next = doc._archive?.next_index;
|
|
112
|
-
return typeof next == 'number' && Number.isSafeInteger(next) && next >= 0 ? next : undefined;
|
|
113
|
-
}
|
|
114
|
-
/** The next free index: above every index of `items`, and at least each of `counters`. */
|
|
115
|
-
const nextFree = (items, ...counters) => Math.max(0, ...counters.filter((c) => c !== undefined), ...items.map(item => (itemIndex(item) ?? -1) + 1));
|
|
116
|
-
/**
|
|
117
|
-
* Gives the items without an index (newest first, as in a file) the next indexes from `next`, the oldest first
|
|
118
|
-
* (RFC-7 "Items without an index").
|
|
119
|
-
* @returns the items, and the counter after them.
|
|
120
|
-
*/
|
|
121
|
-
function indexItems(items, next) {
|
|
122
|
-
const result = [...items];
|
|
123
|
-
let changed = false;
|
|
124
|
-
for (let i = result.length - 1; i >= 0; i--)
|
|
125
|
-
if (itemIndex(result[i]) === undefined) {
|
|
126
|
-
result[i] = withIndex(result[i], next++);
|
|
127
|
-
changed = true;
|
|
128
|
-
}
|
|
129
|
-
return { items: result, next, changed };
|
|
130
|
-
}
|
|
131
54
|
/** Every string inside `value`, deeply. */
|
|
132
55
|
function* strings(value) {
|
|
133
56
|
if (typeof value == 'string')
|
|
@@ -145,15 +68,24 @@ function extensionForType(type) {
|
|
|
145
68
|
const entries = Object.entries(fileTypes);
|
|
146
69
|
return entries.find(([, t]) => t.served == essence)?.[0] ?? entries.find(([, t]) => t.accepted.includes(essence))?.[0];
|
|
147
70
|
}
|
|
71
|
+
/** The answer to a POST of an item, checked. */
|
|
72
|
+
function posted(body, path) {
|
|
73
|
+
if (!isObject(body) || !isObject(body.item) || typeof body.item.id != 'string' || typeof body.address != 'string')
|
|
74
|
+
throw new PupsError('server_error', `The server's answer to the POST to ${path} has no item and address (RFC-7, Posting items).`);
|
|
75
|
+
return { item: body.item, address: body.address };
|
|
76
|
+
}
|
|
77
|
+
/** The file part of an item's address. */
|
|
78
|
+
const fileOf = (address) => address.split('#')[0];
|
|
148
79
|
/**
|
|
149
|
-
* A feed on the owner's domain,
|
|
150
|
-
* `/feed/<name>.json`, each with its feed directory for archives, icons and media: `/feed/`, or `/feed/<name>/`.
|
|
80
|
+
* A feed on the owner's domain, kept by the PUPS server according to RFC-7: the main feed `/feed.json`, or a named
|
|
81
|
+
* feed `/feed/<name>.json`, each with its feed directory for archives, icons and media: `/feed/`, or `/feed/<name>/`.
|
|
151
82
|
* The main feed keeps its media in `/feed/images/` and `/feed/media/`, since the rest of `/feed/` belongs to the
|
|
152
83
|
* named feeds.
|
|
153
84
|
*
|
|
154
85
|
* Get one from `session.feed()` or `session.feed('photos')`. The session needs the feed's scopes, see
|
|
155
|
-
* {@link feedScopes}.
|
|
156
|
-
* read-modify-write cycles with ETags, repeated when
|
|
86
|
+
* {@link feedScopes}. Posts are sent to the server one at a time, which gives them their index and puts them into
|
|
87
|
+
* the archives (RFC-13); changes of the feed's settings are read-modify-write cycles with ETags, repeated when
|
|
88
|
+
* another app wrote in between.
|
|
157
89
|
*/
|
|
158
90
|
export class PupsFeed {
|
|
159
91
|
/** The name of a named feed; undefined for the main feed. */
|
|
@@ -163,14 +95,8 @@ export class PupsFeed {
|
|
|
163
95
|
/** The feed directory, e.g. `/feed/` or `/feed/photos/`. */
|
|
164
96
|
directory;
|
|
165
97
|
#session;
|
|
166
|
-
#maxItems;
|
|
167
|
-
#archiveSize;
|
|
168
|
-
#archivesWanted;
|
|
169
|
-
#maxBytes;
|
|
170
98
|
#maxAttempts;
|
|
171
|
-
#postUrls;
|
|
172
99
|
#mentions;
|
|
173
|
-
#template;
|
|
174
100
|
/** @internal Use `session.feed()`. */
|
|
175
101
|
constructor(session, name, options = {}) {
|
|
176
102
|
const { path, directory } = feedPaths(name);
|
|
@@ -178,15 +104,8 @@ export class PupsFeed {
|
|
|
178
104
|
this.path = path;
|
|
179
105
|
this.directory = directory;
|
|
180
106
|
this.#session = session;
|
|
181
|
-
this.#maxItems = options.maxItems ?? 30;
|
|
182
|
-
this.#archiveSize = options.archiveSize ?? 20;
|
|
183
|
-
this.#archivesWanted = options.startArchives ?? true;
|
|
184
|
-
this.#maxBytes = options.maxBytes;
|
|
185
107
|
this.#maxAttempts = options.maxAttempts ?? 8;
|
|
186
|
-
this.#postUrls = options.postUrls ?? true;
|
|
187
108
|
this.#mentions = options.mentions === true ? session.mentions : options.mentions || undefined;
|
|
188
|
-
if (!(this.#archiveSize >= 1 && this.#maxItems >= 1))
|
|
189
|
-
throw new PupsError('invalid_request', 'Feed options: maxItems and archiveSize must be at least 1.');
|
|
190
109
|
}
|
|
191
110
|
/** The public URL of the feed file, its `feed_url`. */
|
|
192
111
|
get url() {
|
|
@@ -198,9 +117,9 @@ export class PupsFeed {
|
|
|
198
117
|
}
|
|
199
118
|
/** Whether the session may write the feed file and the feed directory. */
|
|
200
119
|
get writable() {
|
|
201
|
-
return this.#session.canWrite(this.path) && this.#session.canWrite(this
|
|
120
|
+
return this.#session.canWrite(this.path) && this.#session.canWrite(`${this.directory}images/x`);
|
|
202
121
|
}
|
|
203
|
-
/** Reads the feed file and tells whether it exists, and whether
|
|
122
|
+
/** Reads the feed file and tells whether it exists, and whether the server keeps it. */
|
|
204
123
|
async load(options = {}) {
|
|
205
124
|
try {
|
|
206
125
|
const loaded = await this.#read(this.path, options.signal);
|
|
@@ -215,11 +134,12 @@ export class PupsFeed {
|
|
|
215
134
|
}
|
|
216
135
|
}
|
|
217
136
|
/**
|
|
218
|
-
* Sets up a new feed (RFC-7 "Setting up a feed"): uploads the icons, writes the feed file with the
|
|
219
|
-
* and
|
|
137
|
+
* Sets up a new feed (RFC-7 "Setting up a feed"): uploads the icons, writes the feed file with the `_pups` marker,
|
|
138
|
+
* and registers the feed in `host-meta.json` (unless `register` is false). The server sets the fixed fields.
|
|
220
139
|
* @returns `registered`: false if the feed couldn't be registered; call `register()` again later, or tell the owner
|
|
221
140
|
* to add the link to `host-meta.json` by hand.
|
|
222
|
-
* @throws {PupsError} `precondition_failed` if the feed file exists already; `insufficient_scope
|
|
141
|
+
* @throws {PupsError} `precondition_failed` if the feed file exists already; `insufficient_scope`; `unsupported` if
|
|
142
|
+
* the server doesn't keep feeds.
|
|
223
143
|
*/
|
|
224
144
|
async create(setup, options = {}) {
|
|
225
145
|
const { icon, favicon, title, ...settings } = setup;
|
|
@@ -227,6 +147,7 @@ export class PupsFeed {
|
|
|
227
147
|
throw new PupsError('invalid_request', 'A feed needs a title.');
|
|
228
148
|
this.#checkSettings(settings);
|
|
229
149
|
this.#checkWritable();
|
|
150
|
+
this.#checkKept();
|
|
230
151
|
const uploaded = [];
|
|
231
152
|
try {
|
|
232
153
|
const iconFile = icon && await this.#upload(icon, 'images/icons/icon-', options.signal);
|
|
@@ -239,10 +160,7 @@ export class PupsFeed {
|
|
|
239
160
|
const doc = {
|
|
240
161
|
version: JSON_FEED_VERSION,
|
|
241
162
|
title,
|
|
242
|
-
home_page_url: this.#session.me,
|
|
243
|
-
feed_url: this.url,
|
|
244
163
|
...description === undefined ? {} : { description },
|
|
245
|
-
user_comment: mainComment,
|
|
246
164
|
...iconFile ? { icon: iconFile.url } : {},
|
|
247
165
|
...faviconFile ? { favicon: faviconFile.url } : {},
|
|
248
166
|
...rest,
|
|
@@ -292,16 +210,13 @@ export class PupsFeed {
|
|
|
292
210
|
this.#checkSettings(changes);
|
|
293
211
|
if (changes.title === null || (changes.title !== undefined && !changes.title.trim()))
|
|
294
212
|
throw new PupsError('invalid_request', 'A feed needs a title.');
|
|
295
|
-
return this.#
|
|
296
|
-
const main = await this.#readControlled(this.path, options.signal);
|
|
297
|
-
const doc = { ...main.doc };
|
|
213
|
+
return this.#change(doc => {
|
|
298
214
|
for (const [key, value] of Object.entries(changes))
|
|
299
215
|
if (value === null)
|
|
300
216
|
delete doc[key];
|
|
301
217
|
else if (value !== undefined)
|
|
302
218
|
doc[key] = value;
|
|
303
|
-
|
|
304
|
-
});
|
|
219
|
+
}, options.signal);
|
|
305
220
|
}
|
|
306
221
|
/**
|
|
307
222
|
* Uploads a new icon (512 × 512) to `/feed/images/icons/` (`/feed/<name>/images/icons/` for a named feed) and
|
|
@@ -351,11 +266,12 @@ export class PupsFeed {
|
|
|
351
266
|
return this.#setSubmissions(undefined, options.signal);
|
|
352
267
|
}
|
|
353
268
|
#setSubmissions(submissions, signal) {
|
|
354
|
-
return this.#
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
269
|
+
return this.#change(doc => {
|
|
270
|
+
if (submissions)
|
|
271
|
+
doc._submissions = submissions;
|
|
272
|
+
else
|
|
273
|
+
delete doc._submissions;
|
|
274
|
+
}, signal);
|
|
359
275
|
}
|
|
360
276
|
/**
|
|
361
277
|
* Uploads an image, audio or video file into the feed directory under a new, unique name, by default
|
|
@@ -372,93 +288,34 @@ export class PupsFeed {
|
|
|
372
288
|
return this.#upload(media, `${folder}/${new Date().getUTCFullYear()}/`, options.signal);
|
|
373
289
|
}
|
|
374
290
|
/**
|
|
375
|
-
* Adds a post (RFC-7 "Posting
|
|
376
|
-
*
|
|
377
|
-
*
|
|
378
|
-
* media with `uploadMedia()` before posting.
|
|
379
|
-
* In a feed with archives, a post without `url` gets one from the site's post URL template, if `host-meta.json`
|
|
380
|
-
* has one and `postUrls` isn't false: the page that shows the post (RFC-7 "Post URLs").
|
|
291
|
+
* Adds a post (RFC-7 "Posting items"): sends it to the server, which gives it its index, puts it into the newest
|
|
292
|
+
* archive and at the top of the feed file, and, if the site declares a post URL template, gives it the `url` of
|
|
293
|
+
* its page. Upload media with `uploadMedia()` before posting.
|
|
381
294
|
* With the option `mentions`, the domains the post names and the author of the item it answers are notified
|
|
382
295
|
* (RFC-11) once the post is visible; see `PostResult.mentions`.
|
|
383
|
-
* @returns the post, with `url`: its
|
|
384
|
-
*
|
|
385
|
-
*
|
|
296
|
+
* @returns the post as stored, with `url`: its address, which never changes. The post's page, if it has one, is
|
|
297
|
+
* `item.url`.
|
|
298
|
+
* @throws {PupsError} `not_found` if the feed doesn't exist; `not_pups_controlled`; `unsupported` if the server
|
|
299
|
+
* doesn't keep feeds.
|
|
386
300
|
*/
|
|
387
301
|
async addPost(input, options = {}) {
|
|
388
|
-
const item = this.#newItem(input);
|
|
389
|
-
|
|
390
|
-
let archiveUrl = '';
|
|
391
|
-
let stored = item;
|
|
392
|
-
let firstAttempt = true;
|
|
393
|
-
await this.#transaction(async () => {
|
|
394
|
-
const main = await this.#readControlled(this.path, signal);
|
|
395
|
-
// On a retry, the item may be in the feed file already: another client repaired it from the archive.
|
|
396
|
-
if (firstAttempt && main.doc.items.some(i => i.id == item.id))
|
|
397
|
-
throw new PupsError('invalid_request', `The feed already has an item with the id "${item.id}".`);
|
|
398
|
-
firstAttempt = false;
|
|
399
|
-
const doc = { ...main.doc, _archive: { ...main.doc._archive } };
|
|
400
|
-
const hasArchives = this.#archiveNumber(doc._archive.archive_url) !== undefined;
|
|
401
|
-
if (!hasArchives && !this.#archivesWanted) {
|
|
402
|
-
// A feed without archives: the feed file is all there is, and holds the counter (RFC-7 "Posting").
|
|
403
|
-
archiveUrl = this.url;
|
|
404
|
-
const indexed = indexItems(doc.items, nextFree(doc.items, counterOf(doc)));
|
|
405
|
-
stored = withIndex(item, indexed.next);
|
|
406
|
-
doc._archive.next_index = indexed.next + 1;
|
|
407
|
-
await this.#writeMain({ ...doc, items: this.#newestItems([stored], indexed.items, doc) }, main.etag, signal);
|
|
408
|
-
return;
|
|
409
|
-
}
|
|
410
|
-
if (!hasArchives) {
|
|
411
|
-
const started = await this.#startArchives(main, signal);
|
|
412
|
-
if (started) {
|
|
413
|
-
doc._archive.archive_url = started.url;
|
|
414
|
-
doc.items = started.items;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
const template = await this.#postUrlTemplate(signal);
|
|
418
|
-
const added = await this.#addToArchive(main, doc, item, signal, template);
|
|
419
|
-
archiveUrl = added.url;
|
|
420
|
-
stored = added.item;
|
|
421
|
-
doc._archive.archive_url = added.url;
|
|
422
|
-
if (!hasArchives) {
|
|
423
|
-
// The old chain of a handed-over feed now continues behind the oldest archive, and the newest archive
|
|
424
|
-
// holds the counter.
|
|
425
|
-
delete doc.next_url;
|
|
426
|
-
delete doc._archive.next_index;
|
|
427
|
-
}
|
|
428
|
-
doc.items = this.#newestItems(added.recent, doc.items, doc);
|
|
429
|
-
await this.#writeMain(doc, main.etag, signal);
|
|
430
|
-
});
|
|
431
|
-
return this.#withMentions(options.mentions, this.#result(stored, archiveUrl), archiveUrl, stored, undefined, item => !!item);
|
|
302
|
+
const { item, address } = await this.#post(this.#newItem(input), options.signal);
|
|
303
|
+
return this.#withMentions(options.mentions, this.#result(item, address), fileOf(address), item, undefined, found => !!found);
|
|
432
304
|
}
|
|
433
305
|
/**
|
|
434
|
-
*
|
|
435
|
-
* `addPost()` does this by itself before the first post to a feed that hasn't been indexed yet; call it to
|
|
436
|
-
* index a feed without posting.
|
|
437
|
-
*/
|
|
438
|
-
async assignIndexes(options = {}) {
|
|
439
|
-
const signal = options.signal;
|
|
440
|
-
await this.#transaction(async () => {
|
|
441
|
-
const main = await this.#readControlled(this.path, signal);
|
|
442
|
-
const newest = this.#archiveNumber(main.doc._archive?.archive_url);
|
|
443
|
-
if (newest === undefined) {
|
|
444
|
-
const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)));
|
|
445
|
-
if (indexed.changed || counterOf(main.doc) !== indexed.next)
|
|
446
|
-
await this.#writeMain({ ...main.doc, items: indexed.items, _archive: { ...main.doc._archive, next_index: indexed.next } }, main.etag, signal);
|
|
447
|
-
return;
|
|
448
|
-
}
|
|
449
|
-
const archive = await this.#readArchive(this.#archivePath(newest), signal);
|
|
450
|
-
if (archive && archive != 'foreign' && (counterOf(archive.doc) === undefined || archive.doc.items.some(item => itemIndex(item) === undefined)))
|
|
451
|
-
await this.#indexArchives(main, signal);
|
|
452
|
-
});
|
|
453
|
-
}
|
|
454
|
-
/**
|
|
455
|
-
* Finds a post by id in the archives (or, for a handed-over feed without archives yet, in the feed file).
|
|
306
|
+
* Finds a post by id in the archives.
|
|
456
307
|
* @returns undefined if there is no such post.
|
|
457
308
|
*/
|
|
458
309
|
async getPost(id, options = {}) {
|
|
459
310
|
const main = await this.#read(this.path, options.signal);
|
|
460
|
-
|
|
461
|
-
|
|
311
|
+
if (!main)
|
|
312
|
+
return;
|
|
313
|
+
for await (const file of this.#chain(main, options.signal)) {
|
|
314
|
+
const item = file.doc.items.find(i => i.id == id);
|
|
315
|
+
if (item)
|
|
316
|
+
return this.#result(item, `${this.#session.publicUrl(file.path)}#${encodeURIComponent(id)}`);
|
|
317
|
+
}
|
|
318
|
+
return;
|
|
462
319
|
}
|
|
463
320
|
/**
|
|
464
321
|
* All posts, newest first: the archives from `_archive.archive_url` along `next_url` (for a feed without archives,
|
|
@@ -477,75 +334,39 @@ export class PupsFeed {
|
|
|
477
334
|
}
|
|
478
335
|
}
|
|
479
336
|
/**
|
|
480
|
-
* Edits a post
|
|
481
|
-
*
|
|
482
|
-
* a function that gets a copy of the item and returns the new item, or
|
|
483
|
-
*
|
|
337
|
+
* Edits a post (RFC-7 "Posting items"): reads it from its archive, applies `changes`, and sends it to the server,
|
|
338
|
+
* which replaces it in its archive and in the feed file and sets `date_modified`. `changes` is either an object (a
|
|
339
|
+
* value sets a field, `null` removes it), or a function that gets a copy of the item and returns the new item, or
|
|
340
|
+
* `undefined` to leave it unchanged. The post keeps its id and index.
|
|
484
341
|
*
|
|
485
342
|
* Apps should edit posts only when the owner asks them to, whichever app created them. With the option
|
|
486
|
-
* `mentions`, everyone the old or the new version mentions is notified.
|
|
487
|
-
* archives that has no `url`, and had none before, gets one from the post URL template, as in `addPost()`.
|
|
343
|
+
* `mentions`, everyone the old or the new version mentions is notified.
|
|
488
344
|
* @throws {PupsError} `not_found`
|
|
489
345
|
*/
|
|
490
346
|
async editPost(id, changes, options = {}) {
|
|
491
347
|
const signal = options.signal;
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
// The index never changes (RFC-7 "Indexes").
|
|
504
|
-
if (oldIndex !== undefined)
|
|
505
|
-
item = withIndex(item, oldIndex);
|
|
506
|
-
// A post of a feed with archives that never had a url may get one (RFC-7 "Post URLs").
|
|
507
|
-
if (oldIndex !== undefined && !old.url && !item.url && this.#archiveNumber(main.doc._archive?.archive_url) !== undefined)
|
|
508
|
-
item = this.#withPostUrl(item, oldIndex, await this.#postUrlTemplate(signal));
|
|
509
|
-
if (file != main)
|
|
510
|
-
await this.#writeArchive(file, replaceAt(file.doc.items, index, item), signal);
|
|
511
|
-
const mainIndex = main.doc.items.findIndex(i => i.id == id);
|
|
512
|
-
if (mainIndex >= 0)
|
|
513
|
-
await this.#writeMain({ ...main.doc, items: replaceAt(main.doc.items, mainIndex, item) }, main.etag, signal);
|
|
514
|
-
edit = { old, item, fileUrl };
|
|
515
|
-
return this.#result(item, fileUrl);
|
|
516
|
-
});
|
|
517
|
-
const done = edit;
|
|
518
|
-
return done ? this.#withMentions(options.mentions, result, done.fileUrl, done.item, done.old, found => found?.date_modified == done.item.date_modified) : result;
|
|
348
|
+
const current = await this.getPost(id, options);
|
|
349
|
+
if (!current)
|
|
350
|
+
throw new PupsError('not_found', `There is no post with the id "${id}" in ${this.path} or its archives.`);
|
|
351
|
+
const old = current.item;
|
|
352
|
+
const changed = typeof changes == 'function' ? await changes(clone(old)) : this.#applyChanges(clone(old), changes);
|
|
353
|
+
if (!changed)
|
|
354
|
+
return current;
|
|
355
|
+
// The index names the post for the server (RFC-7 "Posting items"), and never changes.
|
|
356
|
+
const { _pups: _marker, ...rest } = changed;
|
|
357
|
+
const { item, address } = await this.#post({ ...rest, id, _archive: { ...isObject(rest._archive) ? rest._archive : {}, ...old._archive } }, signal);
|
|
358
|
+
return this.#withMentions(options.mentions, this.#result(item, address), fileOf(address), item, old, found => found?.date_modified == item.date_modified);
|
|
519
359
|
}
|
|
520
360
|
/**
|
|
521
|
-
* Deletes a post from its archive and from the feed file, which
|
|
522
|
-
* from the archives. With `deleteMedia`, it also deletes the files in the feed directory that the
|
|
523
|
-
* and no other post does; this reads all archives.
|
|
361
|
+
* Deletes a post (RFC-7 "Posting items"): the server removes it from its archive and from the feed file, which it
|
|
362
|
+
* fills up again from the archives. With `deleteMedia`, it also deletes the files in the feed directory that the
|
|
363
|
+
* post references and no other post does; this reads all archives.
|
|
524
364
|
* @returns the deleted item, and the public URLs of the deleted media files.
|
|
525
365
|
* @throws {PupsError} `not_found`
|
|
526
366
|
*/
|
|
527
367
|
async deletePost(id, options = {}) {
|
|
528
368
|
const signal = options.signal;
|
|
529
|
-
|
|
530
|
-
const item = await this.#transaction(async () => {
|
|
531
|
-
const { main, file, index } = await this.#findWritable(id, signal);
|
|
532
|
-
fileUrl = this.#session.publicUrl(file.path);
|
|
533
|
-
const item = file.doc.items[index];
|
|
534
|
-
if (file != main) {
|
|
535
|
-
await this.#writeArchive(file, file.doc.items.filter(i => i.id != id), signal);
|
|
536
|
-
// Fill the feed file up again from the archives, which no longer contain the item.
|
|
537
|
-
const newest = [];
|
|
538
|
-
for await (const archive of this.#chain(main, signal)) {
|
|
539
|
-
newest.push(...archive.doc.items.filter(i => i.id != id));
|
|
540
|
-
if (newest.length >= this.#maxItems)
|
|
541
|
-
break;
|
|
542
|
-
}
|
|
543
|
-
await this.#writeMain({ ...main.doc, items: this.#newestItems(newest, [], main.doc) }, main.etag, signal);
|
|
544
|
-
}
|
|
545
|
-
else
|
|
546
|
-
await this.#writeMain({ ...main.doc, items: main.doc.items.filter(i => i.id != id) }, main.etag, signal);
|
|
547
|
-
return item;
|
|
548
|
-
});
|
|
369
|
+
const { item, address } = await this.#post({ id, _pups: { delete: true } }, signal);
|
|
549
370
|
const deletedMedia = [];
|
|
550
371
|
if (options.deleteMedia) {
|
|
551
372
|
const candidates = new Set(this.#mediaUrls(item));
|
|
@@ -559,7 +380,7 @@ export class PupsFeed {
|
|
|
559
380
|
deletedMedia.push(url);
|
|
560
381
|
}
|
|
561
382
|
}
|
|
562
|
-
const mentions = this.#sendMentions(options.mentions,
|
|
383
|
+
const mentions = this.#sendMentions(options.mentions, fileOf(address), undefined, item, found => !found);
|
|
563
384
|
return { item, deletedMedia, ...mentions ? { mentions } : {} };
|
|
564
385
|
}
|
|
565
386
|
/**
|
|
@@ -575,9 +396,9 @@ export class PupsFeed {
|
|
|
575
396
|
}
|
|
576
397
|
/**
|
|
577
398
|
* Submits a post that answers an item of an RFC-4 feed, e.g. a comment, to that feed's `_submissions.url`
|
|
578
|
-
* (RFC-4 "Submitting"): `source` is the post's
|
|
579
|
-
*
|
|
580
|
-
*
|
|
399
|
+
* (RFC-4 "Submitting"): `source` is the post's address, `target` its `_source.inReplyTo`. Call it after `addPost()`
|
|
400
|
+
* or `editPost()`, also to submit an edit or a delete again. Show the target's terms of service and what its
|
|
401
|
+
* `republish` means before the first submission.
|
|
581
402
|
* @throws {PupsError} `not_found`; `invalid_request` if the post answers nothing; `unsupported` if the target
|
|
582
403
|
* feed takes no submissions.
|
|
583
404
|
* @deprecated Comments and group posts don't belong in a feed for readers (RFC-7 "Comment feeds"). Use
|
|
@@ -652,21 +473,12 @@ export class PupsFeed {
|
|
|
652
473
|
}
|
|
653
474
|
if (!isFeedDocument(doc))
|
|
654
475
|
throw new PupsError('invalid_feed', `${path} is not a JSON Feed.`);
|
|
655
|
-
return { path, doc
|
|
656
|
-
}
|
|
657
|
-
/** Reads a file that must exist and carry the `_pups` marker. */
|
|
658
|
-
async #readControlled(path, signal) {
|
|
659
|
-
const loaded = await this.#read(path, signal);
|
|
660
|
-
if (!loaded)
|
|
661
|
-
throw new PupsError('not_found', path == this.path ? `There is no feed at ${path} yet. Set it up with create().` : `${path} doesn't exist.`);
|
|
662
|
-
if (!isControlled(loaded.doc))
|
|
663
|
-
throw notControlled(path);
|
|
664
|
-
return loaded;
|
|
476
|
+
return { path, doc, etag: file.etag };
|
|
665
477
|
}
|
|
666
478
|
/**
|
|
667
479
|
* The files that hold all items: the archives from `_archive.archive_url` along `next_url`, as far as they are files
|
|
668
|
-
* on this server. A feed without archives
|
|
669
|
-
*
|
|
480
|
+
* on this server. A feed without archives (handed over, not written yet) holds its items in the feed file and the
|
|
481
|
+
* pages its `next_url` names.
|
|
670
482
|
*/
|
|
671
483
|
async *#chain(main, signal) {
|
|
672
484
|
const visited = new Set([main.path]);
|
|
@@ -697,308 +509,54 @@ export class PupsFeed {
|
|
|
697
509
|
yield file;
|
|
698
510
|
}
|
|
699
511
|
}
|
|
700
|
-
async #find(main, id, signal) {
|
|
701
|
-
for await (const file of this.#chain(main, signal)) {
|
|
702
|
-
const index = file.doc.items.findIndex(item => item.id == id);
|
|
703
|
-
if (index >= 0)
|
|
704
|
-
return { main, file, index };
|
|
705
|
-
}
|
|
706
|
-
return;
|
|
707
|
-
}
|
|
708
|
-
async #findWritable(id, signal) {
|
|
709
|
-
const main = await this.#readControlled(this.path, signal);
|
|
710
|
-
const found = await this.#find(main, id, signal);
|
|
711
|
-
if (!found)
|
|
712
|
-
throw new PupsError('not_found', `There is no post with the id "${id}" in ${this.path} or its archives.`);
|
|
713
|
-
if (!isControlled(found.file.doc))
|
|
714
|
-
throw notControlled(found.file.path);
|
|
715
|
-
return found;
|
|
716
|
-
}
|
|
717
512
|
// Writing
|
|
718
|
-
/**
|
|
719
|
-
async #
|
|
720
|
-
|
|
721
|
-
try {
|
|
722
|
-
return await operation();
|
|
723
|
-
}
|
|
724
|
-
catch (e) {
|
|
725
|
-
if (!isPupsError(e, 'precondition_failed') || attempt >= this.#maxAttempts)
|
|
726
|
-
throw e;
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
/**
|
|
730
|
-
* Writes the feed file. Sets the fixed fields, so that a feed the owner handed over gets them on its first write,
|
|
731
|
-
* and upgrades JSON Feed 1.0 (RFC-7 "Handing over an existing feed"). A feed with archives gets the archive template
|
|
732
|
-
* and size of RFC-13, and its optional `next_url` is kept equal to `archive_url` (RFC-7 "Reading").
|
|
733
|
-
*/
|
|
734
|
-
async #writeMain(doc, etag, signal) {
|
|
735
|
-
const { author, ...rest } = doc;
|
|
736
|
-
const fixed = {
|
|
737
|
-
...rest,
|
|
738
|
-
version: JSON_FEED_VERSION,
|
|
739
|
-
home_page_url: this.#session.me,
|
|
740
|
-
feed_url: this.url,
|
|
741
|
-
user_comment: mainComment,
|
|
742
|
-
};
|
|
743
|
-
if (author !== undefined && fixed.authors === undefined)
|
|
744
|
-
fixed.authors = [author];
|
|
745
|
-
const archiveUrl = fixed._archive?.archive_url;
|
|
746
|
-
if (fixed._archive)
|
|
747
|
-
fixed._archive = { about: ARCHIVE_SPEC, ...fixed._archive };
|
|
748
|
-
if (this.#archiveNumber(archiveUrl) !== undefined) {
|
|
749
|
-
fixed._archive = { ...fixed._archive, archive_template: this.#archiveTemplate(), archive_size: this.#archiveSize };
|
|
750
|
-
if (fixed.next_url !== undefined)
|
|
751
|
-
fixed.next_url = archiveUrl;
|
|
752
|
-
}
|
|
753
|
-
await this.#session.replace(this.path, serialize(fixed), etag, { contentType: FEED_CONTENT_TYPE, signal });
|
|
754
|
-
return fixed;
|
|
755
|
-
}
|
|
756
|
-
/**
|
|
757
|
-
* Writes an archive with `items`, and with the counter `next_index` if given. An archive of an earlier draft gets its
|
|
758
|
-
* `_archive` fields and comment of RFC-13 (`number`, `updates_url`).
|
|
759
|
-
*/
|
|
760
|
-
async #writeArchive(archive, items, signal, nextIndex) {
|
|
761
|
-
const n = this.#archiveNumber(this.#session.publicUrl(archive.path));
|
|
762
|
-
const fields = { about: ARCHIVE_SPEC, ...archive.doc._archive, updates_url: this.url, ...n === undefined ? {} : { number: n } };
|
|
763
|
-
if (nextIndex !== undefined)
|
|
764
|
-
fields.next_index = nextIndex;
|
|
765
|
-
const doc = { ...archive.doc, user_comment: archiveComment(this.url), items, _archive: fields };
|
|
766
|
-
await this.#session.replace(archive.path, serialize(doc), archive.etag, { contentType: FEED_CONTENT_TYPE, signal });
|
|
767
|
-
}
|
|
768
|
-
/**
|
|
769
|
-
* The items of the feed file: the newest archive items first (which also repairs items an interrupted post wrote
|
|
770
|
-
* only into the archive), then the other items of the feed file, at most `maxItems`, fewer if `maxBytes` is set
|
|
771
|
-
* and exceeded, but at least 10.
|
|
772
|
-
*/
|
|
773
|
-
#newestItems(recent, current, doc) {
|
|
774
|
-
const ids = new Set(recent.map(item => item.id));
|
|
775
|
-
const items = [...recent, ...current.filter(item => !ids.has(item.id))].slice(0, this.#maxItems);
|
|
776
|
-
if (this.#maxBytes)
|
|
777
|
-
while (items.length > minFeedItems && byteLength(serialize({ ...doc, items })) > this.#maxBytes)
|
|
778
|
-
items.pop();
|
|
779
|
-
return items;
|
|
780
|
-
}
|
|
781
|
-
// Archives
|
|
782
|
-
#archivePath(n) {
|
|
783
|
-
return `${this.directory}feed.${String(n).padStart(6, '0')}.json`;
|
|
784
|
-
}
|
|
785
|
-
#archiveUrl(n) {
|
|
786
|
-
return this.#session.publicUrl(this.#archivePath(n));
|
|
787
|
-
}
|
|
788
|
-
/** `_archive.archive_template` (RFC-13): the archive URL with `{number}` for the number. */
|
|
789
|
-
#archiveTemplate() {
|
|
790
|
-
return this.#archiveUrl(0).replace(/000000\.json$/, '{number}.json');
|
|
791
|
-
}
|
|
792
|
-
/** The number of the archive at `url`, or undefined if `url` is not an archive file of this feed. */
|
|
793
|
-
#archiveNumber(url) {
|
|
794
|
-
const path = url && pathFromPublicUrl(this.#session.server, url);
|
|
795
|
-
if (!path?.startsWith(this.directory))
|
|
796
|
-
return;
|
|
797
|
-
const match = /^feed\.(\d{6})\.json$/.exec(path.slice(this.directory.length));
|
|
798
|
-
return match ? Number(match[1]) : undefined;
|
|
799
|
-
}
|
|
800
|
-
/**
|
|
801
|
-
* A new archive with the feed fields of the feed file (RFC-13 "Feed fields of an archive"), except `_submissions`:
|
|
802
|
-
* whether a feed accepts comments is said by its feed file alone.
|
|
803
|
-
*/
|
|
804
|
-
#newArchive(n, main, items, nextUrl, nextIndex) {
|
|
805
|
-
const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, _archive, _submissions: _s, ...fields } = main;
|
|
806
|
-
const podcast = fields._podcast;
|
|
807
|
-
if (isObject(podcast) && 'liveItems' in podcast) {
|
|
808
|
-
const { liveItems: _live, ...rest } = podcast;
|
|
809
|
-
fields._podcast = rest;
|
|
810
|
-
}
|
|
811
|
-
return {
|
|
812
|
-
...fields,
|
|
813
|
-
version: JSON_FEED_VERSION,
|
|
814
|
-
home_page_url: this.#session.me,
|
|
815
|
-
feed_url: this.#archiveUrl(n),
|
|
816
|
-
user_comment: archiveComment(this.url),
|
|
817
|
-
...nextUrl ? { next_url: nextUrl } : {},
|
|
818
|
-
items,
|
|
819
|
-
_pups: { about: PUPS_FEED_SPEC, ..._pups, pupsControlled: true },
|
|
820
|
-
_archive: { about: ARCHIVE_SPEC, updates_url: this.url, number: n, ...nextIndex === undefined ? {} : { next_index: nextIndex } },
|
|
821
|
-
};
|
|
822
|
-
}
|
|
823
|
-
async #createArchive(n, main, items, nextUrl, signal, nextIndex) {
|
|
824
|
-
await this.#session.create(this.#archivePath(n), serialize(this.#newArchive(n, main, items, nextUrl, nextIndex)), { contentType: FEED_CONTENT_TYPE, signal });
|
|
825
|
-
}
|
|
826
|
-
/**
|
|
827
|
-
* Reads an archive for writing.
|
|
828
|
-
* @returns undefined if it doesn't exist, 'foreign' if it exists but is no PUPS archive.
|
|
829
|
-
*/
|
|
830
|
-
async #readArchive(path, signal) {
|
|
513
|
+
/** Sends an item to the server (RFC-7 "Posting items"). */
|
|
514
|
+
async #post(item, signal) {
|
|
515
|
+
this.#checkKept();
|
|
831
516
|
try {
|
|
832
|
-
|
|
833
|
-
return loaded && !isControlled(loaded.doc) ? 'foreign' : loaded;
|
|
517
|
+
return posted((await this.#session.post(this.path, item, { signal })).body, this.path);
|
|
834
518
|
}
|
|
835
519
|
catch (e) {
|
|
836
|
-
if (isPupsError(e, '
|
|
837
|
-
|
|
520
|
+
if (isPupsError(e, 'not_pups_controlled'))
|
|
521
|
+
throw notControlled(this.path);
|
|
522
|
+
if (isPupsError(e, 'not_found') && !await this.#session.get(this.path, { signal }))
|
|
523
|
+
throw new PupsError('not_found', `There is no feed at ${this.path} yet. Set it up with create().`, { cause: e });
|
|
838
524
|
throw e;
|
|
839
525
|
}
|
|
840
526
|
}
|
|
841
527
|
/**
|
|
842
|
-
*
|
|
843
|
-
*
|
|
844
|
-
* feed
|
|
845
|
-
* @returns the URL of the newest archive and the feed's items with their indexes, or undefined if the feed has no
|
|
846
|
-
* items.
|
|
528
|
+
* Changes the feed file's fields with `change` and writes it with `If-Match`; reads it again and repeats when
|
|
529
|
+
* someone else wrote in between, up to `maxAttempts` times. The server keeps the items and the archive fields.
|
|
530
|
+
* @returns the feed as written.
|
|
847
531
|
*/
|
|
848
|
-
async #
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
const
|
|
856
|
-
|
|
532
|
+
async #change(change, signal) {
|
|
533
|
+
for (let attempt = 1;; attempt++) {
|
|
534
|
+
const main = await this.#read(this.path, signal);
|
|
535
|
+
if (!main)
|
|
536
|
+
throw new PupsError('not_found', `There is no feed at ${this.path} yet. Set it up with create().`);
|
|
537
|
+
if (!isControlled(main.doc))
|
|
538
|
+
throw notControlled(this.path);
|
|
539
|
+
const doc = clone(main.doc);
|
|
540
|
+
change(doc);
|
|
857
541
|
try {
|
|
858
|
-
await this.#
|
|
542
|
+
await this.#session.replace(this.path, serialize(doc), main.etag, { contentType: FEED_CONTENT_TYPE, signal });
|
|
543
|
+
return doc;
|
|
859
544
|
}
|
|
860
545
|
catch (e) {
|
|
861
|
-
if (!isPupsError(e, 'precondition_failed'))
|
|
546
|
+
if (!isPupsError(e, 'precondition_failed') || attempt >= this.#maxAttempts)
|
|
862
547
|
throw e;
|
|
863
|
-
// Left behind by an interrupted start: complete it, as long as it holds only these items.
|
|
864
|
-
const existing = await this.#readArchive(this.#archivePath(n), signal);
|
|
865
|
-
const ids = new Set(items.map(item => item.id));
|
|
866
|
-
if (!existing || existing == 'foreign' || !existing.doc.items.every(item => ids.has(item.id)))
|
|
867
|
-
throw new PupsError('conflict', `${this.#archivePath(n)} exists already, but ${this.path} has no archive_url. Remove the file, or set _archive.archive_url (RFC-7, Starting the archives).`);
|
|
868
|
-
await this.#writeArchive(existing, items, signal, nextIndex);
|
|
869
548
|
}
|
|
870
|
-
url = this.#archiveUrl(n);
|
|
871
549
|
}
|
|
872
|
-
return url ? { url, items: indexed.items } : undefined;
|
|
873
550
|
}
|
|
874
|
-
/**
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
*/
|
|
879
|
-
async #indexArchives(main, signal) {
|
|
880
|
-
const files = [];
|
|
881
|
-
for await (const file of this.#chain(main, signal)) {
|
|
882
|
-
// Pages behind the oldest archive of a handed-over feed are never written, and keep their items unindexed.
|
|
883
|
-
if (file == main || !isControlled(file.doc))
|
|
884
|
-
break;
|
|
885
|
-
files.push(file);
|
|
886
|
-
}
|
|
887
|
-
if (!files.length)
|
|
551
|
+
/** The number of the archive at `url`, or undefined if `url` is not an archive file of this feed. */
|
|
552
|
+
#archiveNumber(url) {
|
|
553
|
+
const path = url && pathFromPublicUrl(this.#session.server, url);
|
|
554
|
+
if (!path?.startsWith(this.directory))
|
|
888
555
|
return;
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
for (const file of [...files].reverse()) {
|
|
892
|
-
const indexed = indexItems(file.doc.items, next);
|
|
893
|
-
next = indexed.next;
|
|
894
|
-
for (const item of indexed.items)
|
|
895
|
-
indexes.set(item.id, itemIndex(item));
|
|
896
|
-
const newest = file == files[0];
|
|
897
|
-
if (indexed.changed || (newest && counterOf(file.doc) !== next))
|
|
898
|
-
await this.#writeArchive(file, indexed.items, signal, newest ? next : undefined);
|
|
899
|
-
}
|
|
900
|
-
let changed = false;
|
|
901
|
-
const items = main.doc.items.map(item => {
|
|
902
|
-
const index = indexes.get(item.id);
|
|
903
|
-
if (index === undefined || itemIndex(item) === index)
|
|
904
|
-
return item;
|
|
905
|
-
changed = true;
|
|
906
|
-
return withIndex(item, index);
|
|
907
|
-
});
|
|
908
|
-
if (changed)
|
|
909
|
-
await this.#writeMain({ ...main.doc, items }, main.etag, signal);
|
|
910
|
-
}
|
|
911
|
-
/**
|
|
912
|
-
* Adds an item to the newest archive, or to a new archive if the newest holds `archiveSize` items (RFC-7
|
|
913
|
-
* "Posting"). Writes only archives; the caller writes the feed file afterwards.
|
|
914
|
-
* The item gets its index from the archive's counter (RFC-7 "Indexes"); a newest archive without a counter is
|
|
915
|
-
* indexed first, and the post then starts again.
|
|
916
|
-
* @returns the archive's URL, the newest items known from the archives, newest first, and the item as stored.
|
|
917
|
-
*/
|
|
918
|
-
async #addToArchive(main, doc, item, signal, template) {
|
|
919
|
-
const place = (index) => this.#withPostUrl(withIndex(item, index), index, template);
|
|
920
|
-
const newest = this.#archiveNumber(doc._archive?.archive_url);
|
|
921
|
-
let previous = [];
|
|
922
|
-
// The index for the item if it goes into a new archive.
|
|
923
|
-
let next = nextFree(doc.items, newest === undefined ? counterOf(doc) : undefined);
|
|
924
|
-
if (newest !== undefined) {
|
|
925
|
-
const existing = await this.#readArchive(this.#archivePath(newest), signal);
|
|
926
|
-
if (!existing) {
|
|
927
|
-
// The owner deleted it: create it again, linked to the next older archive, with an index above all known ones.
|
|
928
|
-
const before = newest ? await this.#readArchive(this.#archivePath(newest - 1), signal) : undefined;
|
|
929
|
-
if (before && before != 'foreign')
|
|
930
|
-
next = nextFree([...doc.items, ...before.doc.items], counterOf(before.doc));
|
|
931
|
-
const stored = place(next);
|
|
932
|
-
await this.#createArchive(newest, doc, [stored], newest ? this.#archiveUrl(newest - 1) : undefined, signal, next + 1);
|
|
933
|
-
return { url: this.#archiveUrl(newest), recent: [stored], item: stored };
|
|
934
|
-
}
|
|
935
|
-
if (existing != 'foreign') {
|
|
936
|
-
if (counterOf(existing.doc) === undefined) {
|
|
937
|
-
await this.#indexArchives(main, signal);
|
|
938
|
-
throw conflict(`${this.path} was indexed, so it`);
|
|
939
|
-
}
|
|
940
|
-
// Items that a client without indexes added get theirs first (RFC-7 "Items without an index").
|
|
941
|
-
const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc)));
|
|
942
|
-
const copy = indexed.items.find(i => i.id == item.id);
|
|
943
|
-
const stored = place(copy ? itemIndex(copy) : indexed.next);
|
|
944
|
-
const merged = mergeItems(indexed.items, [stored]);
|
|
945
|
-
if (merged.length <= this.#archiveSize) {
|
|
946
|
-
await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1);
|
|
947
|
-
return { url: this.#archiveUrl(newest), recent: merged, item: stored };
|
|
948
|
-
}
|
|
949
|
-
if (indexed.changed)
|
|
950
|
-
await this.#writeArchive(existing, indexed.items, signal, indexed.next);
|
|
951
|
-
previous = indexed.items;
|
|
952
|
-
next = indexed.next;
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
// The archive before the new one: the newest, or for a feed without archives the end of its old chain.
|
|
956
|
-
const nextUrl = newest === undefined ? doc.next_url : this.#archiveUrl(newest);
|
|
957
|
-
for (let n = newest === undefined ? 0 : newest + 1; n <= maxArchiveNumber; n++) {
|
|
958
|
-
const stored = place(next);
|
|
959
|
-
try {
|
|
960
|
-
await this.#createArchive(n, doc, [stored], nextUrl, signal, next + 1);
|
|
961
|
-
return { url: this.#archiveUrl(n), recent: [stored, ...previous], item: stored };
|
|
962
|
-
}
|
|
963
|
-
catch (e) {
|
|
964
|
-
if (!isPupsError(e, 'precondition_failed'))
|
|
965
|
-
throw e;
|
|
966
|
-
}
|
|
967
|
-
// The archive exists: left behind by an interrupted client, or created by another client just now.
|
|
968
|
-
const existing = await this.#readArchive(this.#archivePath(n), signal);
|
|
969
|
-
if (existing && existing != 'foreign' && existing.doc.next_url == nextUrl) {
|
|
970
|
-
const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc), next));
|
|
971
|
-
const copy = indexed.items.find(i => i.id == item.id);
|
|
972
|
-
const added = place(copy ? itemIndex(copy) : indexed.next);
|
|
973
|
-
const merged = mergeItems(indexed.items, [added]);
|
|
974
|
-
if (merged.length <= this.#archiveSize) {
|
|
975
|
-
await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1);
|
|
976
|
-
return { url: this.#archiveUrl(n), recent: [...merged, ...previous], item: added };
|
|
977
|
-
}
|
|
978
|
-
}
|
|
979
|
-
const current = await this.#session.get(this.path, { signal });
|
|
980
|
-
if (current?.etag != main.etag)
|
|
981
|
-
throw conflict(this.path);
|
|
982
|
-
}
|
|
983
|
-
throw new PupsError('conflict', `No free archive number in ${this.directory}.`);
|
|
556
|
+
const match = /^feed\.(\d{6,})\.json$/.exec(path.slice(this.directory.length));
|
|
557
|
+
return match ? Number(match[1]) : undefined;
|
|
984
558
|
}
|
|
985
559
|
// Items and media
|
|
986
|
-
/** The site's post URL template from `host-meta.json`, read once; undefined if there is none or it can't be read. */
|
|
987
|
-
#postUrlTemplate(signal) {
|
|
988
|
-
if (!this.#postUrls)
|
|
989
|
-
return Promise.resolve(undefined);
|
|
990
|
-
this.#template ??= this.#session.hostMeta.get({ signal })
|
|
991
|
-
.then(doc => doc.properties?.[POST_URL_TEMPLATE])
|
|
992
|
-
.then(template => validTemplate(template) ? template : undefined, () => undefined);
|
|
993
|
-
return this.#template;
|
|
994
|
-
}
|
|
995
|
-
/** The item with the `url` from the post URL template (RFC-7 "Post URLs"), unless it has one. */
|
|
996
|
-
#withPostUrl(item, index, template) {
|
|
997
|
-
if (!template || item.url)
|
|
998
|
-
return item;
|
|
999
|
-
const vars = { feed: this.path.slice(1, -'.json'.length), index: String(index), id: encodeURIComponent(item.id) };
|
|
1000
|
-
return { ...item, url: template.replace(/\{(feed|index|id)\}/g, (_, name) => vars[name]) };
|
|
1001
|
-
}
|
|
1002
560
|
#newItem(input) {
|
|
1003
561
|
const { id, markdown, date_published, ...fields } = input;
|
|
1004
562
|
if (id !== undefined && (typeof id != 'string' || !id))
|
|
@@ -1012,16 +570,14 @@ export class PupsFeed {
|
|
|
1012
570
|
this.#setMarkdown(item, markdown);
|
|
1013
571
|
if (item.content_html === undefined && item.content_text === undefined)
|
|
1014
572
|
throw new PupsError('invalid_request', 'A post needs content_html, content_text or markdown (JSON Feed requires content).');
|
|
1015
|
-
//
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
continue;
|
|
1020
|
-
const { index: _index, ...rest } = value;
|
|
573
|
+
// An item with an index names an existing item; the server gives new items theirs (RFC-7 "Posting items").
|
|
574
|
+
delete item._pups;
|
|
575
|
+
if (isObject(item._archive)) {
|
|
576
|
+
const { index: _index, ...rest } = item._archive;
|
|
1021
577
|
if (Object.keys(rest).length)
|
|
1022
|
-
item
|
|
578
|
+
item._archive = rest;
|
|
1023
579
|
else
|
|
1024
|
-
delete item
|
|
580
|
+
delete item._archive;
|
|
1025
581
|
}
|
|
1026
582
|
return item;
|
|
1027
583
|
}
|
|
@@ -1058,9 +614,9 @@ export class PupsFeed {
|
|
|
1058
614
|
if (item.content_html === undefined)
|
|
1059
615
|
item.content_text = markdown;
|
|
1060
616
|
}
|
|
1061
|
-
#result(item,
|
|
617
|
+
#result(item, address) {
|
|
1062
618
|
const index = itemIndex(item);
|
|
1063
|
-
return { id: item.id, ...index === undefined ? {} : { index }, item, url:
|
|
619
|
+
return { id: item.id, ...index === undefined ? {} : { index }, item, url: address };
|
|
1064
620
|
}
|
|
1065
621
|
/**
|
|
1066
622
|
* The URLs of this feed's media files (not icons, not archives) that an item references. For the main feed, only
|
|
@@ -1101,16 +657,13 @@ export class PupsFeed {
|
|
|
1101
657
|
let old;
|
|
1102
658
|
let doc;
|
|
1103
659
|
try {
|
|
1104
|
-
doc = await this.#
|
|
1105
|
-
|
|
1106
|
-
old = main.doc[field];
|
|
1107
|
-
const changed = { ...main.doc };
|
|
660
|
+
doc = await this.#change(doc => {
|
|
661
|
+
old = doc[field];
|
|
1108
662
|
if (uploaded)
|
|
1109
|
-
|
|
663
|
+
doc[field] = uploaded.url;
|
|
1110
664
|
else
|
|
1111
|
-
delete
|
|
1112
|
-
|
|
1113
|
-
});
|
|
665
|
+
delete doc[field];
|
|
666
|
+
}, signal);
|
|
1114
667
|
}
|
|
1115
668
|
catch (e) {
|
|
1116
669
|
if (uploaded)
|
|
@@ -1143,6 +696,10 @@ export class PupsFeed {
|
|
|
1143
696
|
else if (!['title', 'description', 'authors', 'language', 'expired'].includes(key) && !key.startsWith('_'))
|
|
1144
697
|
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 "_".`);
|
|
1145
698
|
}
|
|
699
|
+
#checkKept() {
|
|
700
|
+
if (!this.#session.server.keptFeeds)
|
|
701
|
+
throw new PupsError('unsupported', `This PUPS server doesn't keep feeds: its configuration has no "kept_feeds": true (RFC-7, Server requirements).`);
|
|
702
|
+
}
|
|
1146
703
|
#checkWritable() {
|
|
1147
704
|
if (!this.writable)
|
|
1148
705
|
throw new PupsError('insufficient_scope', `Writing ${this.path} needs the scopes ${this.scopes.join(' ')} (RFC-7, Server requirements).`);
|