@wtfalch/chat 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/README.md CHANGED
@@ -56,7 +56,15 @@ summary carries `unreadCount`, Matrix's own notification count; `chat.
56
56
  totalUnreadCount()` sums it across every room, for the agora's badge.
57
57
  `chat.markRoomRead(roomId)` sends `m.read` for the newest event and clears
58
58
  that room's count right away -- call it when a room is opened and again when
59
- the person reaches the newest message. `chat.connectionStatus()` (and
59
+ the person reaches the newest message. Each summary also carries
60
+ `lastMessage` -- the room's newest real message (sender, text, timestamp),
61
+ reduced the same way `timeline()` reduces one, so an edit's already-folded
62
+ text and an attachment's file name show here too, kept current by the same
63
+ sync loop as everything else on the summary. `null` for a room with nothing
64
+ to show yet, and always `null` for an unanswered invitation, since an
65
+ invitee's client has no timeline to read before joining. A redacted message
66
+ or a state event landing in the timeline (a pin, for instance) is skipped,
67
+ never shown as a preview. `chat.connectionStatus()` (and
60
68
  `onConnectionStatusChanged`) is `'connected'`, `'catching-up'` or
61
69
  `'offline'`, for a status the UI can render.
62
70
 
@@ -256,7 +264,14 @@ reply, and answers `/event` and `/relations`, which is what matrix-js-sdk
256
264
  asks for while it builds a thread. It echoes every accepted send back
257
265
  through sync carrying its transaction id, so a reaction shows up the way it
258
266
  does against a homeserver, and it answers redactions -- which is how a
259
- reaction is taken back.
267
+ reaction is taken back. It also answers `/search`, a plain case-insensitive
268
+ substring match over every message body it has recorded, newest first,
269
+ scoped to `filter.rooms` when the client sends one -- a room seeded with
270
+ `encrypted: true` never matches, the same as a real, unindexed encrypted
271
+ room would not. A room seeded with `invitedAccount` delivers as `rooms.
272
+ invite` instead of `rooms.join` -- the stripped state real Matrix hands an
273
+ invitee, with no timeline of its own, for proving `lastMessage` (and
274
+ `membership`) against an invitation without a real homeserver.
260
275
 
261
276
  ## Integration tests
262
277
 
@@ -331,6 +346,36 @@ the next page; it is `null` once there is nothing older. It resumes exactly
331
346
  after the last file returned, so none is skipped or repeated. The last page can
332
347
  come back empty.
333
348
 
349
+ ## Search
350
+
351
+ ([wtfalch/agora#252](https://github.com/wtfalch/agora/issues/252),
352
+ [wtfalch/agora#31](https://github.com/wtfalch/agora/issues/31)).
353
+ `chat.search(query, { roomId, limit })` finds a message by a word or phrase,
354
+ across every room this account is joined to, or just `roomId` when given,
355
+ through Synapse's own `POST /search` (`room_events`, newest first) -- the
356
+ same event-mapping code `timeline()` uses, so a result is a plain
357
+ `ChatTimelineEvent` next to the room it came from. `limit` (default 50)
358
+ stops collection once that many results are in, following Synapse's own
359
+ `next_batch` as far as it takes to get there.
360
+
361
+ Permission filtering is Synapse's own: it only ever searches rooms this
362
+ account has joined, and this package layers nothing of its own on top --
363
+ a person who left a room, or was removed, finds nothing from it on their
364
+ next search, with no filter this package wrote itself.
365
+
366
+ **Encrypted rooms say so, rather than returning nothing.** Crypto stays off
367
+ in this package today (the module comment says why), so a real encrypted
368
+ room's cleartext was never in Synapse's index to begin with -- an empty
369
+ `results` from one would read as "nothing found" when the honest answer is
370
+ "cannot search here". `search` returns
371
+ `{ results, unsearchableRoomIds }`: `unsearchableRoomIds` lists every
372
+ joined room this search could not look inside because it carries
373
+ `m.room.encryption` state. A room-scoped search of an encrypted room is
374
+ `[roomId]` with `results` always empty; a search across every room lists
375
+ every encrypted one it is in, whatever it did or did not find elsewhere.
376
+ This is the one deviation from agora#252's own bare-array shape, a campaign
377
+ decision recorded against it.
378
+
334
379
  ## First-ship local proof
335
380
 
336
381
  See [the browser/Electron fixture](test/acceptance/README.md) for the repeatable
@@ -52,6 +52,12 @@ const TYPING_TIMEOUT_MS = 20_000;
52
52
  * already passed the `contains_url` filter server-side, so a larger page
53
53
  * costs one round trip, not one screenful. */
54
54
  const ROOM_FILES_PAGE_SIZE = 50;
55
+ /** `search`'s own default when a caller passes no `limit`. Unlike
56
+ * `roomFiles`, which walks every page Synapse has when given none, a
57
+ * search with no cap at all would follow `next_batch` across a room's
58
+ * entire history for one keystroke -- a bound by default is the safer
59
+ * read of "search this" than "fetch everything ever said". */
60
+ const SEARCH_LIMIT_DEFAULT = 50;
55
61
  /**
56
62
  * A chat session behind the exchange: a matrix-js-sdk `MatrixClient` the
57
63
  * caller never sees, refreshed on its own, exposing only what a UI needs.
@@ -321,20 +327,44 @@ export function createChatClient(options) {
321
327
  .filter((room) => !(HIDDEN_TAG in room.tags))
322
328
  .map((room) => {
323
329
  const muted = isMuted(target, room.roomId);
330
+ const membership = room.getMyMembership() === KnownMembership.Invite
331
+ ? 'invite'
332
+ : 'join';
324
333
  return {
325
334
  id: room.roomId,
326
335
  name: room.name,
336
+ // An invitee's client never gets a timeline to read before
337
+ // joining -- there is nothing here `lastMessage` could show.
338
+ lastMessage: membership === 'invite' ? null : roomLastMessage(room),
327
339
  isDirect: direct.has(room.roomId) || Boolean(room.getDMInviter()),
328
- membership: room.getMyMembership() === KnownMembership.Invite
329
- ? 'invite'
330
- : 'join',
331
- unreadCount: room.getMyMembership() === KnownMembership.Invite
332
- ? 1
333
- : roomUnreadCount(target, room, muted),
340
+ membership,
341
+ unreadCount: membership === 'invite' ? 1 : roomUnreadCount(target, room, muted),
334
342
  muted,
335
343
  };
336
344
  });
337
345
  }
346
+ /** See `ChatRoomLastMessage`. Walks the room's live timeline newest
347
+ * first -- the same direction `unreadTimelineCount` walks it, for the
348
+ * same reason: the answer is almost always the last event, so this
349
+ * rarely looks past it. Built on `toTimelineEvent` rather than reading
350
+ * the raw event, so an edit's already-folded text and an attachment's
351
+ * name are exactly what a caller reading `timeline()` would see, not a
352
+ * second, slightly different reduction of the same event. */
353
+ function roomLastMessage(room) {
354
+ const events = room.getLiveTimeline().getEvents();
355
+ for (const event of [...events].reverse()) {
356
+ const mapped = toTimelineEvent(event, room, false);
357
+ if (!mapped || mapped.deleted)
358
+ continue;
359
+ return {
360
+ senderName: mapped.senderName,
361
+ body: mapped.attachment?.name ?? mapped.body,
362
+ ts: mapped.ts,
363
+ mine: mapped.mine,
364
+ };
365
+ }
366
+ return null;
367
+ }
338
368
  /** A room's own `unreadCount` -- see `ChatRoomSummary.unreadCount` for
339
369
  * why a muted room (or one `unreliableServerCount` still distrusts)
340
370
  * takes the larger of Synapse's own count and the local walk, rather
@@ -922,6 +952,72 @@ export function createChatClient(options) {
922
952
  }
923
953
  return { files, next: from };
924
954
  }
955
+ /** Joined rooms this account cannot search inside, because Synapse never
956
+ * indexed their cleartext -- an `m.room.encryption` state event is the
957
+ * one thing that means that (see `ChatSearchResults`). Scoped to
958
+ * `roomId` when given, since that is the only room a room-scoped search
959
+ * could ever have reported unsearchable. The company space is excluded
960
+ * the same way `readRooms` excludes it: it is what `people()` reads,
961
+ * not a room in Chat's sense, and never one `search` was ever asked
962
+ * about. */
963
+ function unsearchableRoomIds(target, roomId) {
964
+ return target
965
+ .getRooms()
966
+ .filter((room) => room.getMyMembership() === KnownMembership.Join)
967
+ .filter((room) => !room.isSpaceRoom())
968
+ .filter((room) => (roomId ? room.roomId === roomId : true))
969
+ .filter((room) => room.hasEncryptionStateEvent())
970
+ .map((room) => room.roomId);
971
+ }
972
+ /** `query`, across `options.roomId` or every room this account is
973
+ * joined to, through Synapse's own `POST /search` -- see
974
+ * `ChatClient.search`'s own doc for what that means for permissions and
975
+ * encryption. `filter.rooms` is the one thing that ever narrows the
976
+ * request itself; everything else Synapse decides on its own, including
977
+ * how many results one page of `next_batch` carries. */
978
+ async function search(query, options) {
979
+ if (!client)
980
+ throw new Error('chat: search called before start()');
981
+ const target = client;
982
+ const roomId = options?.roomId;
983
+ const limit = options?.limit ?? SEARCH_LIMIT_DEFAULT;
984
+ // A room-scoped search of an encrypted room has nothing to ask Synapse
985
+ // at all: its messages were never in the index to begin with, and the
986
+ // one room this search could ever have reported unsearchable already
987
+ // is that room.
988
+ if (roomId && target.getRoom(roomId)?.hasEncryptionStateEvent()) {
989
+ return { results: [], unsearchableRoomIds: [roomId] };
990
+ }
991
+ const mapper = target.getEventMapper();
992
+ const results = [];
993
+ let nextBatch;
994
+ do {
995
+ const body = {
996
+ search_categories: {
997
+ room_events: {
998
+ search_term: query,
999
+ order_by: 'recent',
1000
+ ...(roomId ? { filter: { rooms: [roomId] } } : {}),
1001
+ },
1002
+ },
1003
+ };
1004
+ const response = await target.search({ body, next_batch: nextBatch });
1005
+ const roomEvents = response.search_categories.room_events;
1006
+ for (const hit of roomEvents.results ?? []) {
1007
+ if (results.length >= limit)
1008
+ break;
1009
+ const raw = hit.result;
1010
+ const room = target.getRoom(raw.room_id);
1011
+ if (!room)
1012
+ continue;
1013
+ const mapped = toTimelineEvent(mapper(raw), room, false);
1014
+ if (mapped)
1015
+ results.push({ roomId: raw.room_id, event: mapped });
1016
+ }
1017
+ nextBatch = roomEvents.next_batch;
1018
+ } while (nextBatch && results.length < limit);
1019
+ return { results, unsearchableRoomIds: unsearchableRoomIds(target, roomId) };
1020
+ }
925
1021
  /** Builds the Matrix content once, here rather than in `markdown.ts`:
926
1022
  * `msgtype`/`format`/`formatted_body` are Matrix's own shape, and this
927
1023
  * is the only file in the package that touches matrix-js-sdk (see
@@ -1822,6 +1918,7 @@ export function createChatClient(options) {
1822
1918
  onTimelineChanged,
1823
1919
  paginate,
1824
1920
  roomFiles,
1921
+ search,
1825
1922
  sendMessage,
1826
1923
  editMessage,
1827
1924
  deleteMessage,
@@ -19,6 +19,19 @@ export type FakeRoomSeed = {
19
19
  /** Messages already in the room when the first sync lands, oldest first.
20
20
  * Defaults to none. */
21
21
  messages?: FakeMessageSeed[];
22
+ /** Seeds an `m.room.encryption` state event -- the one thing `search`
23
+ * reads to report a room unsearchable (agora#252). Defaults to
24
+ * `false`. */
25
+ encrypted?: boolean;
26
+ /** Seeds this room as an unanswered invitation to the fake account
27
+ * itself, rather than a room it has joined -- a `rooms.invite` entry
28
+ * with the stripped state real Matrix delivers one in, the one shape
29
+ * `membership: 'invite'` ever comes from. `messages` is ignored: a real
30
+ * invitee's client has no timeline to read before joining. Defaults to
31
+ * `undefined` (the room is joined, as every other seed is). */
32
+ invitedAccount?: {
33
+ inviter?: string;
34
+ };
22
35
  };
23
36
  export type FakeMessageSeed = {
24
37
  /** Defaults to a minted `$seeded-<n>`. Give one to reply to it. */
@@ -96,6 +96,12 @@ export class FakeChatServer {
96
96
  #tokenSeq = 0;
97
97
  #batchSeq = 0;
98
98
  #eventSeq = 0;
99
+ /** Every event's own place in this server's history, oldest first, keyed
100
+ * by event id -- what `/search`'s "newest first" sorts by. Kept apart
101
+ * from `#events` itself (rather than reading array position) so a
102
+ * redaction rewriting an entry in place never disturbs where it sorts. */
103
+ #insertOrder = new Map();
104
+ #insertSeq = 0;
99
105
  #pending;
