@wtfalch/chat 0.8.0 → 0.10.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
@@ -2,7 +2,13 @@
2
2
 
3
3
  Team chat, on Matrix. Mirrors [`@wtfalch/email`](https://github.com/wtfalch/email)'s
4
4
  shape: a client the agora gives a way to get a token, a React section built on
5
- it, and a fake of both for stories and tests.
5
+ it.
6
+
7
+ ## Breaking in 0.10.0
8
+
9
+ - `stop()` returns `Promise<void>` instead of `void`. It settles once every store the client built is destroyed, and it never rejects. A hand-written `ChatClient` with `stop: () => {}` no longer compiles; return a resolved promise.
10
+ - A `start()` that `stop()` overtook rejects with `ChatStartCancelledError`, exported from the package. Attach a handler when you do not await `start()`.
11
+ - The `./fake` export is gone. An app that needs a stand-in for development keeps its own copy.
6
12
 
7
13
  ## Exports
8
14
 
@@ -10,7 +16,6 @@ it, and a fake of both for stories and tests.
10
16
  | --- | --- |
11
17
  | `@wtfalch/chat` | `createChatClient`: a matrix-js-sdk `MatrixClient` behind the token exchange, refreshed on its own, exposing a small typed API |
12
18
  | `@wtfalch/chat/react` | The `Chat` component: rooms, a timeline, a composer, direct messages, threads, reactions and mentions |
13
- | `@wtfalch/chat/fake` | A real `createChatClient`, wired to a fake exchange and a fake homeserver instead of the network |
14
19
  | `@wtfalch/chat/chat.css` | Styles, on `@wtfalch/design` tokens |
15
20
 
16
21
  ## The client
@@ -29,6 +34,10 @@ await chat.start();
29
34
  chat.onRoomsChanged((rooms) => render(rooms));
30
35
  ```
31
36
 
37
+ A `start()` that `stop()` overtakes rejects with `ChatStartCancelledError`; if you do not await it, attach a handler:
38
+ `void chat.start().catch((error) => { if (!(error instanceof ChatStartCancelledError)) report(error); });`
39
+ `stop()` returns a Promise that settles once the store is destroyed; it never rejects.
40
+
32
41
  `createChatClient` takes only a way to get a current ZITADEL access token
33
42
  (`getAccessToken`) -- it knows nothing else about the agora, and never imports
34
43
  an Agora type. On `start()`, it `POST`s `exchangeUrl` with that token and a
@@ -275,6 +284,21 @@ with `redactMessage(roomId, eventId)`, and bans a person from a channel with
275
284
  `banPerson(roomId, subject, reason?)` until `unbanPerson(roomId, subject)`.
276
285
  Admins act as `@chat-admin`, and only in channels the service created.
277
286
 
287
+ **Topics, browsing and new rooms.** `ChatRoomSummary.topic` is the room's
288
+ `m.room.topic` as plain text (trimmed, at most `MAX_TOPIC_LENGTH` characters),
289
+ and `canSetTopic` says whether this person's power level allows
290
+ `chat.setRoomTopic(roomId, topic)`, which rejects without calling the
291
+ homeserver when it does not. `chat.browseRooms()` lists the company space's
292
+ `public` and `restricted` child rooms on this server that the person is not
293
+ in (`{ id, name, topic?, memberCount }`, by name); a room from another
294
+ server, an invite-only room and a sub-space never appear.
295
+ `chat.joinBrowsableRoom(roomId)` joins one of them and rejects for any other
296
+ id. `chat.createRoom({ name, topic?, visibility: 'public' | 'private' })`
297
+ creates a channel through `apps/chat-service`'s `POST /_chat/rooms` (the
298
+ homeserver refuses a named room from a member), under the same rules as the
299
+ admin API, with the creator as its admin, and resolves with the room id once
300
+ it is in `rooms()`.
301
+
278
302
  **Pinned messages** ([#8](https://github.com/wtfalch/chat/issues/8)).
279
303
  `chat.pinMessage(roomId, eventId)` and `chat.unpinMessage(roomId, eventId)` add
280
304
  to and take from Matrix's own `m.room.pinned_events` state, one list the whole
@@ -310,10 +334,13 @@ entities, `svg onload`, `object`/`embed`/`form`/`base`/`meta`, every `on*`
310
334
  handler, the `<scr<script>ipt>` trick, foreign image sources, and messages
311
335
  built out of nothing but depth or siblings.
312
336
 
313
- ## The fake
337
+ ## The test double
338
+
339
+ Not exported and not published: `src/chat/fake` is this package's own test
340
+ double, left out of the build.
314
341
 
315
342
  ```ts
316
- import { fakeChat } from '@wtfalch/chat/fake';
343
+ import { fakeChat } from '../fake/index.ts';
317
344
 
318
345
  const { client, server, dispose } = fakeChat();
319
346
  await client.start();
@@ -324,7 +351,7 @@ dispose();
324
351
  Like `@wtfalch/email`'s `fakeMail`, this is a fake transport, not a fake
325
352
  client: `createChatClient` and matrix-js-sdk run unchanged, against a fake
326
353
  exchange and homeserver answered by intercepting `fetch`. `FakeChatServer`
327
- (also exported) gives a test finer control -- seeding rooms (with a starting
354
+ gives a test finer control -- seeding rooms (with a starting
328
355
  `notificationCount`), seeding the company space (`isSpace`) and who is in it
329
356
  (`members`, `invited`), adding, renaming or delivering someone leaving a room
330
357
  mid-test, sending a message into one, invalidating the current token to
@@ -110,8 +110,17 @@ export function createChatAdmin(options) {
110
110
  });
111
111
  const data = await response.json().catch(() => null);
112
112
  if (!response.ok) {
113
- const code = record(data) && typeof data.error === 'string' && /^[a-z_]{1,64}$/.test(data.error)
114
- ? data.error
113
+ // The shared estate envelope (`@wtfalch/contracts`):
114
+ // `{ error: { code, message, reason? } }`. `reason`, when the
115
+ // service sent one, is the finer-grained value this SDK's own
116
+ // `code` has always carried (`user_not_found`, not just the closed
117
+ // nine-value `not_found`) -- preferred for that reason.
118
+ const errorField = record(data) ? data.error : undefined;
119
+ const nested = record(errorField) ? errorField : undefined;
120
+ const candidate = (nested && typeof nested.reason === 'string' ? nested.reason : undefined) ??
121
+ (nested && typeof nested.code === 'string' ? nested.code : undefined);
122
+ const code = typeof candidate === 'string' && /^[a-z_]{1,64}$/.test(candidate)
123
+ ? candidate
115
124
  : 'request_failed';
116
125
  throw new ChatAdminError(response.status, code);
117
126
  }
@@ -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.
@@ -35,4 +42,10 @@ export declare const MAX_UPLOAD_BYTES: number;
35
42
  * no-op while `clientRunning` is still true, so a plain retry would never
36
43
  * resume syncing.
37
44
  */
45
+ /** Rejection of a `start()` that `stop()` overtook. */
46
+ export declare class ChatStartCancelledError extends Error {
47
+ constructor(options?: {
48
+ cause?: unknown;
49
+ });
50
+ }
38
51
  export declare function createChatClient(options: CreateChatClientOptions): ChatClient;
@@ -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) {
@@ -146,6 +179,13 @@ const SEARCH_LIMIT_DEFAULT = 50;
146
179
  * no-op while `clientRunning` is still true, so a plain retry would never
147
180
  * resume syncing.
148
181
  */
182
+ /** Rejection of a `start()` that `stop()` overtook. */
183
+ export class ChatStartCancelledError extends Error {
184
+ constructor(options) {
185
+ super('chat: start cancelled by stop()', options);
186
+ this.name = 'ChatStartCancelledError';
187
+ }
188
+ }
149
189
  export function createChatClient(options) {
150
190
  const { exchangeUrl, getAccessToken, deviceId, storeName, encryptionEnabled } = options;
151
191
  let client;
@@ -175,6 +215,11 @@ export function createChatClient(options) {
175
215
  /** The account `secretStorageKeys` belongs to. */
176
216
  let secretStorageUserId;
177
217
  let starting;
218
+ // Bumped by `stop()`; a `start()` compares it after each await to learn it
219
+ // was overtaken. `teardown` settles once the last stop's store is destroyed.
220
+ let generation = 0;
221
+ let teardown = Promise.resolve();
222
+ const buildsInFlight = new Set();
178
223
  let refreshTimer;
179
224
  let recovering;
180
225
  let resyncing;
@@ -495,6 +540,8 @@ export function createChatClient(options) {
495
540
  markedUnread: isMarkedUnread(room),
496
541
  archived: roomArchived(room),
497
542
  starred: FAVOURITE_TAG in room.tags,
543
+ topic: roomTopic(room),
544
+ canSetTopic: canSetTopic(target, room),
498
545
  };
499
546
  });
500
547
  }
