@estiva-app/interop 0.40.0 → 0.41.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/projection.ts CHANGED
@@ -12,8 +12,8 @@
12
12
  * anything: it becomes an integration written against one app, which is the
13
13
  * thing the whole exercise argues against.
14
14
  */
15
- import { decodeNaddr, decodeNevent, encodeNaddr, encodeNevent, findNaddrs, pointerToAddress, referenceToPointer, type AddressPointer, type EventPointer } from '@estiva-app/protocol'
16
- import { imetaOf, parseProfile, type Imeta, type Profile, type SignedEvent } from '@estiva-app/protocol'
15
+ import { decodeNevent, encodeNaddr, encodeNevent, pointerToAddress, referenceToPointer, type AddressPointer, type EventPointer } from '@estiva-app/protocol'
16
+ import { parseProfile, type Profile, type SignedEvent } from '@estiva-app/protocol'
17
17
  import { MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING } from '@estiva-app/protocol'
18
18
  import {
19
19
  attachmentsInDocument,
@@ -23,6 +23,14 @@ import {
23
23
  parseBlockDocument,
24
24
  } from '@estiva-app/protocol'
25
25
  import { planPlaceFile, planUnlistFile, type FolderRef } from './folders.js'
26
+ /*
27
+ SPEC §6.4's comment strength and §6.3's ordering are the conversation
28
+ package's (CON-5): one copy of each rule, read here for a file's `comments`,
29
+ `conversationsOf` and every change fold. Its `isCommentOn` is stricter than
30
+ the copy that lived here — a `kind:9` is never a comment (CON-20 migrated
31
+ them), a reply is never a root, and `ts` is trusted only inside its own second.
32
+ */
33
+ import { byOrder, isCommentOn, orderingMs } from '@estiva-app/conversation'
26
34
 
27
35
  /** Query the relay. Returns matching events; shape mirrors the HTTP bridge. */
28
36
  export type QueryFn = (filters: Record<string, unknown>[]) => Promise<SignedEvent[]>
@@ -347,7 +355,8 @@ function rootOf(event: SignedEvent): string {
347
355
  * on another file, a `kind:9` whose body names this one — and those are
348
356
  * *Mentioned in*, which §6.4 says MUST NOT be presented as the file's own
349
357
  * discussion. A badge counting them said "3" beside an issue with one comment.
350
- * See `isCommentOn` for the per-kind rule.
358
+ * See `@estiva-app/conversation`'s `isCommentOn` for the per-kind rule, which
359
+ * this passes the owner's declared comment kinds (§7.3).
351
360
  */
352
361
  export async function conversationsOf(
353
362
  files: ForeignObject[],
@@ -397,6 +406,7 @@ export async function conversationsOf(
397
406
  if (asked.length === 0) return {}
398
407
 
399
408
  const refOf = new Map(asked.map((a) => [a.address, a.ref]))
409
+ const kindsOf = new Map(asked.map((a) => [a.address, a.filter.kinds]))
400
410
  const conversations: Record<string, ConversationMessage[]> = {}
401
411
  for (const a of asked) conversations[a.ref] = []
402
412
 
@@ -425,7 +435,7 @@ export async function conversationsOf(
425
435
  neither when it merely mentions them. `isCommentOn` is §6.4's rule.
426
436
  */
427
437
  const ref = event.tags
428
- .filter((t) => t[0] === 'a' && t[1] && refOf.has(t[1]) && isCommentOn(event, t[1]))
438
+ .filter((t) => t[0] === 'a' && t[1] && refOf.has(t[1]) && isCommentOn(event, t[1], kindsOf.get(t[1])))
429
439
  .map((t) => refOf.get(t[1]))
430
440
  .find((found) => found !== undefined)
431
441
  if (ref !== undefined) {
@@ -528,242 +538,6 @@ export async function threadsOf(
528
538
  return { roots, replies }
529
539
  }
530
540
 
531
- /**
532
- * How many targets a reaction read asks about — SPEC §6.6, decided by CON-1.
533
- *
534
- * A `kind:7` carries no `h` and no `a`, so reactions are found only by asking
535
- * for the ids on screen, and the number asked for is a horizon every reader
536
- * shares: two apps with different N disagree about a count, legitimately and
537
- * unfixably. The value is the specification's, not this package's.
538
- */
539
- export const REACTION_HORIZON = 100
540
-
541
- /** A `kind:7` on a comment. */
542
- export interface CommentReaction {
543
- id: string
544
- emoji: string
545
- by: string
546
- at: number
547
- }
548
-
549
- /** A `kind:9101` resolution assertion on a comment (PEEK-128). */
550
- export interface CommentResolution {
551
- id: string
552
- action: 'resolved' | 'reopened'
553
- by: string
554
- at: number
555
- /** The assertion's free text, when it carried one. */
556
- message?: string
557
- /** The reply that carried the resolution, when the writer named one. */
558
- supportingEventId?: string
559
- }
560
-
561
- /** What has been done to one comment since it was written. */
562
- export interface CommentDecoration {
563
- /**
564
- * The newest `kind:40003` — the body to show, and when. RFC 0.4 §7.2.1: a
565
- * reader MUST be told the body changed, so this is kept beside the original
566
- * rather than folded over it; the consumer draws the marker.
567
- *
568
- * When the caller passes the target's `body`, `at` and `by` are those of the
569
- * last edit that **changed** the body — content not byte-identical to the
570
- * body it replaced — and `edit` is absent when none did (§7.2.1, amended
571
- * 2026-09-23, CON-5: the mark is about the body). `body` is always the newest
572
- * edit's content. Without `body` it is the newest edit, as before.
573
- */
574
- edit?: { body: string; at: number; by: string }
575
- /**
576
- * The `imeta` set of the newest edit that carries at least one — RFC 0.4
577
- * §7.2.1 as amended 2026-09-23 (CON-5). A set replaces the target's own; it
578
- * does not append. Absent when no edit carries one, in which case the
579
- * target's own attachments stand: an edit with no `imeta` means "unchanged".
580
- */
581
- attachments?: Imeta[]
582
- /** Every reaction found, in the order the relay holds them. Empty inside the horizon means none. */
583
- reactions: CommentReaction[]
584
- /** Oldest first; the last one is the current state. Empty means never resolved. */
585
- resolutions: CommentResolution[]
586
- }
587
-
588
- /** The answer of {@link commentDecorationsOf}. */
589
- export interface CommentDecorations {
590
- /** Keyed by comment id. A target nothing happened to is present, with nothing in it. */
591
- byId: Record<string, CommentDecoration>
592
- /**
593
- * How many of the targets were **not** asked about reactions, because they
594
- * fell outside the horizon. SPEC §6.6 makes reporting this a MUST: a cap
595
- * nobody can see is indistinguishable from "nobody reacted".
596
- */
597
- reactionTargetsOmitted: number
598
- }
599
-
600
- /** The three kinds a comment's decorations come in. Numbers, and here for the same reason `KIND_BARE_FILE` is. */
601
- const KIND_REACTION = 7
602
- const KIND_ASSERTION = 9101
603
- const KIND_MESSAGE_EDIT = 40003
604
-
605
- /**
606
- * The message a `kind:40003` edits: **the first `e` whose value is 64 hex,
607
- * marker ignored**, lowercased (SPEC §6.8, PEE-38). That is exactly the event
608
- * whose ownership the relay checked (`validate_edit_ownership`), and a reader
609
- * MUST NOT apply an edit to any other `e` — nothing refuses an edit carrying a
610
- * second one, so `['e', <own>, '', 'mention'], ['e', <victim>]` is accepted on
611
- * the writer's own message and must not be drawn on the victim's.
612
- *
613
- * Undefined when there is none, which the relay refuses; a reader holding one
614
- * anyway applies it nowhere.
615
- */
616
- export function editTargetOf(event: { tags: readonly (readonly string[])[] }): string | undefined {
617
- const tag = event.tags.find((t) => t[0] === 'e' && typeof t[1] === 'string' && /^[0-9a-fA-F]{64}$/.test(t[1]))
618
- return tag?.[1].toLowerCase()
619
- }
620
-
621
- /** Ids per `#e` filter. A comfortable fraction of the relay's page, so one filter's answer is never cut. */
622
- const DECORATION_TARGETS_PER_FILTER = 100
623
-
624
- /**
625
- * What has been done to a set of comments — edits, reactions, resolutions — in
626
- * one request, read by `#e`.
627
- *
628
- * **A second round trip, and that is why this is a function rather than part of
629
- * {@link resolveForeignObject}.** Everything that read returns is addressed by
630
- * `#a`, so it arrives with the root. An edit (`kind:40003`), a reaction
631
- * (`kind:7`) and a resolution (`kind:9101`) name the *comment* by `e` and not
632
- * the file, so they cannot be asked for until the comment ids are known. A
633
- * widget that never draws comments should not pay for that, so a consumer
634
- * that draws a conversation asks here with the ids it has — the roots off the
635
- * object, the replies off its thread read — and pays once for both.
636
- *
637
- * Three rules, each from the ticket that established it:
638
- *
639
- * - **Edits fold newest-wins** (CON-8). The original stays on the relay and so
640
- * does every edit; the fold is the reader's, and this is it. Attachments
641
- * fold separately (CON-5): the newest edit carrying `imeta` sets them.
642
- * - **Reactions have a horizon of {@link REACTION_HORIZON} targets** (SPEC
643
- * §6.6, CON-1) — the *newest* targets by `at`, one budget across whatever
644
- * id spaces the caller mixes, and the number left out is reported. Edits
645
- * and resolutions have no horizon: they are one event per change, not one
646
- * per reader.
647
- * - **A resolution is a `kind:9101` carrying `t=resolution`** (PEEK-128); its
648
- * `action` tag is the state, its content the rationale, and a second `e`
649
- * marked `support` names the reply that carried it.
650
- *
651
- * Nothing here checks who wrote an edit against who wrote the comment. The
652
- * relay adjudicates writes; a `40003` it stored is one it accepted — **for
653
- * the `e` it checked**, which is why an edit lands only on
654
- * {@link editTargetOf} and never on another `e` it carries.
655
- */
656
- export async function commentDecorationsOf(
657
- targets: readonly { id: string; at: number; body?: string }[],
658
- query: QueryFn,
659
- ): Promise<CommentDecorations> {
660
- const byId: Record<string, CommentDecoration> = {}
661
- const unique = new Map<string, number>()
662
- for (const t of targets) if (!unique.has(t.id)) unique.set(t.id, t.at)
663
- for (const id of unique.keys()) byId[id] = { reactions: [], resolutions: [] }
664
- if (unique.size === 0) return { byId, reactionTargetsOmitted: 0 }
665
-
666
- const ids = [...unique.keys()]
667
- // Newest first, ties on the higher id so the cut is stable between reads.
668
- const forReactions = [...unique]
669
- .sort((a, b) => b[1] - a[1] || (a[0] > b[0] ? -1 : 1))
670
- .slice(0, REACTION_HORIZON)
671
- .map(([id]) => id)
672
-
673
- const filters: Record<string, unknown>[] = []
674
- const chunked = (list: string[]) => {
675
- const out: string[][] = []
676
- for (let i = 0; i < list.length; i += DECORATION_TARGETS_PER_FILTER) {
677
- out.push(list.slice(i, i + DECORATION_TARGETS_PER_FILTER))
678
- }
679
- return out
680
- }
681
- for (const chunk of chunked(ids)) {
682
- filters.push({ kinds: [KIND_MESSAGE_EDIT, KIND_ASSERTION], '#e': chunk, limit: RELAY_PAGE_CEILING })
683
- }
684
- for (const chunk of chunked(forReactions)) {
685
- filters.push({ kinds: [KIND_REACTION], '#e': chunk, limit: RELAY_PAGE_CEILING })
686
- }
687
-
688
- const seen = new Set<string>()
689
- const edits = new Map<string, SignedEvent[]>()
690
- const bodies = new Map<string, string>()
691
- for (const t of targets) if (t.body !== undefined && !bodies.has(t.id)) bodies.set(t.id, t.body)
692
- for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
693
- const events = await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))
694
- for (const event of events) {
695
- if (seen.has(event.id)) continue
696
- seen.add(event.id)
697
- /*
698
- An edit's target is the one the relay checked ownership of, and no
699
- other (SPEC §6.8, PEE-38): see {@link editTargetOf}. For the rest, the
700
- `e` that names one of *our* targets — a resolution carries a second `e`
701
- for its supporting reply, so its first `e` is not necessarily the target.
702
- `hasOwn`, not `in`: an `e` of `constructor` is anybody's to write, and
703
- `in` finds it on the prototype.
704
- */
705
- const ours = (id: string | undefined): id is string => id !== undefined && Object.hasOwn(byId, id)
706
- const target =
707
- event.kind === KIND_MESSAGE_EDIT
708
- ? editTargetOf(event)
709
- : event.tags.find((t) => t[0] === 'e' && ours(t[1]) && !t[3])?.[1]
710
- if (!ours(target)) continue
711
- const into = byId[target]
712
- if (event.kind === KIND_MESSAGE_EDIT) {
713
- edits.set(target, [...(edits.get(target) ?? []), event])
714
- } else if (event.kind === KIND_REACTION) {
715
- if (!forReactions.includes(target)) continue
716
- into.reactions.push({ id: event.id, emoji: event.content, by: event.pubkey, at: event.created_at })
717
- } else if (event.kind === KIND_ASSERTION) {
718
- if (tagValue(event, 't') !== 'resolution') continue
719
- const action = tagValue(event, 'action')
720
- if (action !== 'resolved' && action !== 'reopened') continue
721
- const support = event.tags.find((t) => t[0] === 'e' && t[3] === 'support')?.[1]
722
- into.resolutions.push({
723
- id: event.id,
724
- action,
725
- by: event.pubkey,
726
- at: event.created_at,
727
- ...(event.content ? { message: event.content } : {}),
728
- ...(support ? { supportingEventId: support } : {}),
729
- })
730
- }
731
- }
732
- }
733
- for (const [target, list] of edits) {
734
- const ordered = [...list].sort(byOrder)
735
- const into = byId[target]
736
- const newest = ordered[ordered.length - 1]
737
- let body = bodies.get(target)
738
- if (body === undefined) {
739
- into.edit = { body: newest.content, at: newest.created_at, by: newest.pubkey }
740
- } else {
741
- // Replayed from the target's own body, so "byte-identical to the body it
742
- // replaces" is judged against the body as it then stood.
743
- let changed: SignedEvent | undefined
744
- for (const edit of ordered) {
745
- if (edit.content !== body) changed = edit
746
- body = edit.content
747
- }
748
- if (changed) into.edit = { body: newest.content, at: changed.created_at, by: changed.pubkey }
749
- }
750
- for (let i = ordered.length - 1; i >= 0; i--) {
751
- const set = imetaOf(ordered[i])
752
- if (set.length > 0) {
753
- into.attachments = set
754
- break
755
- }
756
- }
757
- }
758
- const oldestFirst = (a: { at: number; id: string }, b: { at: number; id: string }) =>
759
- a.at - b.at || (a.id < b.id ? -1 : 1)
760
- for (const decoration of Object.values(byId)) {
761
- decoration.reactions.sort(oldestFirst)
762
- decoration.resolutions.sort(oldestFirst)
763
- }
764
- return { byId, reactionTargetsOmitted: ids.length - forReactions.length }
765
- }
766
-
767
541
  /** How the owning app says its records should be read. */
768
542
  interface RecordsRule {
769
543
  changeKind: number
@@ -1349,53 +1123,6 @@ export function folderOf(root: SignedEvent): string | null {
1349
1123
  const hasTagValue = (e: SignedEvent, name: string, value: string) =>
1350
1124
  e.tags.some((t) => t[0] === name && t[1] === value)
1351
1125
 
1352
- /** The addresses a body names by `nostr:naddr…`; a pointer that will not decode is prose. */
1353
- function namedInBody(body: string): Set<string> {
1354
- const addresses = new Set<string>()
1355
- for (const naddr of findNaddrs(body)) {
1356
- try {
1357
- addresses.add(pointerToAddress(decodeNaddr(naddr)))
1358
- } catch {
1359
- // A malformed pointer is prose.
1360
- }
1361
- }
1362
- return addresses
1363
- }
1364
-
1365
- /**
1366
- * Is this event a *comment* on the address, rather than a message elsewhere
1367
- * that merely names it?
1368
- *
1369
- * Both arrive by the object's `#a` read — the `a` tag is the index of every
1370
- * reference, whichever strength — and SPEC §6.4 says an app MUST NOT present
1371
- * the two as one list: a comment is the object's own discussion, a mention is
1372
- * *Mentioned in*. Until CON-15 this package handed the raw `#a` union to
1373
- * {@link resolveForeignObject}'s `comments` and {@link conversationsOf}, and
1374
- * a widget said "3" beside an issue with one comment and two mentions. The
1375
- * rule is §6.4's per-tag one, applied per kind (CON-13, CON-14):
1376
- *
1377
- * - A `kind:1111`'s uppercase `A` is the comment — NIP-22's thread root. One
1378
- * whose `A` is another file is that file's conversation; its `a` for this
1379
- * one is the index of a reference. One with no `A` at all is read by its
1380
- * `a`, the way §6.4 says to read it rather than drop the thread.
1381
- * - Any other comment kind has no `A`, so its `a` is read against its body.
1382
- * A `kind:9` whose body names the address is the index of that reference —
1383
- * what Peek writes for every `[`-menu reference in a topic message — and a
1384
- * mention. One whose body does not is the anchor of a comment written
1385
- * before REW-10 moved comments to `1111`, which is not replaceable and so
1386
- * reads as a comment for good.
1387
- *
1388
- * `commentDecorationsOf` is deliberately not behind this: a reaction or a
1389
- * status on a comment is about the *comment*, whatever that comment is about.
1390
- */
1391
- function isCommentOn(event: SignedEvent, address: string): boolean {
1392
- if (event.kind === KIND_COMMENT) {
1393
- const roots = event.tags.filter((t) => t[0] === 'A' && t[1])
1394
- return roots.length > 0 ? roots.some((t) => t[1] === address) : hasTagValue(event, 'a', address)
1395
- }
1396
- return hasTagValue(event, 'a', address) && !namedInBody(event.content).has(address)
1397
- }
1398
-
1399
1126
  /**
1400
1127
  * A manifest event's `content`, or null when it is not parseable JSON.
1401
1128
  *
@@ -2107,33 +1834,6 @@ export async function resolveActingManifest(
2107
1834
  return borrowedFrom(pointer.kind, owner, creators).find((creator) => creator.address === declaredBy) ?? null
2108
1835
  }
2109
1836
 
2110
- /**
2111
- * Ordering key for an append-only event, per the manifest's `records.order`.
2112
- *
2113
- * The manifest declares `["ts", "created_at", "id"]` and, crucially, the
2114
- * condition under which `ts` may be believed: only when it agrees with
2115
- * `created_at` to the second. `created_at` has one-second resolution and the
2116
- * relay validates it, so a `ts` pinned inside that second inherits that
2117
- * validation and can only refine ordering *within* it.
2118
- *
2119
- * Peek enforces that bound itself rather than trusting the writer. Under the
2120
- * honour-system model nothing validates these events (RFC_UPDATES.md §3), so a
2121
- * buggy or pushy client claiming a far-future `ts` would otherwise win every
2122
- * fold forever — in Peek's rendering as much as in the owning app's.
2123
- */
2124
- function orderingMs(event: SignedEvent): number {
2125
- const raw = Number.parseInt(tagValue(event, 'ts') ?? '', 10)
2126
- if (Number.isFinite(raw) && Math.abs(Math.floor(raw / 1000) - event.created_at) <= 1) return raw
2127
- return event.created_at * 1000
2128
- }
2129
-
2130
- /** Total order, oldest first. Ties break on the lower event id (NIP-01's rule). */
2131
- function byOrder(a: SignedEvent, b: SignedEvent): number {
2132
- const [at, bt] = [orderingMs(a), orderingMs(b)]
2133
- if (at !== bt) return at - bt
2134
- return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
2135
- }
2136
-
2137
1837
  /** Replay change events into current field values. Last write wins per field. */
2138
1838
  /**
2139
1839
  * The fold rule a manifest declares, or one that folds nothing — PRO-6.
@@ -3632,10 +3332,10 @@ function assembleObject(plan: ObjectPlan, answered: SignedEvent[], childChanges:
3632
3332
 
3633
3333
  Then narrowed to §6.4's *comment* strength (CON-15): the `a` tag is also the
3634
3334
  index of a mention, and a mention is not this object's discussion. See
3635
- `isCommentOn` for the per-kind rule.
3335
+ `isCommentOn` (`@estiva-app/conversation`) for the per-kind rule.
3636
3336
  */
3637
3337
  const comments = events
3638
- .filter((e) => commentKinds.includes(e.kind) && isCommentOn(e, address))
3338
+ .filter((e) => commentKinds.includes(e.kind) && isCommentOn(e, address, commentKinds))
3639
3339
  .sort(byOrder)
3640
3340
  .map((e) => ({ id: e.id, author: e.pubkey, body: e.content, createdAt: e.created_at }))
3641
3341