pups-client 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/feed.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { isPupsError, PupsError } from './errors.js'
2
2
  import { fileTypes } from './file-types.js'
3
3
  import { pathFromPublicUrl } from './paths.js'
4
+ import { itemHandles } from './handles.js'
5
+ import type { Mentions, MentionReport, MentionSource, PlannedMention, Submission } from './mentions.js'
4
6
  import type { Scope } from './scopes.js'
5
7
  import type { Body, PupsSession } from './session.js'
6
- import { randomString } from './util.js'
8
+ import { isObject, randomString } from './util.js'
7
9
 
8
10
  /** The link relation that registers a feed in `host-meta.json` (RFC-7). A placeholder in RFC-7. */
9
11
  export const FEED_REL = 'https://bigwide.net/ns/feed'
@@ -17,16 +19,20 @@ export const POST_URL_TEMPLATE = 'https://bigwide.net/ns/post-url-template'
17
19
  /** The `about` of the `_pups` object: RFC-7. Not its final location; readers must not rely on it. */
18
20
  export const PUPS_FEED_SPEC = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-7-Feed-Publishing-with-PUPS.md'
19
21
 
22
+ /** The `about` of the `_archive` object: RFC-13 (JSON Feed Archives). Not its final location either. */
23
+ export const ARCHIVE_SPEC = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-13-JSON-Feed-Archives.md'
24
+
20
25
  const RFC1_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-1-Source-for-JSON-Feeds.md'
26
+ const RFC4_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-4-Feed-Submissions.md'
21
27
  const JSON_FEED_VERSION = 'https://jsonfeed.org/version/1.1'
22
28
  const FEED_CONTENT_TYPE = 'application/feed+json'
23
29
  const maxArchiveNumber = 999_999
24
30
  /** The feed file keeps at least this many items, also when `maxBytes` is exceeded (RFC-7 "Size in bytes"). */
25
31
  const minFeedItems = 10
26
32
 
27
- 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.`
33
+ 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.`
28
34
  const archiveComment = (feedUrl: string) =>
29
- `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.`
35
+ `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.`
30
36
 
31
37
  /** Feed names (RFC-7 "Named feeds"): 1 to 40 lowercase letters, digits and `-`, not starting or ending with `-`. */
32
38
  const feedNamePattern = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/
@@ -35,7 +41,7 @@ const feedNamePattern = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/
35
41
  const mainMediaFolders = ['images', 'media']
36
42
 
37
43
  /** Top-level fields that are fixed or managed by RFC-7, and can't be set through `create()` or `updateSettings()`. */
38
- const reservedFields = new Set(['version', 'home_page_url', 'feed_url', 'user_comment', 'next_url', 'items', 'hubs', '_pups', 'icon', 'favicon'])
44
+ const reservedFields = new Set(['version', 'home_page_url', 'feed_url', 'user_comment', 'next_url', 'items', 'hubs', '_pups', '_archive', 'icon', 'favicon'])
39
45
 
