@estiva-app/conversation 0.3.0 → 0.5.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/CHANGELOG.md CHANGED
@@ -6,6 +6,46 @@ none. A change to how an event is read is a MINOR in `0.x` even when no
6
6
  signature moved, because two apps on different versions would then disagree
7
7
  about a conversation.
8
8
 
9
+ ## 0.5.0 — 2026-10-03
10
+
11
+ **What `[` offers, and in what order** (PEE-21, CON-26's ranking, Miky
12
+ 2026-10-02/03). Needs protocol 0.24.0, unchanged.
13
+
14
+ - `rankReferences({messages, files, query, ownKinds?, caps?})` — two capped
15
+ sections, Messages (this thread or file, then its parent) above Files (this
16
+ Folder, then recently read, then search hits only once something is typed).
17
+ Typed, a better title match beats a higher tier; an archived file goes after
18
+ every other row of the same match, typed or not, and an open issue before a
19
+ closed one; the app's own kinds break what ties are left. `REFERENCE_CAPS`
20
+ is 4 and 6.
21
+ - `referenceMatch(text, query)` — 4 whole, 3 start, 2 word start, 1 anywhere.
22
+ - `fileReference(address)` — `nostr:naddr…` with no relay hint, the bytes a
23
+ pasted link resolves to.
24
+ - `referenceSearch({search})` — the search tier per keystroke: debounced,
25
+ cached, a failure answered as no hits for `retryMs` (5s) and then asked
26
+ again, listeners told when an answer lands. `reset()` it when the signed-in
27
+ person changes.
28
+
29
+ **SPEC:** none of §6 or §9 changes how this package reads or writes. A file
30
+ pick writes what a paste writes and earns `["a", <address>]` through
31
+ `referenceTagsFor`, as §13.1 already says; ranking is a client's choice.
32
+
33
+ ## 0.4.0 — 2026-10-02
34
+
35
+ **A reference records which message it points at** (CON-25, Miky
36
+ 2026-10-02). Needs protocol 0.24.0, unchanged.
37
+
38
+ - `quoteTagsFor(body, own?)` — `["q", <event id>]`, one per message the body
39
+ references by `nostr:nevent…` or `nostr:note…`, deduplicated, leaving out
40
+ `own`. A writer appends it to a `kind:9` or a `kind:1111` beside the `p`
41
+ and `a` tags the body earns.
42
+ - `eventsNamedInBody` — the ids behind them.
43
+
44
+ **SPEC:** §13.1 gains the `q` rule (estiva-docs, CON-25): a `q` is an index
45
+ of what a message points at, never a reply, and a writer MUST NOT write one
46
+ for an event its body does not name. Reading is unchanged — nothing in this
47
+ package reads `q` yet.
48
+
9
49
  ## 0.3.0 — 2026-10-02
10
50
 
11
51
  **What a composer's pick writes** (CON-27): SPEC §13.1, unchanged. Needs
package/README.md CHANGED
@@ -26,6 +26,7 @@ pass, the clock is a `createdAtMs` you pass, and drafts take their storage.
26
26
  | threading | §6.4 *Replies* | `parentOf`, `groupThreads` |
27
27
  | writing | §6.4 | `buildComment`, `buildReply`, `referenceTagsFor`, `mentionTagsFor` |
28
28
  | what a composer's pick writes | §13.1 | `mentionText`, `messageReference`, `urgentTagsFor`, `URGENT_TAG` |
29
+ | what `[` offers, and in what order | §13.1 | `rankReferences`, `referenceMatch`, `fileReference`, `referenceSearch`, `MESSAGE_TIER`, `FILE_TIER`, `REFERENCE_CAPS` |
29
30
  | ordering | §6.2, §6.3 | `trustedTs`, `orderingMs`, `byOrder` |
30
31
  | edits and attachments | §6.8 | `editTargetOf`, `foldEdits`, `foldAttachments` |
31
32
  | reactions | §6.6 | `REACTION_HORIZON`, `reactionHorizon`, `reactionTargetOf`, `reactionEmojiOf`, `foldReactions` |
package/dist/compose.d.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  * | --- | --- | --- |
12
12
  * | a person (`@`) | `nostr:npub…`, or `@Name` with no key | `p`, from {@link mentionTagsFor} |
13
13
  * | a person, urgently (`!@`) | the same `nostr:npub…`, or `!@Name` | `p`, and {@link urgentTagsFor}'s `["urgent", <pubkey>]` |
14
- * | a message (`[`) | `nostr:nevent…` with its kind and no relay | none yet — a `q` from CON-25 (Decided on CON-26) |
14
+ * | a message (`[`) | `nostr:nevent…` with its kind and no relay | `q`, from {@link quoteTagsFor} (CON-25) |
15
15
  */
16
16
  import { type NostrTag } from '@estiva-app/protocol';
17
17
  /**
@@ -50,4 +50,16 @@ export declare const URGENT_TAG = "urgent";
50
50
  * cannot say which of the people it names were urgent.
51
51
  */
52
52
  export declare function urgentTagsFor(body: string, urgent: readonly string[] | undefined): NostrTag[];
53
+ /** The events a body references by `nostr:nevent…` or `nostr:note…` (§13.1), in the order it names them. */
54
+ export declare function eventsNamedInBody(body: string): Set<string>;
55
+ /**
56
+ * The `q` tags a body earns: `["q", <event id>]`, one per event it references
57
+ * (SPEC §13.1, CON-25). NIP-18's quote, as an index of *which message this one
58
+ * points at* — never a reply, which is `e` (§6.4). Two elements: the relay is
59
+ * the workspace's, and a `[` pick's `nevent` carries no author to fill a third.
60
+ *
61
+ * `own`, when given, is left out — the event a reply already names by `e`, so
62
+ * one message is not both answered and quoted.
63
+ */
64
+ export declare function quoteTagsFor(body: string, own?: string): NostrTag[];
53
65
  //# sourceMappingURL=compose.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"compose.d.ts","sourceRoot":"","sources":["../src/compose.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAA4B,KAAK,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAG9E;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,EAAE,MAAM,UAAQ,GAAG,MAAM,CAGrG;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAEtE;AAED,6FAA6F;AAC7F,eAAO,MAAM,UAAU,WAAW,CAAA;AAElC;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,GAAG,QAAQ,EAAE,CAI7F"}
