@wtfalch/chat 0.9.0 → 0.11.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.
@@ -1,57 +0,0 @@
1
- import { installFakeUploads } from "./xhr.js";
2
- let original;
3
- const routes = [];
4
- /** `.example.test` is reserved: no such host can ever exist, so a request
5
- * to one is always meant for a fake. It only reaches the fallthrough when
6
- * the fake that would have answered it has already been disposed -- a
7
- * request still in flight when a test ended. Such a request is left
8
- * hanging rather than answered: a client nobody is using any more has no
9
- * business succeeding, and any answer at all -- a real DNS failure, or a
10
- * 404 -- comes back as a rejection inside matrix-js-sdk that no test can
11
- * reach and vitest reports as an unhandled error. */
12
- function isFakeHost(input) {
13
- try {
14
- const url = input instanceof Request ? input.url : String(input);
15
- return new URL(url).hostname.endsWith('.example.test');
16
- }
17
- catch {
18
- return false;
19
- }
20
- }
21
- function patched(input, init) {
22
- for (const route of routes) {
23
- const answered = route(input, init);
24
- if (answered)
25
- return answered;
26
- }
27
- if (isFakeHost(input))
28
- return new Promise(() => { });
29
- if (!original) {
30
- throw new Error('fake chat: no route matched and the real fetch was not captured');
31
- }
32
- return original(input, init);
33
- }
34
- /** Registers `route`. Returns a function that unregisters it.
35
- *
36
- * `globalThis.fetch` stays patched once the first route is installed, and
37
- * is never put back: a request made to a disposed fake is still in flight
38
- * when its route goes, and restoring the real `fetch` underneath it sends
39
- * that request to DNS. Everything but a `.example.test` host goes straight
40
- * through to the real `fetch` either way, so nothing else is affected. */
41
- export function installFetchRoute(route) {
42
- installFakeUploads();
43
- if (!original) {
44
- original = globalThis.fetch;
45
- globalThis.fetch = patched;
46
- }
47
- routes.push(route);
48
- let removed = false;
49
- return () => {
50
- if (removed)
51
- return;
52
- removed = true;
53
- const index = routes.indexOf(route);
54
- if (index >= 0)
55
- routes.splice(index, 1);
56
- };
57
- }
@@ -1,4 +0,0 @@
1
- import type { FakeRoomSeed } from './server.ts';
2
- /** A couple of rooms, for a story or a test that wants something to look
3
- * at without seeding its own. */
4
- export declare const SAMPLE_ROOMS: FakeRoomSeed[];
@@ -1,6 +0,0 @@
1
- /** A couple of rooms, for a story or a test that wants something to look
2
- * at without seeding its own. */
3
- export const SAMPLE_ROOMS = [
4
- { id: '!general:chat.example.test', name: 'general', isDirect: false },
5
- { id: '!ada:chat.example.test', name: 'Ada Lovelace', isDirect: true },
6
- ];
@@ -1,400 +0,0 @@
1
- export type FakeRoomSeed = {
2
- id: string;
3
- name: string;
4
- /** Defaults to `false`. Seeds the account's `m.direct` data, keyed by the
5
- * fake peer, unless `members` says who the room is with. */
6
- isDirect?: boolean;
7
- /** Seeds `unread_notifications.notification_count`. Defaults to `0`. */
8
- notificationCount?: number;
9
- /** Seeds `unread_notifications.highlight_count` -- the subset of
10
- * `notificationCount` that mentions this account. Defaults to `0`. */
11
- highlightCount?: number;
12
- /** An `m.space` rather than a room -- the company space. Its `members`
13
- * are what `client.people()` reads. Defaults to `false`. */
14
- isSpace?: boolean;
15
- /** Who else is joined, beyond the fake account itself. Defaults to none
16
- * for a channel; a direct room with no `members` is recorded against
17
- * the fake peer. */
18
- members?: FakeMember[];
19
- /** Who else is invited but has not joined -- a DM whose other side has
20
- * not accepted yet. Defaults to none. */
21
- invited?: FakeMember[];
22
- /** Messages already in the room when the first sync lands, oldest first.
23
- * Defaults to none. */
24
- messages?: FakeMessageSeed[];
25
- /** Seeds an `m.room.encryption` state event -- the one thing `search`
26
- * reads to report a room unsearchable (agora#252). Defaults to
27
- * `false`. */
28
- encrypted?: boolean;
29
- /** Seeds an `m.room.power_levels` state event with `events_default: 100`
30
- * -- the one thing `ChatRoomSummary.archived` and `AdminChannel.archived`
31
- * both read to report a room's member writes locked. Defaults to
32
- * `false`, which seeds no such event (an unset `events_default`
33
- * defaults to `0` in real Matrix, same as the client and admin reads
34
- * treat it). */
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>;
45
- /** Seeds this room as an unanswered invitation to the fake account
46
- * itself, rather than a room it has joined -- a `rooms.invite` entry
47
- * with the stripped state real Matrix delivers one in, the one shape
48
- * `membership: 'invite'` ever comes from. `messages` is ignored: a real
49
- * invitee's client has no timeline to read before joining. Defaults to
50
- * `undefined` (the room is joined, as every other seed is). */
51
- invitedAccount?: {
52
- inviter?: string;
53
- };
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
- };
69
- export type FakeMessageSeed = {
70
- /** Defaults to a minted `$seeded-<n>`. Give one to reply to it. */
71
- id?: string;
72
- body: string;
73
- /** Defaults to the fake peer. */
74
- sender?: string;
75
- /** The id of the message this replies to, making it a `m.thread` reply.
76
- * Matrix threads are one level, so this is always the root's id. */
77
- threadRootId?: string;
78
- /** Seeds an `m.file`/`m.image` in one step, without a real upload round
79
- * trip -- what `roomFiles` (#9) reads `content.url`/`content.info` off
80
- * of. `body` is still the file's name, matching what a real client
81
- * sends. Cheap enough to seed the hundreds of messages a pagination
82
- * test needs. */
83
- attachment?: {
84
- mxcUri: string;
85
- mimeType: string;
86
- size: number;
87
- isImage?: boolean;
88
- };
89
- };
90
- export type FakeMember = {
91
- userId: string;
92
- /** Their `m.room.member` display name. Defaults to the user id. */
93
- name?: string;
94
- /** Marks this member a guest, carrying `GUEST_MARKER_KEY` on their
95
- * `m.room.member` content with `{ until: guestUntil }` -- what
96
- * `client.ts`'s `readGuest` reads into `ChatPerson.guest`. Omitted for
97
- * an ordinary member. */
98
- guestUntil?: string;
99
- };
100
- export type FakeChatServerOptions = {
101
- /** Defaults to a distinct `https://chat.<random>.example.test`, so two
102
- * servers in one test never collide even if their callers forget to set
103
- * one. */
104
- homeserver?: string;
105
- userId?: string;
106
- rooms?: FakeRoomSeed[];
107
- /** How long a minted Matrix token lasts, in ms. Long enough that a test
108
- * which does not care about refresh timing never trips it by accident. */
109
- tokenLifetimeMs?: number;
110
- now?: () => number;
111
- /** Whether `/versions` advertises MSC4133 extended profiles. Defaults to
112
- * `true`; a test simulating production before
113
- * wtfalch/foundry#41 turns it on passes `false`, the same "off" every
114
- * company's Synapse ships with today (`docs/status.md`). */
115
- extendedProfilesEnabled?: boolean;
116
- };
117
- /**
118
- * A fake exchange endpoint and a fake homeserver, both answered by
119
- * intercepting `fetch` -- so `createChatClient`'s real wire code, and the
120
- * real matrix-js-sdk underneath it, run exactly as they would against
121
- * `apps/chat-service` and Synapse. See `intercept.ts`'s module comment.
122
- *
123
- * It implements only what `createChatClient`'s startup needs: `/versions`,
124
- * `/pushrules/`, filter creation, and `/sync`. Anything else falls through
125
- * to whatever else is installed, or the real network.
126
- *
127
- * `/sync` beyond the first request is a manual long-poll: it never answers
128
- * on its own. A test drives it explicitly with `addRoom` and
129
- * `invalidateCurrentToken`, after confirming the request has arrived with
130
- * `waitForParkedPoll()`.
131
- */
132
- export declare class FakeChatServer {
133
- #private;
134
- readonly homeserver: string;
135
- readonly exchangeUrl: string;
136
- /** Controls for upload failure and in-flight UI scenarios. */
137
- uploadBarrier: Promise<void> | null;
138
- uploadStatus: number;
139
- /** What `PUT .../state/m.room.pinned_events/` answers with -- 403 models
140
- * the power-level refusal a room whose power levels predate ticket #8
141
- * gives a member, which `pinMessage`/`unpinMessage` must reject on
142
- * rather than resolve quietly. */
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
- }>;
166
- /** What `PUT .../send/...` answers with -- anything but 200 fails the
167
- * send, with nothing stored. */
168
- sendStatus: number;
169
- /** Holds every thread follow `GET` until it resolves -- for a test of a
170
- * read that is still in flight when the person clicks. */
171
- threadFollowReadBarrier: Promise<void> | null;
172
- /** What a thread follow `GET` answers with. */
173
- threadFollowReadStatus: number;
174
- /** What a thread follow `PUT`/`DELETE` answers with -- anything but 200
175
- * fails the follow or unfollow, with nothing stored. */
176
- threadFollowWriteStatus: number;
177
- /** Every call to the thread follow route, in arrival order. */
178
- readonly threadFollowRequests: Array<{
179
- method: string;
180
- roomId: string;
181
- rootId: string;
182
- }>;
183
- readonly userId: string;
184
- /** The Matrix server name, as `userId` gives it -- what an `mxc://`
185
- * reference from this homeserver names. */
186
- readonly serverName: string;
187
- /** How many times `/_chat/exchange` has been called. */
188
- exchangeCount: number;
189
- /** Every Matrix access token this server has ever minted, oldest first --
190
- * for a test that asserts one was never logged. */
191
- readonly mintedTokens: string[];
192
- /** Every `m.read` receipt this server has answered, in arrival order --
193
- * for a test that asserts `markRoomRead` actually called the wire. */
194
- readonly receipts: Array<{
195
- roomId: string;
196
- eventId: string;
197
- }>;
198
- /** Every content report the client filed (#29), with the exact body it
199
- * sent. */
200
- readonly reports: Array<{
201
- roomId: string;
202
- eventId: string;
203
- body: unknown;
204
- }>;
205
- /** Every room `/createRoom` has made, in order -- for a test that asserts
206
- * what shape a DM was created in. */
207
- readonly createdRooms: Array<{
208
- id: string;
209
- isDirect: boolean;
210
- invite: string[];
211
- }>;
212
- /** Every event this server has accepted from the client, in order -- for
213
- * a test that asserts what relation a reply was sent with. */
214
- readonly sent: Array<{
215
- roomId: string;
216
- eventId: string;
217
- type: string;
218
- content: Record<string, unknown>;
219
- }>;
220
- /** Every file the client has uploaded, by media id -- so a test can
221
- * assert what went up, and so the download route has something to
222
- * answer with. */
223
- readonly media: Map<string, {
224
- bytes: ArrayBuffer;
225
- contentType: string;
226
- }>;
227
- /** Every media download this server has answered, with the header the
228
- * request carried -- for a test that asserts nothing reaches the
229
- * legacy unauthenticated endpoints, and that the token was sent. */
230
- readonly mediaRequests: Array<{
231
- path: string;
232
- authorised: boolean;
233
- }>;
234
- /** Who follows which thread, as `apps/chat-service`'s thread follow
235
- * route keeps it: `roomId rootId` -> whether the person unfollowed. A
236
- * thread with no entry is not followed. */
237
- readonly threadFollows: Map<string, {
238
- muted: boolean;
239
- }>;
240
- /** What `apps/chat-service`'s `GET /_chat/status/{userId}` holds per
241
- * person: the automatic `meeting` overlay a call pushed. No entry reads
242
- * as `{ kind: null, sequence: 0 }`, as the real route does. */
243
- readonly automaticStatuses: Map<string, {
244
- kind: "meeting" | null;
245
- sequence: number;
246
- }>;
247
- /** Every `PUT .../typing/...` this server has answered, in order -- for a
248
- * test that asserts `sendTyping` actually reached the wire, with what
249
- * it sent. */
250
- readonly sentTyping: Array<{
251
- roomId: string;
252
- userId: string;
253
- typing: boolean;
254
- timeoutMs?: number;
255
- }>;
256
- /** Every `PUT .../presence/{userId}/status` this server has answered, in
257
- * order -- the immediate half of `announcePresence`. */
258
- readonly sentPresence: Array<{
259
- userId: string;
260
- presence: string;
261
- }>;
262
- /** Set to refuse the next presence `PUT` with `M_LIMIT_EXCEEDED`, the
263
- * way a real Synapse refuses a second presence change inside ten
264
- * seconds (`rc_presence.per_user`). Clears itself after one refusal. */
265
- refuseNextPresence: boolean;
266
- /** The `set_presence` query parameter every `/sync` has carried, in
267
- * order, `undefined` where the client omitted it. This is the half that
268
- * actually makes an announcement survive, so a test that only checked
269
- * `sentPresence` would pass against a client that cannot hold anybody
270
- * away for longer than one poll. */
271
- readonly syncPresence: Array<string | undefined>;
272
- /** Every `PUT`/`DELETE` on an MSC4133 extended-profile property this
273
- * server has answered, in order -- what `ChatClient.setOwnStatus`
274
- * writes. `value: undefined` records a delete. */
275
- readonly extendedProfileWrites: Array<{
276
- userId: string;
277
- key: string;
278
- value: unknown;
279
- }>;
280
- /** Every `PUT .../sendToDevice/...` this server has answered, in order --
281
- * what a `CryptoApi` verification request (chat#69) sends on its way
282
- * out. Recorded rather than delivered to another device: the methods
283
- * this fake exists for (`getVerificationRequestsToDeviceInProgress`)
284
- * read the sender's own `OlmMachine` state, which only needs the send to
285
- * succeed, not to be received. */
286
- readonly sentToDevice: Array<{
287
- eventType: string;
288
- body: unknown;
289
- }>;
290
- /** Rooms currently carrying the room-scoped `dont_notify` push rule, for
291
- * a test that wants to assert on the server's own state rather than
292
- * only through the client's `rooms()`. */
293
- get mutedRoomIds(): string[];
294
- /** Rooms currently carrying MSC2867's marked-unread flag, for a test that
295
- * wants to assert on the server's own state rather than only through the
296
- * client's `rooms()`. */
297
- get markedUnreadRoomIds(): string[];
298
- constructor(options?: FakeChatServerOptions);
299
- /** Sets `userId`'s MSC4133 extended-profile `key` directly, for a test
300
- * simulating "somebody else already has this set on the server" --
301
- * `ChatClient.status`'s background fetch then reads it exactly as it
302
- * would a real peer's. Real Matrix never lets a client PUT anyone's
303
- * profile but its own, which is why this exists as a server-side seed
304
- * rather than something `setOwnStatus` could reach. */
305
- seedExtendedProfile(userId: string, key: string, value: unknown): void;
306
- dispose(): void;
307
- /** Resolves once a `/sync` request is parked waiting for a test to drive
308
- * it -- immediately if one already is. */
309
- waitForParkedPoll(): Promise<void>;
310
- /** Delivers a parked poll as if another of this account's own devices
311
- * had just written `type` room account data for `roomId` -- a draft,
312
- * most likely -- the way a real incremental `/sync` carries a change
313
- * made from elsewhere. Throws if nothing is parked -- await
314
- * `waitForParkedPoll()` first. */
315
- receiveRoomAccountData(roomId: string, type: string, content: Record<string, unknown>): void;
316
- /** Adds a room and, if a poll is parked, delivers it now. Throws if
317
- * nothing is parked -- await `waitForParkedPoll()` first. */
318
- addRoom(seed: FakeRoomSeed): void;
319
- /** Answers a parked poll with nothing new -- proving the connection is
320
- * healthy (a real incremental sync, just an empty one) without adding a
321
- * room. Throws if nothing is parked. */
322
- respondEmpty(): void;
323
- /** Ends every currently-minted token, as if the person's session had been
324
- * revoked or the token had simply expired server-side. If a poll is
325
- * parked, it is answered with `M_UNKNOWN_TOKEN` immediately; otherwise
326
- * the next request to arrive gets it. */
327
- invalidateCurrentToken(): void;
328
- /** Answers a parked poll with a `400`, as Synapse does when it refuses
329
- * the client's stored `since` position (confirmed live after a long
330
- * enough time offline). Throws if nothing is parked. */
331
- refuseCurrentPoll(): void;
332
- /** Delivers a parked poll as an existing, already-known room receiving
333
- * one new message from the fake peer -- a timeline event and a bumped
334
- * notification count together, the way a real incremental `/sync`
335
- * carries both at once. `highlightCount` defaults to `0`: an ordinary
336
- * message that does not mention this account, same as Matrix would
337
- * report. Pass it to simulate a mention arriving. Returns the minted
338
- * event id, for a test that then calls `markRoomRead` against it.
339
- * Throws if nothing is parked. */
340
- receiveMessage(roomId: string, notificationCount?: number, highlightCount?: number): string;
341
- /** Delivers a parked poll renaming an already-known room -- an
342
- * `m.room.name` state event, the way a real incremental `/sync` carries
343
- * a rename. Throws if nothing is parked. */
344
- renameRoom(roomId: string, name: string): void;
345
- /** Delivers a parked poll with the fake account leaving `roomId` -- a
346
- * `rooms.leave` block, the way a real incremental `/sync` reports a kick
347
- * or a self-leave. Throws if nothing is parked. */
348
- leaveRoom(roomId: string): void;
349
- /** Delivers a parked poll as `m.typing` for `roomId` -- Matrix's own
350
- * shape: an EDU with no sender of its own, always the room's complete
351
- * current set of typing user ids, never a diff against the last one.
352
- * Pass an empty list for what Matrix does on its own once a typing
353
- * state's timeout elapses server-side; this fake never does that by
354
- * itself, so a test drives both halves explicitly. Throws if nothing is
355
- * parked. */
356
- receiveTyping(roomId: string, userIds: string[]): void;
357
- /** Delivers a parked poll as `userId`'s public read receipt on
358
- * `eventId` in `roomId` -- the `m.receipt` EDU another person's client
359
- * causes by reading. Throws if nothing is parked. */
360
- receiveReceipt(roomId: string, eventId: string, userId: string): void;
361
- /** Delivers a parked poll as an `m.presence` EDU for somebody else --
362
- * Matrix's own three states (`online`/`unavailable`/`offline`), or
363
- * MSC3026's unstable `org.matrix.msc3026.busy` -- for a test that drives
364
- * `presence()`/`onPresenceChanged` without a live homeserver. Presence
365
- * EDUs are account-wide, not room-scoped, so this carries no room id --
366
- * see `#answerParked`'s own `presence.events`. Throws if nothing is
367
- * parked. */
368
- receivePresence(userId: string, presence: string): void;
369
- /** Delivers a parked poll as somebody else reacting to a message.
370
- * Returns the minted event id, so a test can then redact it. Throws if
371
- * nothing is parked. */
372
- receiveReaction(roomId: string, targetId: string, key: string, sender?: string): string;
373
- /** Delivers a parked poll as one more message arriving in an existing
374
- * room -- threaded, when `threadRootId` is given. Returns the minted
375
- * event id. Throws if nothing is parked. */
376
- receiveThreadReply(roomId: string, threadRootId: string, body?: string): string;
377
- /** Delivers a parked poll as somebody else editing one of their own
378
- * messages: an `m.replace` carrying `m.new_content`, which is the whole
379
- * of how Matrix edits a message. Returns the edit's own event id.
380
- * Throws if nothing is parked. */
381
- receiveEdit(roomId: string, targetId: string, body: string, sender?: string): string;
382
- /** Delivers a parked poll as a message being redacted. The target keeps
383
- * its place in the room's record with its content emptied, exactly as
384
- * `#route`'s own redact endpoint does and as Synapse does -- a redacted
385
- * event is still an event. Throws if nothing is parked. */
386
- receiveRedaction(roomId: string, targetId: string, sender?: string): string;
387
- /** The device ids that have uploaded `device_keys` so far. */
388
- uploadedDeviceIds(): string[];
389
- /** Delivers to-device events (a verification request, say) to the one
390
- * client this fake serves, on its next `/sync` -- straight away if a poll
391
- * is parked. Each event is `{ type, sender, content }`. Only one client
392
- * can be answered at a time: this fake has a single parked poll, so it
393
- * cannot route a to-device message from one live client to another, and
394
- * `sendToDevice` writes stay recorded in `sentToDevice` only. */
395
- deliverToDevice(events: Array<{
396
- type: string;
397
- sender: string;
398
- content: unknown;
399
- }>): void;
400
- }