100
106
  #parkedWaiters = [];
101
107
  #disposed = false;
@@ -357,6 +363,16 @@ export class FakeChatServer {
357
363
  origin_server_ts: now,
358
364
  content: { name: seed.name },
359
365
  });
366
+ if (seed.encrypted) {
367
+ events.push({
368
+ type: 'm.room.encryption',
369
+ state_key: '',
370
+ event_id: `$encryption-${seed.id}`,
371
+ sender: this.userId,
372
+ origin_server_ts: now,
373
+ content: { algorithm: 'm.megolm.v1.aes-sha2' },
374
+ });
375
+ }
360
376
  return {
361
377
  summary: {},
362
378
  state: { events },
@@ -370,6 +386,52 @@ export class FakeChatServer {
370
386
  unread_notifications: { highlight_count: 0, notification_count: seed.notificationCount ?? 0 },
371
387
  };
372
388
  }
389
+ /** A room's invite-state entry: the stripped state real Matrix delivers
390
+ * in `rooms.invite`, for a seed carrying `invitedAccount` -- the one
391
+ * shape `membership: 'invite'` ever comes from, and the only entry with
392
+ * no timeline of its own: a real invitee's client gets none to read
393
+ * before joining, which is why `ChatRoomSummary.lastMessage` is always
394
+ * `null` for such a room. `messages` on the seed is ignored, for the
395
+ * same reason. */
396
+ #inviteEntry(seed) {
397
+ const now = this.#now();
398
+ const inviter = seed.invitedAccount?.inviter ?? this.userId;
399
+ const events = [
400
+ {
401
+ type: 'm.room.create',
402
+ state_key: '',
403
+ event_id: `$create-${seed.id}`,
404
+ sender: inviter,
405
+ origin_server_ts: now,
406
+ content: { creator: inviter, room_version: '10' },
407
+ },
408
+ {
409
+ type: 'm.room.name',
410
+ state_key: '',
411
+ event_id: `$name-${seed.id}`,
412
+ sender: inviter,
413
+ origin_server_ts: now,
414
+ content: { name: seed.name },
415
+ },
416
+ {
417
+ type: 'm.room.member',
418
+ state_key: inviter,
419
+ event_id: `$member-${seed.id}-inviter`,
420
+ sender: inviter,
421
+ origin_server_ts: now,
422
+ content: { membership: 'join', displayname: inviter },
423
+ },
424
+ {
425
+ type: 'm.room.member',
426
+ state_key: this.userId,
427
+ event_id: `$member-${seed.id}-self`,
428
+ sender: inviter,
429
+ origin_server_ts: now,
430
+ content: { membership: 'invite', ...(seed.isDirect ? { is_direct: true } : {}) },
431
+ },
432
+ ];
433
+ return { invite_state: { events } };
434
+ }
373
435
  /** One `m.room.message`, threaded when the seed names a root. The
374
436
  * `m.thread` relation is the whole of what makes a reply a thread reply
375
437
  * -- matrix-js-sdk reads it off the event and routes it, exactly as it
@@ -412,10 +474,14 @@ export class FakeChatServer {
412
474
  #materialise(seed) {
413
475
  if (this.#events.has(seed.id))
414
476
  return;
415
- this.#events.set(seed.id, (seed.messages ?? []).map((message) => this.#messageEvent(message)));
477
+ const events = (seed.messages ?? []).map((message) => this.#messageEvent(message));
478
+ this.#events.set(seed.id, events);
479
+ for (const event of events)
480
+ this.#insertOrder.set(event.event_id, this.#insertSeq++);
416
481
  }
417
482
  #record(roomId, event) {
418
483
  this.#events.set(roomId, [...(this.#events.get(roomId) ?? []), event]);
484
+ this.#insertOrder.set(event.event_id, this.#insertSeq++);
419
485
  }
420
486
  /** One room's incremental entry, carrying just these events -- and,
421
487
  * given some, ephemeral ones (`m.typing`) alongside them, the way a real
@@ -542,11 +608,16 @@ export class FakeChatServer {
542
608
  }
543
609
  #fullSyncBody() {
544
610
  const join = {};
545
- for (const room of this.#rooms)
546
- join[room.id] = this.#joinEntry(room);
611
+ const invite = {};
612
+ for (const room of this.#rooms) {
613
+ if (room.invitedAccount)
614
+ invite[room.id] = this.#inviteEntry(room);
615
+ else
616
+ join[room.id] = this.#joinEntry(room);
617
+ }
547
618
  return {
548
619
  next_batch: this.#nextBatch(),
549
- rooms: { join },
620
+ rooms: { join, invite },
550
621
  account_data: { events: this.#accountDataEvents() },
551
622
  presence: { events: [] },
552
623
  to_device: { events: [] },
@@ -831,6 +902,74 @@ export class FakeChatServer {
831
902
  ...(end ? { end } : {}),
832
903
  }));
833
904
  }
905
+ // `ChatClient.search`'s own wire call (agora#252, agora#31): a plain
906
+ // case-insensitive substring match over every `m.room.message` body
907
+ // this fake has recorded, newest first, scoped to `filter.rooms` when
908
+ // the client sent one. Reads `#events` live rather than a snapshot
909
+ // taken at record time, so a redacted message (its content already
910
+ // emptied by the `redact` route) stops matching immediately, the same
911
+ // as a real search index would once Synapse's own redaction handling
912
+ // catches up to it. `next_batch` pages a deliberately small five at a
913
+ // time, so a unit test can prove `search`'s own paging without seeding
914
+ // hundreds of messages.
915
+ //
916
+ // An encrypted room's messages never match. This fake stores every
917
+ // body as plain text regardless of `encrypted` -- there is no real
918
+ // Megolm session here to encrypt against -- but a real Synapse never
919
+ // has a cleartext body to index for such a room in the first place, so
920
+ // a fake that let one match would prove `search` filters encrypted
921
+ // rooms out itself, which is exactly what it must not do (the fake's
922
+ // own module comment, and `ChatSearchResults`).
923
+ if (url.pathname === '/_matrix/client/v3/search' &&
924
+ init?.method === 'POST' &&
925
+ this.#authorised(init)) {
926
+ let body = {};
927
+ try {
928
+ body = JSON.parse(String(init?.body ?? '{}'));
929
+ }
930
+ catch {
931
+ // Same tolerance as every other body this fake parses.
932
+ }
933
+ const term = (body.search_categories?.room_events?.search_term ?? '').toLowerCase();
934
+ const roomFilter = body.search_categories?.room_events?.filter?.rooms;
935
+ const encryptedRoomIds = new Set(this.#rooms.filter((room) => room.encrypted).map((room) => room.id));
936
+ const flattened = [];
937
+ for (const [roomId, events] of this.#events) {
938
+ if (roomFilter && !roomFilter.includes(roomId))
939
+ continue;
940
+ if (encryptedRoomIds.has(roomId))
941
+ continue;
942
+ for (const event of events)
943
+ flattened.push({ roomId, event });
944
+ }
945
+ const matches = flattened
946
+ .filter((entry) => entry.event.type === 'm.room.message')
947
+ .filter((entry) => {
948
+ const value = entry.event.content.body;
949
+ return typeof value === 'string' && value.toLowerCase().includes(term);
950
+ })
951
+ .sort((a, b) => (this.#insertOrder.get(b.event.event_id) ?? 0) -
952
+ (this.#insertOrder.get(a.event.event_id) ?? 0));
953
+ const pageSize = 5;
954
+ const from = url.searchParams.get('next_batch');
955
+ const start = from?.startsWith('idx-') ? Number(from.slice('idx-'.length)) : 0;
956
+ const chunk = matches.slice(start, start + pageSize);
957
+ const nextIndex = start + chunk.length;
958
+ const nextBatch = nextIndex < matches.length ? `idx-${nextIndex}` : undefined;
959
+ return Promise.resolve(jsonResponse(200, {
960
+ search_categories: {
961
+ room_events: {
962
+ count: matches.length,
963
+ results: chunk.map((entry) => ({
964
+ rank: 1,
965
+ result: { ...entry.event, room_id: entry.roomId },
966
+ })),
967
+ highlights: [],
968
+ ...(nextBatch ? { next_batch: nextBatch } : {}),
969
+ },
970
+ },
971
+ }));
972
+ }
834
973
  const send = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/send\/([^/]+)\/([^/]+)$/);
835
974
  if (send && this.#authorised(init)) {
836
975
  let content = {};
@@ -7,4 +7,4 @@
7
7
  * `README.md` and the chat plan, section 9.
8
8
  */
