@estiva-app/conversation 0.33.0 → 0.35.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/places.ts CHANGED
@@ -26,7 +26,7 @@
26
26
  */
27
27
  import { fileIdOf, KIND, type SignedEvent, type UnsignedEvent } from '@estiva-app/protocol'
28
28
  import { FILE_ADDRESS, FOLDER_ID, KIND_APP_DATA, KIND_CHANGE } from './kinds.js'
29
- import { APPDATA_TAG, FOLLOW_FIELD_PREFIX, memberOfField } from './membership.js'
29
+ import { APPDATA_TAG, FOLLOW_FIELD_PREFIX, buildMembershipChange, memberOfField } from './membership.js'
30
30
  import { byOrder } from './order.js'
31
31
  import { REPLY_FLOOR_CONTEXT, belowReplyFloor, effectiveReadAt, streamMarkerOf, threadContext } from './readState.js'
32
32
  import { peopleNamedInBody } from './strength.js'
@@ -106,6 +106,8 @@ export interface Following {
106
106
  allSince?: number
107
107
  /** Every way in that holds now. */
108
108
  ways: WayIn[]
109
+ /** Who put them in, when the way `added` holds and somebody else signed the Add; undefined for their own join. */
110
+ addedBy?: string
109
111
  }
110
112
 
111
113
  type Act = { event: Event; act: 'creation' | 'level' | 'clear' | 'join' | 'leave'; level?: Level }
@@ -294,6 +296,7 @@ export function followingOf(place: Place, person: string, facts: PlaceFacts): Fo
294
296
  if (joined) {
295
297
  out.ways.push('added')
296
298
  starts.push(joined.event.created_at)
299
+ if (joined.event.pubkey !== person) out.addedBy = joined.event.pubkey
297
300
  }
298
301
  // 3. Made it: the first record orders before everything, so any leave ends it.
299
302
  const made = after.find((a) => a.act === 'creation')
@@ -322,6 +325,194 @@ export function followingOf(place: Place, person: string, facts: PlaceFacts): Fo
322
325
  return { ...out, in: true, level: chosen?.level ?? 'important', since: Math.min(...starts), ...(chosen?.allSince !== undefined ? { allSince: chosen.allSince } : {}) }
323
326
  }
324
327
 
