@wtfalch/chat 0.8.0 → 0.9.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
@@ -275,6 +275,21 @@ with `redactMessage(roomId, eventId)`, and bans a person from a channel with
275
275
  `banPerson(roomId, subject, reason?)` until `unbanPerson(roomId, subject)`.
276
276
  Admins act as `@chat-admin`, and only in channels the service created.
277
277
 
278
+ **Topics, browsing and new rooms.** `ChatRoomSummary.topic` is the room's
279
+ `m.room.topic` as plain text (trimmed, at most `MAX_TOPIC_LENGTH` characters),
280
+ and `canSetTopic` says whether this person's power level allows
281
+ `chat.setRoomTopic(roomId, topic)`, which rejects without calling the
282
+ homeserver when it does not. `chat.browseRooms()` lists the company space's
283
+ `public` and `restricted` child rooms on this server that the person is not
284
+ in (`{ id, name, topic?, memberCount }`, by name); a room from another
285
+ server, an invite-only room and a sub-space never appear.
286
+ `chat.joinBrowsableRoom(roomId)` joins one of them and rejects for any other
287
+ id. `chat.createRoom({ name, topic?, visibility: 'public' | 'private' })`
288
+ creates a channel through `apps/chat-service`'s `POST /_chat/rooms` (the
289
+ homeserver refuses a named room from a member), under the same rules as the
290
+ admin API, with the creator as its admin, and resolves with the room id once
291
+ it is in `rooms()`.
292
+
278
293
  **Pinned messages** ([#8](https://github.com/wtfalch/chat/issues/8)).
279
294
  `chat.pinMessage(roomId, eventId)` and `chat.unpinMessage(roomId, eventId)` add
280
295
  to and take from Matrix's own `m.room.pinned_events` state, one list the whole
@@ -4,6 +4,13 @@ import type { ChatClient, CreateChatClientOptions } from './types.ts';
4
4
  * so at once, rather than after the whole thing has gone up and Synapse
5
5
  * has refused it. */
6
6
  export declare const MAX_UPLOAD_BYTES: number;
7
+ /** The longest topic this package shows or sends, in characters. */
8
+ export declare const MAX_TOPIC_LENGTH = 250;
9
+ /** The longest room name this package shows from a room it has not joined. */
10
+ export declare const MAX_ROOM_NAME_LENGTH = 100;
11
+ /** A topic is whatever its setter wrote, so it is normalised on the way in
12
+ * from a room and on the way out to one. */
13
+ export declare function normaliseTopic(raw: string): string;
7
14
  /**
8
15
  * A chat session behind the exchange: a matrix-js-sdk `MatrixClient` the
9
16
  * caller never sees, refreshed on its own, exposing only what a UI needs.
@@ -77,12 +77,45 @@ function mediaProxyUrl(exchangeUrl, mxc, roomId, eventId) {
77
77
  url.searchParams.set('eventId', eventId);
78
78
  return url.toString();
79
79
  }
80
+ /** The longest topic this package shows or sends, in characters. */
81
+ export const MAX_TOPIC_LENGTH = 250;
82
+ /** The longest room name this package shows from a room it has not joined. */
83
+ export const MAX_ROOM_NAME_LENGTH = 100;
84
+ const BROWSE_PAGE_SIZE = 50;
85
+ const BROWSE_MAX_PAGES = 10;
86
+ const BROWSE_TIMEOUT_MS = 15_000;
87
+ const CREATE_ROOM_TIMEOUT_MS = 20_000;
88
+ /** Untrusted text made plain: control characters out (a line break becomes
89
+ * a space, runs of space collapse), trimmed, capped to `max` characters. */
90
+ function normaliseText(raw, max) {
91
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: that is the point
92
+ const plain = raw.replace(/[\s\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, ' ').trim();
93
+ return [...plain].slice(0, max).join('').trim();
94
+ }
95
+ /** A topic is whatever its setter wrote, so it is normalised on the way in
96
+ * from a room and on the way out to one. */
97
+ export function normaliseTopic(raw) {
98
+ return normaliseText(raw, MAX_TOPIC_LENGTH);
99
+ }
100
+ function withTimeout(call, ms, what) {
101
+ let timer;
102
+ const timeout = new Promise((_, reject) => {
103
+ timer = setTimeout(() => reject(new Error(`chat: ${what} timed out`)), ms);
104
+ });
105
+ return Promise.race([call, timeout]).finally(() => clearTimeout(timer));
106
+ }
80
107
  /** Where a thread's follow state lives: `apps/chat-service`'s
81
108
  * `/_chat/threads/...`, next to `exchangeUrl` like the media proxy. */
82
109
  function threadFollowUrl(exchangeUrl, roomId, threadId) {
83
110
  const base = exchangeUrl.replace(/\/_chat\/exchange\/?$/, '');
84
111
  return `${base}/_chat/threads/${encodeURIComponent(roomId)}/${encodeURIComponent(threadId)}/follow`;
85
112
  }
113
+ /** Where a member creates a channel: `apps/chat-service`'s
114
+ * `POST /_chat/rooms`, next to `exchangeUrl`. */
115
+ function createRoomUrl(exchangeUrl) {
116
+ const base = exchangeUrl.replace(/\/_chat\/exchange\/?$/, '');
117
+ return `${base}/_chat/rooms`;
118
+ }
86
119
  /** Where the automatic status overlay a person's call pushed is read back:
87
120
  * `apps/chat-service`'s `GET /_chat/status/{userId}`, next to `exchangeUrl`. */
88
121
  function automaticStatusUrl(exchangeUrl, userId) {
@@ -495,6 +528,8 @@ export function createChatClient(options) {
495
528
  markedUnread: isMarkedUnread(room),
496
529
  archived: roomArchived(room),
497
530
  starred: FAVOURITE_TAG in room.tags,
531
+ topic: roomTopic(room),
532
+ canSetTopic: canSetTopic(target, room),
498
533
  };
499
534
  });
500
535
  }
@@ -1613,6 +1648,188 @@ export function createChatClient(options) {
1613
1648
  ?.getContent()?.events_default;
1614
1649
  return Number(eventsDefault ?? 0) >= 100;
1615
1650
  }
1651
+ function roomTopic(room) {
1652
+ const raw = room.currentState
1653
+ .getStateEvents(EventType.RoomTopic, '')
1654
+ ?.getContent().topic;
1655
+ const topic = typeof raw === 'string' ? normaliseTopic(raw) : '';
1656
+ return topic === '' ? undefined : topic;
1657
+ }
1658
+ function canSetTopic(target, room) {
1659
+ const userId = target.getUserId();
1660
+ return (userId !== null &&
1661
+ room.getMyMembership() === KnownMembership.Join &&
1662
+ room.currentState.maySendStateEvent(EventType.RoomTopic, userId));
1663
+ }
1664
+ /** The company space(s): joined `m.space` rooms hosted on this person's
1665
+ * own homeserver. */
1666
+ function companySpaces(target) {
1667
+ const server = homeserverName(target.getUserId());
1668
+ return target
1669
+ .getRooms()
1670
+ .filter((room) => room.isSpaceRoom() &&
1671
+ room.getMyMembership() === KnownMembership.Join &&
1672
+ server !== undefined &&
1673
+ homeserverName(room.roomId) === server);
1674
+ }
1675
+ function homeserverName(id) {
1676
+ const at = id?.indexOf(':') ?? -1;
1677
+ return id && at > 0 ? id.slice(at + 1) : undefined;
1678
+ }
1679
+ /** See `ChatClient.browseRooms`. */
1680
+ async function browseRooms() {
1681
+ const target = client;
1682
+ if (!target)
1683
+ return [];
1684
+ const server = homeserverName(target.getUserId());
1685
+ const found = new Map();
1686
+ for (const space of companySpaces(target)) {
1687
+ let from;
1688
+ for (let page = 0; page < BROWSE_MAX_PAGES; page += 1) {
1689
+ const result = await withTimeout(target.getRoomHierarchy(space.roomId, BROWSE_PAGE_SIZE, 1, false, from), BROWSE_TIMEOUT_MS, 'browseRooms');
1690
+ for (const child of result.rooms ?? []) {
1691
+ if (child.room_id === space.roomId || child.room_type !== undefined)
1692
+ continue;
1693
+ if (homeserverName(child.room_id) !== server)
1694
+ continue;
1695
+ // matrix-js-sdk types `join_rule` as `Knock` only; the wire carries any rule.
1696
+ const joinRule = child.join_rule;
1697
+ if (joinRule !== 'public' && joinRule !== 'restricted')
1698
+ continue;
1699
+ const membership = target.getRoom(child.room_id)?.getMyMembership();
1700
+ if (membership === KnownMembership.Join || membership === KnownMembership.Invite) {
1701
+ continue;
1702
+ }
1703
+ const name = normaliseText(child.name ?? '', MAX_ROOM_NAME_LENGTH);
1704
+ const topic = normaliseTopic(child.topic ?? '');
1705
+ found.set(child.room_id, {
1706
+ id: child.room_id,
1707
+ name: name === '' ? child.room_id : name,
1708
+ ...(topic === '' ? {} : { topic }),
1709
+ memberCount: Number.isFinite(child.num_joined_members)
1710
+ ? Math.max(0, child.num_joined_members)
1711
+ : 0,
1712
+ });
1713
+ }
1714
+ from = result.next_batch;
1715
+ if (!from)
1716
+ break;
1717
+ }
1718
+ }
1719
+ return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
1720
+ }
1721
+ /** See `ChatClient.joinBrowsableRoom`. */
1722
+ async function joinBrowsableRoom(roomId) {
1723
+ const target = client;
1724
+ if (!target)
1725
+ throw new Error('chat: joinBrowsableRoom called before start()');
1726
+ const listed = await browseRooms();
1727
+ if (!listed.some((room) => room.id === roomId)) {
1728
+ throw new Error(`chat: ${roomId} is not a room of this company that can be joined`);
1729
+ }
1730
+ await target.joinRoom(roomId);
1731
+ if (client === target)
1732
+ notify();
1733
+ }
1734
+ /** See `ChatClient.createRoom`. The service is the only way: the
1735
+ * homeserver refuses a named room from a member. The rules a channel is
1736
+ * made under (naming, join rule, encryption, power levels) are the
1737
+ * service's, shared with the admin API. */
1738
+ async function createRoom(input) {
1739
+ if (!client)
1740
+ throw new Error('chat: createRoom called before start()');
1741
+ const target = client;
1742
+ const name = normaliseText(String(input.name ?? ''), Number.POSITIVE_INFINITY);
1743
+ if (name === '')
1744
+ throw new Error('chat: a room needs a name');
1745
+ if ([...name].length > MAX_ROOM_NAME_LENGTH) {
1746
+ throw new Error(`chat: a room name is at most ${MAX_ROOM_NAME_LENGTH} characters`);
1747
+ }
1748
+ if (input.visibility !== 'public' && input.visibility !== 'private') {
1749
+ throw new Error('chat: a room is either public or private');
1750
+ }
1751
+ const topic = normaliseTopic(String(input.topic ?? ''));
1752
+ const body = JSON.stringify({
1753
+ name,
1754
+ ...(topic === '' ? {} : { topic }),
1755
+ visibility: input.visibility,
1756
+ });
1757
+ const request = () => fetch(createRoomUrl(exchangeUrl), {
1758
+ method: 'POST',
1759
+ headers: {
1760
+ Authorization: `Bearer ${target.getAccessToken() ?? ''}`,
1761
+ 'Content-Type': 'application/json',
1762
+ },
1763
+ body,
1764
+ redirect: 'error',
1765
+ credentials: 'omit',
1766
+ signal: AbortSignal.timeout(CREATE_ROOM_TIMEOUT_MS),
1767
+ });
1768
+ let response = await request();
1769
+ if (response.status === 401 && client === target) {
1770
+ await refreshToken();
1771
+ response = await request();
1772
+ }
1773
+ if (!response.ok)
1774
+ throw new Error(`chat: room creation refused: ${response.status}`);
1775
+ const roomId = (await response.json()).room_id;
1776
+ if (typeof roomId !== 'string' || roomId === '') {
1777
+ throw new Error('chat: room creation answered without a room id');
1778
+ }
1779
+ await awaitJoinedRoom(target, roomId);
1780
+ return roomId;
1781
+ }
1782
+ /** Resolves once `target` has the room as joined. Bounded by
1783
+ * `CREATE_ROOM_TIMEOUT_MS`, rejects when `target` is no longer the live
1784
+ * client (`stop()` or a swap disposed it), and leaves no listener behind
1785
+ * on any path. */
1786
+ async function awaitJoinedRoom(target, roomId) {
1787
+ const ready = () => target.getRoom(roomId)?.getMyMembership() === KnownMembership.Join;
1788
+ if (ready())
1789
+ return;
1790
+ let check;
1791
+ try {
1792
+ await withTimeout(new Promise((resolve, reject) => {
1793
+ check = () => {
1794
+ if (client !== target) {
1795
+ reject(new Error('chat: the client was replaced while the room was being created'));
1796
+ }
1797
+ else if (ready())
1798
+ resolve();
1799
+ };
1800
+ target.on(ClientEvent.Room, check);
1801
+ target.on(RoomEvent.MyMembership, check);
1802
+ target.on(ClientEvent.Sync, check);
1803
+ }), CREATE_ROOM_TIMEOUT_MS, 'waiting for the new room');
1804
+ }
1805
+ catch (error) {
1806
+ // `stop()` / a swap removes every listener, so the wait can only end
1807
+ // by timing out: say why.
1808
+ if (client !== target) {
1809
+ throw new Error('chat: the client was replaced while the room was being created');
1810
+ }
1811
+ throw error;
1812
+ }
1813
+ finally {
1814
+ if (check) {
1815
+ target.off(ClientEvent.Room, check);
1816
+ target.off(RoomEvent.MyMembership, check);
1817
+ target.off(ClientEvent.Sync, check);
1818
+ }
1819
+ }
1820
+ }
1821
+ /** See `ChatClient.setRoomTopic`. */
1822
+ async function setRoomTopic(roomId, topic) {
1823
+ if (!client)
1824
+ throw new Error('chat: setRoomTopic called before start()');
1825
+ const room = client.getRoom(roomId);
1826
+ if (!room)
1827
+ throw new Error(`chat: not in room ${roomId}`);
1828
+ if (!canSetTopic(client, room)) {
1829
+ throw new Error(`chat: not allowed to set the topic of ${roomId}`);
1830
+ }
1831
+ await client.sendStateEvent(roomId, EventType.RoomTopic, { topic: normaliseTopic(topic) }, '');
1832
+ }
1616
1833
  function pinnedEventIds(room) {
1617
1834
  const content = room.currentState
1618
1835
  .getStateEvents(EventType.RoomPinnedEvents, '')
@@ -2667,6 +2884,10 @@ export function createChatClient(options) {
2667
2884
  toggleReaction,
2668
2885
  pinMessage,
2669
2886
  unpinMessage,
2887
+ setRoomTopic,
2888
+ createRoom,
2889
+ browseRooms,
2890
+ joinBrowsableRoom,
2670
2891
  pinnedMessages,
2671
2892
  startDirectMessage,
2672
2893
  hideDirectMessage,
@@ -1,7 +1,7 @@
1
1
  import type { ChatClient } from '../types.ts';
2
2
  import { FakeChatServer, type FakeChatServerOptions } from './server.ts';
3
3
  export { FakeChatServer } from './server.ts';
4
- export type { FakeChatServerOptions, FakeMember, FakeMessageSeed, FakeRoomSeed, } from './server.ts';
4
+ export type { FakeChatServerOptions, FakeHierarchyChild, FakeMember, FakeMessageSeed, FakeRoomSeed, } from './server.ts';
5
5
  export { SAMPLE_ROOMS } from './sample.ts';
6
6
  export type FakeChatOptions = FakeChatServerOptions & {
7
7
  storeName?: string;
@@ -33,6 +33,15 @@ export type FakeRoomSeed = {
33
33
  * defaults to `0` in real Matrix, same as the client and admin reads
34
34
  * treat it). */
35
35
  archived?: boolean;
36
+ /** For a space: the children its `GET .../hierarchy` lists. Joining one
37
+ * through `POST /join` makes it a joined room. */
38
+ children?: FakeHierarchyChild[];
39
+ /** Seeds an `m.room.topic` state event. Defaults to none. */
40
+ topic?: string;
41
+ /** Seeds the content of `m.room.power_levels` (`users`, `state_default`,
42
+ * ...), merged over `archived`'s `events_default`. Defaults to none,
43
+ * which seeds no such event. */
44
+ powerLevels?: Record<string, unknown>;
36
45
  /** Seeds this room as an unanswered invitation to the fake account
37
46
  * itself, rather than a room it has joined -- a `rooms.invite` entry
38
47
  * with the stripped state real Matrix delivers one in, the one shape
@@ -43,6 +52,20 @@ export type FakeRoomSeed = {
43
52
  inviter?: string;
44
53
  };
45
54
  };
55
+ /** One child the fake company space lists in `GET .../hierarchy`. Fields
56
+ * the homeserver would send are passed through as given, so a test can
57
+ * seed a federated room, a sub-space or an invite-only room. */
58
+ export type FakeHierarchyChild = {
59
+ id: string;
60
+ name?: string;
61
+ topic?: string;
62
+ /** Defaults to `restricted`, how the company's channels are created. */
63
+ joinRule?: string;
64
+ /** `m.space` for a sub-space. Omitted for a room. */
65
+ roomType?: string;
66
+ /** Defaults to `0`. */
67
+ memberCount?: number;
68
+ };
46
69
  export type FakeMessageSeed = {
47
70
  /** Defaults to a minted `$seeded-<n>`. Give one to reply to it. */
48
71
  id?: string;
@@ -118,6 +141,28 @@ export declare class FakeChatServer {
118
141
  * gives a member, which `pinMessage`/`unpinMessage` must reject on
119
142
  * rather than resolve quietly. */
120
143
  pinStatus: number;
144
+ /** Every `m.room.topic` the client has written, in order -- for a test
145
+ * that asserts what went on the wire, or that nothing did. */
146
+ readonly topicWrites: Array<{
147
+ roomId: string;
148
+ content: Record<string, unknown>;
149
+ }>;
150
+ /** What `POST /_chat/rooms` answers with -- anything but 201 fails the
151
+ * creation, with nothing made. */
152
+ createRoomStatus: number;
153
+ /** Every `POST /_chat/rooms` the client made, with the bearer token and
154
+ * the exact body it sent. */
155
+ readonly createRoomRequests: Array<{
156
+ authorised: boolean;
157
+ body: unknown;
158
+ }>;
159
+ /** Every room the client joined through `POST /join`, in order. */
160
+ readonly joinedThroughApi: string[];
161
+ /** Every `GET .../hierarchy` the client made, with its `from` token. */
162
+ readonly hierarchyRequests: Array<{
163
+ roomId: string;
164
+ from: string | null;
165
+ }>;
121
166
  /** What `PUT .../send/...` answers with -- anything but 200 fails the
122
167
  * send, with nothing stored. */
123
168
  sendStatus: number;
@@ -36,6 +36,19 @@ export class FakeChatServer {
36
36
  * gives a member, which `pinMessage`/`unpinMessage` must reject on
37
37
  * rather than resolve quietly. */
38
38
  pinStatus = 200;
39
+ /** Every `m.room.topic` the client has written, in order -- for a test
40
+ * that asserts what went on the wire, or that nothing did. */
41
+ topicWrites = [];
42
+ /** What `POST /_chat/rooms` answers with -- anything but 201 fails the
43
+ * creation, with nothing made. */
44
+ createRoomStatus = 201;
45
+ /** Every `POST /_chat/rooms` the client made, with the bearer token and
46
+ * the exact body it sent. */
47
+ createRoomRequests = [];
48
+ /** Every room the client joined through `POST /join`, in order. */
49
+ joinedThroughApi = [];
50
+ /** Every `GET .../hierarchy` the client made, with its `from` token. */
51
+ hierarchyRequests = [];
39
52
  /** What `PUT .../send/...` answers with -- anything but 200 fails the
40
53
  * send, with nothing stored. */
41
54
  sendStatus = 200;
@@ -516,14 +529,24 @@ export class FakeChatServer {
516
529
  content: { algorithm: 'm.megolm.v1.aes-sha2' },
517
530
  });
518
531
  }
519
- if (seed.archived) {
532
+ if (seed.topic !== undefined) {
533
+ events.push({
534
+ type: 'm.room.topic',
535
+ state_key: '',
536
+ event_id: `$topic-${seed.id}`,
537
+ sender: this.userId,
538
+ origin_server_ts: now,
539
+ content: { topic: seed.topic },
540
+ });
541
+ }
542
+ if (seed.archived || seed.powerLevels) {
520
543
  events.push({
521
544
  type: 'm.room.power_levels',
522
545
  state_key: '',
523
546
  event_id: `$power-levels-${seed.id}`,
524
547
  sender: this.userId,
525
548
  origin_server_ts: now,
526
- content: { events_default: 100 },
549
+ content: { ...(seed.archived ? { events_default: 100 } : {}), ...seed.powerLevels },
527
550
  });
528
551
  }
529
552
  return {
@@ -1270,6 +1293,81 @@ export class FakeChatServer {
1270
1293
  this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
1271
1294
  return Promise.resolve(jsonResponse(200, { event_id: event.event_id }));
1272
1295
  }
1296
+ const hierarchy = url.pathname.match(/^\/_matrix\/client\/v1\/rooms\/([^/]+)\/hierarchy$/);
1297
+ if (hierarchy && this.#authorised(init)) {
1298
+ const roomId = decodeURIComponent(hierarchy[1]);
1299
+ const from = url.searchParams.get('from');
1300
+ this.hierarchyRequests.push({ roomId, from });
1301
+ const space = this.#rooms.find((room) => room.id === roomId && room.isSpace);
1302
+ if (!space) {
1303
+ return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'unknown' }));
1304
+ }
1305
+ const children = space.children ?? [];
1306
+ const limit = Number(url.searchParams.get('limit') ?? children.length + 1) || 1;
1307
+ const start = from ? Number(from) : 0;
1308
+ const page = children.slice(start, start + limit);
1309
+ const next = start + limit < children.length ? String(start + limit) : undefined;
1310
+ const toRoom = (child) => ({
1311
+ room_id: child.id,
1312
+ name: child.name,
1313
+ topic: child.topic,
1314
+ join_rule: child.joinRule ?? 'restricted',
1315
+ num_joined_members: child.memberCount ?? 0,
1316
+ world_readable: false,
1317
+ guest_can_join: false,
1318
+ ...(child.roomType ? { room_type: child.roomType } : {}),
1319
+ children_state: [],
1320
+ });
1321
+ return Promise.resolve(jsonResponse(200, {
1322
+ rooms: [
1323
+ ...(start === 0
1324
+ ? [{ ...toRoom({ id: space.id, name: space.name, roomType: 'm.space' }) }]
1325
+ : []),
1326
+ ...page.map(toRoom),
1327
+ ],
1328
+ ...(next ? { next_batch: next } : {}),
1329
+ }));
1330
+ }
1331
+ const join = url.pathname.match(/^\/_matrix\/client\/v3\/join\/([^/]+)$/);
1332
+ if (join && init?.method === 'POST' && this.#authorised(init)) {
1333
+ const roomId = decodeURIComponent(join[1]);
1334
+ const child = this.#rooms
1335
+ .flatMap((room) => room.children ?? [])
1336
+ .find((candidate) => candidate.id === roomId);
1337
+ if (!child) {
1338
+ return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'unknown' }));
1339
+ }
1340
+ this.joinedThroughApi.push(roomId);
1341
+ const seed = { id: roomId, name: child.name ?? roomId, topic: child.topic };
1342
+ this.#rooms.push(seed);
1343
+ this.#materialise(seed);
1344
+ this.#deliverOrQueue({ [roomId]: this.#joinEntry(seed) });
1345
+ return Promise.resolve(jsonResponse(200, { room_id: roomId }));
1346
+ }
1347
+ const topicState = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/state\/m\.room\.topic\/?$/);
1348
+ if (topicState && this.#authorised(init)) {
1349
+ let content = {};
1350
+ try {
1351
+ content = JSON.parse(String(init?.body ?? '{}'));
1352
+ }
1353
+ catch {
1354
+ // Same tolerance as every other route here.
1355
+ }
1356
+ const roomId = decodeURIComponent(topicState[1]);
1357
+ this.topicWrites.push({ roomId, content });
1358
+ this.#eventSeq += 1;
1359
+ const event = {
1360
+ type: 'm.room.topic',
1361
+ state_key: '',
1362
+ event_id: `$topic-${this.#eventSeq}`,
1363
+ sender: this.userId,
1364
+ origin_server_ts: this.#now(),
1365
+ content,
1366
+ };
1367
+ this.#record(roomId, event);
1368
+ this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
1369
+ return Promise.resolve(jsonResponse(200, { event_id: event.event_id }));
1370
+ }
1273
1371
  // Uploads go to `/_matrix/media/v3/upload`, which is still the