@@ -1613,6 +1660,188 @@ export function createChatClient(options) {
1613
1660
  ?.getContent()?.events_default;
1614
1661
  return Number(eventsDefault ?? 0) >= 100;
1615
1662
  }
1663
+ function roomTopic(room) {
1664
+ const raw = room.currentState
1665
+ .getStateEvents(EventType.RoomTopic, '')
1666
+ ?.getContent().topic;
1667
+ const topic = typeof raw === 'string' ? normaliseTopic(raw) : '';
1668
+ return topic === '' ? undefined : topic;
1669
+ }
1670
+ function canSetTopic(target, room) {
1671
+ const userId = target.getUserId();
1672
+ return (userId !== null &&
1673
+ room.getMyMembership() === KnownMembership.Join &&
1674
+ room.currentState.maySendStateEvent(EventType.RoomTopic, userId));
1675
+ }
1676
+ /** The company space(s): joined `m.space` rooms hosted on this person's
1677
+ * own homeserver. */
1678
+ function companySpaces(target) {
1679
+ const server = homeserverName(target.getUserId());
1680
+ return target
1681
+ .getRooms()
1682
+ .filter((room) => room.isSpaceRoom() &&
1683
+ room.getMyMembership() === KnownMembership.Join &&
1684
+ server !== undefined &&
1685
+ homeserverName(room.roomId) === server);
1686
+ }
1687
+ function homeserverName(id) {
1688
+ const at = id?.indexOf(':') ?? -1;
1689
+ return id && at > 0 ? id.slice(at + 1) : undefined;
1690
+ }
1691
+ /** See `ChatClient.browseRooms`. */
1692
+ async function browseRooms() {
1693
+ const target = client;
1694
+ if (!target)
1695
+ return [];
1696
+ const server = homeserverName(target.getUserId());
1697
+ const found = new Map();
1698
+ for (const space of companySpaces(target)) {
1699
+ let from;
1700
+ for (let page = 0; page < BROWSE_MAX_PAGES; page += 1) {
1701
+ const result = await withTimeout(target.getRoomHierarchy(space.roomId, BROWSE_PAGE_SIZE, 1, false, from), BROWSE_TIMEOUT_MS, 'browseRooms');
1702
+ for (const child of result.rooms ?? []) {
1703
+ if (child.room_id === space.roomId || child.room_type !== undefined)
1704
+ continue;
1705
+ if (homeserverName(child.room_id) !== server)
1706
+ continue;
1707
+ // matrix-js-sdk types `join_rule` as `Knock` only; the wire carries any rule.
1708
+ const joinRule = child.join_rule;
1709
+ if (joinRule !== 'public' && joinRule !== 'restricted')
1710
+ continue;
1711
+ const membership = target.getRoom(child.room_id)?.getMyMembership();
1712
+ if (membership === KnownMembership.Join || membership === KnownMembership.Invite) {
1713
+ continue;
1714
+ }
1715
+ const name = normaliseText(child.name ?? '', MAX_ROOM_NAME_LENGTH);
1716
+ const topic = normaliseTopic(child.topic ?? '');
1717
+ found.set(child.room_id, {
1718
+ id: child.room_id,
1719
+ name: name === '' ? child.room_id : name,
1720
+ ...(topic === '' ? {} : { topic }),
1721
+ memberCount: Number.isFinite(child.num_joined_members)
1722
+ ? Math.max(0, child.num_joined_members)
1723
+ : 0,
1724
+ });
1725
+ }
1726
+ from = result.next_batch;
1727
+ if (!from)
1728
+ break;
1729
+ }
1730
+ }
1731
+ return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
1732
+ }
1733
+ /** See `ChatClient.joinBrowsableRoom`. */
1734
+ async function joinBrowsableRoom(roomId) {
1735
+ const target = client;
1736
+ if (!target)
1737
+ throw new Error('chat: joinBrowsableRoom called before start()');
1738
+ const listed = await browseRooms();
1739
+ if (!listed.some((room) => room.id === roomId)) {
1740
+ throw new Error(`chat: ${roomId} is not a room of this company that can be joined`);
1741
+ }
1742
+ await target.joinRoom(roomId);
1743
+ if (client === target)
1744
+ notify();
1745
+ }
1746
+ /** See `ChatClient.createRoom`. The service is the only way: the
1747
+ * homeserver refuses a named room from a member. The rules a channel is
1748
+ * made under (naming, join rule, encryption, power levels) are the
1749
+ * service's, shared with the admin API. */
1750
+ async function createRoom(input) {
1751
+ if (!client)
1752
+ throw new Error('chat: createRoom called before start()');
1753
+ const target = client;
1754
+ const name = normaliseText(String(input.name ?? ''), Number.POSITIVE_INFINITY);
1755
+ if (name === '')
1756
+ throw new Error('chat: a room needs a name');
1757
+ if ([...name].length > MAX_ROOM_NAME_LENGTH) {
1758
+ throw new Error(`chat: a room name is at most ${MAX_ROOM_NAME_LENGTH} characters`);
1759
+ }
1760
+ if (input.visibility !== 'public' && input.visibility !== 'private') {
1761
+ throw new Error('chat: a room is either public or private');
1762
+ }
1763
+ const topic = normaliseTopic(String(input.topic ?? ''));
1764
+ const body = JSON.stringify({
1765
+ name,
1766
+ ...(topic === '' ? {} : { topic }),
1767
+ visibility: input.visibility,
1768
+ });
1769
+ const request = () => fetch(createRoomUrl(exchangeUrl), {
1770
+ method: 'POST',
1771
+ headers: {
1772
+ Authorization: `Bearer ${target.getAccessToken() ?? ''}`,
1773
+ 'Content-Type': 'application/json',
1774
+ },
1775
+ body,
1776
+ redirect: 'error',
1777
+ credentials: 'omit',
1778
+ signal: AbortSignal.timeout(CREATE_ROOM_TIMEOUT_MS),
1779
+ });
1780
+ let response = await request();
1781
+ if (response.status === 401 && client === target) {
1782
+ await refreshToken();
1783
+ response = await request();
1784
+ }
1785
+ if (!response.ok)
1786
+ throw new Error(`chat: room creation refused: ${response.status}`);
1787
+ const roomId = (await response.json()).room_id;
1788
+ if (typeof roomId !== 'string' || roomId === '') {
1789
+ throw new Error('chat: room creation answered without a room id');
1790
+ }
1791
+ await awaitJoinedRoom(target, roomId);
1792
+ return roomId;
1793
+ }
1794
+ /** Resolves once `target` has the room as joined. Bounded by
1795
+ * `CREATE_ROOM_TIMEOUT_MS`, rejects when `target` is no longer the live
1796
+ * client (`stop()` or a swap disposed it), and leaves no listener behind
1797
+ * on any path. */
1798
+ async function awaitJoinedRoom(target, roomId) {
1799
+ const ready = () => target.getRoom(roomId)?.getMyMembership() === KnownMembership.Join;
1800
+ if (ready())
1801
+ return;
1802
+ let check;
1803
+ try {
1804
+ await withTimeout(new Promise((resolve, reject) => {
1805
+ check = () => {
1806
+ if (client !== target) {
1807
+ reject(new Error('chat: the client was replaced while the room was being created'));
1808
+ }
1809
+ else if (ready())
1810
+ resolve();
1811
+ };
1812
+ target.on(ClientEvent.Room, check);
1813
+ target.on(RoomEvent.MyMembership, check);
1814
+ target.on(ClientEvent.Sync, check);
1815
+ }), CREATE_ROOM_TIMEOUT_MS, 'waiting for the new room');
1816
+ }
1817
+ catch (error) {
1818
+ // `stop()` / a swap removes every listener, so the wait can only end
1819
+ // by timing out: say why.
1820
+ if (client !== target) {
1821
+ throw new Error('chat: the client was replaced while the room was being created');
1822
+ }
1823
+ throw error;
1824
+ }
1825
+ finally {
1826
+ if (check) {
1827
+ target.off(ClientEvent.Room, check);
1828
+ target.off(RoomEvent.MyMembership, check);
1829
+ target.off(ClientEvent.Sync, check);
1830
+ }
1831
+ }
1832
+ }
1833
+ /** See `ChatClient.setRoomTopic`. */
1834
+ async function setRoomTopic(roomId, topic) {
1835
+ if (!client)
1836
+ throw new Error('chat: setRoomTopic called before start()');
1837
+ const room = client.getRoom(roomId);
1838
+ if (!room)
1839
+ throw new Error(`chat: not in room ${roomId}`);
1840
+ if (!canSetTopic(client, room)) {
1841
+ throw new Error(`chat: not allowed to set the topic of ${roomId}`);
1842
+ }
1843
+ await client.sendStateEvent(roomId, EventType.RoomTopic, { topic: normaliseTopic(topic) }, '');
1844
+ }
1616
1845
  function pinnedEventIds(room) {
1617
1846
  const content = room.currentState
1618
1847
  .getStateEvents(EventType.RoomPinnedEvents, '')
@@ -1967,6 +2196,7 @@ export function createChatClient(options) {
1967
2196
  async function swapClient(target, creds, wipeStore) {
1968
2197
  disposeClient(target);
1969
2198
  cryptoClosed = true;
2199
+ await destroyStore(target.store);
1970
2200
  let wiped = !wipeStore;
1971
2201
  let created;
1972
2202
  for (let delay = REBUILD_RETRY_MS; !created; delay = Math.min(delay * 2, REBUILD_RETRY_MAX_MS)) {
@@ -1976,7 +2206,26 @@ export function createChatClient(options) {
1976
2206
  if (!wiped)
1977
2207
  await target.store.deleteAllData();
1978
2208
  wiped = true;
1979
- created = await buildClient(creds);
2209
+ if (client !== target)
2210
+ return undefined;
2211
+ // Registered with `stop()`, which waits on it; a build `stop()`
2212
+ // overtook destroys its own store and answers `undefined`.
2213
+ const building = buildClient(creds).then(async (built) => {
2214
+ if (client !== target) {
2215
+ disposeClient(built);
2216
+ await destroyStore(built.store);
2217
+ return undefined;
2218
+ }
2219
+ return built;
2220
+ });
2221
+ const tracked = building.catch(() => undefined);
2222
+ buildsInFlight.add(tracked);
2223
+ try {
2224
+ created = await building;
2225
+ }
2226
+ finally {
2227
+ buildsInFlight.delete(tracked);
2228
+ }
1980
2229
  }
1981
2230
  catch {
1982
2231
  await new Promise((resolve) => setTimeout(resolve, delay));
@@ -1984,6 +2233,7 @@ export function createChatClient(options) {
1984
2233
  }
1985
2234
  if (client !== target) {
1986
2235
  disposeClient(created);
2236
+ await destroyStore(created.store);
1987
2237
  return undefined;
1988
2238
  }
1989
2239
  if (latestToken)
@@ -1997,6 +2247,15 @@ export function createChatClient(options) {
1997
2247
  target.stopClient();
1998
2248
  target.removeAllListeners();
1999
2249
  }
2250
+ /** Never rejects: a failed destroy is reported and teardown goes on. */
2251
+ async function destroyStore(store) {
2252
+ try {
2253
+ await store.destroy();
2254
+ }
2255
+ catch (error) {
2256
+ console.error('chat: store destroy failed', error);
2257
+ }
2258
+ }
2000
2259
  async function buildClient(creds) {
2001
2260
  if (secretStorageUserId !== creds.userId)
2002
2261
  secretStorageKeys.clear();
@@ -2021,9 +2280,15 @@ export function createChatClient(options) {
2021
2280
  },
2022
2281
  },
2023
2282
  });
2024
- if (encryptionEnabled)
2025
- await initCrypto(created);
2026
- await store.startup();
2283
+ try {
2284
+ if (encryptionEnabled)
2285
+ await initCrypto(created);
2286
+ await store.startup();
2287
+ }
2288
+ catch (error) {
2289
+ await destroyStore(store);
2290
+ throw error;
2291
+ }
2027
2292
  return created;
2028
2293
  }
2029
2294
  function attachListeners(created) {
@@ -2063,8 +2328,16 @@ export function createChatClient(options) {
2063
2328
  async function start() {
2064
2329
  if (starting)
2065
2330
  return starting;
2331
+ const myGeneration = generation;
2332
+ const cancelled = () => generation !== myGeneration;
2066
2333
  const attempt = (async () => {
2334
+ // Never open the IndexedDB while the previous one is still closing.
2335
+ await teardown;
2336
+ if (cancelled())
2337
+ throw new ChatStartCancelledError();
2067
2338
  const body = await performExchange();
2339
+ if (cancelled())
2340
+ throw new ChatStartCancelledError();
2068
2341
  // Built before anything touches the outer closure's state (`client`,
2069
2342
  // the listeners, the refresh timer): a WASM fetch or a blocked
2070
2343
  // IndexedDB can throw inside `buildClient`, and `created` is still a
@@ -2074,12 +2347,38 @@ export function createChatClient(options) {
2074
2347
  // client exists, as `IndexedDBStore` requires (it needs
2075
2348
  // `setUserCreator`, which the client constructor calls, before it can
2076
2349
  // replay persisted `m.presence`).
2077
- const created = await buildClient({
2350
+ // `stop()` waits on `building`, which also destroys a store whose
2351
+ // start was overtaken.
2352
+ const building = buildClient({
2078
2353
  baseUrl: body.homeserver,
2079
2354
  userId: body.user_id,
2080
2355
  accessToken: body.access_token,
2081
2356
  deviceId: body.device_id,
2357
+ }).then(async (built) => {
2358
+ if (cancelled()) {
2359
+ disposeClient(built);
2360
+ await destroyStore(built.store);
2361
+ }
2362
+ return built;
2082
2363
  });
2364
+ const tracked = building.catch(() => undefined);
2365
+ buildsInFlight.add(tracked);
2366
+ let created;
2367
+ try {
2368
+ created = await building;
2369
+ }
2370
+ catch (error) {
2371
+ if (cancelled()) {
2372
+ console.error('chat: build failed after stop()', error);
2373
+ throw new ChatStartCancelledError({ cause: error });
2374
+ }
2375
+ throw error;
2376
+ }
2377
+ finally {
2378
+ buildsInFlight.delete(tracked);
2379
+ }
2380
+ if (cancelled())
2381
+ throw new ChatStartCancelledError();
2083
2382
  client = created;
2084
2383
  attachListeners(created);
2085
2384
  scheduleRefresh(body.expires_at);
@@ -2128,8 +2427,19 @@ export function createChatClient(options) {
2128
2427
  starting = undefined;
2129
2428
  clearTimeout(refreshTimer);
2130
2429
  refreshTimer = undefined;
2131
- if (client)
2132
- disposeClient(client);
2430
+ const stopped = client;
2431
+ if (stopped)
2432
+ disposeClient(stopped);
2433
+ generation += 1;
2434
+ const previous = teardown;
2435
+ const building = [...buildsInFlight];
2436
+ buildsInFlight.clear();
2437
+ teardown = (async () => {
2438
+ await previous;
2439
+ await Promise.all(building);
2440
+ if (stopped)
2441
+ await destroyStore(stopped.store);
2442
+ })();
2133
2443
  cryptoClosed = false;
2134
2444
  // A recovery still sleeping in `swapClient` must not make the next
2135
2445
  // client's recovery wait on it.
@@ -2137,6 +2447,7 @@ export function createChatClient(options) {
2137
2447
  resyncing = undefined;
2138
2448
  client = undefined;
2139
2449
  setStatus('offline');
2450
+ return teardown;
2140
2451
  }
2141
2452
  function onRoomsChanged(listener) {
2142
2453
  listeners.add(listener);
@@ -2333,10 +2644,20 @@ export function createChatClient(options) {
2333
2644
  void fetchAutomaticStatus(userId);
2334
2645
  try {
2335
2646
  const raw = await target.getExtendedProfileProperty(userId, STATUS_PROFILE_KEY);
2647
+ // A reply that lands after `stop()` or a client swap must not write;
2648
+ // the placeholder goes, so the next read fetches through the live client.
2649
+ if (client !== target) {
2650
+ if (chatStatusCache.get(userId) === null)
2651
+ chatStatusCache.delete(userId);
2652
+ return;
2653
+ }
2336
2654
  notifyStatusChanged(userId, isChatStatus(raw) ? raw : null);
2337
2655
  }
2338
2656
  catch {
2339
- notifyStatusChanged(userId, null);
2657
+ if (client === target)
2658
+ notifyStatusChanged(userId, null);
2659
+ else if (chatStatusCache.get(userId) === null)
2660
+ chatStatusCache.delete(userId);
2340
2661
  }
2341
2662
  }
2342
2663
  /** See `ChatClient.status`. Exported as `status` on the returned client
@@ -2667,6 +2988,10 @@ export function createChatClient(options) {
2667
2988
  toggleReaction,
2668
2989
  pinMessage,
2669
2990
  unpinMessage,
2991
+ setRoomTopic,
2992
+ createRoom,
2993
+ browseRooms,
2994
+ joinBrowsableRoom,
2670
2995
  pinnedMessages,
2671
2996
  startDirectMessage,
2672
2997
  hideDirectMessage,
@@ -18,8 +18,17 @@ export async function exchange(exchangeUrl, getAccessToken, deviceId) {
18
18
  if (!response.ok) {
19
19
  let reason;
20
20
  try {
21
+ // The shared estate envelope (`@wtfalch/contracts`):
22
+ // `{ error: { code, message, reason? } }`. `reason`, when the
23
+ // service sent one, is the more specific of the two -- `code` is
24
+ // only the closed nine-value set.
21
25
  const problem = (await response.json());
22
- reason = typeof problem.reason === 'string' ? problem.reason : undefined;
26
+ reason =
27
+ typeof problem.error?.reason === 'string'
28
+ ? problem.error.reason
29
+ : typeof problem.error?.code === 'string'
30
+ ? problem.error.code
31
+ : undefined;
23
32
  }
24
33
  catch {
25
34
  // The body was not JSON, or was empty. The status is still enough to
@@ -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 { ChatStartCancelledError, 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 { ChatStartCancelledError, createChatClient, MAX_ROOM_NAME_LENGTH, MAX_TOPIC_LENGTH, MAX_UPLOAD_BYTES, normaliseTopic, } from "./client.js";