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