9
9
  export { createChatClient, MAX_UPLOAD_BYTES } from './client.ts';
10
- export type { ChatAttachment, ChatRoomFilesPage, ChatClient, ChatConnectionStatus, ChatPerson, ChatRoomSummary, ChatUploadProgress, CreateChatClientOptions, ExchangeBody, } from './types.ts';
10
+ export type { ChatAttachment, ChatRoomFilesPage, ChatClient, ChatConnectionStatus, ChatPerson, ChatRoomLastMessage, ChatRoomSummary, ChatSearchResults, ChatTimelineEvent, ChatUploadProgress, CreateChatClientOptions, ExchangeBody, } from './types.ts';
@@ -10,12 +10,38 @@ export type ExchangeBody = {
10
10
  access_token: string;
11
11
  expires_at: string;
12
12
  };
13
+ /** The newest visible message in a room's live timeline, for a chat list to
14
+ * draw under the room's name the way `@wtfalch/email`'s thread list already
15
+ * does. `null` for a room whose timeline holds nothing to show: an
16
+ * unanswered invitation (`ChatRoomSummary.membership === 'invite'`, always,
17
+ * since an invitee's client never gets one to read before joining) or a
18
+ * joined room with no message yet.
19
+ *
20
+ * An edited message shows its already-latest text, for free: matrix-js-sdk
21
+ * folds an `m.replace` onto the message it replaces before this ever reads
22
+ * it, the same as `ChatTimelineEvent.body` does (see `edited`'s own
23
+ * comment). A redacted message is skipped rather than shown as a
24
+ * tombstone -- the room's previous message stands in for it, one step
25
+ * further back, same as a list would rather not announce what was deleted
26
+ * to somebody who has not opened the room. */
27
+ export type ChatRoomLastMessage = {
28
+ readonly senderName: string;
29
+ /** The message's text, or an attachment's file name for one that carries
30
+ * no text of its own -- there is nothing else to preview a file with. */
31
+ readonly body: string;
32
+ readonly ts: number;
33
+ /** Whether the signed-in person sent it -- a list draws "You: ..." off
34
+ * this rather than comparing `senderName` to anything. */
35
+ readonly mine: boolean;
36
+ };
13
37
  /** A joined room or invitation, reduced to what a chat list needs to draw
14
38
  * itself. Nothing here is a Matrix type: a UI built on this package never
15
39
  * imports matrix-js-sdk. */
