@estiva-app/conversation 0.1.0 → 0.2.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/dist/strength.js CHANGED
@@ -148,8 +148,8 @@ export function referenceTagsFor(body, own = '') {
148
148
  }
149
149
  /** The most `p` tags a message carries — Buzz's cap, and `buildMessage`'s. */
150
150
  export const MAX_MENTIONED_PEOPLE = 50;
151
- /** The people a body mentions by `nostr:npub…`, as `p` tags, capped at {@link MAX_MENTIONED_PEOPLE}. */
152
- export function mentionTagsFor(body) {
151
+ /** The people a body mentions by `nostr:npub…` (§13.1), in the order it names them. */
152
+ export function peopleNamedInBody(body) {
153
153
  const pubkeys = new Set();
154
154
  for (const uri of findNostrUris(body)) {
155
155
  if (!/^nostr:npub1/i.test(uri))
@@ -161,6 +161,10 @@ export function mentionTagsFor(body) {
161
161
  // A malformed key is prose.
162
162
  }
163
163
  }
164
- return [...pubkeys].slice(0, MAX_MENTIONED_PEOPLE).map((p) => ['p', p]);
164
+ return pubkeys;
165
+ }
166
+ /** The people a body mentions by `nostr:npub…`, as `p` tags, capped at {@link MAX_MENTIONED_PEOPLE}. */
167
+ export function mentionTagsFor(body) {
168
+ return [...peopleNamedInBody(body)].slice(0, MAX_MENTIONED_PEOPLE).map((p) => ['p', p]);
165
169
  }
166
170
  //# sourceMappingURL=strength.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"strength.js","sourceRoot":"","sources":["../src/strength.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,gBAAgB,EAAmC,MAAM,sBAAsB,CAAA;AAC5I,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAQzC,MAAM,MAAM,GAAG,CAAC,KAAgC,EAAE,IAAY,EAAY,EAAE,CAC1E,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,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GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAA;AAC5C,CAAC;AAED,8EAA8E;AAC9E,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,CAAA;AAEtC,uFAAuF;AACvF,MAAM,UAAU,iBAAiB,CAAC,IAAY;IAC5C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAA;IACjC,KAAK,MAAM,GAAG,IAAI,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC;QACtC,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC;YAAE,SAAQ;QACxC,IAAI,CAAC;YACH,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAA;QAC9B,CAAC;QAAC,MAAM,CAAC;YACP,4BAA4B;QAC9B,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAA;AAChB,CAAC;AAED,wGAAwG;AACxG,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,OAAO,CAAC,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,oBAAoB,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAA;AACzF,CAAC"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * What is unread — SPEC §11.8 *What membership changes about unread*, judged
3
+ * against §11.3's effective marker.
4
+ *
5
+ * A message in a stream is unread for `P` when all of these hold:
6
+ *
7
+ * 1. `P` is a member and has not muted the stream, or its content mentions `P`;
8
+ * 2. `P` did not write it;
9
+ * 3. its `created_at` is at or after the second `P` became a member;
10
+ * 4. it is newer than `P`'s effective marker.
11
+ *
12
+ * For a file, membership is {@link membershipOf}'s fold, and condition 3 is
13
+ * what settles a file with no marker (§11.6): unread from joining, not from
14
+ * the start of a horizon. A channel's general stream takes its membership
15
+ * from the roster, which carries no join time — so `since` is undefined and
16
+ * what counts without a marker is the app's `floor`.
17
+ *
18
+ * An app lights nothing for a stream it has no screen for (§11.8); that is
19
+ * the caller's to decide by not asking.
20
+ */
21
+ import type { SignedEvent } from '@estiva-app/protocol';
22
+ type Message = Pick<SignedEvent, 'id' | 'pubkey' | 'kind' | 'created_at' | 'tags' | 'content'>;
23
+ /** Who is judging one stream, and on what terms. */
24
+ export interface StreamJudge {
25
+ /** The stream's context (§11.1): the file's address, or the channel uuid for its general stream. */
26
+ stream: string;
27
+ /** The person reading. */
28
+ me: string;
29
+ /** Whether `me` is a member — {@link membershipOf} for a file, the roster for a channel. */
30
+ member: boolean;
31
+ /** Unix seconds `me` became a member; undefined for a channel, where the roster has no join time. */
32
+ since?: number;
33
+ /** Whether `me` muted the stream (`estiva:muted:v1`). A mention still counts. */
34
+ muted?: boolean;
35
+ /**
36
+ * For a stream with no marker, the earliest `created_at` that counts — the
37
+ * app's choice for a channel (§11.6). A file member does not need it: `since`
38
+ * already bounds it. Undefined counts everything.
39
+ */
40
+ floor?: number;
41
+ }
42
+ /**
43
+ * The unread messages of one stream, oldest first per thread. `messages` is
44
+ * the stream's own (see {@link streamOf} for a file); a reply is judged
45
+ * against `thread:<root>` as well as the stream (§11.3).
46
+ *
47
+ * A dot is `unreadIn(…).length > 0`; a divider goes above the first unread
48
+ * message of each thread.
49
+ */
50
+ export declare function unreadIn<E extends Message>(messages: readonly E[], merged: Readonly<Record<string, number>>, judge: StreamJudge): E[];
51
+ /** Whether one message is unread: §11.8's four conditions. `root` is its thread's root id when it is a reply. */
52
+ export declare function isUnread(message: Message, root: string | undefined, merged: Readonly<Record<string, number>>, judge: StreamJudge): boolean;
53
+ export {};
54
+ //# sourceMappingURL=unread.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unread.d.ts","sourceRoot":"","sources":["../src/unread.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAKvD,KAAK,OAAO,GAAG,IAAI,CAAC,WAAW,EAAE,IAAI,GAAG,QAAQ,GAAG,MAAM,GAAG,YAAY,GAAG,MAAM,GAAG,SAAS,CAAC,CAAA;AAE9F,oDAAoD;AACpD,MAAM,WAAW,WAAW;IAC1B,oGAAoG;IACpG,MAAM,EAAE,MAAM,CAAA;IACd,0BAA0B;IAC1B,EAAE,EAAE,MAAM,CAAA;IACV,4FAA4F;IAC5F,MAAM,EAAE,OAAO,CAAA;IACf,qGAAqG;IACrG,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,iFAAiF;IACjF,KAAK,CAAC,EAAE,OAAO,CAAA;IACf;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED;;;;;;;GAOG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,OAAO,EAAE,QAAQ,EAAE,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,WAAW,GAAG,CAAC,EAAE,CAgBrI;AAED,iHAAiH;AACjH,wBAAgB,QAAQ,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAU1I"}
package/dist/unread.js ADDED
@@ -0,0 +1,50 @@
1
+ import { effectiveReadAt, threadContext } from './readState.js';
2
+ import { peopleNamedInBody } from './strength.js';
3
+ import { groupThreads } from './threads.js';
4
+ /**
5
+ * The unread messages of one stream, oldest first per thread. `messages` is
6
+ * the stream's own (see {@link streamOf} for a file); a reply is judged
7
+ * against `thread:<root>` as well as the stream (§11.3).
8
+ *
9
+ * A dot is `unreadIn(…).length > 0`; a divider goes above the first unread
10
+ * message of each thread.
11
+ */
12
+ export function unreadIn(messages, merged, judge) {
13
+ const { roots, replies } = groupThreads(messages);
14
+ const out = [];
15
+ const consider = (message, root) => {
16
+ if (isUnread(message, root, merged, judge))
17
+ out.push(message);
18
+ };
19
+ for (const root of roots) {
20
+ consider(root, undefined);
21
+ for (const reply of replies[root.id] ?? [])
22
+ consider(reply, root.id);
23
+ }
24
+ const held = new Set(roots.map((r) => r.id));
25
+ for (const [root, list] of Object.entries(replies)) {
26
+ if (held.has(root))
27
+ continue;
28
+ for (const reply of list)
29
+ consider(reply, root);
30
+ }
31
+ return out;
32
+ }
33
+ /** Whether one message is unread: §11.8's four conditions. `root` is its thread's root id when it is a reply. */
34
+ export function isUnread(message, root, merged, judge) {
35
+ if (message.pubkey === judge.me)
36
+ return false;
37
+ const mentioned = peopleNamedInBody(message.content).has(judge.me);
38
+ if (!mentioned && (!judge.member || judge.muted))
39
+ return false;
40
+ if (judge.since !== undefined && message.created_at < judge.since)
41
+ return false;
42
+ const thread = root === undefined ? undefined : threadContext(root);
43
+ const marker = thread === undefined ? merged[judge.stream] : effectiveReadAt(merged, thread, judge.stream);
44
+ if (marker !== undefined)
45
+ return message.created_at > marker;
46
+ if (judge.since !== undefined)
47
+ return true;
48
+ return judge.floor === undefined || message.created_at >= judge.floor;
49
+ }
50
+ //# sourceMappingURL=unread.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unread.js","sourceRoot":"","sources":["../src/unread.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAC/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAwB3C;;;;;;;GAOG;AACH,MAAM,UAAU,QAAQ,CAAoB,QAAsB,EAAE,MAAwC,EAAE,KAAkB;IAC9H,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAA;IACjD,MAA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,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IAC9D,IAAI,KAAK,CAAC,KAAK,KAAK,SAAS,IAAI,OAAO,CAAC,UAAU,GAAG,KAAK,CAAC,KAAK;QAAE,OAAO,KAAK,CAAA;IAC/E,MAAM,MAAM,GAAG,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;IACnE,MAAM,MAAM,GAAG,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;IAC1G,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,OAAO,CAAC,UAAU,GAAG,MAAM,CAAA;IAC5D,IAAI,KAAK,CAAC,KAAK,KAAK,SAAS;QAAE,OAAO,IAAI,CAAA;IAC1C,OAAO,KAAK,CAAC,KAAK,KAAK,SAAS,IAAI,OAAO,CAAC,UAAU,IAAI,KAAK,CAAC,KAAK,CAAA;AACvE,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@estiva-app/conversation",
3
- "version": "0.1.0",
4
- "description": "The conversation rules of the Estiva SPEC (§6.2–§6.8): comment and mention strengths, threading, the edit, reaction and attachment folds, NIP-22 comment and reply builders, and drafts. A convenience an app adopts, never a requirement.",
3
+ "version": "0.2.0",
4
+ "description": "The conversation rules of the Estiva SPEC (§6.2–§6.8, §11): comment and mention strengths, threading, the edit, reaction and attachment folds, NIP-22 comment and reply builders, drafts, NIP-RS read state, membership and unread. A convenience an app adopts, never a requirement.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "exports": {
package/src/builders.ts CHANGED
@@ -8,9 +8,7 @@
8
8
  * NIP-22 pair below, whose shape the SPEC decided rather than Buzz.
9
9
  */
10
10
  import { imetaTag, toNostrSeconds, type Imeta, type NostrTag, type UnsignedEvent } from '@estiva-app/protocol'
11
- import { KIND_COMMENT } from './kinds.js'
12
-
13
- const FOLDER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
11
+ import { FOLDER_ID, KIND_COMMENT } from './kinds.js'
14
12
 
15
13
  /**
16
14
  * A `kind:1111` is channel-scoped when it carries an `h` and **global when it
package/src/index.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  * apps: it imports no app's data layer, opens no socket, and takes every
13
13
  * environment touch — the relay read, the clock, storage — as a parameter.
14
14
  */
15
- export const CONVERSATION_VERSION = '0.1.0'
15
+ export const CONVERSATION_VERSION = '0.2.0'
16
16
 
17
17
  export {
18
18
  KIND_MESSAGE,
@@ -37,6 +37,7 @@ export {
37
37
  threadStrength,
38
38
  referenceTagsFor,
39
39
  mentionTagsFor,
40
+ peopleNamedInBody,
40
41
  MAX_MENTIONED_PEOPLE,
41
42
  type Strength,
42
43
  } from './strength.js'
@@ -63,6 +64,73 @@ export { decorationsOf, type Decoration, type Decorations, type Resolution, type
63
64
 
64
65
  export { buildComment, buildReply, offersEditAndDelete, type CommentRef } from './builders.js'
65
66
 
67
+ export {
68
+ KIND_CHANGE,
69
+ MEMBER_FIELD_PREFIX,
70
+ memberField,
71
+ memberOfField,
72
+ mentions,
73
+ streamOf,
74
+ membershipOf,
75
+ membersOf,
76
+ membershipFilters,
77
+ candidateFilesOf,
78
+ buildMembershipChange,
79
+ MUTED_D_TAG,
80
+ APPDATA_TAG,
81
+ parseMutedBlob,
82
+ serializeMutedBlob,
83
+ buildMutedEvent,
84
+ mutedFilter,
85
+ mutedFromFollowed,
86
+ type Membership,
87
+ type MutedList,
88
+ } from './membership.js'
89
+
90
+ export {
91
+ READ_STATE_TAG,
92
+ READ_STATE_D_PREFIX,
93
+ MAX_CONTEXTS,
94
+ MAX_CONTEXT_ID_BYTES,
95
+ MAX_TIMESTAMP,
96
+ MAX_CLIENT_ID_BYTES,
97
+ MAX_BLOB_BYTES,
98
+ MAX_CONTEXTS_BYTES,
99
+ READ_STATE_HORIZON_DAYS,
100
+ channelContext,
101
+ fileContext,
102
+ threadContext,
103
+ messageContext,
104
+ toContextSeconds,
105
+ isPublishableContextId,
106
+ loadSlotIdentity,
107
+ rotateSlotId,
108
+ readStateDTag,
109
+ parseReadStateBlob,
110
+ serializeReadStateBlob,
111
+ capContextsToBytes,
112
+ advanceContexts,
113
+ buildReadStateEvent,
114
+ allSlotsFilter,
115
+ mergeSlots,
116
+ classifyOwnSlots,
117
+ effectiveReadAt,
118
+ fetchReadState,
119
+ publishReadState,
120
+ type SlotIdentity,
121
+ type SlotStorage,
122
+ type SlotSource,
123
+ type RandomBytes,
124
+ type ReadStateBlob,
125
+ type CappedContexts,
126
+ type SlotBlob,
127
+ type OwnSlotVerdict,
128
+ type Nip44,
129
+ type FetchedReadState,
130
+ } from './readState.js'
131
+
132
+ export { unreadIn, isUnread, type StreamJudge } from './unread.js'
133
+
66
134
  export {
67
135
  createDraftStore,
68
136
  draftKeys,
package/src/kinds.ts CHANGED
@@ -17,6 +17,16 @@ export const KIND_DELETION = KIND.DELETION
17
17
  /** An assertion; with `t=resolution` it resolves or reopens a comment (PEEK-128). */
18
18
  export const KIND_ASSERTION = KIND.ASSERTION
19
19
 
20
+ /** A field change (SPEC §6.2). Not in protocol's `KIND`; the number is the SPEC's. */
21
+ export const KIND_CHANGE = 1851
22
+ /** NIP-78 app data: read state (§11.6) and app-private storage (§12). */
23
+ export const KIND_APP_DATA = KIND.APP_DATA
24
+
25
+ /** A Folder's channel id: a lowercase UUID v4. */
26
+ export const FOLDER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
27
+ /** A file's address, `<kind>:<pubkey>:<d>`: kind 30000–39999, 64 lowercase hex, `d` verbatim and without whitespace. */
28
+ export const FILE_ADDRESS = /^3[0-9]{4}:[0-9a-f]{64}:[^\s]*$/
29
+
20
30
  /** Whether the event is a message or a comment — what a conversation lists. */
21
31
  export const isConversationKind = (kind: number): boolean => kind === KIND_MESSAGE || kind === KIND_COMMENT
22
32
 
@@ -0,0 +1,328 @@
1
+ /**
2
+ * Membership — SPEC §11.8: whose unread a file's conversation is.
3
+ *
4
+ * A person is told about a file's conversation when they are a **member** of
5
+ * the file, and every app computes that the same way, from public events: the
6
+ * file's root, the messages in its stream (§11.1) and its `kind:1851`
7
+ * changes. A Folder's members are its channel roster, which is the relay's
8
+ * and not folded here.
9
+ *
10
+ * | join | the event |
11
+ * | --- | --- |
12
+ * | created it | the root, ordered before every other event for the file |
13
+ * | took part | a message in the stream, by `P` |
14
+ * | was mentioned | a message in the stream whose content names `P` (`nostr:npub…`) |
15
+ * | was placed | a `kind:1851` on the file, not a membership field, with a non-empty `value`, carrying `["p", P]` |
16
+ * | was added, or joined | a `kind:1851` setting `member:<P>` to `true`, by anyone |
17
+ *
18
+ * A **leave** is a `member:<P>` = `false` signed by `P`; one signed by anybody
19
+ * else is ignored. Joins and leaves order as §6.3 orders changes, `P` is a
20
+ * member when the last is a join, and a member **since** the earliest join
21
+ * after the last leave.
22
+ *
23
+ * *Placed* is the `p` alone, so membership and the `#p` discovery query are
24
+ * the same set. A placement written without one does not count (on production,
25
+ * most assignee changes before 2026-10-01).
26
+ *
27
+ * Muting is private and separate (§11.8 *Muting is private*): see
28
+ * {@link parseMutedBlob}.
29
+ */
30
+ import type { SignedEvent, UnsignedEvent } from '@estiva-app/protocol'
31
+ import { FILE_ADDRESS as ADDRESS, FOLDER_ID, KIND_APP_DATA, KIND_CHANGE, KIND_COMMENT, KIND_MESSAGE } from './kinds.js'
32
+ import { byOrder } from './order.js'
33
+ import { anchorsOf, isCommentOn, peopleNamedInBody } from './strength.js'
34
+ import { groupThreads } from './threads.js'
35
+
36
+ export { KIND_CHANGE }
37
+
38
+ /** The field prefix of a membership change: `member:<pubkey>`. */
39
+ export const MEMBER_FIELD_PREFIX = 'member:'
40
+
41
+ const PUBKEY = /^[0-9a-f]{64}$/
42
+
43
+ type Event = Pick<SignedEvent, 'id' | 'pubkey' | 'kind' | 'created_at' | 'tags' | 'content'>
44
+
45
+ /** A relay filter, as `QueryFn` takes one. */
46
+ type Filter = Record<string, unknown>
47
+
48
+ const tag = (event: Pick<SignedEvent, 'tags'>, name: string): string | undefined => event.tags.find((t) => t[0] === name)?.[1]
49
+
50
+ /** The membership field for a person: `member:<pubkey>`. */
51
+ export function memberField(pubkey: string): string {
52
+ if (!PUBKEY.test(pubkey)) throw new Error(`not a lowercase hex pubkey: ${JSON.stringify(pubkey)}`)
53
+ return `${MEMBER_FIELD_PREFIX}${pubkey}`
54
+ }
55
+
56
+ /** The person a `member:<pubkey>` field names, or undefined when it is not one. */
57
+ export function memberOfField(field: string | undefined): string | undefined {
58
+ if (!field?.startsWith(MEMBER_FIELD_PREFIX)) return undefined
59
+ const pubkey = field.slice(MEMBER_FIELD_PREFIX.length)
60
+ return PUBKEY.test(pubkey) ? pubkey : undefined
61
+ }
62
+
63
+ /**
64
+ * Does the message's content mention the person — a `nostr:npub…` in its body.
65
+ * A `p` tag alone is not a mention for membership: the comment builders tag
66
+ * the file's author and the parent's on every comment (§6.4), so a `p` would
67
+ * re-join an author who left.
68
+ */
69
+ export function mentions(event: Pick<SignedEvent, 'content'>, pubkey: string): boolean {
70
+ return peopleNamedInBody(event.content).has(pubkey)
71
+ }
72
+
73
+ /** The address of an addressable event, `<kind>:<pubkey>:<d>`. */
74
+ function addressOf(event: Pick<SignedEvent, 'kind' | 'pubkey' | 'tags'>): string | undefined {
75
+ if (event.kind < 30000 || event.kind > 39999) return undefined
76
+ return `${event.kind}:${event.pubkey}:${tag(event, 'd') ?? ''}`
77
+ }
78
+
79
+ /**
80
+ * The messages in a file's stream (§11.1): every root that is a comment on it,
81
+ * and every reply in those threads. A `kind:1111` reply whose root the read
82
+ * does not hold still counts when its `A` is the file — a reply copies its
83
+ * thread's object. A `kind:9` never roots a file's stream (§6.4, CON-20).
84
+ */
85
+ export function streamOf<E extends Event>(file: string, events: readonly E[]): E[] {
86
+ const conversation = events.filter((e) => e.kind === KIND_COMMENT || e.kind === KIND_MESSAGE)
87
+ const { roots, replies, missingRoots } = groupThreads(conversation)
88
+ const missing = new Set(missingRoots)
89
+ const out: E[] = []
90
+ for (const root of roots) {
91
+ if (!isCommentOn(root, file)) continue
92
+ out.push(root, ...(replies[root.id] ?? []))
93
+ }
94
+ for (const id of missing) {
95
+ for (const reply of replies[id] ?? []) if (reply.kind === KIND_COMMENT && anchorsOf(reply).includes(file)) out.push(reply)
96
+ }
97
+ return out.sort(byOrder)
98
+ }
99
+
100
+ /** Whether a person is a member of a file, and since which second. */
101
+ export interface Membership {
102
+ member: boolean
103
+ /** Unix seconds: the `created_at` of the first join after the last leave. Undefined when not a member. */
104
+ since?: number
105
+ }
106
+
107
+ const NOT_A_MEMBER: Membership = { member: false }
108
+
109
+ /** `creation` is the root: it orders before everything else for the file, whichever version the reader holds. */
110
+ type Step = { event: Event; join: boolean; creation?: boolean }
111
+
112
+ /**
113
+ * Every join and leave in a file's events, per person. `events` may hold
114
+ * anything; only the file's root versions, its stream and its `kind:1851`
115
+ * changes are read.
116
+ */
117
+ function stepsOf(file: string, events: readonly Event[]): Map<string, Step[]> {
118
+ const steps = new Map<string, Step[]>()
119
+ const add = (person: string, event: Event, join: boolean, creation = false) => {
120
+ if (!PUBKEY.test(person)) return
121
+ const list = steps.get(person) ?? []
122
+ list.push({ event, join, creation })
123
+ steps.set(person, list)
124
+ }
125
+
126
+ // A relay keeps only the latest version of an addressable event, so the root
127
+ // the reader holds is usually the last edit. Its join is ordered first, so
128
+ // an edit after a leave does not make the author a member again.
129
+ const versions = events.filter((e) => addressOf(e) === file).sort(byOrder)
130
+ if (versions[0]) add(versions[0].pubkey, versions[0], true, true)
131
+
132
+ for (const message of streamOf(file, events)) {
133
+ add(message.pubkey, message, true)
134
+ for (const person of peopleNamedInBody(message.content)) add(person, message, true)
135
+ }
136
+
137
+ for (const change of events) {
138
+ if (change.kind !== KIND_CHANGE || !change.tags.some((t) => t[0] === 'a' && t[1] === file)) continue
139
+ const field = tag(change, 'field')
140
+ const value = tag(change, 'value')
141
+ const member = memberOfField(field)
142
+ if (member !== undefined) {
143
+ if (value === 'true') add(member, change, true)
144
+ else if (value === 'false' && change.pubkey === member) add(member, change, false)
145
+ continue
146
+ }
147
+ // A change with an empty value takes someone off (an unassign) and places nobody, whatever `p` it carries.
148
+ if (field?.startsWith(MEMBER_FIELD_PREFIX) || !value) continue
149
+ for (const t of change.tags) if (t[0] === 'p' && typeof t[1] === 'string') add(t[1], change, true)
150
+ }
151
+ return steps
152
+ }
153
+
154
+ function fold(steps: readonly Step[] | undefined): Membership {
155
+ if (!steps || steps.length === 0) return NOT_A_MEMBER
156
+ const ordered = [...steps].sort(
157
+ (a, b) => Number(b.creation ?? false) - Number(a.creation ?? false) || byOrder(a.event, b.event) || Number(a.join) - Number(b.join),
158
+ )
159
+ if (!ordered[ordered.length - 1].join) return NOT_A_MEMBER
160
+ // Since: the earliest second among the joins after the last leave — the creation's
161
+ // held version can be a later edit than the author's first comment.
162
+ let since: number | undefined
163
+ for (const step of ordered) {
164
+ if (!step.join) since = undefined
165
+ else since = since === undefined ? step.event.created_at : Math.min(since, step.event.created_at)
166
+ }
167
+ return { member: true, since }
168
+ }
169
+
170
+ /**
171
+ * One person's membership of one file (§11.8 *The fold*), from the file's own
172
+ * events: its root, its stream and its changes.
173
+ */
174
+ export function membershipOf(file: string, person: string, events: readonly Event[]): Membership {
175
+ return fold(stepsOf(file, events).get(person))
176
+ }
177
+
178
+ /** Every member of a file and since when, from the file's own events. People who left are absent. */
179
+ export function membersOf(file: string, events: readonly Event[]): Map<string, Membership> {
180
+ const members = new Map<string, Membership>()
181
+ for (const [person, steps] of stepsOf(file, events)) {
182
+ const membership = fold(steps)
183
+ if (membership.member) members.set(person, membership)
184
+ }
185
+ return members
186
+ }
187
+
188
+ /**
189
+ * The filters that find every file a person may be a member of (§11.8): the
190
+ * changes that name them, what they wrote, and what mentions them. Each
191
+ * candidate file is then read and folded with {@link membershipOf}. The files
192
+ * they created are the app's own query; `since` bounds all three.
193
+ */
194
+ export function membershipFilters(person: string, since?: number): Filter[] {
195
+ if (!PUBKEY.test(person)) throw new Error(`not a lowercase hex pubkey: ${JSON.stringify(person)}`)
196
+ const bound = since === undefined ? {} : { since }
197
+ return [
198
+ { kinds: [KIND_CHANGE], '#p': [person], ...bound },
199
+ { kinds: [KIND_COMMENT, KIND_MESSAGE], authors: [person], ...bound },
200
+ { kinds: [KIND_COMMENT, KIND_MESSAGE], '#p': [person], ...bound },
201
+ ]
202
+ }
203
+
204
+ /**
205
+ * The files an event can make a person a member of: a change's `a`, a
206
+ * comment's `A` (or every `a` when it has none). A `kind:9` names none — its
207
+ * file, if any, is its root's, which the app resolves by reading the thread.
208
+ */
209
+ export function candidateFilesOf(event: Pick<SignedEvent, 'kind' | 'tags'>): string[] {
210
+ if (event.kind === KIND_CHANGE) return event.tags.filter((t) => t[0] === 'a' && ADDRESS.test(t[1] ?? '')).map((t) => t[1])
211
+ return anchorsOf(event).filter((a) => ADDRESS.test(a))
212
+ }
213
+
214
+ /**
215
+ * A membership change (§11.8 *The membership change*): `true` adds a person,
216
+ * by anyone; `false` is a leave and counts only when the person signs it
217
+ * themselves. Tag order: `a`, `field`, `value`, `h`, `ts`, `p`.
218
+ *
219
+ * Sign one only when the person chose it — joining, leaving, or adding
220
+ * somebody. Never to migrate a private follow (§11.8 *Following, retired*).
221
+ *
222
+ * `content` is the note an activity feed shows, as for every change: a change
223
+ * with none renders as a blank line in Ship's feed. "Join", "Leave" or "Add"
224
+ * by default.
225
+ */
226
+ export function buildMembershipChange(
227
+ pubkey: string,
228
+ createdAtMs: number,
229
+ args: { file: string; folder: string; person: string; member: boolean; note?: string },
230
+ ): UnsignedEvent {
231
+ const note = args.note ?? (!args.member ? 'Leave' : args.person === pubkey ? 'Join' : 'Add')
232
+ if (!ADDRESS.test(args.file)) throw new Error(`not a file address: ${JSON.stringify(args.file)}`)
233
+ if (!FOLDER_ID.test(args.folder)) throw new Error(`not a Folder id (lowercase UUID v4): ${JSON.stringify(args.folder)}`)
234
+ if (!Number.isSafeInteger(createdAtMs) || createdAtMs < 0) throw new Error(`not epoch milliseconds: ${createdAtMs}`)
235
+ return {
236
+ pubkey,
237
+ created_at: Math.floor(createdAtMs / 1000),
238
+ kind: KIND_CHANGE,
239
+ tags: [
240
+ ['a', args.file],
241
+ ['field', memberField(args.person)],
242
+ ['value', args.member ? 'true' : 'false'],
243
+ ['h', args.folder],
244
+ ['ts', String(createdAtMs)],
245
+ ['p', args.person],
246
+ ],
247
+ content: note,
248
+ }
249
+ }
250
+
251
+ // ── Muting: private, suite-wide (§11.8 *Muting is private*, §12) ────────────
252
+
253
+ /** The `d` of the person's mute list. */
254
+ export const MUTED_D_TAG = 'estiva:muted:v1'
255
+
256
+ /** The `t` every §12 app-private blob carries. */
257
+ export const APPDATA_TAG = 'estiva-appdata'
258
+
259
+ /** The decrypted mute list: file addresses and channel uuids. */
260
+ export interface MutedList {
261
+ v: 1
262
+ updatedAt: number
263
+ keys: string[]
264
+ }
265
+
266
+ const isMuteKey = (key: unknown): key is string => typeof key === 'string' && (ADDRESS.test(key) || FOLDER_ID.test(key))
267
+
268
+ /** The mute list from its decrypted content, or undefined when it is not a v1 list. Unknown keys are dropped. */
269
+ export function parseMutedBlob(plaintext: string): MutedList | undefined {
270
+ let value: unknown
271
+ try {
272
+ value = JSON.parse(plaintext)
273
+ } catch {
274
+ return undefined
275
+ }
276
+ if (!value || typeof value !== 'object') return undefined
277
+ const { v, updatedAt, keys } = value as Record<string, unknown>
278
+ if (v !== 1 || typeof updatedAt !== 'number' || !Number.isFinite(updatedAt) || !Array.isArray(keys)) return undefined
279
+ return { v: 1, updatedAt, keys: [...new Set(keys.filter(isMuteKey))].sort() }
280
+ }
281
+
282
+ /** The plaintext to encrypt to self: keys de-duplicated and sorted, so equal lists are equal bytes. */
283
+ export function serializeMutedBlob(keys: Iterable<string>, updatedAt: number): string {
284
+ return JSON.stringify({ v: 1, updatedAt, keys: [...new Set([...keys].filter(isMuteKey))].sort() })
285
+ }
286
+
287
+ /**
288
+ * The unsigned `kind:30078` holding the encrypted mute list. Whole blob, last
289
+ * write wins (§12.3): a writer reads the current list, changes it, and writes
290
+ * all of it.
291
+ */
292
+ export function buildMutedEvent(pubkey: string, createdAtMs: number, ciphertext: string): UnsignedEvent {
293
+ return {
294
+ pubkey,
295
+ created_at: Math.floor(createdAtMs / 1000),
296
+ kind: KIND_APP_DATA,
297
+ tags: [
298
+ ['d', MUTED_D_TAG],
299
+ ['t', APPDATA_TAG],
300
+ ],
301
+ content: ciphertext,
302
+ }
303
+ }
304
+
305
+ /** The filter for the person's mute list. */
306
+ export function mutedFilter(pubkey: string): Filter {
307
+ return { kinds: [KIND_APP_DATA], authors: [pubkey], '#d': [MUTED_D_TAG], limit: 1 }
308
+ }
309
+
310
+ /**
311
+ * The one migration from a retired `estiva:followed:v1` blob: its `muted`
312
+ * keys, to merge into the mute list. Peek wrote `muted` as a map of key to
313
+ * epoch ms, and for one day as a plain list; both read. Its followed `keys`
314
+ * are **not** returned — the list was private, so nothing may publish them as
315
+ * memberships — and a followed Folder is dropped, since the roster decides a
316
+ * general stream.
317
+ */
318
+ export function mutedFromFollowed(followedPlaintext: string): string[] {
319
+ let value: unknown
320
+ try {
321
+ value = JSON.parse(followedPlaintext)
322
+ } catch {
323
+ return []
324
+ }
325
+ const muted = value && typeof value === 'object' ? (value as Record<string, unknown>).muted : undefined
326
+ const keys = Array.isArray(muted) ? muted : muted && typeof muted === 'object' ? Object.keys(muted) : []
327
+ return [...new Set(keys.filter(isMuteKey))].sort()
328
+ }