1
+ {"version":3,"file":"compose.d.ts","sourceRoot":"","sources":["../src/compose.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAoF,KAAK,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAGtI;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,EAAE,MAAM,UAAQ,GAAG,MAAM,CAGrG;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAEtE;AAED,6FAA6F;AAC7F,eAAO,MAAM,UAAU,WAAW,CAAA;AAElC;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,GAAG,QAAQ,EAAE,CAI7F;AAWD,4GAA4G;AAC5G,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAY3D;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,SAAK,GAAG,QAAQ,EAAE,CAI/D"}
package/dist/compose.js CHANGED
@@ -11,9 +11,9 @@
11
11
  * | --- | --- | --- |
12
12
  * | a person (`@`) | `nostr:npub…`, or `@Name` with no key | `p`, from {@link mentionTagsFor} |
13
13
  * | a person, urgently (`!@`) | the same `nostr:npub…`, or `!@Name` | `p`, and {@link urgentTagsFor}'s `["urgent", <pubkey>]` |
14
- * | a message (`[`) | `nostr:nevent…` with its kind and no relay | none yet — a `q` from CON-25 (Decided on CON-26) |
14
+ * | a message (`[`) | `nostr:nevent…` with its kind and no relay | `q`, from {@link quoteTagsFor} (CON-25) |
15
15
  */
16
- import { encodeNevent, encodeNpub } from '@estiva-app/protocol';
16
+ import { bech32Decode, convertBits, decodeNevent, encodeNevent, encodeNpub, findNostrUris } from '@estiva-app/protocol';
17
17
  import { mentionTagsFor } from './strength.js';
18
18
  /**
19
19
  * A person as the body names them.
@@ -59,4 +59,45 @@ export function urgentTagsFor(body, urgent) {
59
59
  const named = new Set(mentionTagsFor(body).map((tag) => tag[1]));
60
60
  return [...new Set(urgent)].filter((pubkey) => named.has(pubkey)).map((pubkey) => [URGENT_TAG, pubkey]);
61
61
  }
62
+ /** The event id a `note1…` names: its 32 bytes, as hex. Throws on anything else. */
63
+ function decodeNote(encoded) {
64
+ const { hrp, data } = bech32Decode(encoded.toLowerCase());
65
+ if (hrp !== 'note')
66
+ throw new Error(`expected a note, got ${hrp}`);
67
+ const bytes = convertBits(data, 5, 8, false);
68
+ if (bytes.length !== 32)
69
+ throw new Error('a note is 32 bytes');
70
+ return bytes.map((b) => b.toString(16).padStart(2, '0')).join('');
71
+ }
72
+ /** The events a body references by `nostr:nevent…` or `nostr:note…` (§13.1), in the order it names them. */
73
+ export function eventsNamedInBody(body) {
74
+ const ids = new Set();
75
+ for (const uri of findNostrUris(body)) {
76
+ const bech = uri.slice('nostr:'.length);
77
+ try {
78
+ if (bech.startsWith('nevent1'))
79
+ ids.add(decodeNevent(bech).id);
80
+ else if (bech.startsWith('note1'))
81
+ ids.add(decodeNote(bech));
82
+ }
83
+ catch {
84
+ // A malformed pointer is prose.
85
+ }
86
+ }
87
+ return ids;
88
+ }
89
+ /**
90
+ * The `q` tags a body earns: `["q", <event id>]`, one per event it references
91
+ * (SPEC §13.1, CON-25). NIP-18's quote, as an index of *which message this one
92
+ * points at* — never a reply, which is `e` (§6.4). Two elements: the relay is
93
+ * the workspace's, and a `[` pick's `nevent` carries no author to fill a third.
94
+ *
95
+ * `own`, when given, is left out — the event a reply already names by `e`, so
96
+ * one message is not both answered and quoted.
97
+ */
98
+ export function quoteTagsFor(body, own = '') {
99
+ const ids = eventsNamedInBody(body);
100
+ ids.delete(own);
101
+ return [...ids].map((id) => ['q', id]);
102
+ }
62
103
  //# sourceMappingURL=compose.js.map
@@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AAI,CAAC,CAAC,EAAE,CAAC,CAAA;iBACzD,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAA;QAC9D,CAAC;QAAC,MAAM,CAAC;YACP,gCAAgC;QAClC,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,YAAY,CAAC,IAAY,EAAE,GAAG,GAAG,EAAE;IACjD,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAA;IACnC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IACf,OAAO,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,CAAA;AACxC,CAAC"}
package/dist/index.d.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 declare const CONVERSATION_VERSION = "0.3.0";
15
+ export declare const CONVERSATION_VERSION = "0.5.0";
16
16
  export { KIND_MESSAGE, KIND_COMMENT, KIND_EDIT, KIND_REACTION, KIND_DELETION, KIND_ASSERTION, isConversationKind, isEventId, } from './kinds.js';
17
17
  export { trustedTs, orderingMs, byOrder } from './order.js';
18
18
  export { namedInBody, isReply, anchorsOf, isCommentOn, referencesAddress, strengthOn, threadStrength, referenceTagsFor, mentionTagsFor, peopleNamedInBody, MAX_MENTIONED_PEOPLE, type Strength, } from './strength.js';
@@ -21,7 +21,8 @@ export { editTargetOf, editsByTarget, foldEdits, foldAttachments, type EditFold
21
21
  export { REACTION_HORIZON, REACTION_EMOJI, reactionTargetOf, reactionEmojiOf, reactionHorizon, reactionEventsOf, foldReactions, groupReactions, type ReactionHorizon, type ReactionEvent, type Reaction, } from './reactions.js';
22
22
  export { decorationsOf, type Decoration, type Decorations, type Resolution, type QueryFn } from './decorations.js';
23
23
  export { buildComment, buildReply, offersEditAndDelete, type CommentRef } from './builders.js';
24
- export { mentionText, messageReference, URGENT_TAG, urgentTagsFor } from './compose.js';
24
+ export { eventsNamedInBody, mentionText, messageReference, quoteTagsFor, URGENT_TAG, urgentTagsFor } from './compose.js';
25
+ export { FILE_TIER, fileReference, MESSAGE_TIER, rankReferences, REFERENCE_CAPS, referenceMatch, referenceSearch, type RankedReferences, type RankReferencesInput, type ReferenceCandidate, type ReferenceSearch, type ReferenceSearchFn, type ReferenceSearchOptions, type ReferenceType, } from './references.js';
25
26
  export { KIND_CHANGE, MEMBER_FIELD_PREFIX, memberField, memberOfField, mentions, streamOf, membershipOf, membersOf, membershipFilters, candidateFilesOf, buildMembershipChange, MUTED_D_TAG, APPDATA_TAG, parseMutedBlob, serializeMutedBlob, buildMutedEvent, mutedFilter, mutedFromFollowed, type Membership, type MutedList, } from './membership.js';
26
27
  export { READ_STATE_TAG, READ_STATE_D_PREFIX, MAX_CONTEXTS, MAX_CONTEXT_ID_BYTES, MAX_TIMESTAMP, MAX_CLIENT_ID_BYTES, MAX_BLOB_BYTES, MAX_CONTEXTS_BYTES, READ_STATE_HORIZON_DAYS, channelContext, fileContext, threadContext, messageContext, toContextSeconds, isPublishableContextId, loadSlotIdentity, rotateSlotId, readStateDTag, parseReadStateBlob, serializeReadStateBlob, capContextsToBytes, advanceContexts, buildReadStateEvent, allSlotsFilter, mergeSlots, classifyOwnSlots, effectiveReadAt, fetchReadState, publishReadState, type SlotIdentity, type SlotStorage, type SlotSource, type RandomBytes, type ReadStateBlob, type CappedContexts, type SlotBlob, type OwnSlotVerdict, type Nip44, type FetchedReadState, } from './readState.js';
27
28
  export { unreadIn, isUnread, type StreamJudge } from './unread.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;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B,EACjB,gBAAgB,EAChB,qBAAqB,EACrB,WAAW,EACX,WAAW,EACX,cAAc,EACd,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,iBAAiB,EACjB,KAAK,UAAU,EACf,KAAK,SAAS,GACf,MAAM,iBAAiB,CAAA;AAExB,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,oBAAoB,EACpB,aAAa,EACb,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,EACd,WAAW,EACX,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,kBAAkB,EAClB,sBAAsB,EACtB,kBAAkB,EAClB,eAAe,EACf,mBAAmB,EACnB,cAAc,EACd,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,cAAc,EACd,gBAAgB,EAChB,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,QAAQ,EACb,KAAK,cAAc,EACnB,KAAK,KAAK,EACV,KAAK,gBAAgB,GACtB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAA;AAElE,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,KAAK,UAAU,EACf,KAAK,YAAY,GAClB,MAAM,aAAa,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,oBAAoB,UAAU,CAAA;AAE3C,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,aAAa,EACb,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,SAAS,GACV,MAAM,YAAY,CAAA;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O,EACL,WAAW,EACX,mBAAmB,EACnB,WAAW,EACX,aAAa,EACb,QAAQ,EACR,QAAQ,EACR,YAAY,EACZ,SAAS,EACT,iBAAiB,EACjB,gBAAgB,EAChB,qBAAqB,EACrB,WAAW,EACX,WAAW,EACX,cAAc,EACd,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,iBAAiB,EACjB,KAAK,UAAU,EACf,KAAK,SAAS,GACf,MAAM,iBAAiB,CAAA;AAExB,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,oBAAoB,EACpB,aAAa,EACb,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,EACd,WAAW,EACX,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,kBAAkB,EAClB,sBAAsB,EACtB,kBAAkB,EAClB,eAAe,EACf,mBAAmB,EACnB,cAAc,EACd,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,cAAc,EACd,gBAAgB,EAChB,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,QAAQ,EACb,KAAK,cAAc,EACnB,KAAK,KAAK,EACV,KAAK,gBAAgB,GACtB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAA;AAElE,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,KAAK,UAAU,EACf,KAAK,YAAY,GAClB,MAAM,aAAa,CAAA"}
package/dist/index.js 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.3.0';
15
+ export const CONVERSATION_VERSION = '0.5.0';
16
16
  export { KIND_MESSAGE, KIND_COMMENT, KIND_EDIT, KIND_REACTION, KIND_DELETION, KIND_ASSERTION, isConversationKind, isEventId, } from './kinds.js';
17
17
  export { trustedTs, orderingMs, byOrder } from './order.js';
18
18
  export { namedInBody, isReply, anchorsOf, isCommentOn, referencesAddress, strengthOn, threadStrength, referenceTagsFor, mentionTagsFor, peopleNamedInBody, MAX_MENTIONED_PEOPLE, } from './strength.js';
@@ -21,7 +21,8 @@ export { editTargetOf, editsByTarget, foldEdits, foldAttachments } from './edits
21
21
  export { REACTION_HORIZON, REACTION_EMOJI, reactionTargetOf, reactionEmojiOf, reactionHorizon, reactionEventsOf, foldReactions, groupReactions, } from './reactions.js';
22
22
  export { decorationsOf } from './decorations.js';
23
23
  export { buildComment, buildReply, offersEditAndDelete } from './builders.js';
24
- export { mentionText, messageReference, URGENT_TAG, urgentTagsFor } from './compose.js';
24
+ export { eventsNamedInBody, mentionText, messageReference, quoteTagsFor, URGENT_TAG, urgentTagsFor } from './compose.js';
25
+ export { FILE_TIER, fileReference, MESSAGE_TIER, rankReferences, REFERENCE_CAPS, referenceMatch, referenceSearch, } from './references.js';
25
26
  export { KIND_CHANGE, MEMBER_FIELD_PREFIX, memberField, memberOfField, mentions, streamOf, membershipOf, membersOf, membershipFilters, candidateFilesOf, buildMembershipChange, MUTED_D_TAG, APPDATA_TAG, parseMutedBlob, serializeMutedBlob, buildMutedEvent, mutedFilter, mutedFromFollowed, } from './membership.js';
26
27
  export { READ_STATE_TAG, READ_STATE_D_PREFIX, MAX_CONTEXTS, MAX_CONTEXT_ID_BYTES, MAX_TIMESTAMP, MAX_CLIENT_ID_BYTES, MAX_BLOB_BYTES, MAX_CONTEXTS_BYTES, READ_STATE_HORIZON_DAYS, channelContext, fileContext, threadContext, messageContext, toContextSeconds, isPublishableContextId, loadSlotIdentity, rotateSlotId, readStateDTag, parseReadStateBlob, serializeReadStateBlob, capContextsToBytes, advanceContexts, buildReadStateEvent, allSlotsFilter, mergeSlots, classifyOwnSlots, effectiveReadAt, fetchReadState, publishReadState, } from './readState.js';
27
28
  export { unreadIn, isUnread } from './unread.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAA;AAE3C,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,aAAa,EACb,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,SAAS,GACV,MAAM,YAAY,CAAA;AAEnB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAE3D,OAAO,EACL,WAAW,EACX,OAAO,EACP,SAAS,EACT,WAAW,EACX,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,gBAAgB,EAChB,cAAc,EACd,iBAAiB,EACjB,oBAAoB,GAErB,MAAM,eAAe,CAAA;AAEtB,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAiB,MAAM,cAAc,CAAA;AAEpE,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,eAAe,EAAiB,MAAM,YAAY,CAAA;AAEnG,OAAO,EACL,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,aAAa,EACb,cAAc,GAIf,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EAAE,aAAa,EAAoE,MAAM,kBAAkB,CAAA;AAElH,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,mBAAmB,EAAmB,MAAM,eAAe,CAAA;AAE9F,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAEvF,OAAO,EACL,WAAW,EACX,mBAAmB,EACnB,WAAW,EACX,aAAa,EACb,QAAQ,EACR,QAAQ,EACR,YAAY,EACZ,SAAS,EACT,iBAAiB,EACjB,gBAAgB,EAChB,qBAAqB,EACrB,WAAW,EACX,WAAW,EACX,cAAc,EACd,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,iBAAiB,GAGlB,MAAM,iBAAiB,CAAA;AAExB,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,oBAAoB,EACpB,aAAa,EACb,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,EACd,WAAW,EACX,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,kBAAkB,EAClB,sBAAsB,EACtB,kBAAkB,EAClB,eAAe,EACf,mBAAmB,EACnB,cAAc,EACd,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,cAAc,EACd,gBAAgB,GAWjB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAoB,MAAM,aAAa,CAAA;AAElE,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,SAAS,EACT,gBAAgB,EAChB,eAAe,GAGhB,MAAM,aAAa,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAA;AAE3C,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,aAAa,EACb,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,SAAS,GACV,MAAM,YAAY,CAAA;AAEnB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAE3D,OAAO,EACL,WAAW,EACX,OAAO,EACP,SAAS,EACT,WAAW,EACX,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,gBAAgB,EAChB,cAAc,EACd,iBAAiB,EACjB,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ACf,mBAAmB,EACnB,cAAc,EACd,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,cAAc,EACd,gBAAgB,GAWjB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAoB,MAAM,aAAa,CAAA;AAElE,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,SAAS,EACT,gBAAgB,EAChB,eAAe,GAGhB,MAAM,aAAa,CAAA"}
@@ -0,0 +1,128 @@
1
+ /** What a reference names, as the row's type word says it (label objects by type, not app). */
2
+ export type ReferenceType = 'message' | 'issue' | 'project' | 'topic';
3
+ /** Something `[` can offer. */
4
+ export interface ReferenceCandidate {
5
+ /** The event id of a message, the `kind:pubkey:d` address of a file. Unique across the list. */
6
+ id: string;
7
+ /** `nostr:…`, exactly as the body will carry it: {@link fileReference} or `messageReference`. */
8
+ uri: string;
9
+ type: ReferenceType;
10
+ kind: number;
11
+ /** A file's current title; a message's author. */
12
+ title: string;
13
+ /** An issue's project title, a message's opening words; `''` when there is none. */
14
+ caption: string;
15
+ /** A message's text, matched beside `title`. Files match on `title` only. */
16
+ search?: string;
17
+ /** 0 is closest: {@link MESSAGE_TIER} or {@link FILE_TIER}. */
18
+ tier: number;
19
+ /** A done or cancelled issue: offered, after an open one on an equal match. */
20
+ closed?: boolean;
21
+ /**
22
+ * An archived file, or an issue in an archived project: offered at the lowest
23
+ * priority — after every row that is not, on an equal match (Miky, 2026-10-03).
24
+ */
25
+ archived?: boolean;
26
+ /** When it was written or last read, in seconds — newer first within a tier. */
27
+ at?: number;
28
+ }
29
+ /** Where a message sits relative to the box you are writing in. */
30
+ export declare const MESSAGE_TIER: {
31
+ readonly here: 0;
32
+ readonly parent: 1;
33
+ };
34
+ /** Where a file sits relative to you. `search` only ever comes from typing. */
35
+ export declare const FILE_TIER: {
36
+ readonly folder: 0;
37
+ readonly recent: 1;
38
+ readonly search: 2;
39
+ };
40
+ /** How many rows each section shows (Miky, 2026-10-03): the box stays at the old list's height. */
41
+ export declare const REFERENCE_CAPS: {
42
+ readonly messages: 4;
43
+ readonly files: 6;
44
+ };
45
+ export interface RankedReferences {
46
+ messages: ReferenceCandidate[];
47
+ files: ReferenceCandidate[];
48
+ }
49
+ export interface RankReferencesInput {
50
+ messages: readonly ReferenceCandidate[];
51
+ files: readonly ReferenceCandidate[];
52
+ /** What was typed after `[`. */
53
+ query: string;
54
+ /** The kinds the app itself writes — the last tie-breaker. */
55
+ ownKinds?: readonly number[];
56
+ caps?: {
57
+ messages: number;
58
+ files: number;
59
+ };
60
+ }
61
+ /**
62
+ * How well `text` holds `query`: 4 the whole of it, 3 its start, 2 the start of
63
+ * a word, 1 anywhere — or every word of the query at a word's start. 0 is no
64
+ * match. Case and runs of spaces are ignored.
65
+ */
66
+ export declare function referenceMatch(text: string, query: string): number;
67
+ /**
68
+ * The two sections `[` draws, each ranked and capped.
69
+ *
70
+ * Nothing in the `search` tier is offered with nothing typed, nor anything that
71
+ * does not match what was typed. Ties end on recency, then the title, so the
72
+ * list holds still between keystrokes.
73
+ */
74
+ export declare function rankReferences({ messages, files, query, ownKinds, caps }: RankReferencesInput): RankedReferences;
75
+ /**
76
+ * A file as the body references it: `nostr:naddr…` with no relay hint, the
77
+ * same bytes a pasted link resolves to — so it earns its `["a", <address>]`
78
+ * through `referenceTagsFor` and draws as the same widget (SPEC §13.1). The
79
+ * title is never in the body: a file from a private Folder named in a wider
80
+ * one leaks nothing but its pointer.
81
+ *
82
+ * `address` is `kind:pubkey:d`; anything else throws.
83
+ */
84
+ export declare function fileReference(address: string): string;
85
+ /** What a {@link referenceSearch} asks the relay for: the files whose title holds `query`. */
86
+ export type ReferenceSearchFn = (query: string) => Promise<readonly ReferenceCandidate[]>;
87
+ export interface ReferenceSearch {
88
+ /**
89
+ * The search tier for `query`: what the relay last answered for it, or —
90
+ * while it is asked — for the longest query before it that it answered.
91
+ * Asks it, after a pause, when it has not been asked.
92
+ */
93
+ hits(query: string): readonly ReferenceCandidate[];
94
+ /** Called when an answer lands; returns the unsubscribe. */
95
+ subscribe(listener: () => void): () => void;
96
+ /**
97
+ * Drops what is pending and what was answered. Call it when the signed-in
98
+ * person changes: answers are kept by the text asked, not by who asked, and
99
+ * the last person's hits name files the next one may not be able to read.
100
+ */
101
+ reset(): void;
102
+ }
103
+ export interface ReferenceSearchOptions {
104
+ search: ReferenceSearchFn;
105
+ /** The pause after a keystroke before asking. Default 200ms. */
106
+ delayMs?: number;
107
+ /** How long a failed query answers no hits before it may be asked again. Default 5s. */
108
+ retryMs?: number;
109
+ /** Shorter queries ask nothing. Default 2. */
110
+ minLength?: number;
111
+ }
112
+ /**
113
+ * The third Files tier, as the list asks for it on every keystroke: answers
114
+ * now from what it holds, and asks the relay behind it.
115
+ *
116
+ * The rows already on screen never wait for the relay: a slow or failing
117
+ * search leaves them as they are, with no spinner and no error row
118
+ * (PEE-21). A failure answers no hits for `retryMs`, so a rate limit is not
119
+ * hammered on every render, and is then forgotten, so one blip does not hide
120
+ * that query for the rest of the session. Answers are filtered again by
121
+ * {@link rankReferences}, so a shorter query's hits shown meanwhile never
122
+ * offer a row the typed text does not match.
123
+ *
124
+ * Only the pause is cancelled by the next keystroke: a query already asked
125
+ * keeps its answer, which is still true of that query.
126
+ */
127
+ export declare function referenceSearch({ search, delayMs, retryMs, minLength }: ReferenceSearchOptions): ReferenceSearch;
128
+ //# sourceMappingURL=references.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"references.d.ts","sourceRoot":"","sources":["../src/references.ts"],"names":[],"mappings":"AAuBA,+FAA+F;AAC/F,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,GAAG,OAAO,CAAA;AAErE,+BAA+B;AAC/B,MAAM,WAAW,kBAAkB;IACjC,gGAAgG;IAChG,EAAE,EAAE,MAAM,CAAA;IACV,iGAAiG;IACjG,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,aAAa,CAAA;IACnB,IAAI,EAAE,MAAM,CAAA;IAC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B,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAErD;AAED,8FAA8F;AAC9F,MAAM,MAAM,iBAAiB,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,SAAS,kBAAkB,EAAE,CAAC,CAAA;AAKzF,MAAM,WAAW,eAAe;IAC9B;;;;OAIG;IACH,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,kBAAkB,EAAE,CAAA;IAClD,4DAA4D;IAC5D,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAA;IAC3C;;;;OAIG;IACH,KAAK,IAAI,IAAI,CAAA;CACd;AAED,MAAM,WAAW,sBAAsB;IACrC,MAAM,EAAE,iBAAiB,CAAA;IACzB,gEAAgE;IAChE,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,wFAAwF;IACxF,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,8CAA8C;IAC9C,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,eAAe,CAAC,EAAE,MAAM,EAAE,OAAa,EAAE,OAAc,EAAE,SAAa,EAAE,EAAE,sBAAsB,GAAG,eAAe,CAgEjI"}
@@ -0,0 +1,203 @@
1
+ /**
2
+ * What `[` offers, and in what order — CON-26's ranking (Miky, 2026-10-02),
3
+ * in one place for every app (PEE-21).
4
+ *
5
+ * Two capped sections, Messages above Files:
6
+ *
7
+ * - **Messages:** this thread or file first, then the parent file's.
8
+ * - **Files:** this Folder first, then files you read recently (your §11 read
9
+ * markers), then everything else, which you reach only by typing (relay
10
+ * search).
11
+ *
12
+ * With nothing typed the tiers set the order. Once you type, a better title
13
+ * match beats a higher tier; an open issue goes before a done or cancelled
14
+ * one on an equal match (Miky, 2026-10-03); the app's own kinds only break the
15
+ * ties that are left.
16
+ *
17
+ * The menu that draws the result is an editor's (`@estiva-app/ui/editor`'s
18
+ * `ReferenceTrigger`); this is the half a client that does not use React can
19
+ * take too. Where the candidates come from — a Folder's files, the read
20
+ * markers, a relay search — is the app's: each app holds them differently.
21
+ */
22
+ import { addrToNaddr } from '@estiva-app/protocol';
23
+ /** Where a message sits relative to the box you are writing in. */
24
+ export const MESSAGE_TIER = { here: 0, parent: 1 };
25
+ /** Where a file sits relative to you. `search` only ever comes from typing. */
26
+ export const FILE_TIER = { folder: 0, recent: 1, search: 2 };
27
+ /** How many rows each section shows (Miky, 2026-10-03): the box stays at the old list's height. */
28
+ export const REFERENCE_CAPS = { messages: 4, files: 6 };
29
+ const normalize = (text) => text.toLowerCase().replace(/\s+/g, ' ').trim();
30
+ const isWordStart = (text, at) => at === 0 || !/[\p{L}\p{N}]/u.test(text[at - 1]);
31
+ /**
32
+ * How well `text` holds `query`: 4 the whole of it, 3 its start, 2 the start of
33
+ * a word, 1 anywhere — or every word of the query at a word's start. 0 is no
34
+ * match. Case and runs of spaces are ignored.
35
+ */
36
+ export function referenceMatch(text, query) {
37
+ const t = normalize(text);
38
+ const q = normalize(query);
39
+ if (!q)
40
+ return 0;
41
+ if (t === q)
42
+ return 4;
43
+ if (t.startsWith(q))
44
+ return 3;
45
+ let at = t.indexOf(q);
46
+ if (at < 0) {
47
+ const words = q.split(' ');
48
+ if (words.length < 2)
49
+ return 0;
50
+ const starts = (w) => {
51
+ for (let i = t.indexOf(w); i >= 0; i = t.indexOf(w, i + 1))
52
+ if (isWordStart(t, i))
53
+ return true;
54
+ return false;
55
+ };
56
+ return words.every(starts) ? 1 : 0;
57
+ }
58
+ for (; at >= 0; at = t.indexOf(q, at + 1))
59
+ if (isWordStart(t, at))
60
+ return 2;
61
+ return 1;
62
+ }
63
+ /** Keeps each id once, at its closest tier. */
64
+ function closest(candidates) {
65
+ const best = new Map();
66
+ for (const c of candidates) {
67
+ const known = best.get(c.id);
68
+ if (!known || c.tier < known.tier)
69
+ best.set(c.id, c);
70
+ }
71
+ return [...best.values()];
72
+ }
73
+ const newer = (a, b) => (b.at ?? 0) - (a.at ?? 0);
74
+ /**
75
+ * The two sections `[` draws, each ranked and capped.
76
+ *
77
+ * Nothing in the `search` tier is offered with nothing typed, nor anything that
78
+ * does not match what was typed. Ties end on recency, then the title, so the
79
+ * list holds still between keystrokes.
80
+ */
81
+ export function rankReferences({ messages, files, query, ownKinds = [], caps = REFERENCE_CAPS }) {
82
+ const typed = normalize(query) !== '';
83
+ const own = new Set(ownKinds);
84
+ const ownFirst = (a, b) => Number(!own.has(a.kind)) - Number(!own.has(b.kind));
85
+ const byTitle = (a, b) => a.title.localeCompare(b.title);
86
+ const messageScore = (m) => Math.max(referenceMatch(m.title, query), referenceMatch(m.search ?? m.caption, query));
87
+ const shownMessages = closest(messages)
88
+ .map((m) => ({ m, score: typed ? messageScore(m) : 0 }))
89
+ .filter(({ score }) => !typed || score > 0)
90
+ .sort((a, b) => b.score - a.score || a.m.tier - b.m.tier || newer(a.m, b.m) || a.m.id.localeCompare(b.m.id))
91
+ .slice(0, caps.messages)
92
+ .map(({ m }) => m);
93
+ const shownFiles = closest(files)
94
+ .filter((f) => typed || f.tier !== FILE_TIER.search)
95
+ .map((f) => ({ f, score: typed ? referenceMatch(f.title, query) : 0 }))
96
+ .filter(({ score }) => !typed || score > 0)
97
+ .sort((a, b) => b.score - a.score ||
98
+ Number(!!a.f.archived) - Number(!!b.f.archived) ||
99
+ (typed ? Number(!!a.f.closed) - Number(!!b.f.closed) || a.f.tier - b.f.tier : a.f.tier - b.f.tier || Number(!!a.f.closed) - Number(!!b.f.closed)) ||
100
+ ownFirst(a.f, b.f) ||
101
+ newer(a.f, b.f) ||
102
+ byTitle(a.f, b.f))
103
+ .slice(0, caps.files)
104
+ .map(({ f }) => f);
105
+ return { messages: shownMessages, files: shownFiles };
106
+ }
107
+ /**
108
+ * A file as the body references it: `nostr:naddr…` with no relay hint, the
109
+ * same bytes a pasted link resolves to — so it earns its `["a", <address>]`
110
+ * through `referenceTagsFor` and draws as the same widget (SPEC §13.1). The
111
+ * title is never in the body: a file from a private Folder named in a wider
112
+ * one leaks nothing but its pointer.
113
+ *
114
+ * `address` is `kind:pubkey:d`; anything else throws.
115
+ */
116
+ export function fileReference(address) {
117
+ return `nostr:${addrToNaddr(address)}`;
118
+ }
119
+ // The package targets no runtime's lib, and a pause is all it needs of one.
120
+ const timers = globalThis;
121
+ /**
122
+ * The third Files tier, as the list asks for it on every keystroke: answers
123
+ * now from what it holds, and asks the relay behind it.
124
+ *
125
+ * The rows already on screen never wait for the relay: a slow or failing
126
+ * search leaves them as they are, with no spinner and no error row
127
+ * (PEE-21). A failure answers no hits for `retryMs`, so a rate limit is not
128
+ * hammered on every render, and is then forgotten, so one blip does not hide
129
+ * that query for the rest of the session. Answers are filtered again by
130
+ * {@link rankReferences}, so a shorter query's hits shown meanwhile never
131
+ * offer a row the typed text does not match.
132
+ *
133
+ * Only the pause is cancelled by the next keystroke: a query already asked
134
+ * keeps its answer, which is still true of that query.
135
+ */
136
+ export function referenceSearch({ search, delayMs = 200, retryMs = 5000, minLength = 2 }) {
137
+ const answered = new Map();
138
+ const asking = new Set();
139
+ const listeners = new Set();
140
+ let paused = null;
141
+ const cancel = () => {
142
+ if (paused)
143
+ timers.clearTimeout(paused.timer);
144
+ paused = null;
145
+ };
146
+ const ask = (query) => {
147
+ cancel();
148
+ const timer = timers.setTimeout(() => {
149
+ paused = null;
150
+ asking.add(query);
151
+ search(query)
152
+ .then((found) => found, () => {
153
+ const failed = [];
154
+ timers.setTimeout(() => {
155
+ if (answered.get(query) === failed)
156
+ answered.delete(query);
157
+ }, retryMs);
158
+ return failed;
159
+ })
160
+ .then((found) => {
161
+ if (!asking.delete(query))
162
+ return;
163
+ answered.set(query, found.length ? found.map((f) => ({ ...f, tier: FILE_TIER.search })) : found);
164
+ // A session's worth of queries; the oldest goes first.
165
+ if (answered.size > 64)
166
+ answered.delete(answered.keys().next().value);
167
+ for (const listener of listeners)
168
+ listener();
169
+ });
170
+ }, delayMs);
171
+ paused = { query, timer };
172
+ };
173
+ return {
174
+ hits(raw) {
175
+ const query = normalize(raw);
176
+ if (query.length < minLength) {
177
+ cancel();
178
+ return [];
179
+ }
180
+ const known = answered.get(query);
181
+ if (known)
182
+ return known;
183
+ if (paused?.query !== query && !asking.has(query))
184
+ ask(query);
185
+ for (let n = query.length - 1; n >= minLength; n--) {
186
+ const shorter = answered.get(query.slice(0, n).trim());
187
+ if (shorter)
188
+ return shorter;
189
+ }
190
+ return [];
191
+ },
192
+ subscribe(listener) {
193
+ listeners.add(listener);
194
+ return () => listeners.delete(listener);
195
+ },
196
+ reset() {
197
+ cancel();
198
+ asking.clear();
199
+ answered.clear();
200
+ },
201
+ };
202
+ }
203
+ //# sourceMappingURL=references.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"references.js","sourceRoot":"","sources":["../src/references.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAgClD,mEAAmE;AACnE,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAW,CAAA;AAE3D,+EAA+E;AAC/E,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAW,CAAA;AAErE,mGAAmG;AACnG,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAW,CAAA;AAiBhE,MAAM,SAAS,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAA;AAElF,MAAM,WAAW,GAAG,CAAC,IAAY,EAAE,EAAU,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,EAA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,OAAO,KAAK,CAAA;YACvB,IAAI,MAAM,EAAE,KAAK,KAAK,KAAK,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC;gBAAE,GAAG,CAAC,KAAK,CAAC,CAAA;YAC7D,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,SAAS,EAAE,CAAC,EAAE,EAAE,CAAC;gBACnD,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;gBACtD,IAAI,OAAO;oBAAE,OAAO,OAAO,CAAA;YAC7B,CAAC;YACD,OAAO,EAAE,CAAA;QACX,CAAC;QACD,SAAS,CAAC,QAAQ;YAChB,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;YACvB,OAAO,GAAG,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;QACzC,CAAC;QACD,KAAK;YACH,MAAM,EAAE,CAAA;YACR,MAAM,CAAC,KAAK,EAAE,CAAA;YACd,QAAQ,CAAC,KAAK,EAAE,CAAA;QAClB,CAAC;KACF,CAAA;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/conversation",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
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",
package/src/compose.ts CHANGED
@@ -11,9 +11,9 @@
11
11
  * | --- | --- | --- |
12
12
  * | a person (`@`) | `nostr:npub…`, or `@Name` with no key | `p`, from {@link mentionTagsFor} |
13
13
  * | a person, urgently (`!@`) | the same `nostr:npub…`, or `!@Name` | `p`, and {@link urgentTagsFor}'s `["urgent", <pubkey>]` |
14
- * | a message (`[`) | `nostr:nevent…` with its kind and no relay | none yet — a `q` from CON-25 (Decided on CON-26) |
14
+ * | a message (`[`) | `nostr:nevent…` with its kind and no relay | `q`, from {@link quoteTagsFor} (CON-25) |
15
15
  */
16
- import { encodeNevent, encodeNpub, type NostrTag } from '@estiva-app/protocol'
16
+ import { bech32Decode, convertBits, decodeNevent, encodeNevent, encodeNpub, findNostrUris, type NostrTag } from '@estiva-app/protocol'
17
17
  import { mentionTagsFor } from './strength.js'
18
18
 
19
19
  /**
@@ -61,3 +61,42 @@ export function urgentTagsFor(body: string, urgent: readonly string[] | undefine
61
61
  const named = new Set(mentionTagsFor(body).map((tag) => tag[1]))
62
62
  return [...new Set(urgent)].filter((pubkey) => named.has(pubkey)).map((pubkey) => [URGENT_TAG, pubkey])
63
63
  }
64
+
65
+ /** The event id a `note1…` names: its 32 bytes, as hex. Throws on anything else. */
66
+ function decodeNote(encoded: string): string {
67
+ const { hrp, data } = bech32Decode(encoded.toLowerCase())
68
+ if (hrp !== 'note') throw new Error(`expected a note, got ${hrp}`)
69
+ const bytes = convertBits(data, 5, 8, false)
70
+ if (bytes.length !== 32) throw new Error('a note is 32 bytes')
71
+ return bytes.map((b) => b.toString(16).padStart(2, '0')).join('')
72
+ }
73
+
74
+ /** The events a body references by `nostr:nevent…` or `nostr:note…` (§13.1), in the order it names them. */
75
+ export function eventsNamedInBody(body: string): Set<string> {
76
+ const ids = new Set<string>()
77
+ for (const uri of findNostrUris(body)) {
78
+ const bech = uri.slice('nostr:'.length)
79
+ try {
80
+ if (bech.startsWith('nevent1')) ids.add(decodeNevent(bech).id)
81
+ else if (bech.startsWith('note1')) ids.add(decodeNote(bech))
82
+ } catch {
83
+ // A malformed pointer is prose.
84
+ }
85
+ }
86
+ return ids
87
+ }
88
+
89
+ /**
90
+ * The `q` tags a body earns: `["q", <event id>]`, one per event it references
91
+ * (SPEC §13.1, CON-25). NIP-18's quote, as an index of *which message this one
92
+ * points at* — never a reply, which is `e` (§6.4). Two elements: the relay is
93
+ * the workspace's, and a `[` pick's `nevent` carries no author to fill a third.
94
+ *
95
+ * `own`, when given, is left out — the event a reply already names by `e`, so
96
+ * one message is not both answered and quoted.
97
+ */
98
+ export function quoteTagsFor(body: string, own = ''): NostrTag[] {
99
+ const ids = eventsNamedInBody(body)
100
+ ids.delete(own)
101
+ return [...ids].map((id) => ['q', id])
102
+ }
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.3.0'
15
+ export const CONVERSATION_VERSION = '0.5.0'
16
16
 
17
17
  export {
18
18
  KIND_MESSAGE,
@@ -64,7 +64,24 @@ export { decorationsOf, type Decoration, type Decorations, type Resolution, type
64
64
 
65
65
  export { buildComment, buildReply, offersEditAndDelete, type CommentRef } from './builders.js'
66
66
 
67
- export { mentionText, messageReference, URGENT_TAG, urgentTagsFor } from './compose.js'
67
+ export { eventsNamedInBody, mentionText, messageReference, quoteTagsFor, URGENT_TAG, urgentTagsFor } from './compose.js'
68
+
69
+ export {
70
+ FILE_TIER,
71
+ fileReference,
72
+ MESSAGE_TIER,
73
+ rankReferences,
74
+ REFERENCE_CAPS,
75
+ referenceMatch,
76
+ referenceSearch,
77
+ type RankedReferences,
78
+ type RankReferencesInput,
79
+ type ReferenceCandidate,
80
+ type ReferenceSearch,
81
+ type ReferenceSearchFn,
82
+ type ReferenceSearchOptions,
83
+ type ReferenceType,
84
+ } from './references.js'
68
85
 
69
86
  export {
70
87
  KIND_CHANGE,
@@ -0,0 +1,284 @@
1
+ /**
2
+ * What `[` offers, and in what order — CON-26's ranking (Miky, 2026-10-02),
3
+ * in one place for every app (PEE-21).
4
+ *
5
+ * Two capped sections, Messages above Files:
6
+ *
7
+ * - **Messages:** this thread or file first, then the parent file's.
8
+ * - **Files:** this Folder first, then files you read recently (your §11 read
9
+ * markers), then everything else, which you reach only by typing (relay
10
+ * search).
11
+ *
12
+ * With nothing typed the tiers set the order. Once you type, a better title
13
+ * match beats a higher tier; an open issue goes before a done or cancelled
14
+ * one on an equal match (Miky, 2026-10-03); the app's own kinds only break the
15
+ * ties that are left.
16
+ *
17
+ * The menu that draws the result is an editor's (`@estiva-app/ui/editor`'s
18
+ * `ReferenceTrigger`); this is the half a client that does not use React can
19
+ * take too. Where the candidates come from — a Folder's files, the read
20
+ * markers, a relay search — is the app's: each app holds them differently.
21
+ */
22
+ import { addrToNaddr } from '@estiva-app/protocol'
23
+
24
+ /** What a reference names, as the row's type word says it (label objects by type, not app). */
25
+ export type ReferenceType = 'message' | 'issue' | 'project' | 'topic'
26
+
27
+ /** Something `[` can offer. */
28
+ export interface ReferenceCandidate {
29
+ /** The event id of a message, the `kind:pubkey:d` address of a file. Unique across the list. */
30
+ id: string
31
+ /** `nostr:…`, exactly as the body will carry it: {@link fileReference} or `messageReference`. */
32
+ uri: string
33
+ type: ReferenceType
34
+ kind: number
35
+ /** A file's current title; a message's author. */
36
+ title: string
37
+ /** An issue's project title, a message's opening words; `''` when there is none. */
38
+ caption: string
39
+ /** A message's text, matched beside `title`. Files match on `title` only. */
40
+ search?: string
41
+ /** 0 is closest: {@link MESSAGE_TIER} or {@link FILE_TIER}. */
42
+ tier: number
43
+ /** A done or cancelled issue: offered, after an open one on an equal match. */
44
+ closed?: boolean
45
+ /**
46
+ * An archived file, or an issue in an archived project: offered at the lowest
47
+ * priority — after every row that is not, on an equal match (Miky, 2026-10-03).
48
+ */
49
+ archived?: boolean
50
+ /** When it was written or last read, in seconds — newer first within a tier. */
51
+ at?: number
52
+ }
53
+
54
+ /** Where a message sits relative to the box you are writing in. */
55
+ export const MESSAGE_TIER = { here: 0, parent: 1 } as const
56
+
57
+ /** Where a file sits relative to you. `search` only ever comes from typing. */
58
+ export const FILE_TIER = { folder: 0, recent: 1, search: 2 } as const
59
+
60
+ /** How many rows each section shows (Miky, 2026-10-03): the box stays at the old list's height. */
61
+ export const REFERENCE_CAPS = { messages: 4, files: 6 } as const
62
+
63
+ export interface RankedReferences {
64
+ messages: ReferenceCandidate[]
65
+ files: ReferenceCandidate[]
66
+ }
67
+
68
+ export interface RankReferencesInput {
69
+ messages: readonly ReferenceCandidate[]
70
+ files: readonly ReferenceCandidate[]
71
+ /** What was typed after `[`. */
72
+ query: string
73
+ /** The kinds the app itself writes — the last tie-breaker. */
74
+ ownKinds?: readonly number[]
75
+ caps?: { messages: number; files: number }
76
+ }
77
+
78
+ const normalize = (text: string) => text.toLowerCase().replace(/\s+/g, ' ').trim()
79
+
80
+ const isWordStart = (text: string, at: number) => at === 0 || !/[\p{L}\p{N}]/u.test(text[at - 1]!)
81
+
82
+ /**
83
+ * How well `text` holds `query`: 4 the whole of it, 3 its start, 2 the start of
84
+ * a word, 1 anywhere — or every word of the query at a word's start. 0 is no
85
+ * match. Case and runs of spaces are ignored.
86
+ */
87
+ export function referenceMatch(text: string, query: string): number {
88
+ const t = normalize(text)
89
+ const q = normalize(query)
90
+ if (!q) return 0
91
+ if (t === q) return 4
92
+ if (t.startsWith(q)) return 3
93
+ let at = t.indexOf(q)
94
+ if (at < 0) {
95
+ const words = q.split(' ')
96
+ if (words.length < 2) return 0
97
+ const starts = (w: string) => {
98
+ for (let i = t.indexOf(w); i >= 0; i = t.indexOf(w, i + 1)) if (isWordStart(t, i)) return true
99
+ return false
100
+ }
101
+ return words.every(starts) ? 1 : 0
102
+ }
103
+ for (; at >= 0; at = t.indexOf(q, at + 1)) if (isWordStart(t, at)) return 2
104
+ return 1
105
+ }
106
+
107
+ /** Keeps each id once, at its closest tier. */
108
+ function closest(candidates: readonly ReferenceCandidate[]): ReferenceCandidate[] {
109
+ const best = new Map<string, ReferenceCandidate>()
110
+ for (const c of candidates) {
111
+ const known = best.get(c.id)
112
+ if (!known || c.tier < known.tier) best.set(c.id, c)
113
+ }
114
+ return [...best.values()]
115
+ }
116
+
117
+ const newer = (a: ReferenceCandidate, b: ReferenceCandidate) => (b.at ?? 0) - (a.at ?? 0)
118
+
119
+ /**
120
+ * The two sections `[` draws, each ranked and capped.
121
+ *
122
+ * Nothing in the `search` tier is offered with nothing typed, nor anything that
123
+ * does not match what was typed. Ties end on recency, then the title, so the
124
+ * list holds still between keystrokes.
125
+ */
126
+ export function rankReferences({ messages, files, query, ownKinds = [], caps = REFERENCE_CAPS }: RankReferencesInput): RankedReferences {
127
+ const typed = normalize(query) !== ''
128
+ const own = new Set(ownKinds)
129
+ const ownFirst = (a: ReferenceCandidate, b: ReferenceCandidate) => Number(!own.has(a.kind)) - Number(!own.has(b.kind))
130
+ const byTitle = (a: ReferenceCandidate, b: ReferenceCandidate) => a.title.localeCompare(b.title)
131
+
132
+ const messageScore = (m: ReferenceCandidate) => Math.max(referenceMatch(m.title, query), referenceMatch(m.search ?? m.caption, query))
133
+ const shownMessages = closest(messages)
134
+ .map((m) => ({ m, score: typed ? messageScore(m) : 0 }))
135
+ .filter(({ score }) => !typed || score > 0)
136
+ .sort((a, b) => b.score - a.score || a.m.tier - b.m.tier || newer(a.m, b.m) || a.m.id.localeCompare(b.m.id))
137
+ .slice(0, caps.messages)
138
+ .map(({ m }) => m)
139
+
140
+ const shownFiles = closest(files)
141
+ .filter((f) => typed || f.tier !== FILE_TIER.search)
142
+ .map((f) => ({ f, score: typed ? referenceMatch(f.title, query) : 0 }))
143
+ .filter(({ score }) => !typed || score > 0)
144
+ .sort(
145
+ (a, b) =>
146
+ b.score - a.score ||
147
+ Number(!!a.f.archived) - Number(!!b.f.archived) ||
148
+ (typed ? Number(!!a.f.closed) - Number(!!b.f.closed) || a.f.tier - b.f.tier : a.f.tier - b.f.tier || Number(!!a.f.closed) - Number(!!b.f.closed)) ||
149
+ ownFirst(a.f, b.f) ||
150
+ newer(a.f, b.f) ||
151
+ byTitle(a.f, b.f),
152
+ )
153
+ .slice(0, caps.files)
154
+ .map(({ f }) => f)
155
+
156
+ return { messages: shownMessages, files: shownFiles }
157
+ }
158
+
159
+ /**
160
+ * A file as the body references it: `nostr:naddr…` with no relay hint, the
161
+ * same bytes a pasted link resolves to — so it earns its `["a", <address>]`
162
+ * through `referenceTagsFor` and draws as the same widget (SPEC §13.1). The
163
+ * title is never in the body: a file from a private Folder named in a wider
164
+ * one leaks nothing but its pointer.
165
+ *
166
+ * `address` is `kind:pubkey:d`; anything else throws.
167
+ */
168
+ export function fileReference(address: string): string {
169
+ return `nostr:${addrToNaddr(address)}`
170
+ }
171
+
172
+ /** What a {@link referenceSearch} asks the relay for: the files whose title holds `query`. */
173
+ export type ReferenceSearchFn = (query: string) => Promise<readonly ReferenceCandidate[]>
174
+
175
+ // The package targets no runtime's lib, and a pause is all it needs of one.
176
+ const timers = globalThis as unknown as { setTimeout(run: () => void, ms: number): unknown; clearTimeout(id: unknown): void }
177
+
178
+ export interface ReferenceSearch {
179
+ /**
180
+ * The search tier for `query`: what the relay last answered for it, or —
181
+ * while it is asked — for the longest query before it that it answered.
182
+ * Asks it, after a pause, when it has not been asked.
183
+ */
184
+ hits(query: string): readonly ReferenceCandidate[]
185
+ /** Called when an answer lands; returns the unsubscribe. */
186
+ subscribe(listener: () => void): () => void
187
+ /**
188
+ * Drops what is pending and what was answered. Call it when the signed-in
189
+ * person changes: answers are kept by the text asked, not by who asked, and
190
+ * the last person's hits name files the next one may not be able to read.
191
+ */
192
+ reset(): void
193
+ }
194
+
195
+ export interface ReferenceSearchOptions {
196
+ search: ReferenceSearchFn
197
+ /** The pause after a keystroke before asking. Default 200ms. */
198
+ delayMs?: number
199
+ /** How long a failed query answers no hits before it may be asked again. Default 5s. */
200
+ retryMs?: number
201
+ /** Shorter queries ask nothing. Default 2. */
202
+ minLength?: number
203
+ }
204
+
205
+ /**
206
+ * The third Files tier, as the list asks for it on every keystroke: answers
207
+ * now from what it holds, and asks the relay behind it.
208
+ *
209
+ * The rows already on screen never wait for the relay: a slow or failing
210
+ * search leaves them as they are, with no spinner and no error row
211
+ * (PEE-21). A failure answers no hits for `retryMs`, so a rate limit is not
212
+ * hammered on every render, and is then forgotten, so one blip does not hide
213
+ * that query for the rest of the session. Answers are filtered again by
214
+ * {@link rankReferences}, so a shorter query's hits shown meanwhile never
215
+ * offer a row the typed text does not match.
216
+ *
217
+ * Only the pause is cancelled by the next keystroke: a query already asked
218
+ * keeps its answer, which is still true of that query.
219
+ */
220
+ export function referenceSearch({ search, delayMs = 200, retryMs = 5000, minLength = 2 }: ReferenceSearchOptions): ReferenceSearch {
221
+ const answered = new Map<string, readonly ReferenceCandidate[]>()
222
+ const asking = new Set<string>()
223
+ const listeners = new Set<() => void>()
224
+ let paused: { query: string; timer: unknown } | null = null
225
+
226
+ const cancel = () => {
227
+ if (paused) timers.clearTimeout(paused.timer)
228
+ paused = null
229
+ }
230
+
231
+ const ask = (query: string) => {
232
+ cancel()
233
+ const timer = timers.setTimeout(() => {
234
+ paused = null
235
+ asking.add(query)
236
+ search(query)
237
+ .then(
238
+ (found) => found,
239
+ () => {
240
+ const failed: readonly ReferenceCandidate[] = []
241
+ timers.setTimeout(() => {
242
+ if (answered.get(query) === failed) answered.delete(query)
243
+ }, retryMs)
244
+ return failed
245
+ },
246
+ )
247
+ .then((found) => {
248
+ if (!asking.delete(query)) return
249
+ answered.set(query, found.length ? found.map((f) => ({ ...f, tier: FILE_TIER.search })) : found)
250
+ // A session's worth of queries; the oldest goes first.
251
+ if (answered.size > 64) answered.delete(answered.keys().next().value!)
252
+ for (const listener of listeners) listener()
253
+ })
254
+ }, delayMs)
255
+ paused = { query, timer }
256
+ }
257
+
258
+ return {
259
+ hits(raw) {
260
+ const query = normalize(raw)
261
+ if (query.length < minLength) {
262
+ cancel()
263
+ return []
264
+ }
265
+ const known = answered.get(query)
266
+ if (known) return known
267
+ if (paused?.query !== query && !asking.has(query)) ask(query)
268
+ for (let n = query.length - 1; n >= minLength; n--) {
269
+ const shorter = answered.get(query.slice(0, n).trim())
270
+ if (shorter) return shorter
271
+ }
272
+ return []
273
+ },
274
+ subscribe(listener) {
275
+ listeners.add(listener)
276
+ return () => listeners.delete(listener)
277
+ },
278
+ reset() {
279
+ cancel()
280
+ asking.clear()
281
+ answered.clear()
282
+ },
283
+ }
284
+ }