16
40
  export type ChatRoomSummary = {
17
41
  readonly id: string;
18
42
  readonly name: string;
43
+ /** See `ChatRoomLastMessage`. */
44
+ readonly lastMessage: ChatRoomLastMessage | null;
19
45
  /** Whether this is a direct message or group DM, from the
20
46
  * account's `m.direct` data (or an invitation's `is_direct` flag) --
21
47
  * rather than guessing from membership counts. */
@@ -182,6 +208,24 @@ export type ChatTimelinePage = {
182
208
  * comes back with nothing more behind it. */
183
209
  readonly hasMore: boolean;
184
210
  };
211
+ /** What `search` finds, across the rooms it was allowed to look in.
212
+ * `results` is newest first, each carrying the room it was found in
213
+ * alongside the message itself -- a global search has no single room to
214
+ * hang the result off, so it travels with every one. `unsearchableRoomIds`
215
+ * is every joined room this search could not look inside because it is
216
+ * encrypted: `[roomId]` for a room-scoped search of an encrypted room
217
+ * (`results` is then always empty), or every encrypted room this account
218
+ * is in for a search across all of them. Synapse never indexes an
219
+ * encrypted room's cleartext, so an empty `results` there is silence, not
220
+ * "nothing found" -- a caller reads `unsearchableRoomIds` to tell the two
221
+ * apart (agora#252, agora#31). */
222
+ export type ChatSearchResults = {
223
+ readonly results: readonly {
224
+ roomId: string;
225
+ event: ChatTimelineEvent;
226
+ }[];
227
+ readonly unsearchableRoomIds: readonly string[];
228
+ };
185
229
  /** Whether the sync loop is caught up, working to catch up (after a
186
230
  * network drop, or recovering from a refused sync position with a fresh
187
231
  * full sync), or not connected at all. */
@@ -304,6 +348,23 @@ export type ChatClient = {
304
348
  limit?: number;
305
349
  before?: string;
306
350
  }) => Promise<ChatRoomFilesPage>;
351
+ /** A word or phrase, across every room this account is joined to, or just
352
+ * `options.roomId`, through Synapse's own server-side search
353
+ * (`POST /search`, `room_events`, newest first) -- so permission
354
+ * filtering is Synapse's: a room this account has left never appears,
355
+ * with no filter of this package's own layered on top (agora#31).
356
+ * `limit` stops once that many results are collected, following
357
+ * `next_batch` as far as it takes to get there; defaults to 50.
358
+ *
359
+ * Encrypted rooms are reported, not silently skipped -- see
360
+ * `ChatSearchResults`. That is the one search this package can commit to
361
+ * today: crypto stays off (the module comment says why), so a real
362
+ * encrypted room's cleartext was never in Synapse's index to begin with
363
+ * (agora#252). */
364
+ search: (query: string, options?: {
365
+ roomId?: string;
366
+ limit?: number;
367
+ }) => Promise<ChatSearchResults>;
307
368
  /** Everyone joined to `roomId`, by name, the signed-in person included --
308
369
  * who a message in this room can mention. A room's own membership, not
309
370
  * the company's: mentioning somebody who is not here would notify
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/chat",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "A Matrix chat client behind the agora's token exchange.",
5
5
  "license": "MIT",
6
6
  "type": "module",