328
+ // ── Who a place lists ───────────────────────────────────────────────────────
329
+
330
+ /** One person a place lists, and how they are in it. */
331
+ export interface Listed {
332
+ pubkey: string
333
+ level: Level
334
+ /** Every way in that holds, of the ones anyone can see: `team` only for the team's members. */
335
+ ways: WayIn[]
336
+ since?: number
337
+ /** Who added them, when somebody else did. */
338
+ addedBy?: string
339
+ }
340
+
341
+ /**
342
+ * Who a place lists (§11.8 *Who a place lists*), worked out from public
343
+ * events alone so every reader gets the same list: everyone who chose a level
344
+ * (at that level), everyone added or joined (at their level, or Important),
345
+ * its author, and, on a team's chat and spaces, the team's members at the
346
+ * default. Someone in it only through a team they follow is not named until
347
+ * they choose a level, and a member's private opt-out is not seen: the list
348
+ * undercounts. All first, then Important, each by since.
349
+ *
350
+ * `viewer`, with their own private teams list, is listed as they are in it:
351
+ * gone once they turned the default off, there when a team they follow
352
+ * reaches them. Everyone else sees them by public events alone.
353
+ *
354
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-place-lists-who-chose-a-level-and-its-teams-members.md
355
+ */
356
+ export function placeListing(place: Place, facts: Omit<PlaceFacts, 'teams'>, viewer?: { pubkey: string; teams?: TeamsList }): Listed[] {
357
+ const people = new Set<string>()
358
+ const versions = place.address.startsWith(`${KIND_TEAM}:`) ? [] : facts.events.filter((e) => addressOf(e) === place.address)
359
+ for (const v of versions) people.add(v.pubkey)
360
+ for (const change of facts.events) {
361
+ if (change.kind !== KIND_CHANGE || tag(change, 'a') !== place.address) continue
362
+ const field = tag(change, 'field')
363
+ const member = memberOfField(field)
364
+ if (member !== undefined) people.add(member)
365
+ else if (field?.startsWith(FOLLOW_FIELD_PREFIX)) people.add(field.slice(FOLLOW_FIELD_PREFIX.length))
366
+ }
367
+ if (placeKindOf(place, facts.listing) !== 'topic') for (const m of teamMembersOf(place.team, facts.roster ?? [])) people.add(m.pubkey)
368
+ if (viewer) people.add(viewer.pubkey)
369
+
370
+ const listed: Listed[] = []
371
+ for (const pubkey of people) {
372
+ if (!PUBKEY.test(pubkey)) continue
373
+ // Nobody else's private teams list is readable: their following through a team they follow never shows.
374
+ const own = pubkey === viewer?.pubkey ? viewer.teams : undefined
375
+ const f = followingOf(place, pubkey, { ...facts, teams: own })
376
+ if (!f.in || !f.level) continue
377
+ listed.push({ pubkey, level: f.level, ways: f.ways, ...(f.since !== undefined ? { since: f.since } : {}), ...(f.addedBy ? { addedBy: f.addedBy } : {}) })
378
+ }
379
+ const rank = (l: Listed) => (l.level === 'all' ? 0 : 1)
380
+ return listed.sort((a, b) => rank(a) - rank(b) || (a.since ?? 0) - (b.since ?? 0) || a.pubkey.localeCompare(b.pubkey))
381
+ }
382
+
383
+ // ── Add, and the switch: Not following, Important, All, back to the default ──
384
+
385
+ /**
386
+ * The `prev` an Add of `person` to the place names (§11.8): the person's own
387
+ * leave, when it is the field's current change. Undefined when they never
388
+ * left, or were put back in since — an Add needs none then.
389
+ */
390
+ function currentLeaveOf(place: Place, person: string, events: readonly Event[]): Event | undefined {
391
+ const last = actsOf(place, person, events)
392
+ .filter((a) => a.act === 'join' || a.act === 'leave')
393
+ .at(-1)
394
+ return last?.act === 'leave' ? last.event : undefined
395
+ }
396
+
397
+ /** The ms a change sorts at (§6.3): its `ts` where it agrees with `created_at`, else `created_at`. */
398
+ function sortMsOf(event: Event): number {
399
+ const ts = Number(tag(event, 'ts'))
400
+ return Number.isSafeInteger(ts) && Math.floor(ts / 1000) === event.created_at ? ts : event.created_at * 1000
401
+ }
402
+
403
+ /**
404
+ * Add a person to a topic, a space or a team's chat (§11.8): a `member:<P>` =
405
+ * `true` by anyone, naming the person's leave with `prev` when they left. The
406
+ * relay refuses a change that does not sort after its `prev` (§6.2), so an
407
+ * adder whose clock is behind the leave stamps the Add 1 ms after it. `folder` is the
408
+ * place's own team: its root's `h`, or the team itself for its chat. `events`
409
+ * are the place's events, as {@link placeFilters} read them.
410
+ *
411
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/anyone-may-add-a-person-to-a-file.md
412
+ */
413
+ export function buildPlaceAdd(
414
+ pubkey: string,
415
+ createdAtMs: number,
416
+ args: { place: Place; folder: string; person: string; events: readonly Event[]; note?: string },
417
+ ): UnsignedEvent {
418
+ const leave = currentLeaveOf(args.place, args.person, args.events)
419
+ const prev = leave?.id
420
+ const at = leave ? Math.max(createdAtMs, sortMsOf(leave) + 1) : createdAtMs
421
+ return buildMembershipChange(pubkey, at, {
422
+ file: args.place.address,
423
+ folder: args.folder,
424
+ person: args.person,
425
+ member: true,
426
+ ...(args.note !== undefined ? { note: args.note } : {}),
427
+ ...(prev !== undefined ? { prev } : {}),
428
+ })
429
+ }
430
+
431
+ /** What the switch on a place can be set to: a level, Not following, or back to the team's default. */
432
+ export type SwitchChoice = Level | 'not-following' | 'default'
433
+
434
+ /** What the switch shows for a person on a place. */
435
+ export interface SwitchState {
436
+ /** The level that lights for them, or Not following. A mute already kept shows as Not following (§11.8 *Muting*). */
437
+ shown: Level | 'not-following'
438
+ /** Whether a team's default would reach them here, were it not turned off. */
439
+ defaultReaches: boolean
440
+ /** A default reaches them and they chose a level, or turned it off. "Back to the default" is offered then. */
441
+ againstDefault: boolean
442
+ }
443
+
444
+ /** The id the private `off` list names a place by: a topic's or space's `d`, a team's chat by the team's uuid. */
445
+ export function placeOffId(place: Place): string {
446
+ return dOf(place.address)
447
+ }
448
+
449
+ /** What the switch shows for `person` on the place, from what {@link placeFilters} read. */
450
+ export function switchStateOf(place: Place, person: string, facts: PlaceFacts, opts: { muted?: boolean } = {}): SwitchState {
451
+ const following = followingOf(place, person, facts)
452
+ const id = placeOffId(place)
453
+ const off = facts.teams?.off.includes(id) ?? false
454
+ const withDefault = off ? followingOf(place, person, { ...facts, teams: { ...facts.teams!, off: facts.teams!.off.filter((o) => o !== id) } }) : following
455
+ const defaultReaches = withDefault.ways.includes('team')
456
+ const shown = opts.muted || !following.in || !following.level ? 'not-following' : following.level
457
+ return { shown, defaultReaches, againstDefault: defaultReaches && (off || following.ways.includes('level')) }
458
+ }
459
+
460
+ /** The writes one choice on the switch takes. */
461
+ export interface SwitchWrites {
462
+ /** The public changes to sign as the person, in order: a level, or a leave. */
463
+ changes: UnsignedEvent[]
464
+ /** The private `off` list's change, when the choice turns a team's default off or back on ({@link withPlaceOff}). */
465
+ off?: { id: string; off: boolean }
466
+ /** Whether a mute already kept for the place is taken out (§11.8 *Muting*): choosing a level or the default does. */
467
+ clearsMute: boolean
468
+ }
469
+
470
+ /**
471
+ * The writes for one choice on a place's switch (§11.8). A level is a
472
+ * `follow:<P>`. Not following is never public: a leave only when `P` chose
473
+ * a level, joined, was added or made the place, and an `off` entry when a
474
+ * team's default reaches `P` — a place `P` is in only by a default gets the
475
+ * entry alone. Back to the default is an empty `follow:<P>` when a level was
476
+ * chosen, and takes the place out of `off`. `folder` is the place's own team:
477
+ * its root's `h`, or the team itself for its chat.
478
+ *
479
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-persons-level-on-a-place-is-theirs-alone.md
480
+ */
481
+ export function switchWrites(
482
+ pubkey: string,
483
+ createdAtMs: number,
484
+ args: { place: Place; folder: string; choice: SwitchChoice; following: Following; teams?: TeamsList },
485
+ ): SwitchWrites {
486
+ const { place, folder, choice, following } = args
487
+ const id = placeOffId(place)
488
+ const isOff = args.teams?.off.includes(id) ?? false
489
+ if (choice === 'all' || choice === 'important') {
490
+ return { changes: [buildLevelChange(pubkey, createdAtMs, { place: place.address, folder, level: choice })], clearsMute: true }
491
+ }
492
+ if (choice === 'default') {
493
+ const changes = following.ways.includes('level') ? [buildLevelChange(pubkey, createdAtMs, { place: place.address, folder, level: '' })] : []
494
+ return { changes, ...(isOff ? { off: { id, off: false } } : {}), clearsMute: true }
495
+ }
496
+ const byDefault = following.ways.includes('team')
497
+ const joined = following.ways.some((w) => w === 'added' || w === 'author')
498
+ // Where a default reaches P and only a chosen level holds besides, clearing the level reads as
499
+ // "back to the default" to everyone else: nobody sees that P switched the place off.
500
+ const changes = joined || (following.ways.includes('level') && !byDefault)
501
+ ? [buildMembershipChange(pubkey, createdAtMs, { file: place.address, folder, person: pubkey, member: false })]
502
+ : following.ways.includes('level')
503
+ ? [buildLevelChange(pubkey, createdAtMs, { place: place.address, folder, level: '' })]
504
+ : []
505
+ return { changes, ...(byDefault ? { off: { id, off: true } } : {}), clearsMute: false }
506
+ }
507
+
508
+ /** The teams list with a place's default turned off, or back on: what to serialize, encrypt and write whole. */
509
+ export function withPlaceOff(list: Pick<TeamsList, 'teams' | 'off'> | undefined, change: { id: string; off: boolean }): Pick<TeamsList, 'teams' | 'off'> {
510
+ const off = new Set(list?.off ?? [])
511
+ if (change.off) off.add(change.id)
512
+ else off.delete(change.id)
513
+ return { teams: { ...(list?.teams ?? {}) }, off: [...off].sort() }
514
+ }
515
+
325
516
  /**
326
517
  * The filters that read what {@link followingOf} needs for one place: its
327
518
  * root and changes, the team's roster, the team's list and the commands
package/src/refusals.ts CHANGED
@@ -88,7 +88,7 @@ const RULES: readonly [RegExp, RefusalCause][] = [
88
88
  [/timestamp too far|clock/i, 'clock'],
89
89
  [/auth-required|insufficient scope|does not match authenticated|signed out|sign in|\b401\b|token_rejected|session_expired/i, 'signed-out'],
90
90
  [/archived/i, 'archived'],
91
- [/target (event )?not found|not (editable|deletable) by you|was deleted|no longer on this page/i, 'gone'],
91
+ [/(target|parent) (event )?not found|not (editable|deletable) by you|was deleted|no longer on this page/i, 'gone'],
92
92
  [/^(restricted|blocked):|not a (channel |relay )?member|only members|no longer (post|write)|banned|timed out until|writes are fenced|\b403\b/i, 'no-access'],
93
93
  ]
94
94
 
package/src/shape.ts CHANGED
@@ -143,15 +143,14 @@ export function foldThreads(events: readonly SignedEvent[], options: { viewer?:
143
143
  thread others answered; a channel `kind:9` names no author, and stays
144
144
  `missing`.
145
145
  */