40
46
  export interface FeedAuthor {
41
47
  name?: string
@@ -70,28 +76,43 @@ export interface FeedItem {
70
76
  tags?: string[]
71
77
  language?: string
72
78
  attachments?: FeedAttachment[]
73
- /** The item's `_pups` object, with its index (RFC-7 "Indexes"). */
74
- _pups?: ItemMarker
79
+ /** The item's `_archive` object, with its index (RFC-13 "Indexes"). */
80
+ _archive?: ItemArchive
75
81
  [field: string]: unknown
76
82
  }
77
83
 
78
- /** The `_pups` object of an item. */
79
- export interface ItemMarker {
80
- /** The item's index: 0 for a feed's first item, then counting up; never changed, never used again (RFC-7 "Indexes"). */
84
+ /** The `_archive` object of an item (RFC-13). */
85
+ export interface ItemArchive {
86
+ /** The item's index: 0 for a feed's first item, then counting up; never changed, never used again (RFC-13 "Indexes"). */
81
87
  index?: number
82
88
  [field: string]: unknown
83
89
  }
84
90
 
85
- /** The `_pups` object of a feed file or archive. */
91
+ /** @deprecated The index moved from `_pups` to `_archive` (RFC-13): use ItemArchive. */
92
+ export type ItemMarker = ItemArchive
93
+
94
+ /** The `_pups` object of a feed file or archive: the marker of RFC-7. */
86
95
  export interface PupsMarker {
87
96
  about?: string
88
97
  pupsControlled?: boolean
98
+ [field: string]: unknown
99
+ }
100
+
101
+ /** The `_archive` object of a feed file or archive (RFC-13). */
102
+ export interface ArchiveFields {
103
+ about?: string
89
104
  /** In the feed file: the public URL of the newest archive. */
90
105
  archive_url?: string
106
+ /** In the feed file: the URL of every archive, with `{number}` for its six-digit number. */
107
+ archive_template?: string
108
+ /** In the feed file: the most items an archive holds. */
109
+ archive_size?: number
91
110
  /** In an archive: the public URL of the feed file, which readers poll. */
92
111
  updates_url?: string
112
+ /** In an archive: its number, from 0 for the oldest. */
113
+ number?: number
93
114
  /**
94
- * The index the next new item gets (RFC-7 "Indexes"). Valid in the newest archive, or in the feed file of a feed
115
+ * The index the next new item gets (RFC-13 "Indexes"). Valid in the newest archive, or in the feed file of a feed
95
116
  * without archives.
96
117
  */
97
118
  next_index?: number
@@ -115,6 +136,7 @@ export interface FeedDocument {
115
136
  hubs?: unknown[]
116
137
  items: FeedItem[]
117
138
  _pups?: PupsMarker
139
+ _archive?: ArchiveFields
118
140
  [field: string]: unknown
119
141
  }
120
142
 
@@ -131,6 +153,26 @@ export interface FeedSettings {
131
153
  [extension: `_${string}`]: unknown
132
154
  }
133
155
 
156
+ /**
157
+ * The rules for comments of RFC-4 "Policies". Missing rules have RFC-4's defaults; servers may add others. The PUPS
158
+ * server's receiver enforces `title`, `minLength`, `maxLength`, `requireSocialSpec`, `allowEdit` and `allowDelete`.
159
+ */
160
+ export interface CommentPolicy {
161
+ title?: 'required' | 'allowed' | 'none'
162
+ minLength?: number
163
+ maxLength?: number
164
+ requireSocialSpec?: boolean
165
+ allowEdit?: boolean
166
+ allowDelete?: boolean
167
+ [rule: string]: unknown
168
+ }
169
+
170
+ /**
171
+ * Whether a feed accepts comments (RFC-4 `_submissions`): `pups` through the PUPS server's receiver, `other`
172
+ * through another service, such as an rssmention server, or `off`.
173
+ */
174
+ export type CommentsState = 'pups' | 'other' | 'off'
175
+
134
176
  /** Changes to the settings: a value sets the field, `null` removes it, `undefined` leaves it unchanged. */
135
177
  export type FeedSettingsChanges = { [K in keyof FeedSettings]?: FeedSettings[K] | null }
136
178
 
@@ -189,6 +231,11 @@ export interface PostResult {
189
231
  * as the `source` of an RFC-4 webmention. In a feed without archives, the feed file's URL plus `#<id>`.
190
232
  */
191
233
  url: string
234
+ /**
235
+ * With the option `mentions`: the RFC-11 mentions, sent once the post is visible at its public URL. Never
236
+ * rejects. Missing if the post names and answers no one.
237
+ */
238
+ mentions?: Promise<MentionReport[]>
192
239
  }
193
240
 
194
241
  export interface MediaResult {
@@ -233,6 +280,12 @@ export interface FeedOptions {
233
280
  * declares one and the post has no `url` (RFC-7 "Post URLs"). Default true.
234
281
  */
235
282
  postUrls?: boolean
283
+ /**
284
+ * Whether to send RFC-11 mentions after `addPost()`, `editPost()` and `deletePost()`: to the domains a post names
285
+ * (`@tim.example.com`) and to the author of the item it answers. `true` uses `session.mentions`. Default false.
286
+ * Each write can decide otherwise with its own option `mentions`, e.g. with the accounts the author confirmed.
287
+ */
288
+ mentions?: boolean | Mentions
236
289
  }
237
290
 
238
291
  /** A feed registered in `host-meta.json`. */
@@ -246,6 +299,13 @@ export interface FeedLink {
246
299
 
247
300
  type Signal = { signal?: AbortSignal }
248
301
 
302
+ /**
303
+ * Which RFC-11 mentions a write sends: `true` all of them, `false` none, or a list from `planMentions()`, e.g. the
304
+ * accounts the author confirmed. Default: the feed's option `mentions`.
305
+ */
306
+ export type MentionChoice = boolean | PlannedMention[]
307
+ type WithMentions = Signal & { mentions?: MentionChoice }
308
+
249
309
  interface Loaded {
250
310
  path: string
251
311
  doc: FeedDocument
@@ -273,8 +333,6 @@ function feedPaths(name?: string): { path: `/${string}`; directory: `/${string}`
273
333
  return { path: `/feed/${name}.json`, directory: `/feed/${name}/` }
274
334
  }
275
335
 
276
- const isObject = (value: unknown): value is Record<string, unknown> =>
277
- !!value && typeof value == 'object' && !Array.isArray(value)
278
336
 
279
337
  const isFeedDocument = (value: unknown): value is FeedDocument =>
280
338
  isObject(value) && typeof value.version == 'string' && value.version.startsWith('https://jsonfeed.org/version/1')
@@ -304,13 +362,42 @@ function mergeItems(existing: FeedItem[], incoming: FeedItem[]): FeedItem[] {
304
362
  return [...incoming.filter(item => !present.has(item.id)), ...existing.map(item => byId.get(item.id) ?? item)]
305
363
  }
306
364
 
307
- /** The index of an item (RFC-7 "Indexes"), or undefined if it has none. */
365
+ /** The index of an item (RFC-13 "Indexes"), also from `_pups` of earlier drafts, or undefined if it has none. */
308
366
  export function itemIndex(item: FeedItem): number | undefined {
309
- const index = isObject(item._pups) ? item._pups.index : undefined
367
+ const index = isObject(item._archive) && item._archive.index !== undefined ? item._archive.index : isObject(item._pups) ? item._pups.index : undefined
310
368
  return typeof index == 'number' && Number.isSafeInteger(index) && index >= 0 ? index : undefined
311
369
  }
312
370
 
313
- const withIndex = (item: FeedItem, index: number): FeedItem => ({ ...item, _pups: { ...isObject(item._pups) ? item._pups : {}, index } })
371
+ const withIndex = (item: FeedItem, index: number): FeedItem => ({ ...item, _archive: { ...isObject(item._archive) ? item._archive : {}, index } })
372
+
373
+ /** The fields of RFC-13 that earlier drafts of RFC-7 kept in `_pups`. */
374
+ const legacyArchiveFields = ['archive_url', 'updates_url', 'next_index'] as const
375
+
376
+ /**
377
+ * Moves the fields that earlier drafts kept in `_pups` into `_archive` (RFC-13 "Earlier drafts"), in the file and its
378
+ * items, where `_archive` doesn't have them already. Changes `doc`.
379
+ */
380
+ function upgradeArchiveFields(doc: FeedDocument): FeedDocument {
381
+ const move = (from: Record<string, unknown>, to: Record<string, unknown>, keys: readonly string[]) => {
382
+ for (const key of keys) if (key in from) {
383
+ if (to[key] === undefined) to[key] = from[key]
384
+ delete from[key]
385
+ }
386
+ }
387
+ if (isObject(doc._pups) && legacyArchiveFields.some(key => key in doc._pups!)) {
388
+ const archive: ArchiveFields = { about: ARCHIVE_SPEC, ...isObject(doc._archive) ? doc._archive : {} }
389
+ move(doc._pups, archive, legacyArchiveFields)
390
+ doc._archive = archive
391
+ }
392
+ for (const item of doc.items)
393
+ if (isObject(item._pups) && 'index' in item._pups) {
394
+ const archive: ItemArchive = isObject(item._archive) ? item._archive : {}
395
+ move(item._pups, archive, ['index'])
396
+ item._archive = archive
397
+ if (!Object.keys(item._pups).length) delete item._pups
398
+ }
399
+ return doc
400
+ }
314
401
 
315
402
  /** A post URL template (RFC-6 "Post URLs"): an https URL with `{index}` or `{id}`. */
316
403
  function validTemplate(template: unknown): template is string {
@@ -322,9 +409,9 @@ function validTemplate(template: unknown): template is string {
322
409
  }
323
410
  }
324
411
 
325
- /** The counter `_pups.next_index` of a file, if it has a valid one. */
412
+ /** The counter `_archive.next_index` of a file, if it has a valid one. */
326
413
  function counterOf(doc: FeedDocument): number | undefined {
327
- const next = doc._pups?.next_index
414
+ const next = doc._archive?.next_index
328
415
  return typeof next == 'number' && Number.isSafeInteger(next) && next >= 0 ? next : undefined
329
416
  }
330
417
 
@@ -386,6 +473,7 @@ export class PupsFeed {
386
473
  readonly #maxBytes?: number
387
474
  readonly #maxAttempts: number
388
475
  readonly #postUrls: boolean
476
+ readonly #mentions?: Mentions
389
477
  #template?: Promise<string | undefined>
390
478
 
391
479
  /** @internal Use `session.feed()`. */
@@ -401,6 +489,7 @@ export class PupsFeed {
401
489
  this.#maxBytes = options.maxBytes
402
490
  this.#maxAttempts = options.maxAttempts ?? 8
403
491
  this.#postUrls = options.postUrls ?? true
492
+ this.#mentions = options.mentions === true ? session.mentions : options.mentions || undefined
404
493
  if (!(this.#archiveSize >= 1 && this.#maxItems >= 1))
405
494
  throw new PupsError('invalid_request', 'Feed options: maxItems and archiveSize must be at least 1.')
406
495
  }
@@ -526,6 +615,52 @@ export class PupsFeed {
526
615
  return this.#setImage('favicon', media, options.signal)
527
616
  }
528
617
 
618
+ /** Whether the PUPS server can receive comments on the feed's posts (`comment_endpoint`, RFC-6 "Built-in receiver"). */
619
+ get commentsAvailable(): boolean {
620
+ return !!this.#session.server.commentEndpoint
621
+ }
622
+
623
+ /** Whether the feed accepts comments, and through whom; `doc` is the feed file, e.g. from `load()`. */
624
+ comments(doc: FeedDocument): CommentsState {
625
+ const submissions = doc._submissions
626
+ if (!isObject(submissions)) return 'off'
627
+ const endpoint = this.#session.server.commentEndpoint
628
+ return endpoint && submissions.url == endpoint ? 'pups' : 'other'
629
+ }
630
+
631
+ /**
632
+ * Lets readers comment on the feed's posts through the PUPS server, which puts the comments into the owner's inbox
633
+ * (RFC-6 "Built-in receiver"): writes RFC-4 `_submissions` into the feed file, with `comment_endpoint` as `url`,
634
+ * the comments policy (RFC-4's defaults for `title`, `minLength` and `maxLength`, overridden by `policy`) and
635
+ * `republish: "no"`. Replaces the `_submissions` of another service; check `comments()` first and ask the owner.
636
+ * Single posts are closed with `_commenting: { allowComments: false }` (RFC-4).
637
+ * @throws {PupsError} `unsupported` if the server has no `comment_endpoint`.
638
+ */
639
+ async enableComments(settings: { policy?: CommentPolicy; tos?: string } = {}, options: Signal = {}): Promise<FeedDocument> {
640
+ const url = this.#session.server.commentEndpoint
641
+ if (!url) throw new PupsError('unsupported', 'This PUPS server doesn\'t receive comments: its configuration has no comment_endpoint (RFC-6, Built-in receiver).')
642
+ return this.#setSubmissions({
643
+ about: RFC4_URL,
644
+ url,
645
+ ...settings.tos ? { tos: settings.tos } : {},
646
+ policies: { comments: { title: 'none', minLength: 2, maxLength: 2000, ...settings.policy } },
647
+ republish: 'no',
648
+ }, options.signal)
649
+ }
650
+
651
+ /** Closes the feed for comments: removes `_submissions` from the feed file, whichever service it names. */
652
+ disableComments(options: Signal = {}): Promise<FeedDocument> {
653
+ return this.#setSubmissions(undefined, options.signal)
654
+ }
655
+
656
+ #setSubmissions(submissions: Record<string, unknown> | undefined, signal?: AbortSignal): Promise<FeedDocument> {
657
+ return this.#transaction(async () => {
658
+ const main = await this.#readControlled(this.path, signal)
659
+ const { _submissions: _old, ...doc } = main.doc
660
+ return this.#writeMain(submissions ? { ...doc, _submissions: submissions } : doc, main.etag, signal)
661
+ })
662
+ }
663
+
529
664
  /**
530
665
  * Uploads an image, audio or video file into the feed directory under a new, unique name, by default
531
666
  * `images/<year>/…` for images and `media/<year>/…` for everything else. Reference it from a post by its `url`.
@@ -548,11 +683,13 @@ export class PupsFeed {
548
683
  * media with `uploadMedia()` before posting.
549
684
  * In a feed with archives, a post without `url` gets one from the site's post URL template, if `host-meta.json`
550
685
  * has one and `postUrls` isn't false: the page that shows the post (RFC-7 "Post URLs").
686
+ * With the option `mentions`, the domains the post names and the author of the item it answers are notified
687
+ * (RFC-11) once the post is visible; see `PostResult.mentions`.
551
688
  * @returns the post, with `url`: its archive's URL plus `#<id>`, which never changes; for a feed without
552
689
  * archives, the feed file's URL plus `#<id>`, valid while the post is among the newest. The post's page, if it
553
690
  * has one, is `item.url`.
554
691
  */
555
- async addPost(input: PostInput, options: Signal = {}): Promise<PostResult> {
692
+ async addPost(input: PostInput, options: WithMentions = {}): Promise<PostResult> {
556
693
  const item = this.#newItem(input)
557
694
  const signal = options.signal
558
695
  let archiveUrl = ''
@@ -564,21 +701,21 @@ export class PupsFeed {
564
701
  if (firstAttempt && main.doc.items.some(i => i.id == item.id))
565
702
  throw new PupsError('invalid_request', `The feed already has an item with the id "${item.id}".`)
566
703
  firstAttempt = false
567
- const doc: FeedDocument = { ...main.doc, _pups: { ...main.doc._pups } }
568
- const hasArchives = this.#archiveNumber(doc._pups!.archive_url) !== undefined
704
+ const doc: FeedDocument = { ...main.doc, _archive: { ...main.doc._archive } }
705
+ const hasArchives = this.#archiveNumber(doc._archive!.archive_url) !== undefined
569
706
  if (!hasArchives && !this.#archivesWanted) {
570
707
  // A feed without archives: the feed file is all there is, and holds the counter (RFC-7 "Posting").
571
708
  archiveUrl = this.url
572
709
  const indexed = indexItems(doc.items, nextFree(doc.items, counterOf(doc)))
573
710
  stored = withIndex(item, indexed.next)
574
- doc._pups!.next_index = indexed.next + 1
711
+ doc._archive!.next_index = indexed.next + 1
575
712
  await this.#writeMain({ ...doc, items: this.#newestItems([stored], indexed.items, doc) }, main.etag, signal)
576
713
  return
577
714
  }
578
715
  if (!hasArchives) {
579
716
  const started = await this.#startArchives(main, signal)
580
717
  if (started) {
581
- doc._pups!.archive_url = started.url
718
+ doc._archive!.archive_url = started.url
582
719
  doc.items = started.items
583
720
  }
584
721
  }
@@ -586,17 +723,17 @@ export class PupsFeed {
586
723
  const added = await this.#addToArchive(main, doc, item, signal, template)
587
724
  archiveUrl = added.url
588
725
  stored = added.item
589
- doc._pups!.archive_url = added.url
726
+ doc._archive!.archive_url = added.url
590
727
  if (!hasArchives) {
591
728
  // The old chain of a handed-over feed now continues behind the oldest archive, and the newest archive
592
729
  // holds the counter.
593
730
  delete doc.next_url
594
- delete doc._pups!.next_index
731
+ delete doc._archive!.next_index
595
732
  }
596
733
  doc.items = this.#newestItems(added.recent, doc.items, doc)
597
734
  await this.#writeMain(doc, main.etag, signal)
598
735
  })
599
- return this.#result(stored, archiveUrl)
736
+ return this.#withMentions(options.mentions, this.#result(stored, archiveUrl), archiveUrl, stored, undefined, item => !!item)
600
737
  }
601
738
 
602
739
  /**
@@ -608,11 +745,11 @@ export class PupsFeed {
608
745
  const signal = options.signal
609
746
  await this.#transaction(async () => {
610
747
  const main = await this.#readControlled(this.path, signal)
611
- const newest = this.#archiveNumber(main.doc._pups?.archive_url)
748
+ const newest = this.#archiveNumber(main.doc._archive?.archive_url)
612
749
  if (newest === undefined) {
613
750
  const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)))
614
751
  if (indexed.changed || counterOf(main.doc) !== indexed.next)
615
- await this.#writeMain({ ...main.doc, items: indexed.items, _pups: { ...main.doc._pups, next_index: indexed.next } }, main.etag, signal)
752
+ await this.#writeMain({ ...main.doc, items: indexed.items, _archive: { ...main.doc._archive, next_index: indexed.next } }, main.etag, signal)
616
753
  return
617
754
  }
618
755
  const archive = await this.#readArchive(this.#archivePath(newest), signal)
@@ -632,7 +769,7 @@ export class PupsFeed {
632
769
  }
633
770
 
634
771
  /**
635
- * All posts, newest first: the archives from `_pups.archive_url` along `next_url` (for a feed without archives,
772
+ * All posts, newest first: the archives from `_archive.archive_url` along `next_url` (for a feed without archives,
636
773
  * the feed file and its `next_url` chain). Each post is returned once.
637
774
  */
638
775
  async *posts(options: Signal = {}): AsyncGenerator<FeedItem> {
@@ -653,13 +790,16 @@ export class PupsFeed {
653
790
  * a function that gets a copy of the item and returns the new item, or `undefined` to leave it unchanged. The
654
791
  * function may run more than once.
655
792
  *
656
- * Apps should edit posts only when the owner asks them to, whichever app created them. A post of a feed with
793
+ * Apps should edit posts only when the owner asks them to, whichever app created them. With the option
794
+ * `mentions`, everyone the old or the new version mentions is notified. A post of a feed with
657
795
  * archives that has no `url`, and had none before, gets one from the post URL template, as in `addPost()`.
658
796
  * @throws {PupsError} `not_found`
659
797
  */
660
- async editPost(id: string, changes: PostChanges | ((item: FeedItem) => FeedItem | undefined | Promise<FeedItem | undefined>), options: Signal = {}): Promise<PostResult> {
798
+ async editPost(id: string, changes: PostChanges | ((item: FeedItem) => FeedItem | undefined | Promise<FeedItem | undefined>), options: WithMentions = {}): Promise<PostResult> {
661
799
  const signal = options.signal
662
- return this.#transaction(async () => {
800
+ let edit: { old: FeedItem; item: FeedItem; fileUrl: string } | undefined
801
+ const result = await this.#transaction(async () => {
802
+ edit = undefined
663
803
  const { main, file, index } = await this.#findWritable(id, signal)
664
804
  const old = file.doc.items[index]!
665
805
  const fileUrl = this.#session.publicUrl(file.path)
@@ -670,13 +810,16 @@ export class PupsFeed {
670
810
  // The index never changes (RFC-7 "Indexes").
671
811
  if (oldIndex !== undefined) item = withIndex(item, oldIndex)
672
812
  // A post of a feed with archives that never had a url may get one (RFC-7 "Post URLs").
673
- if (oldIndex !== undefined && !old.url && !item.url && this.#archiveNumber(main.doc._pups?.archive_url) !== undefined)
813
+ if (oldIndex !== undefined && !old.url && !item.url && this.#archiveNumber(main.doc._archive?.archive_url) !== undefined)
674
814
  item = this.#withPostUrl(item, oldIndex, await this.#postUrlTemplate(signal))
675
815
  if (file != main) await this.#writeArchive(file, replaceAt(file.doc.items, index, item), signal)
676
816
  const mainIndex = main.doc.items.findIndex(i => i.id == id)
677
817
  if (mainIndex >= 0) await this.#writeMain({ ...main.doc, items: replaceAt(main.doc.items, mainIndex, item) }, main.etag, signal)
818
+ edit = { old, item, fileUrl }
678
819
  return this.#result(item, fileUrl)
679
820
  })
821
+ const done = edit as typeof edit
822
+ return done ? this.#withMentions(options.mentions, result, done.fileUrl, done.item, done.old, found => found?.date_modified == done.item.date_modified) : result
680
823
  }
681
824
 
682
825
  /**
@@ -686,10 +829,12 @@ export class PupsFeed {
686
829
  * @returns the deleted item, and the public URLs of the deleted media files.
687
830
  * @throws {PupsError} `not_found`
688
831
  */
689
- async deletePost(id: string, options: Signal & { deleteMedia?: boolean } = {}): Promise<{ item: FeedItem; deletedMedia: string[] }> {
832
+ async deletePost(id: string, options: WithMentions & { deleteMedia?: boolean } = {}): Promise<{ item: FeedItem; deletedMedia: string[]; mentions?: Promise<MentionReport[]> }> {
690
833
  const signal = options.signal
834
+ let fileUrl = ''
691
835
  const item = await this.#transaction(async () => {
692
836
  const { main, file, index } = await this.#findWritable(id, signal)
837
+ fileUrl = this.#session.publicUrl(file.path)
693
838
  const item = file.doc.items[index]!
694
839
  if (file != main) {
695
840
  await this.#writeArchive(file, file.doc.items.filter(i => i.id != id), signal)
@@ -715,7 +860,77 @@ export class PupsFeed {
715
860
  if (path && await this.#deleteQuietly(path, signal)) deletedMedia.push(url)
716
861
  }
717
862
  }
718
- return { item, deletedMedia }
863
+ const mentions = this.#sendMentions(options.mentions, fileUrl, undefined, item, found => !found)
864
+ return { item, deletedMedia, ...mentions ? { mentions } : {} }
865
+ }
866
+
867
+ /**
868
+ * Sends the RFC-11 mentions of a post now, e.g. to try again those that failed (see `Mentions.notifyAll()`). With
869
+ * `previous`, the version before an edit, also to the accounts that one mentioned.
870
+ * @throws {PupsError} `not_found`
871
+ */
872
+ async sendMentions(id: string, options: Signal & { previous?: FeedItem } = {}): Promise<MentionReport[]> {
873
+ const post = await this.getPost(id, options)
874
+ if (!post) throw new PupsError('not_found', `The feed has no post with the id "${id}".`)
875
+ return this.#mentionSender.notifyAll({ source: post.url, item: post.item, previous: options.previous, me: this.#session.me }, options)
876
+ }
877
+
878
+ /**
879
+ * Submits a post that answers an item of an RFC-4 feed, e.g. a comment, to that feed's `_submissions.url`
880
+ * (RFC-4 "Submitting"): `source` is the post's archive URL plus `#<id>`, `target` its `_source.inReplyTo`. Call it
881
+ * after `addPost()` or `editPost()`, also to submit an edit or a delete again. Show the target's terms of service
882
+ * and what its `republish` means before the first submission.
883
+ * @throws {PupsError} `not_found`; `invalid_request` if the post answers nothing; `unsupported` if the target
884
+ * feed takes no submissions.
885
+ */
886
+ async submit(id: string, options: Signal = {}): Promise<Submission> {
887
+ const post = await this.getPost(id, options)
888
+ if (!post) throw new PupsError('not_found', `The feed has no post with the id "${id}".`)
889
+ const source = isObject(post.item._source) ? post.item._source : {}
890
+ if (typeof source.inReplyTo != 'string') throw new PupsError('invalid_request', `The post "${id}" has no _source.inReplyTo, so it answers nothing (RFC-4).`)
891
+ return this.#session.mentions.submit(post.url, source.inReplyTo, options)
892
+ }
893
+
894
+ /**
895
+ * The RFC-11 mentions a post would send (see `Mentions.plan()`), e.g. to ask the author before posting:
896
+ *
897
+ * ```ts
898
+ * const planned = await feed.planMentions(input)
899
+ * const confirmed = planned.length && await askToNotify(planned) ? planned : false // the app's dialog
900
+ * await feed.addPost(input, { mentions: confirmed })
901
+ * ```
902
+ *
903
+ * For an edit, pass the post as it will be and the current version as `previous`; for a delete, only `previous`.
904
+ */
905
+ planMentions(post: MentionSource | undefined, options: Signal & { previous?: MentionSource; discover?: boolean } = {}): Promise<PlannedMention[]> {
906
+ return this.#mentionSender.plan({ item: post, previous: options.previous, me: this.#session.me }, options)
907
+ }
908
+
909
+ get #mentionSender(): Mentions {
910
+ return this.#mentions ?? this.#session.mentions
911
+ }
912
+
913
+ /** The result with the RFC-11 mentions of the post, if the write sends them (see `#sendMentions()`). */
914
+ #withMentions(choice: MentionChoice | undefined, result: PostResult, fileUrl: string, item: FeedItem, previous: FeedItem | undefined, ready: (item?: FeedItem) => boolean): PostResult {
915
+ const mentions = this.#sendMentions(choice, fileUrl, item, previous, ready)
916
+ return mentions ? { ...result, mentions } : result
917
+ }
918
+
919
+ /**
920
+ * Sends the RFC-11 mentions of a post in the background, once its file at `fileUrl` is in the state `ready` wants:
921
+ * all, none, or the planned ones, as `choice` (default: the feed's option) says. Undefined if nothing is sent.
922
+ */
923
+ #sendMentions(choice: MentionChoice | undefined, fileUrl: string, item: FeedItem | undefined, previous: FeedItem | undefined, ready: (item?: FeedItem) => boolean): Promise<MentionReport[]> | undefined {
924
+ choice ??= !!this.#mentions
925
+ const relevant = (i?: FeedItem) => !!i && (itemHandles(i).length > 0 || (isObject(i._source) && typeof i._source.inReplyTo == 'string'))
926
+ if (Array.isArray(choice) ? !choice.length : !choice || !(relevant(item) || relevant(previous))) return
927
+ const mentions = this.#mentionSender
928
+ const id = (item ?? previous)!.id
929
+ const source = `${fileUrl}#${encodeURIComponent(id)}`
930
+ return (async () => {
931
+ await mentions.waitForItem(fileUrl, id, ready)
932
+ return Array.isArray(choice) ? mentions.sendPlanned(source, choice) : mentions.notifyAll({ source, item, previous, me: this.#session.me })
933
+ })().catch(() => [])
719
934
  }
720
935
 
721
936
  // Reading
@@ -737,7 +952,7 @@ export class PupsFeed {
737
952
  // Not JSON: handled below.
738
953
  }
739
954
  if (!isFeedDocument(doc)) throw new PupsError('invalid_feed', `${path} is not a JSON Feed.`)
740
- return { path, doc, etag: file.etag }
955
+ return { path, doc: upgradeArchiveFields(doc), etag: file.etag }
741
956
  }
742
957
 
743
958
  /** Reads a file that must exist and carry the `_pups` marker. */
@@ -750,13 +965,13 @@ export class PupsFeed {
750
965
  }
751
966
 
752
967
  /**
753
- * The files that hold all items: the archives from `_pups.archive_url` along `next_url`, as far as they are files
968
+ * The files that hold all items: the archives from `_archive.archive_url` along `next_url`, as far as they are files
754
969
  * on this server. A feed without archives yet (handed over, not posted to) holds its items in the feed file and
755
970
  * the pages its `next_url` names.
756
971
  */
757
972
  async *#chain(main: Loaded, signal?: AbortSignal): AsyncGenerator<Loaded> {
758
973
  const visited = new Set<string>([main.path])
759
- const archive = main.doc._pups?.archive_url
974
+ const archive = main.doc._archive?.archive_url
760
975
  let file: Loaded | undefined = main
761
976
  let next = archive && this.#archiveNumber(archive) !== undefined ? archive : undefined
762
977
  if (next) file = undefined
@@ -807,8 +1022,8 @@ export class PupsFeed {
807
1022
 
808
1023
  /**
809
1024
  * Writes the feed file. Sets the fixed fields, so that a feed the owner handed over gets them on its first write,
810
- * and upgrades JSON Feed 1.0 (RFC-7 "Handing over an existing feed"). The optional `next_url` of a feed with
811
- * archives is kept equal to `archive_url` (RFC-7 "Reading").
1025
+ * and upgrades JSON Feed 1.0 (RFC-7 "Handing over an existing feed"). A feed with archives gets the archive template
1026
+ * and size of RFC-13, and its optional `next_url` is kept equal to `archive_url` (RFC-7 "Reading").
812
1027
  */
813
1028
  async #writeMain(doc: FeedDocument, etag: string, signal?: AbortSignal): Promise<FeedDocument> {
814
1029
  const { author, ...rest } = doc
@@ -820,14 +1035,25 @@ export class PupsFeed {
820
1035
  user_comment: mainComment,
821
1036
  }
822
1037
  if (author !== undefined && fixed.authors === undefined) fixed.authors = [author as FeedAuthor]
823
- if (fixed.next_url !== undefined && this.#archiveNumber(fixed._pups?.archive_url) !== undefined) fixed.next_url = fixed._pups!.archive_url
1038
+ const archiveUrl = fixed._archive?.archive_url
1039
+ if (fixed._archive) fixed._archive = { about: ARCHIVE_SPEC, ...fixed._archive }
1040
+ if (this.#archiveNumber(archiveUrl) !== undefined) {
1041
+ fixed._archive = { ...fixed._archive, archive_template: this.#archiveTemplate(), archive_size: this.#archiveSize }
1042
+ if (fixed.next_url !== undefined) fixed.next_url = archiveUrl
1043
+ }
824
1044
  await this.#session.replace(this.path, serialize(fixed), etag, { contentType: FEED_CONTENT_TYPE, signal })
825
1045
  return fixed
826
1046
  }
827
1047
 
828
- /** Writes an archive with `items`, and with the counter `next_index` if given. */
1048
+ /**
1049
+ * Writes an archive with `items`, and with the counter `next_index` if given. An archive of an earlier draft gets its
1050
+ * `_archive` fields and comment of RFC-13 (`number`, `updates_url`).
1051
+ */
829
1052
  async #writeArchive(archive: Loaded, items: FeedItem[], signal?: AbortSignal, nextIndex?: number) {
830
- const doc = nextIndex === undefined ? { ...archive.doc, items } : { ...archive.doc, items, _pups: { ...archive.doc._pups, next_index: nextIndex } }
1053
+ const n = this.#archiveNumber(this.#session.publicUrl(archive.path))
1054
+ const fields: ArchiveFields = { about: ARCHIVE_SPEC, ...archive.doc._archive, updates_url: this.url, ...n === undefined ? {} : { number: n } }
1055
+ if (nextIndex !== undefined) fields.next_index = nextIndex
1056
+ const doc: FeedDocument = { ...archive.doc, user_comment: archiveComment(this.url), items, _archive: fields }
831
1057
  await this.#session.replace(archive.path, serialize(doc), archive.etag, { contentType: FEED_CONTENT_TYPE, signal })
832
1058
  }
833
1059
 
@@ -854,6 +1080,11 @@ export class PupsFeed {
854
1080
  return this.#session.publicUrl(this.#archivePath(n))
855
1081
  }
856
1082
 
1083
+ /** `_archive.archive_template` (RFC-13): the archive URL with `{number}` for the number. */
1084
+ #archiveTemplate() {
1085
+ return this.#archiveUrl(0).replace(/000000\.json$/, '{number}.json')
1086
+ }
1087
+
857
1088
  /** The number of the archive at `url`, or undefined if `url` is not an archive file of this feed. */
858
1089
  #archiveNumber(url: string | undefined): number | undefined {
859
1090
  const path = url && pathFromPublicUrl(this.#session.server, url)
@@ -862,10 +1093,12 @@ export class PupsFeed {
862
1093
  return match ? Number(match[1]) : undefined
863
1094
  }
864
1095
 
865
- /** A new archive with the feed fields of the feed file (RFC-7 "Archives"). */
1096
+ /**
1097
+ * A new archive with the feed fields of the feed file (RFC-13 "Feed fields of an archive"), except `_submissions`:
1098
+ * whether a feed accepts comments is said by its feed file alone.
1099
+ */
866
1100
  #newArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, nextIndex?: number): FeedDocument {
867
- const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, ...fields } = main
868
- const { archive_url: _archive, next_index: _counter, ...marker } = _pups ?? {}
1101
+ const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, _archive, _submissions: _s, ...fields } = main
869
1102
  const podcast = fields._podcast
870
1103
  if (isObject(podcast) && 'liveItems' in podcast) {
871
1104
  const { liveItems: _live, ...rest } = podcast
@@ -879,7 +1112,8 @@ export class PupsFeed {
879
1112
  user_comment: archiveComment(this.url),
880
1113
  ...nextUrl ? { next_url: nextUrl } : {},
881
1114
  items,
882
- _pups: { about: PUPS_FEED_SPEC, ...marker, pupsControlled: true, updates_url: this.url, ...nextIndex === undefined ? {} : { next_index: nextIndex } },
1115
+ _pups: { about: PUPS_FEED_SPEC, ..._pups, pupsControlled: true },
1116
+ _archive: { about: ARCHIVE_SPEC, updates_url: this.url, number: n, ...nextIndex === undefined ? {} : { next_index: nextIndex } },
883
1117
  }
884
1118
  }
885
1119
 
@@ -925,7 +1159,7 @@ export class PupsFeed {
925
1159
  const existing = await this.#readArchive(this.#archivePath(n), signal)
926
1160
  const ids = new Set(items.map(item => item.id))
927
1161
  if (!existing || existing == 'foreign' || !existing.doc.items.every(item => ids.has(item.id)))
928
- 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).`)
1162
+ 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).`)
929
1163
  await this.#writeArchive(existing, items, signal, nextIndex)
930
1164
  }
931
1165
  url = this.#archiveUrl(n)
@@ -974,7 +1208,7 @@ export class PupsFeed {
974
1208
  */
975
1209
  async #addToArchive(main: Loaded, doc: FeedDocument, item: FeedItem, signal?: AbortSignal, template?: string): Promise<{ url: string; recent: FeedItem[]; item: FeedItem }> {
976
1210
  const place = (index: number) => this.#withPostUrl(withIndex(item, index), index, template)
977
- const newest = this.#archiveNumber(doc._pups?.archive_url)
1211
+ const newest = this.#archiveNumber(doc._archive?.archive_url)
978
1212
  let previous: FeedItem[] = []
979
1213
  // The index for the item if it goes into a new archive.
980
1214
  let next = nextFree(doc.items, newest === undefined ? counterOf(doc) : undefined)
@@ -1065,11 +1299,13 @@ export class PupsFeed {
1065
1299
  if (markdown !== undefined) this.#setMarkdown(item, markdown)
1066
1300
  if (item.content_html === undefined && item.content_text === undefined)
1067
1301
  throw new PupsError('invalid_request', 'A post needs content_html, content_text or markdown (JSON Feed requires content).')
1068
- // The index is given out when the item is added (RFC-7 "Indexes").
1069
- if (isObject(item._pups)) {
1070
- const { index: _index, ...marker } = item._pups
1071
- if (Object.keys(marker).length) item._pups = marker
1072
- else delete item._pups
1302
+ // The index is given out when the item is added (RFC-13 "Indexes").
1303
+ for (const key of ['_archive', '_pups'] as const) {
1304
+ const value = item[key]
1305
+ if (!isObject(value)) continue
1306
+ const { index: _index, ...rest } = value
1307
+ if (Object.keys(rest).length) item[key] = rest
1308
+ else delete item[key]
1073
1309
  }
1074
1310
  return item
1075
1311
  }