pups-client 0.2.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 +26 -1
- 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/feed.d.ts +23 -0
- package/dist/feed.d.ts.map +1 -1
- package/dist/feed.js +176 -36
- package/dist/feed.js.map +1 -1
- 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 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- 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 +39 -7
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +68 -15
- package/dist/session.js.map +1 -1
- package/package.json +1 -1
- package/src/cli/main.ts +4 -4
- package/src/discovery.ts +3 -0
- package/src/feed.ts +193 -38
- package/src/host-meta.ts +43 -7
- package/src/index.ts +2 -1
- package/src/paths.ts +19 -1
- package/src/scopes.ts +33 -11
- package/src/session.ts +75 -18
package/src/feed.ts
CHANGED
|
@@ -64,6 +64,15 @@ export interface FeedItem {
|
|
|
64
64
|
tags?: string[]
|
|
65
65
|
language?: string
|
|
66
66
|
attachments?: FeedAttachment[]
|
|
67
|
+
/** The item's `_pups` object, with its index (RFC-7 "Indexes"). */
|
|
68
|
+
_pups?: ItemMarker
|
|
69
|
+
[field: string]: unknown
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The `_pups` object of an item. */
|
|
73
|
+
export interface ItemMarker {
|
|
74
|
+
/** The item's index: 0 for a feed's first item, then counting up; never changed, never used again (RFC-7 "Indexes"). */
|
|
75
|
+
index?: number
|
|
67
76
|
[field: string]: unknown
|
|
68
77
|
}
|
|
69
78
|
|
|
@@ -75,6 +84,11 @@ export interface PupsMarker {
|
|
|
75
84
|
archive_url?: string
|
|
76
85
|
/** In an archive: the public URL of the feed file, which readers poll. */
|
|
77
86
|
updates_url?: string
|
|
87
|
+
/**
|
|
88
|
+
* The index the next new item gets (RFC-7 "Indexes"). Valid in the newest archive, or in the feed file of a feed
|
|
89
|
+
* without archives.
|
|
90
|
+
*/
|
|
91
|
+
next_index?: number
|
|
78
92
|
[field: string]: unknown
|
|
79
93
|
}
|
|
80
94
|
|
|
@@ -160,6 +174,8 @@ export type PostChanges = { [K in Exclude<keyof PostInput, 'id'>]?: PostInput[K]
|
|
|
160
174
|
|
|
161
175
|
export interface PostResult {
|
|
162
176
|
id: string
|
|
177
|
+
/** The item's index (RFC-7 "Indexes"); undefined for an item that has none yet. */
|
|
178
|
+
index?: number
|
|
163
179
|
/** The item as stored. */
|
|
164
180
|
item: FeedItem
|
|
165
181
|
/**
|
|
@@ -277,6 +293,40 @@ function mergeItems(existing: FeedItem[], incoming: FeedItem[]): FeedItem[] {
|
|
|
277
293
|
return [...incoming.filter(item => !present.has(item.id)), ...existing.map(item => byId.get(item.id) ?? item)]
|
|
278
294
|
}
|
|
279
295
|
|
|
296
|
+
/** The index of an item (RFC-7 "Indexes"), or undefined if it has none. */
|
|
297
|
+
export function itemIndex(item: FeedItem): number | undefined {
|
|
298
|
+
const index = isObject(item._pups) ? item._pups.index : undefined
|
|
299
|
+
return typeof index == 'number' && Number.isSafeInteger(index) && index >= 0 ? index : undefined
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const withIndex = (item: FeedItem, index: number): FeedItem => ({ ...item, _pups: { ...isObject(item._pups) ? item._pups : {}, index } })
|
|
303
|
+
|
|
304
|
+
/** The counter `_pups.next_index` of a file, if it has a valid one. */
|
|
305
|
+
function counterOf(doc: FeedDocument): number | undefined {
|
|
306
|
+
const next = doc._pups?.next_index
|
|
307
|
+
return typeof next == 'number' && Number.isSafeInteger(next) && next >= 0 ? next : undefined
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** The next free index: above every index of `items`, and at least each of `counters`. */
|
|
311
|
+
const nextFree = (items: FeedItem[], ...counters: (number | undefined)[]) =>
|
|
312
|
+
Math.max(0, ...counters.filter((c): c is number => c !== undefined), ...items.map(item => (itemIndex(item) ?? -1) + 1))
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Gives the items without an index (newest first, as in a file) the next indexes from `next`, the oldest first
|
|
316
|
+
* (RFC-7 "Items without an index").
|
|
317
|
+
* @returns the items, and the counter after them.
|
|
318
|
+
*/
|
|
319
|
+
function indexItems(items: FeedItem[], next: number): { items: FeedItem[]; next: number; changed: boolean } {
|
|
320
|
+
const result = [...items]
|
|
321
|
+
let changed = false
|
|
322
|
+
for (let i = result.length - 1; i >= 0; i--)
|
|
323
|
+
if (itemIndex(result[i]!) === undefined) {
|
|
324
|
+
result[i] = withIndex(result[i]!, next++)
|
|
325
|
+
changed = true
|
|
326
|
+
}
|
|
327
|
+
return { items: result, next, changed }
|
|
328
|
+
}
|
|
329
|
+
|
|
280
330
|
/** Every string inside `value`, deeply. */
|
|
281
331
|
function* strings(value: unknown): Generator<string> {
|
|
282
332
|
if (typeof value == 'string') yield value
|
|
@@ -479,6 +529,7 @@ export class PupsFeed {
|
|
|
479
529
|
const item = this.#newItem(input)
|
|
480
530
|
const signal = options.signal
|
|
481
531
|
let archiveUrl = ''
|
|
532
|
+
let stored = item
|
|
482
533
|
let firstAttempt = true
|
|
483
534
|
await this.#transaction(async () => {
|
|
484
535
|
const main = await this.#readControlled(this.path, signal)
|
|
@@ -489,24 +540,57 @@ export class PupsFeed {
|
|
|
489
540
|
const doc: FeedDocument = { ...main.doc, _pups: { ...main.doc._pups } }
|
|
490
541
|
const hasArchives = this.#archiveNumber(doc._pups!.archive_url) !== undefined
|
|
491
542
|
if (!hasArchives && !this.#archivesWanted) {
|
|
492
|
-
// A feed without archives: the feed file is all there is (RFC-7 "Posting").
|
|
543
|
+
// A feed without archives: the feed file is all there is, and holds the counter (RFC-7 "Posting").
|
|
493
544
|
archiveUrl = this.url
|
|
494
|
-
|
|
545
|
+
const indexed = indexItems(doc.items, nextFree(doc.items, counterOf(doc)))
|
|
546
|
+
stored = withIndex(item, indexed.next)
|
|
547
|
+
doc._pups!.next_index = indexed.next + 1
|
|
548
|
+
await this.#writeMain({ ...doc, items: this.#newestItems([stored], indexed.items, doc) }, main.etag, signal)
|
|
495
549
|
return
|
|
496
550
|
}
|
|
497
551
|
if (!hasArchives) {
|
|
498
552
|
const started = await this.#startArchives(main, signal)
|
|
499
|
-
if (started)
|
|
553
|
+
if (started) {
|
|
554
|
+
doc._pups!.archive_url = started.url
|
|
555
|
+
doc.items = started.items
|
|
556
|
+
}
|
|
500
557
|
}
|
|
501
558
|
const added = await this.#addToArchive(main, doc, item, signal)
|
|
502
559
|
archiveUrl = added.url
|
|
560
|
+
stored = added.item
|
|
503
561
|
doc._pups!.archive_url = added.url
|
|
504
|
-
|
|
505
|
-
|
|
562
|
+
if (!hasArchives) {
|
|
563
|
+
// The old chain of a handed-over feed now continues behind the oldest archive, and the newest archive
|
|
564
|
+
// holds the counter.
|
|
565
|
+
delete doc.next_url
|
|
566
|
+
delete doc._pups!.next_index
|
|
567
|
+
}
|
|
506
568
|
doc.items = this.#newestItems(added.recent, doc.items, doc)
|
|
507
569
|
await this.#writeMain(doc, main.etag, signal)
|
|
508
570
|
})
|
|
509
|
-
return this.#result(
|
|
571
|
+
return this.#result(stored, archiveUrl)
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Gives every item of the feed without an index one (RFC-7 "Indexing an existing feed"), and sets the counter.
|
|
576
|
+
* `addPost()` does this by itself before the first post to a feed that hasn't been indexed yet; call it to
|
|
577
|
+
* index a feed without posting.
|
|
578
|
+
*/
|
|
579
|
+
async assignIndexes(options: Signal = {}): Promise<void> {
|
|
580
|
+
const signal = options.signal
|
|
581
|
+
await this.#transaction(async () => {
|
|
582
|
+
const main = await this.#readControlled(this.path, signal)
|
|
583
|
+
const newest = this.#archiveNumber(main.doc._pups?.archive_url)
|
|
584
|
+
if (newest === undefined) {
|
|
585
|
+
const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)))
|
|
586
|
+
if (indexed.changed || counterOf(main.doc) !== indexed.next)
|
|
587
|
+
await this.#writeMain({ ...main.doc, items: indexed.items, _pups: { ...main.doc._pups, next_index: indexed.next } }, main.etag, signal)
|
|
588
|
+
return
|
|
589
|
+
}
|
|
590
|
+
const archive = await this.#readArchive(this.#archivePath(newest), signal)
|
|
591
|
+
if (archive && archive != 'foreign' && (counterOf(archive.doc) === undefined || archive.doc.items.some(item => itemIndex(item) === undefined)))
|
|
592
|
+
await this.#indexArchives(main, signal)
|
|
593
|
+
})
|
|
510
594
|
}
|
|
511
595
|
|
|
512
596
|
/**
|
|
@@ -552,7 +636,10 @@ export class PupsFeed {
|
|
|
552
636
|
const fileUrl = this.#session.publicUrl(file.path)
|
|
553
637
|
const changed = typeof changes == 'function' ? await changes(clone(old)) : this.#applyChanges(clone(old), changes)
|
|
554
638
|
if (!changed) return this.#result(old, fileUrl)
|
|
555
|
-
const
|
|
639
|
+
const oldIndex = itemIndex(old)
|
|
640
|
+
let item: FeedItem = { ...changed, id, date_modified: now() }
|
|
641
|
+
// The index never changes (RFC-7 "Indexes").
|
|
642
|
+
if (oldIndex !== undefined) item = withIndex(item, oldIndex)
|
|
556
643
|
if (file != main) await this.#writeArchive(file, replaceAt(file.doc.items, index, item), signal)
|
|
557
644
|
const mainIndex = main.doc.items.findIndex(i => i.id == id)
|
|
558
645
|
if (mainIndex >= 0) await this.#writeMain({ ...main.doc, items: replaceAt(main.doc.items, mainIndex, item) }, main.etag, signal)
|
|
@@ -706,8 +793,10 @@ export class PupsFeed {
|
|
|
706
793
|
return fixed
|
|
707
794
|
}
|
|
708
795
|
|
|
709
|
-
|
|
710
|
-
|
|
796
|
+
/** Writes an archive with `items`, and with the counter `next_index` if given. */
|
|
797
|
+
async #writeArchive(archive: Loaded, items: FeedItem[], signal?: AbortSignal, nextIndex?: number) {
|
|
798
|
+
const doc = nextIndex === undefined ? { ...archive.doc, items } : { ...archive.doc, items, _pups: { ...archive.doc._pups, next_index: nextIndex } }
|
|
799
|
+
await this.#session.replace(archive.path, serialize(doc), archive.etag, { contentType: FEED_CONTENT_TYPE, signal })
|
|
711
800
|
}
|
|
712
801
|
|
|
713
802
|
/**
|
|
@@ -742,9 +831,9 @@ export class PupsFeed {
|
|
|
742
831
|
}
|
|
743
832
|
|
|
744
833
|
/** A new archive with the feed fields of the feed file (RFC-7 "Archives"). */
|
|
745
|
-
#newArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined): FeedDocument {
|
|
834
|
+
#newArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, nextIndex?: number): FeedDocument {
|
|
746
835
|
const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, ...fields } = main
|
|
747
|
-
const { archive_url: _archive, ...marker } = _pups ?? {}
|
|
836
|
+
const { archive_url: _archive, next_index: _counter, ...marker } = _pups ?? {}
|
|
748
837
|
const podcast = fields._podcast
|
|
749
838
|
if (isObject(podcast) && 'liveItems' in podcast) {
|
|
750
839
|
const { liveItems: _live, ...rest } = podcast
|
|
@@ -758,12 +847,12 @@ export class PupsFeed {
|
|
|
758
847
|
user_comment: archiveComment(this.url),
|
|
759
848
|
...nextUrl ? { next_url: nextUrl } : {},
|
|
760
849
|
items,
|
|
761
|
-
_pups: { about: PUPS_FEED_SPEC, ...marker, pupsControlled: true, updates_url: this.url },
|
|
850
|
+
_pups: { about: PUPS_FEED_SPEC, ...marker, pupsControlled: true, updates_url: this.url, ...nextIndex === undefined ? {} : { next_index: nextIndex } },
|
|
762
851
|
}
|
|
763
852
|
}
|
|
764
853
|
|
|
765
|
-
async #createArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, signal?: AbortSignal) {
|
|
766
|
-
await this.#session.create(this.#archivePath(n), serialize(this.#newArchive(n, main, items, nextUrl)), { contentType: FEED_CONTENT_TYPE, signal })
|
|
854
|
+
async #createArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, signal?: AbortSignal, nextIndex?: number) {
|
|
855
|
+
await this.#session.create(this.#archivePath(n), serialize(this.#newArchive(n, main, items, nextUrl, nextIndex)), { contentType: FEED_CONTENT_TYPE, signal })
|
|
767
856
|
}
|
|
768
857
|
|
|
769
858
|
/**
|
|
@@ -782,17 +871,22 @@ export class PupsFeed {
|
|
|
782
871
|
|
|
783
872
|
/**
|
|
784
873
|
* Puts the items of a feed without archives into new archives of `archiveSize`, oldest first (RFC-7 "Starting the
|
|
785
|
-
* archives"). The
|
|
786
|
-
*
|
|
874
|
+
* archives"). The items get indexes first, and the newest archive the counter. The oldest archive continues the
|
|
875
|
+
* feed's `next_url` chain.
|
|
876
|
+
* @returns the URL of the newest archive and the feed's items with their indexes, or undefined if the feed has no
|
|
877
|
+
* items.
|
|
787
878
|
*/
|
|
788
|
-
async #startArchives(main: Loaded, signal?: AbortSignal): Promise<string | undefined> {
|
|
789
|
-
const
|
|
879
|
+
async #startArchives(main: Loaded, signal?: AbortSignal): Promise<{ url: string; items: FeedItem[] } | undefined> {
|
|
880
|
+
const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)))
|
|
881
|
+
const oldestFirst = [...indexed.items].reverse()
|
|
882
|
+
const count = Math.ceil(oldestFirst.length / this.#archiveSize)
|
|
790
883
|
let url: string | undefined
|
|
791
|
-
for (let n = 0; n
|
|
884
|
+
for (let n = 0; n < count; n++) {
|
|
792
885
|
const items = oldestFirst.slice(n * this.#archiveSize, (n + 1) * this.#archiveSize).reverse()
|
|
793
886
|
const nextUrl = n ? this.#archiveUrl(n - 1) : main.doc.next_url
|
|
887
|
+
const nextIndex = n == count - 1 ? indexed.next : undefined
|
|
794
888
|
try {
|
|
795
|
-
await this.#createArchive(n, main.doc, items, nextUrl, signal)
|
|
889
|
+
await this.#createArchive(n, main.doc, items, nextUrl, signal, nextIndex)
|
|
796
890
|
} catch (e) {
|
|
797
891
|
if (!isPupsError(e, 'precondition_failed')) throw e
|
|
798
892
|
// Left behind by an interrupted start: complete it, as long as it holds only these items.
|
|
@@ -800,53 +894,106 @@ export class PupsFeed {
|
|
|
800
894
|
const ids = new Set(items.map(item => item.id))
|
|
801
895
|
if (!existing || existing == 'foreign' || !existing.doc.items.every(item => ids.has(item.id)))
|
|
802
896
|
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).`)
|
|
803
|
-
await this.#writeArchive(existing, items, signal)
|
|
897
|
+
await this.#writeArchive(existing, items, signal, nextIndex)
|
|
804
898
|
}
|
|
805
899
|
url = this.#archiveUrl(n)
|
|
806
900
|
}
|
|
807
|
-
return url
|
|
901
|
+
return url ? { url, items: indexed.items } : undefined
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/**
|
|
905
|
+
* Indexes a feed with archives whose newest archive has no counter, or items without an index (RFC-7 "Indexing an
|
|
906
|
+
* existing feed"): gives every archived item without an index one, the oldest first, writes the changed archives
|
|
907
|
+
* from the oldest to the newest, the newest with the counter, and then the feed file's copies.
|
|
908
|
+
*/
|
|
909
|
+
async #indexArchives(main: Loaded, signal?: AbortSignal): Promise<void> {
|
|
910
|
+
const files: Loaded[] = []
|
|
911
|
+
for await (const file of this.#chain(main, signal)) {
|
|
912
|
+
// Pages behind the oldest archive of a handed-over feed are never written, and keep their items unindexed.
|
|
913
|
+
if (file == main || !isControlled(file.doc)) break
|
|
914
|
+
files.push(file)
|
|
915
|
+
}
|
|
916
|
+
if (!files.length) return
|
|
917
|
+
let next = nextFree(files.flatMap(file => file.doc.items), ...files.map(file => counterOf(file.doc)))
|
|
918
|
+
const indexes = new Map<string, number>()
|
|
919
|
+
for (const file of [...files].reverse()) {
|
|
920
|
+
const indexed = indexItems(file.doc.items, next)
|
|
921
|
+
next = indexed.next
|
|
922
|
+
for (const item of indexed.items) indexes.set(item.id, itemIndex(item)!)
|
|
923
|
+
const newest = file == files[0]
|
|
924
|
+
if (indexed.changed || (newest && counterOf(file.doc) !== next)) await this.#writeArchive(file, indexed.items, signal, newest ? next : undefined)
|
|
925
|
+
}
|
|
926
|
+
let changed = false
|
|
927
|
+
const items = main.doc.items.map(item => {
|
|
928
|
+
const index = indexes.get(item.id)
|
|
929
|
+
if (index === undefined || itemIndex(item) === index) return item
|
|
930
|
+
changed = true
|
|
931
|
+
return withIndex(item, index)
|
|
932
|
+
})
|
|
933
|
+
if (changed) await this.#writeMain({ ...main.doc, items }, main.etag, signal)
|
|
808
934
|
}
|
|
809
935
|
|
|
810
936
|
/**
|
|
811
937
|
* Adds an item to the newest archive, or to a new archive if the newest holds `archiveSize` items (RFC-7
|
|
812
938
|
* "Posting"). Writes only archives; the caller writes the feed file afterwards.
|
|
813
|
-
*
|
|
939
|
+
* The item gets its index from the archive's counter (RFC-7 "Indexes"); a newest archive without a counter is
|
|
940
|
+
* indexed first, and the post then starts again.
|
|
941
|
+
* @returns the archive's URL, the newest items known from the archives, newest first, and the item as stored.
|
|
814
942
|
*/
|
|
815
|
-
async #addToArchive(main: Loaded, doc: FeedDocument, item: FeedItem, signal?: AbortSignal): Promise<{ url: string; recent: FeedItem[] }> {
|
|
943
|
+
async #addToArchive(main: Loaded, doc: FeedDocument, item: FeedItem, signal?: AbortSignal): Promise<{ url: string; recent: FeedItem[]; item: FeedItem }> {
|
|
816
944
|
const newest = this.#archiveNumber(doc._pups?.archive_url)
|
|
817
945
|
let previous: FeedItem[] = []
|
|
946
|
+
// The index for the item if it goes into a new archive.
|
|
947
|
+
let next = nextFree(doc.items, newest === undefined ? counterOf(doc) : undefined)
|
|
818
948
|
if (newest !== undefined) {
|
|
819
949
|
const existing = await this.#readArchive(this.#archivePath(newest), signal)
|
|
820
950
|
if (!existing) {
|
|
821
|
-
// The owner deleted it: create it again, linked to the next older archive.
|
|
822
|
-
|
|
823
|
-
|
|
951
|
+
// The owner deleted it: create it again, linked to the next older archive, with an index above all known ones.
|
|
952
|
+
const before = newest ? await this.#readArchive(this.#archivePath(newest - 1), signal) : undefined
|
|
953
|
+
if (before && before != 'foreign') next = nextFree([...doc.items, ...before.doc.items], counterOf(before.doc))
|
|
954
|
+
const stored = withIndex(item, next)
|
|
955
|
+
await this.#createArchive(newest, doc, [stored], newest ? this.#archiveUrl(newest - 1) : undefined, signal, next + 1)
|
|
956
|
+
return { url: this.#archiveUrl(newest), recent: [stored], item: stored }
|
|
824
957
|
}
|
|
825
958
|
if (existing != 'foreign') {
|
|
826
|
-
|
|
959
|
+
if (counterOf(existing.doc) === undefined) {
|
|
960
|
+
await this.#indexArchives(main, signal)
|
|
961
|
+
throw conflict(`${this.path} was indexed, so it`)
|
|
962
|
+
}
|
|
963
|
+
// Items that a client without indexes added get theirs first (RFC-7 "Items without an index").
|
|
964
|
+
const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc)))
|
|
965
|
+
const copy = indexed.items.find(i => i.id == item.id)
|
|
966
|
+
const stored = withIndex(item, copy ? itemIndex(copy)! : indexed.next)
|
|
967
|
+
const merged = mergeItems(indexed.items, [stored])
|
|
827
968
|
if (merged.length <= this.#archiveSize) {
|
|
828
|
-
await this.#writeArchive(existing, merged, signal)
|
|
829
|
-
return { url: this.#archiveUrl(newest), recent: merged }
|
|
969
|
+
await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1)
|
|
970
|
+
return { url: this.#archiveUrl(newest), recent: merged, item: stored }
|
|
830
971
|
}
|
|
831
|
-
|
|
972
|
+
if (indexed.changed) await this.#writeArchive(existing, indexed.items, signal, indexed.next)
|
|
973
|
+
previous = indexed.items
|
|
974
|
+
next = indexed.next
|
|
832
975
|
}
|
|
833
976
|
}
|
|
834
977
|
// The archive before the new one: the newest, or for a feed without archives the end of its old chain.
|
|
835
978
|
const nextUrl = newest === undefined ? doc.next_url : this.#archiveUrl(newest)
|
|
836
979
|
for (let n = newest === undefined ? 0 : newest + 1; n <= maxArchiveNumber; n++) {
|
|
980
|
+
const stored = withIndex(item, next)
|
|
837
981
|
try {
|
|
838
|
-
await this.#createArchive(n, doc, [
|
|
839
|
-
return { url: this.#archiveUrl(n), recent: [
|
|
982
|
+
await this.#createArchive(n, doc, [stored], nextUrl, signal, next + 1)
|
|
983
|
+
return { url: this.#archiveUrl(n), recent: [stored, ...previous], item: stored }
|
|
840
984
|
} catch (e) {
|
|
841
985
|
if (!isPupsError(e, 'precondition_failed')) throw e
|
|
842
986
|
}
|
|
843
987
|
// The archive exists: left behind by an interrupted client, or created by another client just now.
|
|
844
988
|
const existing = await this.#readArchive(this.#archivePath(n), signal)
|
|
845
989
|
if (existing && existing != 'foreign' && existing.doc.next_url == nextUrl) {
|
|
846
|
-
const
|
|
990
|
+
const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc), next))
|
|
991
|
+
const copy = indexed.items.find(i => i.id == item.id)
|
|
992
|
+
const added = withIndex(item, copy ? itemIndex(copy)! : indexed.next)
|
|
993
|
+
const merged = mergeItems(indexed.items, [added])
|
|
847
994
|
if (merged.length <= this.#archiveSize) {
|
|
848
|
-
await this.#writeArchive(existing, merged, signal)
|
|
849
|
-
return { url: this.#archiveUrl(n), recent: [...merged, ...previous] }
|
|
995
|
+
await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1)
|
|
996
|
+
return { url: this.#archiveUrl(n), recent: [...merged, ...previous], item: added }
|
|
850
997
|
}
|
|
851
998
|
}
|
|
852
999
|
const current = await this.#session.get(this.path, { signal })
|
|
@@ -869,6 +1016,12 @@ export class PupsFeed {
|
|
|
869
1016
|
if (markdown !== undefined) this.#setMarkdown(item, markdown)
|
|
870
1017
|
if (item.content_html === undefined && item.content_text === undefined)
|
|
871
1018
|
throw new PupsError('invalid_request', 'A post needs content_html, content_text or markdown (JSON Feed requires content).')
|
|
1019
|
+
// The index is given out when the item is added (RFC-7 "Indexes").
|
|
1020
|
+
if (isObject(item._pups)) {
|
|
1021
|
+
const { index: _index, ...marker } = item._pups
|
|
1022
|
+
if (Object.keys(marker).length) item._pups = marker
|
|
1023
|
+
else delete item._pups
|
|
1024
|
+
}
|
|
872
1025
|
return item
|
|
873
1026
|
}
|
|
874
1027
|
|
|
@@ -900,7 +1053,8 @@ export class PupsFeed {
|
|
|
900
1053
|
}
|
|
901
1054
|
|
|
902
1055
|
#result(item: FeedItem, fileUrl: string): PostResult {
|
|
903
|
-
|
|
1056
|
+
const index = itemIndex(item)
|
|
1057
|
+
return { id: item.id, ...index === undefined ? {} : { index }, item, url: `${fileUrl}#${encodeURIComponent(item.id)}` }
|
|
904
1058
|
}
|
|
905
1059
|
|
|
906
1060
|
/**
|
|
@@ -935,7 +1089,8 @@ export class PupsFeed {
|
|
|
935
1089
|
const path = `${this.directory}${prefix}${randomString(9)}.${extension}`
|
|
936
1090
|
const result = await this.#session.create(path, body, { signal })
|
|
937
1091
|
const size = typeof body == 'string' ? byteLength(body) : body instanceof Blob ? body.size : (body as ArrayBuffer | ArrayBufferView).byteLength
|
|
938
|
-
|
|
1092
|
+
// Feed directories are public, so the result always has a URL.
|
|
1093
|
+
return { path, url: result.url!, type, size }
|
|
939
1094
|
}
|
|
940
1095
|
|
|
941
1096
|
async #setImage(field: 'icon' | 'favicon', media: MediaInput | null, signal?: AbortSignal): Promise<FeedDocument> {
|
package/src/host-meta.ts
CHANGED
|
@@ -10,6 +10,8 @@ export interface HostMetaLink {
|
|
|
10
10
|
rel: string
|
|
11
11
|
href?: string
|
|
12
12
|
type?: string
|
|
13
|
+
/** A language tag or `default` → a title (RFC 7033). */
|
|
14
|
+
titles?: Record<string, string>
|
|
13
15
|
properties?: Record<string, string | null>
|
|
14
16
|
[field: string]: unknown
|
|
15
17
|
}
|
|
@@ -92,16 +94,48 @@ export class HostMetaEditor {
|
|
|
92
94
|
return [...new Set(properties)]
|
|
93
95
|
}
|
|
94
96
|
|
|
97
|
+
/** The link properties allowed for links to the file `href` (a path or a public URL): those declared for its well-known path. */
|
|
98
|
+
allowedLinkProperties(href: string): string[] {
|
|
99
|
+
try {
|
|
100
|
+
return wellKnownEntryFor(this.#target(href).path, this.#session.server.wellKnownPaths)?.linkProperties ?? []
|
|
101
|
+
} catch {
|
|
102
|
+
return []
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
95
106
|
/**
|
|
96
|
-
* Adds a link to one of the app's files
|
|
97
|
-
* a
|
|
98
|
-
*
|
|
107
|
+
* Adds a link to one of the app's files, or changes it if the app added it before: its `type`, `titles` and
|
|
108
|
+
* `properties` are then replaced (omitted ones removed). `href` may be a path (relative paths are in the app's own
|
|
109
|
+
* directory) or a public URL; it is sent as the public URL. `titles` maps language tags or `default` to titles;
|
|
110
|
+
* `properties` may only hold the link properties declared for the file's well-known path.
|
|
111
|
+
* @throws {PupsError} `insufficient_scope` if the file, rel or a property isn't allowed, `conflict` if a single-valued
|
|
112
|
+
* rel is taken or the link belongs to the owner or another app.
|
|
99
113
|
*/
|
|
100
|
-
async addLink(link: { rel: string; href: string; type?: string
|
|
114
|
+
async addLink(link: { rel: string; href: string; type?: string; titles?: Record<string, string>; properties?: Record<string, string> },
|
|
115
|
+
options: { signal?: AbortSignal } = {}): Promise<void> {
|
|
101
116
|
const { url } = this.#target(link.href)
|
|
102
117
|
if (!this.allowsRel(link.rel, link.href))
|
|
103
118
|
throw new PupsError('insufficient_scope', `The granted scopes don't allow the rel "${link.rel}" for ${url} (RFC-6, Links).`)
|
|
104
|
-
|
|
119
|
+
const allowed = this.allowedLinkProperties(link.href)
|
|
120
|
+
const bad = Object.keys(link.properties ?? {}).find(p => !allowed.includes(p))
|
|
121
|
+
if (bad)
|
|
122
|
+
throw new PupsError('insufficient_scope', `The link property "${bad}" isn't allowed for ${url}. Allowed: ${allowed.join(', ') || 'none'} (RFC-6, Links).`)
|
|
123
|
+
await this.#post({
|
|
124
|
+
action: 'add', rel: link.rel, href: url, ...link.type ? { type: link.type } : {},
|
|
125
|
+
...link.titles ? { titles: link.titles } : {}, ...link.properties ? { properties: link.properties } : {},
|
|
126
|
+
}, `Adding a ${link.rel} link`, options.signal)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Puts the links of `rel` into the order of `hrefs` (public URLs, or paths of files in the scopes). It must list
|
|
131
|
+
* every link of that rel in `host-meta.json` exactly once, the owner's and other apps' included; read them with
|
|
132
|
+
* {@link get} first.
|
|
133
|
+
* @throws {PupsError} `conflict` if `hrefs` doesn't match the current links, `insufficient_scope` if no granted
|
|
134
|
+
* scope allows the rel.
|
|
135
|
+
*/
|
|
136
|
+
async orderLinks(rel: string, hrefs: string[], options: { signal?: AbortSignal } = {}): Promise<void> {
|
|
137
|
+
const urls = hrefs.map(h => /^[a-z][a-z0-9+.-]*:/i.test(h) ? h : this.#target(h).url)
|
|
138
|
+
await this.#post({ action: 'order', rel, hrefs: urls }, `Ordering the ${rel} links`, options.signal)
|
|
105
139
|
}
|
|
106
140
|
|
|
107
141
|
/** Removes a link the app added. Links of the owner and of other apps are never touched by the server. */
|
|
@@ -124,7 +158,7 @@ export class HostMetaEditor {
|
|
|
124
158
|
}
|
|
125
159
|
|
|
126
160
|
/**
|
|
127
|
-
* The path and public URL of a link target, which must be a file inside the granted scopes.
|
|
161
|
+
* The path and public URL of a link target, which must be a public file inside the granted scopes.
|
|
128
162
|
* @throws {PupsError} `insufficient_scope`
|
|
129
163
|
*/
|
|
130
164
|
#target(href: string): { path: string; url: string } {
|
|
@@ -132,10 +166,12 @@ export class HostMetaEditor {
|
|
|
132
166
|
const path = /^[a-z][a-z0-9+.-]*:/i.test(href) ? pathFromPublicUrl(session.server, href) : session.resolve(href)
|
|
133
167
|
if (!path || !session.canWrite(path))
|
|
134
168
|
throw new PupsError('insufficient_scope', `"${href}" is not a file inside the scopes granted to this app. Links may only point to the app's own files (RFC-6, Links).`)
|
|
169
|
+
if (session.isPrivate(path))
|
|
170
|
+
throw new PupsError('insufficient_scope', `"${href}" is private: it has no public URL and can't be linked (RFC-6, Private areas).`)
|
|
135
171
|
return { path, url: session.publicUrl(path) }
|
|
136
172
|
}
|
|
137
173
|
|
|
138
|
-
async #post(body: Record<string,
|
|
174
|
+
async #post(body: Record<string, unknown>, what: string, signal?: AbortSignal) {
|
|
139
175
|
const endpoint = this.#session.server.hostMetaEndpoint
|
|
140
176
|
if (!endpoint) throw new PupsError('unsupported', `${new URL(this.#session.server.domain).host}'s server can't edit host-meta.json.`)
|
|
141
177
|
const response = await this.#session._authorized(endpoint, {
|
package/src/index.ts
CHANGED
|
@@ -16,7 +16,7 @@ export type {
|
|
|
16
16
|
} from './client.js'
|
|
17
17
|
export { PupsSession } from './session.js'
|
|
18
18
|
export type { Body, JsonBody, SessionChangeEvent, StoredFile, WriteOptions, WriteResult } from './session.js'
|
|
19
|
-
export { FEED_REL, PUPS_FEED_SPEC, PupsFeed, feedScopes } from './feed.js'
|
|
19
|
+
export { FEED_REL, PUPS_FEED_SPEC, PupsFeed, feedScopes, itemIndex } from './feed.js'
|
|
20
20
|
export type {
|
|
21
21
|
FeedAttachment,
|
|
22
22
|
FeedAuthor,
|
|
@@ -28,6 +28,7 @@ export type {
|
|
|
28
28
|
FeedSettingsChanges,
|
|
29
29
|
FeedSetup,
|
|
30
30
|
FeedState,
|
|
31
|
+
ItemMarker,
|
|
31
32
|
MediaInput,
|
|
32
33
|
MediaResult,
|
|
33
34
|
PostChanges,
|
package/src/paths.ts
CHANGED
|
@@ -64,21 +64,39 @@ export function wellKnownEntryFor(path: string, wellKnownPaths: readonly WellKno
|
|
|
64
64
|
return best
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/**
|
|
68
|
+
* Whether an absolute path is in a private area (RFC-6 "Private areas"): `/pups/private/…`, or the `private/`
|
|
69
|
+
* folder of an app's own directory, `/appdata/<client-host>/private/…`. Private files are read only with a token
|
|
70
|
+
* whose scope covers them, and have no public URL. Case-insensitive, like the servers, whose disk may be.
|
|
71
|
+
*/
|
|
72
|
+
export const isPrivate = (path: string) => /^\/(pups\/private\/|appdata\/[^/]+\/private\/[^/])/i.test(path)
|
|
73
|
+
|
|
67
74
|
/** The URL where `path` is written (RFC-6 "Upload API"). */
|
|
68
75
|
export const storageUrl = (server: PupsServer, path: string) => server.storageBase + encodePath(path).slice(1)
|
|
69
76
|
|
|
70
77
|
/**
|
|
71
78
|
* The URL where readers find `path` (RFC-6 "Public URLs"): `public_base` + path, or, for a file under a
|
|
72
79
|
* well-known entry with a `url`, that `url` plus the rest of the path.
|
|
80
|
+
* @throws {PupsError} `invalid_path` for a private file, which has no public URL.
|
|
73
81
|
*/
|
|
74
82
|
export function publicUrl(server: PupsServer, path: string): string {
|
|
83
|
+
if (isPrivate(path))
|
|
84
|
+
throw new PupsError('invalid_path', `${path} is private and has no public URL. Read it with get() (RFC-6, Private areas).`)
|
|
75
85
|
const entry = wellKnownEntryFor(path, server.wellKnownPaths)
|
|
76
86
|
if (entry?.url) return entry.url + encodePath(path.slice(entry.path.length))
|
|
77
87
|
return server.publicBase + encodePath(path).slice(1)
|
|
78
88
|
}
|
|
79
89
|
|
|
80
|
-
/**
|
|
90
|
+
/**
|
|
91
|
+
* The path of a public URL, the reverse of {@link publicUrl}, or undefined if the URL is not a public file of this
|
|
92
|
+
* server. Private files have no public URL, so a URL that maps to one is not a public file either.
|
|
93
|
+
*/
|
|
81
94
|
export function pathFromPublicUrl(server: PupsServer, url: string): string | undefined {
|
|
95
|
+
const path = mapPublicUrl(server, url)
|
|
96
|
+
return path && !isPrivate(path) ? path : undefined
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function mapPublicUrl(server: PupsServer, url: string): string | undefined {
|
|
82
100
|
try {
|
|
83
101
|
const entries = server.wellKnownPaths.filter(w => w.url).sort((a, b) => b.url!.length - a.url!.length)
|
|
84
102
|
for (const entry of entries)
|
package/src/scopes.ts
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import { PupsError } from './errors.js'
|
|
2
2
|
import type { PupsServer } from './discovery.js'
|
|
3
|
-
import { scopeCovers } from './paths.js'
|
|
3
|
+
import { isPrivate, scopeCovers } from './paths.js'
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* A scope an app can request (RFC-6 "Scopes"):
|
|
7
7
|
* - `'identify'`: sign-in only; the session can't write.
|
|
8
|
-
* - `'appdata'`: shorthand for `write:/appdata/<client-host>/`, the app's own directory
|
|
8
|
+
* - `'appdata'`: shorthand for `write:/appdata/<client-host>/`, the app's own directory, including its private
|
|
9
|
+
* folder `private/`.
|
|
9
10
|
* - `` `write:/${string}` ``: a well-known path declared by the server, or a file or directory inside a declared directory.
|
|
11
|
+
* In `/pups/private/`, it also allows reading.
|
|
12
|
+
* - `` `read:/${string}` ``: reading a private path in `/pups/private/` that the server declares, without writing it.
|
|
13
|
+
* Public files need no read scope.
|
|
10
14
|
*/
|
|
11
|
-
export type Scope = 'identify' | 'appdata' | `write:/${string}`
|
|
15
|
+
export type Scope = 'identify' | 'appdata' | `write:/${string}` | `read:/${string}`
|
|
12
16
|
|
|
13
17
|
/** The host of the `client_id`, which names the app's own directory. */
|
|
14
18
|
export const clientHostOf = (clientId: string) => new URL(clientId).hostname
|
|
@@ -24,10 +28,10 @@ export function expandScopes(scopes: readonly Scope[], clientId: string): string
|
|
|
24
28
|
|
|
25
29
|
const scopePathSyntax = /^\/(?:[A-Za-z0-9\-._~/]|%[0-9A-Fa-f]{2})*$/
|
|
26
30
|
|
|
27
|
-
/** The decoded path of a
|
|
28
|
-
|
|
29
|
-
if (!scope.startsWith(
|
|
30
|
-
const encoded = scope.slice(
|
|
31
|
+
/** The decoded path of a `<kind>:` scope, or undefined for other scopes and malformed ones. */
|
|
32
|
+
function scopePath(scope: string, kind: 'write' | 'read'): string | undefined {
|
|
33
|
+
if (!scope.startsWith(`${kind}:`)) return
|
|
34
|
+
const encoded = scope.slice(kind.length + 1)
|
|
31
35
|
if (!scopePathSyntax.test(encoded)) return
|
|
32
36
|
try {
|
|
33
37
|
return decodeURIComponent(encoded)
|
|
@@ -36,14 +40,25 @@ export function writeScopePath(scope: string): string | undefined {
|
|
|
36
40
|
}
|
|
37
41
|
}
|
|
38
42
|
|
|
43
|
+
/** The decoded path of a `write:` scope, or undefined for other scopes and malformed ones. */
|
|
44
|
+
export const writeScopePath = (scope: string) => scopePath(scope, 'write')
|
|
45
|
+
|
|
46
|
+
/** The decoded path of a `read:` scope, or undefined for other scopes and malformed ones. */
|
|
47
|
+
export const readScopePath = (scope: string) => scopePath(scope, 'read')
|
|
48
|
+
|
|
39
49
|
/** The decoded paths of all `write:` scopes in a granted scope list. */
|
|
40
50
|
export const writeScopePaths = (scopes: readonly string[]) =>
|
|
41
51
|
scopes.map(writeScopePath).filter((p): p is string => p !== undefined)
|
|
42
52
|
|
|
53
|
+
/** The decoded paths of the scopes that allow reading private files: every `write:` and every `read:` scope. */
|
|
54
|
+
export const readScopePaths = (scopes: readonly string[]) =>
|
|
55
|
+
[...writeScopePaths(scopes), ...scopes.map(readScopePath).filter((p): p is string => p !== undefined)]
|
|
56
|
+
|
|
43
57
|
/**
|
|
44
58
|
* Checks requested scopes against the server before the redirect, so that problems surface immediately instead of
|
|
45
59
|
* as an OAuth error after a round trip. Only two kinds of write scope exist: the app's own directory, and declared
|
|
46
|
-
* well-known paths (or paths inside declared directories).
|
|
60
|
+
* well-known paths (or paths inside declared directories). Read scopes exist only for declared paths in
|
|
61
|
+
* `/pups/private/`.
|
|
47
62
|
* @throws {PupsError} `invalid_scope`
|
|
48
63
|
*/
|
|
49
64
|
export function validateScopes(scopes: readonly string[], server: PupsServer, clientId: string): void {
|
|
@@ -51,10 +66,13 @@ export function validateScopes(scopes: readonly string[], server: PupsServer, cl
|
|
|
51
66
|
const appDataPath = appDataPathOf(clientId)
|
|
52
67
|
for (const scope of scopes) {
|
|
53
68
|
if (scope == 'identify') continue
|
|
54
|
-
const
|
|
69
|
+
const read = readScopePath(scope)
|
|
70
|
+
if (read !== undefined && !read.startsWith('/pups/private/'))
|
|
71
|
+
throw new PupsError('invalid_scope', `"${scope}": read scopes exist only for private paths in /pups/private/. Public files need no read scope, and an app's own private folder is covered by 'appdata' (RFC-6, Scopes).`)
|
|
72
|
+
const path = read ?? writeScopePath(scope)
|
|
55
73
|
if (path === undefined)
|
|
56
|
-
throw new PupsError('invalid_scope', `"${scope}" is not a PUPS scope. Use 'identify', 'appdata'
|
|
57
|
-
if (path == appDataPath) continue
|
|
74
|
+
throw new PupsError('invalid_scope', `"${scope}" is not a PUPS scope. Use 'identify', 'appdata', 'write:/<path>' or 'read:/pups/private/<path>' (RFC-6, Scopes).`)
|
|
75
|
+
if (path == appDataPath && read === undefined) continue
|
|
58
76
|
if (path.startsWith('/appdata/'))
|
|
59
77
|
throw new PupsError('invalid_scope', `"${scope}": an app may only ask for its own directory, ${appDataPath}. Use the 'appdata' shorthand (RFC-6, Scopes).`)
|
|
60
78
|
const declared = server.wellKnownPaths.some(w => w.path == path || (w.path.endsWith('/') && path.startsWith(w.path)))
|
|
@@ -66,3 +84,7 @@ export function validateScopes(scopes: readonly string[], server: PupsServer, cl
|
|
|
66
84
|
/** Whether the granted scopes allow writing the absolute path `path`. */
|
|
67
85
|
export const scopesCoverPath = (scopes: readonly string[], path: string) =>
|
|
68
86
|
writeScopePaths(scopes).some(scopePath => scopeCovers(scopePath, path))
|
|
87
|
+
|
|
88
|
+
/** Whether the granted scopes allow reading the absolute path `path`: always for public files, by scope for private ones. */
|
|
89
|
+
export const scopesAllowReading = (scopes: readonly string[], path: string) =>
|
|
90
|
+
!isPrivate(path) || readScopePaths(scopes).some(scopePath => scopeCovers(scopePath, path))
|