146
- /** A comment the read did not return is in the Folder most of its replies were filed in, or none on a tie (§6.5). */
146
+ /**
147
+ A comment the read did not return is in its replies' team when every returned reply names the same `h`, else none (§6.5).
148
+ The relay files a reply only in its comment's team (§6.4, *Replies*), so replies that disagree were not all filed under it.
149
+ */
147
150
  const replyFolderOf = (answers: readonly SignedEvent[]): string | undefined => {
148
- const count = new Map<string, number>()
149
- for (const r of answers) {
150
- const h = values(r, 'h')[0]
151
- if (h) count.set(h, (count.get(h) ?? 0) + 1)
152
- }
153
- const ranked = [...count].sort((a, b) => b[1] - a[1])
154
- return ranked.length > 0 && (ranked.length === 1 || ranked[0][1] > ranked[1][1]) ? ranked[0][0] : undefined
151
+ const teams = new Set(answers.map((r) => values(r, 'h')[0]))
152
+ const [only] = teams
153
+ return teams.size === 1 ? only : undefined
155
154
  }
156
155
  const deletedUnseen = (id: string, answers: readonly SignedEvent[]) => {
157
156
  const comments = answers.filter((r) => r.kind === KIND_COMMENT)
@@ -205,9 +204,8 @@ export function foldThreads(events: readonly SignedEvent[], options: { viewer?:
205
204
  const all = replies[id] ?? []
206
205
  const kept = all.filter((r) => !deletedBy(r.id, r.pubkey)).map(messageOf)
207
206
  const folder = root ? values(root, 'h')[0] : replyFolderOf(all)
208
- // Not returned, only the replies filed in the thread's Folder speak for its comment: one filed elsewhere neither deletes nor clears.
209
- const speaking = root ? all : all.filter((r) => values(r, 'h')[0] === folder)
210
- const state: RootState = (root ? deletedBy(id, root.pubkey) : folder !== undefined && deletedUnseen(id, speaking)) ? 'deleted' : root ? 'present' : 'missing'
207
+ // Not returned, its replies speak for its comment only when they agree on its team; replies that disagree leave it `missing`.
208
+ const state: RootState = (root ? deletedBy(id, root.pubkey) : folder !== undefined && deletedUnseen(id, all)) ? 'deleted' : root ? 'present' : 'missing'
211
209
  const resolution = resolutionOf(resolutions[id.toLowerCase()] ?? [], { folder, replies: kept.map((r) => r.id) })
212
210
  return {
213
211
  id: id.toLowerCase(),
package/src/strength.ts CHANGED
@@ -29,6 +29,7 @@
29
29
  */
30
30
  import { decodeNaddr, decodeNpub, findNaddrs, findNostrUris, FILE_KINDS, fileIdFormOf, fileIdOf, pointerToAddress, type NostrTag, type SignedEvent } from '@estiva-app/protocol'
31
31
  import { KIND_COMMENT } from './kinds.js'
32
+ import { parentOf } from './threads.js'
32
33
 
33
34
  type Tagged = Pick<SignedEvent, 'kind' | 'tags'>
34
35
  type Readable = Pick<SignedEvent, 'kind' | 'tags' | 'content'>
@@ -53,19 +54,17 @@ export function namedInBody(body: string): Set<string> {
53
54
  }
54
55
 
55
56
  /**
56
- * Whether the event answers another: a `kind:9` with any `e`, or a
57
- * `kind:1111` with a lowercase `e` that differs from its `E`.
57
+ * Whether the event answers another: {@link parentOf} names a parent. A
58
+ * `kind:9` with any `e`, or a `kind:1111` with a lowercase `e` that differs
59
+ * from its `E` and no `a` equal to its `A`.
58
60
  *
59
61
  * A top-level comment on an *event* root carries `E` and `e` naming the same
60
- * event and is not a reply. On an address root it carries no `e` at all.
62
+ * event and is not a reply. On an address root it carries no `e`, or, in
63
+ * NIP-22's own shape, an `a` equal to its `A` and an `e` with the file's
64
+ * version id.
61
65
  */
62
66
  export function isReply(event: Pick<SignedEvent, 'kind' | 'tags'>): boolean {
63
- // A NIP-10 `mention`-marked `e` quotes an event; it answers nothing.
64
- const es = event.tags.filter((t) => t[0] === 'e' && typeof t[1] === 'string' && t[1] !== '' && t[3] !== 'mention').map((t) => t[1])
65
- if (es.length === 0) return false
66
- if (event.kind !== KIND_COMMENT) return true
67
- const root = values(event, 'E')[0]
68
- return es.some((e) => e !== root)
67
+ return parentOf(event) !== null
69
68
  }
70
69
 
71
70
  /**
package/src/threads.ts CHANGED
@@ -28,7 +28,9 @@ const es = (event: Pick<SignedEvent, 'tags'>) =>
28
28
  *
29
29
  * - `kind:1111`: the lowercase `e` that is not its `E` — the parent comment.
30
30
  * A top-level comment on an event root carries `E` and `e` naming the same
31
- * event, and is a root.
31
+ * event, and is a root. One with an `a` equal to its `A` names its file as
32
+ * its parent and is a root whatever its `e` says: NIP-22's own shape adds an
33
+ * `e` with the file's version id.
32
34
  * - `kind:9` (and any other kind): the thread — the `root`-marked `e`, else
33
35
  * the `reply`-marked one, else the first unmarked `e` when there is only one,
34
36
  * else the first of several (NIP-10's positional form).
@@ -37,6 +39,8 @@ export function parentOf(event: Tagged): string | null {
37
39
  const tags = es(event)
38
40
  if (tags.length === 0) return null
39
41
  if (event.kind === KIND_COMMENT) {
42
+ const address = event.tags.find((t) => t[0] === 'A')?.[1]
43
+ if (address && event.tags.some((t) => t[0] === 'a' && t[1] === address)) return null
40
44
  const root = event.tags.find((t) => t[0] === 'E')?.[1]
41
45
  return tags.find((t) => t[1] !== root)?.[1] ?? null
42
46
  }