@estiva-app/conversation 0.31.0 → 0.33.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.
@@ -0,0 +1,168 @@
1
+ /**
2
+ * refusals, the one set of words every app says when a send, an edit, a
3
+ * reaction or a file is refused (ONE-4).
4
+ *
5
+ * A refusal comes from the relay (`invalid: …`, `restricted: …`, an HTTP body),
6
+ * from Estiva ID, from the builders' own checks (`content is N bytes, max M`),
7
+ * from the network, or from the app itself. Whatever it was, a person reads
8
+ * one plain reason for its cause, the same in Peek, Ship and Leaf, and never
9
+ * the relay's words: those go to the console. The comment box and the cards
10
+ * put the reason in their sentence ("Not sent: <reason>. Your text is back in
11
+ * the box."), so a reason is lower case and ends with no full stop.
12
+ *
13
+ * An app with a cause of its own hands `{ cause }` rather than a sentence, so
14
+ * its words are these too. A file's own words (`uploadRefusal`) are a whole
15
+ * line on its card, and `tooLarge` stops a file over the relay's limit before
16
+ * it uploads (Miky, 4 Nov: the server's limits, checked in every app first).
17
+ */
18
+ /**
19
+ * Each cause's reason, put in a sentence by the box or the card. `gone` is
20
+ * what the relay says for an edit or a reaction on a message that was deleted
21
+ * or that you can no longer write beside: it does not say which.
22
+ */
23
+ export const REFUSAL_REASONS = {
24
+ 'too-long': 'it is too long',
25
+ gone: 'this message was deleted, or you can no longer write here',
26
+ 'no-access': 'you can no longer write here',
27
+ archived: 'this team is archived',
28
+ busy: 'too many at once, try again in a moment',
29
+ clock: 'your computer’s clock is wrong; set it and try again',
30
+ 'signed-out': 'you are signed out; sign in again',
31
+ unknown: 'something went wrong, try again',
32
+ };
33
+ /** The text a refusal carries: a string, an `Error`'s message, or `{ error }` / `{ message }` / `{ reason }`, one JSON body deep. */
34
+ function textOf(reason) {
35
+ if (reason == null)
36
+ return '';
37
+ if (typeof reason === 'string') {
38
+ const json = reason.trim();
39
+ if (json.startsWith('{')) {
40
+ try {
41
+ return textOf(JSON.parse(json)) || reason;
42
+ }
43
+ catch {
44
+ return reason;
45
+ }
46
+ }
47
+ return reason;
48
+ }
49
+ if (reason instanceof Error)
50
+ return textOf(reason.message);
51
+ if (typeof reason === 'object') {
52
+ const r = reason;
53
+ for (const key of ['error', 'message', 'reason']) {
54
+ const value = r[key];
55
+ if (typeof value === 'string')
56
+ return textOf(value);
57
+ if (value && typeof value === 'object')
58
+ return textOf(value);
59
+ }
60
+ }
61
+ return String(reason);
62
+ }
63
+ const CAUSES = new Set(Object.keys(REFUSAL_REASONS));
64
+ /*
65
+ In order: the first that matches is the cause. Scope and identity before
66
+ `restricted:`, which also prefixes "insufficient scope". Each reason above
67
+ maps back to its own cause, so a reason passed on twice stays the same.
68
+
69
+ Words, because the relay sends no reason code yet (SPEC: "until then a
70
+ refusal is its sentence alone"). When the TEA issue "When the server says
71
+ no, every app knows why" adds them, `refusalCause` reads the code first and
72
+ these rules stay only for a refusal that carries none.
73
+ why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-refusal-starts-with-a-reason-code-every-app-reads.md
74
+ */
75
+ const RULES = [
76
+ [/content (is \d+ bytes, max|exceeds maximum size)|too long/i, 'too-long'],
77
+ [/rate-limited|quota|too many|too busy|relay is busy|admission|\b429\b|concurrency/i, 'busy'],
78
+ [/timestamp too far|clock/i, 'clock'],
79
+ [/auth-required|insufficient scope|does not match authenticated|signed out|sign in|\b401\b|token_rejected|session_expired/i, 'signed-out'],
80
+ [/archived/i, 'archived'],
81
+ [/target (event )?not found|not (editable|deletable) by you|was deleted|no longer on this page/i, 'gone'],
82
+ [/^(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'],
83
+ ];
84
+ /** What a refusal comes to; `{ cause }` is taken as it is. */
85
+ export function refusalCause(reason) {
86
+ if (reason && typeof reason === 'object' && 'cause' in reason) {
87
+ const cause = reason.cause;
88
+ if (typeof cause === 'string' && CAUSES.has(cause))
89
+ return cause;
90
+ }
91
+ const text = textOf(reason);
92
+ for (const [rule, cause] of RULES)
93
+ if (rule.test(text))
94
+ return cause;
95
+ return 'unknown';
96
+ }
97
+ /** The plain reason for any refusal, to say after "Not sent:", "Not saved:" or "Not reacted:". */
98
+ export function refusalReason(reason) {
99
+ return REFUSAL_REASONS[refusalCause(reason)];
100
+ }
101
+ const MB = 1024 * 1024;
102
+ /**
103
+ * The relay's size limits (buzz `BUZZ_MAX_*_BYTES`, read back on production on
104
+ * 4 Nov): a GIF 10 MB, another picture 50 MB, anything else 100 MB, since
105
+ * Cloudflare refuses a larger body before the relay sees it (a video's 500 MB
106
+ * is never reached). Cloudflare's 100 MB is taken as decimal, the lower
107
+ * reading, so nothing that passes here is turned away there.
108
+ */
109
+ export const UPLOAD_LIMITS = { gif: 10 * MB, image: 50 * MB, other: 100_000_000 };
110
+ /** The most a file of this type may be, in bytes. */
111
+ export function uploadLimit(type) {
112
+ const t = (type ?? '').toLowerCase();
113
+ if (t === 'image/gif')
114
+ return UPLOAD_LIMITS.gif;
115
+ if (t.startsWith('image/'))
116
+ return UPLOAD_LIMITS.image;
117
+ return UPLOAD_LIMITS.other;
118
+ }
119
+ // Whole MB either way: 10,485,760 bytes and 100,000,000 bytes both say what the limit is called.
120
+ const tooLargeLine = (bytes) => `Too large: the most is ${bytes % MB === 0 ? bytes / MB : Math.round(bytes / 1e6)} MB`;
121
+ /** The line for a file over its limit, said before it uploads; undefined when it fits. */
122
+ export function tooLarge(file) {
123
+ const limit = uploadLimit(file.type);
124
+ return file.size > limit ? tooLargeLine(limit) : undefined;
125
+ }
126
+ const UPLOAD_LINES = {
127
+ type: 'This type of file can’t be added',
128
+ unreadable: 'This file could not be read',
129
+ busy: 'Too many at once, try again in a moment',
130
+ 'signed-out': 'Sign in again',
131
+ 'no-access': 'You can no longer add files here',
132
+ unknown: 'Could not upload, try again',
133
+ };
134
+ /**
135
+ * The line on a file's card when its upload was refused: from protocol's
136
+ * `upload failed: <status> <body>`, any other error, or `{ cause }`. A 413
137
+ * names the limit the relay gave, or the type's own when Cloudflare answered.
138
+ */
139
+ export function uploadRefusal(reason, file) {
140
+ if (reason && typeof reason === 'object' && 'cause' in reason) {
141
+ const cause = reason.cause;
142
+ if (cause === 'too-large')
143
+ return tooLargeLine(uploadLimit(file?.type));
144
+ if (typeof cause === 'string' && Object.hasOwn(UPLOAD_LINES, cause))
145
+ return UPLOAD_LINES[cause];
146
+ }
147
+ const raw = reason instanceof Error ? reason.message : typeof reason === 'string' ? reason : textOf(reason);
148
+ const status = Number(/upload failed:\s*(\d{3})/i.exec(raw)?.[1] ?? 0);
149
+ const said = textOf(raw.replace(/^.*?upload failed:\s*\d{3}\s*/is, ''));
150
+ if (status === 413 || /file too large/i.test(said)) {
151
+ const max = Number(/max (\d+)\)?/i.exec(said)?.[1] ?? 0);
152
+ if (/dimensions/i.test(said))
153
+ return UPLOAD_LINES.unreadable;
154
+ return tooLargeLine(max || uploadLimit(file?.type));
155
+ }
156
+ if (status === 415 || /content type|unsupported container/i.test(said))
157
+ return UPLOAD_LINES.type;
158
+ if (status === 422 || /metadata|invalid image|duration|resolution/i.test(said))
159
+ return UPLOAD_LINES.unreadable;
160
+ if (status === 429 || /rate limit|concurrency/i.test(said))
161
+ return UPLOAD_LINES.busy;
162
+ if (status === 401 || /authentication failed|signed out/i.test(said))
163
+ return UPLOAD_LINES['signed-out'];
164
+ if (status === 403)
165
+ return UPLOAD_LINES['no-access'];
166
+ return UPLOAD_LINES.unknown;
167
+ }
168
+ //# sourceMappingURL=refusals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refusals.js","sourceRoot":"","sources":["../src/refusals.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAaH;;;;GAIG;AACH,MAAM,CAAC,MAAM,eAAe,GAA2C;IACrE,UAAU,EAAE,gBAAgB;IAC5B,IAAI,EAAE,2DAA2D;IACjE,WAAW,EAAE,8BAA8B;IAC3C,QAAQ,EAAE,uBAAuB;IACjC,IAAI,EAAE,yCAAyC;IAC/C,KAAK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AAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,YAAY,CAAC,IAAI,CAAA;IACpF,IAAI,MAAM,KAAK,GAAG,IAAI,mCAAmC,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,YAAY,CAAC,YAAY,CAAC,CAAA;IACvG,IAAI,MAAM,KAAK,GAAG;QAAE,OAAO,YAAY,CAAC,WAAW,CAAC,CAAA;IACpD,OAAO,YAAY,CAAC,OAAO,CAAA;AAC7B,CAAC"}
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Resolving a thread — SPEC §6.4, "Resolving a thread" (ONE-2), and C51.
3
+ *
4
+ * A `kind:9101` with `t=resolution` resolves or reopens the thread of the
5
+ * top-level message its first unmarked `e` names. Anyone who may write in that
6
+ * message's Folder may write one, and **the newest counts, in §6.3's order**
7
+ * (`byOrder`): `ts` when trusted, then `created_at`, then the higher id.
8
+ * A reader ignores one whose `h` is not its target's Folder, one about a reply
9
+ * (never walked to its root), and drops a `support` outside the thread.
10
+ *
11
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/anyone-who-may-comment-resolves-or-reopens-a-thread-and-the-newest-counts.md
12
+ */
13
+ import type { SignedEvent } from '@estiva-app/protocol';
14
+ /** A `kind:9101` resolution assertion on a message (PEEK-128, SPEC §6.4). */
15
+ export interface Resolution {
16
+ id: string;
17
+ action: 'resolved' | 'reopened';
18
+ by: string;
19
+ /** `created_at`, seconds. */
20
+ at: number;
21
+ /** Where it sorts, epoch milliseconds: the trusted `ts`, else `at` × 1000 (§6.3). */
22
+ orderMs: number;
23
+ /** Its `h`: the Folder it was filed in, which must be its target's. */
24
+ folder?: string;
25
+ /** The assertion's free text, when it carried one. */
26
+ message?: string;
27
+ /** The reply that carried the resolution, when the writer named one. */
28
+ supportingEventId?: string;
29
+ }
30
+ /**
31
+ * The message a `kind:9101` is about: its **first unmarked `e`**, lowercased.
32
+ * Not the first one a reader happens to hold — a resolve listing a stranger
33
+ * first and a thread second is about the stranger.
34
+ */
35
+ export declare function resolutionTargetOf(event: Pick<SignedEvent, 'tags'>): string | undefined;
36
+ /** The event read as a {@link Resolution} with its target, or undefined when it is not one. */
37
+ export declare function resolutionOfEvent(event: SignedEvent): {
38
+ target: string;
39
+ resolution: Resolution;
40
+ } | undefined;
41
+ /** Oldest first by §6.3: `ts` when trusted, then `created_at`, then the lower id. */
42
+ export declare const byResolutionOrder: (a: Resolution, b: Resolution) => number;
43
+ /**
44
+ * A thread's state: the newest of `resolutions` that counts, or undefined when
45
+ * none does (never resolved, or only ones a reader ignores).
46
+ *
47
+ * `resolutions` are those whose target is the thread's **top-level** message;
48
+ * one about a reply is never passed here. `folder` is that message's Folder
49
+ * (for a top-level message the read did not return, its replies'), and
50
+ * `replies` the thread's reply ids: a `support` naming anything else is
51
+ * dropped and the resolve stands.
52
+ */
53
+ export declare function resolutionOf(resolutions: readonly Resolution[], thread: {
54
+ folder: string | undefined;
55
+ replies: readonly string[];
56
+ }): Resolution | undefined;
57
+ /** Every resolution in `events`, by target id, oldest first (§6.3). */
58
+ export declare function resolutionsByTarget(events: readonly SignedEvent[]): Record<string, Resolution[]>;
59
+ //# sourceMappingURL=resolution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolution.d.ts","sourceRoot":"","sources":["../src/resolution.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAIvD,6EAA6E;AAC7E,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAA;IACV,MAAM,EAAE,UAAU,GAAG,UAAU,CAAA;IAC/B,EAAE,EAAE,MAAM,CAAA;IACV,6BAA6B;IAC7B,EAAE,EAAE,MAAM,CAAA;IACV,qFAAqF;IACrF,OAAO,EAAE,MAAM,CAAA;IACf,uEAAuE;IACvE,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,sDAAsD;IACtD,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,wEAAwE;IACxE,iBAAiB,CAAC,EAAE,MAAM,CAAA;CAC3B;AAID;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,IAAI,CAAC,WAAW,EAAE,MAAM,CAAC,GAAG,MAAM,GAAG,SAAS,CAGvF;AAED,+FAA+F;AAC/F,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,WAAW,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,UAAU,CAAA;CAAE,GAAG,SAAS,CAqB5G;AAED,qFAAqF;AACrF,eAAO,MAAM,iBAAiB,GAAI,GAAG,UAAU,EAAE,GAAG,UAAU,KAAG,MACE,CAAA;AAEnE;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAC1B,WAAW,EAAE,SAAS,UAAU,EAAE,EAClC,MAAM,EAAE;IAAE,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GACjE,UAAU,GAAG,SAAS,CAWxB;AAED,uEAAuE;AACvE,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,EAAE,CAAC,CAWhG"}
@@ -0,0 +1,82 @@
1
+ import { isEventId, KIND_ASSERTION } from './kinds.js';
2
+ import { orderingMs } from './order.js';
3
+ const tagValue = (event, name) => event.tags.find((t) => t[0] === name)?.[1];
4
+ /**
5
+ * The message a `kind:9101` is about: its **first unmarked `e`**, lowercased.
6
+ * Not the first one a reader happens to hold — a resolve listing a stranger
7
+ * first and a thread second is about the stranger.
8
+ */
9
+ export function resolutionTargetOf(event) {
10
+ const tag = event.tags.find((t) => t[0] === 'e' && !t[3]);
11
+ return tag && isEventId(tag[1]) ? tag[1].toLowerCase() : undefined;
12
+ }
13
+ /** The event read as a {@link Resolution} with its target, or undefined when it is not one. */
14
+ export function resolutionOfEvent(event) {
15
+ if (event.kind !== KIND_ASSERTION || tagValue(event, 't') !== 'resolution')
16
+ return undefined;
17
+ const action = tagValue(event, 'action');
18
+ if (action !== 'resolved' && action !== 'reopened')
19
+ return undefined;
20
+ const target = resolutionTargetOf(event);
21
+ if (!target)
22
+ return undefined;
23
+ const support = event.tags.find((t) => t[0] === 'e' && t[3] === 'support')?.[1];
24
+ const folder = tagValue(event, 'h');
25
+ return {
26
+ target,
27
+ resolution: {
28
+ id: event.id,
29
+ action,
30
+ by: event.pubkey,
31
+ at: event.created_at,
32
+ orderMs: orderingMs(event),
33
+ ...(folder ? { folder } : {}),
34
+ ...(event.content ? { message: event.content } : {}),
35
+ ...(isEventId(support) ? { supportingEventId: support.toLowerCase() } : {}),
36
+ },
37
+ };
38
+ }
39
+ /** Oldest first by §6.3: `ts` when trusted, then `created_at`, then the lower id. */
40
+ export const byResolutionOrder = (a, b) => a.orderMs - b.orderMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
41
+ /**
42
+ * A thread's state: the newest of `resolutions` that counts, or undefined when
43
+ * none does (never resolved, or only ones a reader ignores).
44
+ *
45
+ * `resolutions` are those whose target is the thread's **top-level** message;
46
+ * one about a reply is never passed here. `folder` is that message's Folder
47
+ * (for a top-level message the read did not return, its replies'), and
48
+ * `replies` the thread's reply ids: a `support` naming anything else is
49
+ * dropped and the resolve stands.
50
+ */
51
+ export function resolutionOf(resolutions, thread) {
52
+ if (!thread.folder)
53
+ return undefined;
54
+ const newest = resolutions
55
+ .filter((r) => r.folder === thread.folder)
56
+ .sort(byResolutionOrder)
57
+ .at(-1);
58
+ if (!newest?.supportingEventId)
59
+ return newest;
60
+ const replies = new Set(thread.replies.map((id) => id.toLowerCase()));
61
+ if (replies.has(newest.supportingEventId))
62
+ return newest;
63
+ const { supportingEventId: _dropped, ...kept } = newest;
64
+ return kept;
65
+ }
66
+ /** Every resolution in `events`, by target id, oldest first (§6.3). */
67
+ export function resolutionsByTarget(events) {
68
+ const out = {};
69
+ const seen = new Set();
70
+ for (const event of events) {
71
+ if (seen.has(event.id))
72
+ continue;
73
+ seen.add(event.id);
74
+ const read = resolutionOfEvent(event);
75
+ if (read)
76
+ (out[read.target] ??= []).push(read.resolution);
77
+ }
78
+ for (const list of Object.values(out))
79
+ list.sort(byResolutionOrder);
80
+ return out;
81
+ }
82
+ //# sourceMappingURL=resolution.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolution.js","sourceRoot":"","sources":["../src/resolution.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAmBvC,MAAM,QAAQ,GAAG,CAAC,KAAgC,EAAE,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;AAE/G;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAgC;IACjE,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACzD,OAAO,GAAG,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,SAAS,CAAA;AACpE,CAAC;AAED,+FAA+F;AAC/F,MAAM,UAAU,iBAAiB,CAAC,KAAkB;IAClD,IAAI,KAAK,CAAC,IAAI,KAAK,cAAc,IAAI,QAAQ,CAAC,KAAK,EAAE,GAAG,CAAC,KAAK,YAAY;QAAE,OAAO,SAAS,CAAA;IAC5F,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,EAAE,QAAQ,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,CAAA;QAClB,MAAM,IAAI,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAA;QACrC,IAAI,IAAI;YAAE,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;IAC3D,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;QAAE,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAA;IACnE,OAAO,GAAG,CAAA;AACZ,CAAC"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * One shape for a message, a reply and a thread — SPEC §6.3–§6.8 and §6.4's
3
+ * "Resolving a thread", folded once for every app (ONE-2).
4
+ *
5
+ * Peek, Ship and Leaf each read a conversation into their own shape until
6
+ * now, and they disagreed: on which resolve counts, on what a deleted
7
+ * comment's thread shows, and on whether a reaction is known by its person's
8
+ * key or name. {@link foldThreads} is the one answer. It draws nothing — the
9
+ * kit in `@estiva-app/ui` takes words and nodes, and this sits below it.
10
+ *
11
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-conversation-is-one-shared-thing-and-only-its-colours-are-the-apps.md
12
+ */
13
+ import { type Embed, type Imeta, type PartPointer, type Quote, type SignedEvent } from '@estiva-app/protocol';
14
+ import { type Reaction } from './reactions.js';
15
+ import { type Resolution } from './resolution.js';
16
+ /** One message — a top-level comment, a channel message or a reply — as it stands after its edits. */
17
+ export interface Message {
18
+ id: string;
19
+ kind: number;
20
+ /** Who wrote it, by key. */
21
+ author: string;
22
+ /** Its `h`: the Folder it was filed in. */
23
+ folder?: string;
24
+ /** When it was written, epoch milliseconds (§6.3: the trusted `ts`, else `created_at` × 1000). */
25
+ at: number;
26
+ /** The text to show: the latest edit's, else its own (§6.8). */
27
+ body: string;
28
+ /** Whether an edit changed the body — what a reader MUST mark (§6.8). */
29
+ edited: boolean;
30
+ /** When the body last changed, epoch milliseconds. Absent unless `edited`. */
31
+ editedAt?: number;
32
+ /** Its files: the latest edit's `imeta` set, else its own (§6.8, C15). */
33
+ files: Imeta[];
34
+ /** The cards its writer carried (`embed`, §13.6.2), after edits (C20). Which of them the body still names is the drawer's (`cardsIn`). */
35
+ cards: Embed[];
36
+ /** The blocks drawn live under it (`part`, §13.6.1). An edit carries none, so these are the message's own. */
37
+ parts: PartPointer[];
38
+ /** What its words link: its `a` and `q` values, or the latest edit's when it was edited, since an edit is the whole new message (§6.4, §6.8). */
39
+ links: string[];
40
+ /**
41
+ * What a comment on part of a document is about (§13.6): the run of blocks
42
+ * in its `block` tag, and the words in its `quote` when it quotes some. An
43
+ * edit never moves it.
44
+ */
45
+ anchor?: {
46
+ blocks: string[];
47
+ quote?: Quote;
48
+ };
49
+ /** Its reactions by emoji, each reactor by key (§6.6). */
50
+ reactions: Reaction[];
51
+ /** The event itself, for what this shape does not carry. */
52
+ event: SignedEvent;
53
+ }
54
+ /**
55
+ * The thread's top-level message, in one of §6.5's three states:
56
+ * - `present` — returned, and not deleted;
57
+ * - `deleted` — its author's `kind:5` came back: drawn as "This comment was
58
+ * deleted", its replies under it;
59
+ * - `missing` — only its replies were read. Drawn as their thread, never as
60
+ * deleted: it may only be outside the read.
61
+ */
62
+ export type RootState = 'present' | 'deleted' | 'missing';
63
+ /** A thread: a top-level message, its replies, and its state. */
64
+ export interface Thread {
65
+ /** The top-level message's id, whether or not it was returned. */
66
+ id: string;
67
+ state: RootState;
68
+ /** The top-level message, when `present`. */
69
+ root?: Message;
70
+ /** Its replies, oldest first by §6.3; a deleted reply is left out. */
71
+ replies: Message[];
72
+ /** The thread's Folder: its top-level message's `h`, else its replies'. */
73
+ folder?: string;
74
+ /** The resolve or reopen that counts (§6.4, C51); absent when none does. `resolution.action` is the state. */
75
+ resolution?: Resolution;
76
+ /**
77
+ * Whether Resolve or Reopen may be offered, as far as the thread can say:
78
+ * only on a top-level message that is `present`. Whether the reader may
79
+ * write in its Folder, and whether its file is archived, is the app's to add.
80
+ */
81
+ resolvable: boolean;
82
+ }
83
+ /**
84
+ * Fold a conversation into its threads (§6.3–§6.8).
85
+ *
86
+ * `events` is everything read for it: its `kind:9` or `kind:1111` messages,
87
+ * and the `kind:40003` edits, `kind:7` reactions, `kind:5` deletions and
88
+ * `kind:9101` resolutions read by `#e` on them. Duplicates are read once.
89
+ * `viewer` marks the viewer's own reactions (`Reaction.mine`).
90
+ *
91
+ * Threads come oldest first by their top-level message, or by their first
92
+ * reply when it was not returned. A reply to a reply is filed under the
93
+ * thread's top-level message (§6.4).
94
+ */
95
+ export declare function foldThreads(events: readonly SignedEvent[], options?: {
96
+ viewer?: string;
97
+ }): Thread[];
98
+ //# sourceMappingURL=shape.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shape.d.ts","sourceRoot":"","sources":["../src/shape.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAML,KAAK,KAAK,EACV,KAAK,KAAK,EACV,KAAK,WAAW,EAChB,KAAK,KAAK,EACV,KAAK,WAAW,EACjB,MAAM,sBAAsB,CAAA;AAI7B,OAAO,EAAoC,KAAK,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAChF,OAAO,EAAqC,KAAK,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAGpF,sGAAsG;AACtG,MAAM,WAAW,OAAO;IACtB,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,4BAA4B;IAC5B,MAAM,EAAE,MAAM,CAAA;IACd,2CAA2C;IAC3C,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,kGAAkG;IAClG,EAAE,EAAE,MAAM,CAAA;IACV,gEAAgE;IAChE,IAAI,EAAE,MAAM,CAAA;IACZ,yEAAyE;IACzE,MAAM,EAAE,OAAO,CAAA;IACf,8EAA8E;IAC9E,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,0EAA0E;IAC1E,KAAK,EAAE,KAAK,EAAE,CAAA;IACd,0IAA0I;IAC1I,KAAK,EAAE,KAAK,EAAE,CAAA;IACd,8GAA8G;IAC9G,KAAK,EAAE,WAAW,EAAE,CAAA;IACpB,iJAAiJ;IACjJ,KAAK,EAAE,MAAM,EAAE,CAAA;IACf;;;;OAIG;IACH,MAAM,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,EAAE,CAAC;QAAC,KAAK,CAAC,EAAE,KAAK,CAAA;KAAE,CAAA;IAC5C,0DAA0D;IAC1D,SAAS,EAAE,QAAQ,EAAE,CAAA;IACrB,4DAA4D;IAC5D,KAAK,EAAE,WAAW,CAAA;CACnB;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS,CAAA;AAEzD,iEAAiE;AACjE,MAAM,WAAW,MAAM;IACrB,kEAAkE;IAClE,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,SAAS,CAAA;IAChB,6CAA6C;IAC7C,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,sEAAsE;IACtE,OAAO,EAAE,OAAO,EAAE,CAAA;IAClB,2EAA2E;IAC3E,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,8GAA8G;IAC9G,UAAU,CAAC,EAAE,UAAU,CAAA;IACvB;;;;OAIG;IACH,UAAU,EAAE,OAAO,CAAA;CACpB;AAyBD;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,MAAM,EAAE,CA8FvG"}
package/dist/shape.js ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * One shape for a message, a reply and a thread — SPEC §6.3–§6.8 and §6.4's
3
+ * "Resolving a thread", folded once for every app (ONE-2).
4
+ *
5
+ * Peek, Ship and Leaf each read a conversation into their own shape until
6
+ * now, and they disagreed: on which resolve counts, on what a deleted
7
+ * comment's thread shows, and on whether a reaction is known by its person's
8
+ * key or name. {@link foldThreads} is the one answer. It draws nothing — the
9
+ * kit in `@estiva-app/ui` takes words and nodes, and this sits below it.
10
+ *
11
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-conversation-is-one-shared-thing-and-only-its-colours-are-the-apps.md
12
+ */
13
+ import { BLOCK_ANCHOR_TAG, imetaOf, partsOf, quoteOf, readRunIds, } from '@estiva-app/protocol';
14
+ import { editsByTarget, foldEdits, foldEmbeds } from './edits.js';
15
+ import { isConversationKind, isEventId, KIND_COMMENT, KIND_DELETION, KIND_REACTION } from './kinds.js';
16
+ import { orderingMs } from './order.js';
17
+ import { groupReactions, reactionEventsOf } from './reactions.js';
18
+ import { resolutionOf, resolutionsByTarget } from './resolution.js';
19
+ import { groupThreads } from './threads.js';
20
+ const values = (event, name) => event.tags.filter((t) => t[0] === name && typeof t[1] === 'string' && t[1] !== '').map((t) => t[1]);
21
+ /**
22
+ * What its author took back: the ids a `kind:5` names by `e`, kept only for
23
+ * the event it names when its signer wrote that event (§6.5). A `kind:5` for
24
+ * an event the read does not hold is kept by its signer, for a top-level
25
+ * message known only from its replies.
26
+ */
27
+ function deletionsOf(events) {
28
+ const by = new Map();
29
+ for (const event of events) {
30
+ if (event.kind !== KIND_DELETION)
31
+ continue;
32
+ for (const id of values(event, 'e')) {
33
+ if (!isEventId(id))
34
+ continue;
35
+ const key = id.toLowerCase();
36
+ if (!by.has(key))
37
+ by.set(key, new Set());
38
+ by.get(key).add(event.pubkey);
39
+ }
40
+ }
41
+ return by;
42
+ }
43
+ /**
44
+ * Fold a conversation into its threads (§6.3–§6.8).
45
+ *
46
+ * `events` is everything read for it: its `kind:9` or `kind:1111` messages,
47
+ * and the `kind:40003` edits, `kind:7` reactions, `kind:5` deletions and
48
+ * `kind:9101` resolutions read by `#e` on them. Duplicates are read once.
49
+ * `viewer` marks the viewer's own reactions (`Reaction.mine`).
50
+ *
51
+ * Threads come oldest first by their top-level message, or by their first
52
+ * reply when it was not returned. A reply to a reply is filed under the
53
+ * thread's top-level message (§6.4).
54
+ */
55
+ export function foldThreads(events, options = {}) {
56
+ const unique = [...new Map(events.map((e) => [e.id, e])).values()];
57
+ const deletions = deletionsOf(unique);
58
+ const deletedBy = (id, author) => author !== undefined && deletions.get(id.toLowerCase())?.has(author) === true;
59
+ /*
60
+ A top-level message the read did not return is known deleted only by its
61
+ author's `kind:5`, and its author only from its replies: a reply's
62
+ lowercase `p` names the comment's author (§6.4). Every `kind:1111` reply
63
+ must name the deletion's signer, so one reply's tags cannot speak for a
64
+ thread others answered; a channel `kind:9` names no author, and stays
65
+ `missing`.
66
+ */
67
+ /** 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). */
68
+ const replyFolderOf = (answers) => {
69
+ const count = new Map();
70
+ for (const r of answers) {
71
+ const h = values(r, 'h')[0];
72
+ if (h)
73
+ count.set(h, (count.get(h) ?? 0) + 1);
74
+ }
75
+ const ranked = [...count].sort((a, b) => b[1] - a[1]);
76
+ return ranked.length > 0 && (ranked.length === 1 || ranked[0][1] > ranked[1][1]) ? ranked[0][0] : undefined;
77
+ };
78
+ const deletedUnseen = (id, answers) => {
79
+ const comments = answers.filter((r) => r.kind === KIND_COMMENT);
80
+ const signers = deletions.get(id.toLowerCase());
81
+ if (!signers || comments.length === 0)
82
+ return false;
83
+ return [...signers].some((signer) => comments.every((r) => r.tags.some((t) => t[0] === 'p' && t[1] === signer)));
84
+ };
85
+ const messages = unique.filter((e) => isConversationKind(e.kind));
86
+ const edits = foldEdits(unique);
87
+ const edited = editsByTarget(unique);
88
+ const cardsOf = foldEmbeds(unique);
89
+ // A taken-back reaction leaves before the one-per-person fold, so the same person's later one counts.
90
+ const reactions = groupReactions(reactionEventsOf(unique.filter((e) => e.kind !== KIND_REACTION || !deletedBy(e.id, e.pubkey))), options.viewer);
91
+ const resolutions = resolutionsByTarget(unique);
92
+ const messageOf = (event) => {
93
+ const id = event.id.toLowerCase();
94
+ const fold = edits[id];
95
+ // An edit is the whole new message (§6.8): what its words link is the latest edit's `a` and `q`.
96
+ const linkSource = edited.get(id)?.at(-1) ?? event;
97
+ const blockTag = event.tags.find((t) => t[0] === BLOCK_ANCHOR_TAG);
98
+ const blocks = blockTag ? readRunIds(blockTag.slice(1)) : undefined;
99
+ const quote = blocks ? quoteOf(event) : undefined;
100
+ const folder = values(event, 'h')[0];
101
+ return {
102
+ id,
103
+ kind: event.kind,
104
+ author: event.pubkey,
105
+ ...(folder ? { folder } : {}),
106
+ at: orderingMs(event),
107
+ body: fold?.body ?? event.content,
108
+ edited: fold?.edited ?? false,
109
+ ...(fold?.editedAt !== undefined ? { editedAt: fold.editedAt } : {}),
110
+ files: fold ? fold.attachments : imetaOf(event),
111
+ cards: cardsOf[id] ?? [],
112
+ parts: partsOf(event),
113
+ links: [...new Set([...values(linkSource, 'a'), ...values(linkSource, 'q')])],
114
+ ...(blocks && event.kind === KIND_COMMENT ? { anchor: { blocks, ...(quote ? { quote } : {}) } } : {}),
115
+ reactions: reactions[id] ?? [],
116
+ event,
117
+ };
118
+ };
119
+ const { roots, replies, missingRoots } = groupThreads(messages);
120
+ const threads = [];
121
+ const thread = (id, root) => {
122
+ const all = replies[id] ?? [];
123
+ const kept = all.filter((r) => !deletedBy(r.id, r.pubkey)).map(messageOf);
124
+ const folder = root ? values(root, 'h')[0] : replyFolderOf(all);
125
+ // Not returned, only the replies filed in the thread's Folder speak for its comment: one filed elsewhere neither deletes nor clears.
126
+ const speaking = root ? all : all.filter((r) => values(r, 'h')[0] === folder);
127
+ const state = (root ? deletedBy(id, root.pubkey) : folder !== undefined && deletedUnseen(id, speaking)) ? 'deleted' : root ? 'present' : 'missing';
128
+ const resolution = resolutionOf(resolutions[id.toLowerCase()] ?? [], { folder, replies: kept.map((r) => r.id) });
129
+ return {
130
+ id: id.toLowerCase(),
131
+ state,
132
+ ...(state === 'present' && root ? { root: messageOf(root) } : {}),
133
+ replies: kept,
134
+ ...(folder ? { folder } : {}),
135
+ ...(resolution ? { resolution } : {}),
136
+ resolvable: state === 'present',
137
+ };
138
+ };
139
+ for (const root of roots)
140
+ threads.push(thread(root.id, root));
141
+ for (const id of missingRoots)
142
+ threads.push(thread(id, undefined));
143
+ // A thread whose top-level message is gone and has no reply left has nothing to draw.
144
+ const drawn = threads.filter((t) => t.root || t.replies.length > 0);
145
+ const firstAt = (t) => t.root?.at ?? t.replies[0].at;
146
+ return drawn.sort((a, b) => firstAt(a) - firstAt(b) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
147
+ }
148
+ //# sourceMappingURL=shape.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shape.js","sourceRoot":"","sources":["../src/shape.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EACL,gBAAgB,EAChB,OAAO,EACP,OAAO,EACP,OAAO,EACP,UAAU,GAMX,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AACjE,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AACtG,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AACvC,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAiB,MAAM,gBAAgB,CAAA;AAChF,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAmB,MAAM,iBAAiB,CAAA;AACpF,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAqE3C,MAAM,MAAM,GAAG,CAAC,KAAgC,EAAE,IAAY,EAAE,EAAE,CAChE,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,GAAG,CAAC,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AM,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC,CAAA;IAClE,sFAAsF;IACtF,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;IACnE,MAAM,OAAO,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;IAC5D,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAClG,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@estiva-app/conversation",
3
- "version": "0.31.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.",
3
+ "version": "0.33.0",
4
+ "description": "The conversation rules of the Estiva SPEC (§6.2–§6.8, §11): comment and mention strengths, threading, one shape for a message and a thread, resolving a thread, the line rule, 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": {