1274
1372
  // upload endpoint under authenticated media -- only *downloads* moved
1275
1373
  // to `/_matrix/client/v1/media`.
@@ -1308,6 +1406,32 @@ export class FakeChatServer {
1308
1406
  }
1309
1407
  // `apps/chat-service`'s thread follow route: the same rule the real one
1310
1408
  // has -- an automatic follow never undoes an unfollow.
1409
+ if (url.pathname === '/_chat/rooms' && init?.method === 'POST') {
1410
+ const authorised = this.#authorised(init);
1411
+ let body = {};
1412
+ try {
1413
+ body = JSON.parse(String(init?.body ?? '{}'));
1414
+ }
1415
+ catch {
1416
+ // Recorded as an empty body below.
1417
+ }
1418
+ this.createRoomRequests.push({ authorised, body });
1419
+ if (!authorised)
1420
+ return Promise.resolve(jsonResponse(401, { error: 'token_invalid' }));
1421
+ if (this.createRoomStatus !== 201) {
1422
+ return Promise.resolve(jsonResponse(this.createRoomStatus, { error: 'refused' }));
1423
+ }
1424
+ this.#roomSeq += 1;
1425
+ const seed = {
1426
+ id: `!channel-${this.#roomSeq}:${this.serverName}`,
1427
+ name: String(body.name),
1428
+ topic: body.topic,
1429
+ };
1430
+ this.#rooms.push(seed);
1431
+ this.#materialise(seed);
1432
+ this.#deliverOrQueue({ [seed.id]: this.#joinEntry(seed) });
1433
+ return Promise.resolve(jsonResponse(201, { room_id: seed.id }));
1434
+ }
1311
1435
  const chatThread = url.pathname.match(/^\/_chat\/threads\/([^/]+)\/([^/]+)\/follow$/);
1312
1436
  if (chatThread) {
1313
1437
  if (!this.#authorised(init)) {
@@ -6,5 +6,5 @@
6
6
  * everything it returns is this package's own small, typed surface. See
7
7
  * `README.md` and the chat plan, section 9.
8
8
  */
9
- export { createChatClient, MAX_UPLOAD_BYTES } from './client.ts';
10
- export type { ChatAttachment, ChatRoomFilesPage, ChatClient, ChatConnectionStatus, ChatPerson, ChatRoomLastMessage, ChatRoomSummary, ChatSearchResults, ChatTimelineEvent, ChatUploadProgress, CreateChatClientOptions, ExchangeBody, } from './types.ts';
9
+ export { createChatClient, MAX_ROOM_NAME_LENGTH, MAX_TOPIC_LENGTH, MAX_UPLOAD_BYTES, normaliseTopic, } from './client.ts';
10
+ export type { ChatAttachment, ChatBrowsableRoom, ChatNewRoom, ChatRoomFilesPage, ChatClient, ChatConnectionStatus, ChatPerson, ChatRoomLastMessage, ChatRoomSummary, ChatSearchResults, ChatTimelineEvent, ChatUploadProgress, CreateChatClientOptions, ExchangeBody, } from './types.ts';
@@ -6,4 +6,4 @@
6
6
  * everything it returns is this package's own small, typed surface. See
7
7
  * `README.md` and the chat plan, section 9.
8
8
  */
9
- export { createChatClient, MAX_UPLOAD_BYTES } from "./client.js";
9
+ export { createChatClient, MAX_ROOM_NAME_LENGTH, MAX_TOPIC_LENGTH, MAX_UPLOAD_BYTES, normaliseTopic, } from "./client.js";
@@ -109,6 +109,33 @@ export type ChatRoomSummary = {
109
109
  * `m.favourite` room tag, synced across every device on the account
110
110
  * the same way `hideDirectMessage`'s tag is (agora#27). */
111
111
  readonly starred: boolean;
112
+ /** The room's `m.room.topic`, as plain text: trimmed and capped (see
113
+ * `normaliseTopic`), because a topic is whatever its setter wrote.
114
+ * Absent when the room has none. */
115
+ readonly topic?: string;
116
+ /** Whether the signed-in person's power level lets them change this
117
+ * room's topic with `setRoomTopic`. A list or room header shows its
118
+ * edit control off this instead of letting the write fail. */
119
+ readonly canSetTopic: boolean;
120
+ };
121
+ /** A room of this company the person is not in yet and may join: a child
122
+ * of the company space with a `public` or `restricted` join rule. Name and
123
+ * topic are plain text, normalised like `ChatRoomSummary.topic`. */
124
+ export type ChatBrowsableRoom = {
125
+ readonly id: string;
126
+ readonly name: string;
127
+ readonly topic?: string;
128
+ /** Joined members, as the homeserver counts them. */
129
+ readonly memberCount: number;
130
+ };
131
+ /** What `createRoom` takes. */
132
+ export type ChatNewRoom = {
133
+ /** Trimmed; must not be empty. */
134
+ name: string;
135
+ topic?: string;
136
+ /** `public`: any member of the company may find and join it (the admin
137
+ * API's own word for it). `private`: invite only. */
138
+ visibility: 'public' | 'private';
112
139
  };
113
140
  /** Someone this person can start a direct message with: a member of the
114
141
  * company space, or a guest sharing a room with them (docs/guests.md,
@@ -804,6 +831,35 @@ export type ChatClient = {
804
831
  * safe against another client writing to the same room's pinned list
805
832
  * at once. */
806
833
  unpinMessage: (roomId: string, eventId: string) => Promise<void>;
834
+ /** Sets `roomId`'s topic. `topic` is trimmed and capped to
835
+ * `MAX_TOPIC_LENGTH` characters, control characters removed; an empty
836
+ * result clears the topic. Rejects, with nothing sent, when the room is
837
+ * unknown or this person's power level cannot send `m.room.topic`
838
+ * (`ChatRoomSummary.canSetTopic` is false). The homeserver stays the
839
+ * authority: a refusal from it rejects too. */
840
+ setRoomTopic: (roomId: string, topic: string) => Promise<void>;
841
+ /** Creates a company channel and resolves with its room id once it is in
842
+ * `rooms()`. Goes through `apps/chat-service` (`POST /_chat/rooms`),
843
+ * because the homeserver refuses a named room from a member; the
844
+ * service applies the admin API's rules (join rule, power levels,
845
+ * encryption default, the link to the company space) and makes the
846
+ * creator an admin (power level 100) of the new room. `name` is trimmed
847
+ * and must be non-empty and at most `MAX_ROOM_NAME_LENGTH` characters;
848
+ * `topic` is normalised and capped like `setRoomTopic`'s. Rejects, with
849
+ * nothing made, on a bad name or visibility, or when the service
850
+ * refuses. */
851
+ createRoom: (input: ChatNewRoom) => Promise<string>;
852
+ /** The company's rooms this person is not in and may join, name order:
853
+ * the children of the company space (the joined `m.space` on this
854
+ * homeserver) whose join rule is `public` or `restricted`, minus rooms
855
+ * already joined or invited, minus rooms hosted on another server and
856
+ * minus sub-spaces. A room federated in from elsewhere never appears,
857
+ * whatever the space lists. Empty before `start()` resolves. */
858
+ browseRooms: () => Promise<ChatBrowsableRoom[]>;
859
+ /** Joins one room `browseRooms` lists. Rejects for any other room id,
860
+ * without calling the homeserver's join -- this is not a way to join
861
+ * an arbitrary room. */
862
+ joinBrowsableRoom: (roomId: string) => Promise<void>;
807
863
  /** `roomId`'s currently pinned messages, in the order `m.room.pinned_
808
864
  * events` lists them, each reduced the same way `timeline()` reduces a
809
865
  * message. A pinned id this client cannot find an event for -- paginated
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/chat",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "A Matrix chat client behind the agora's token exchange.",
5
5
  "license": "MIT",
6
6
  "type": "module",