@wtfalch/chat 0.1.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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +293 -0
  3. package/dist/chat/admin/admin.css +78 -0
  4. package/dist/chat/admin/index.d.ts +92 -0
  5. package/dist/chat/admin/index.js +124 -0
  6. package/dist/chat/admin/react.d.ts +40 -0
  7. package/dist/chat/admin/react.js +169 -0
  8. package/dist/chat/chat.css +1003 -0
  9. package/dist/chat/client.d.ts +30 -0
  10. package/dist/chat/client.js +1300 -0
  11. package/dist/chat/exchange.d.ts +9 -0
  12. package/dist/chat/exchange.js +31 -0
  13. package/dist/chat/fake/index.d.ts +27 -0
  14. package/dist/chat/fake/index.js +48 -0
  15. package/dist/chat/fake/intercept.d.ts +21 -0
  16. package/dist/chat/fake/intercept.js +57 -0
  17. package/dist/chat/fake/sample.d.ts +4 -0
  18. package/dist/chat/fake/sample.js +6 -0
  19. package/dist/chat/fake/server.d.ts +168 -0
  20. package/dist/chat/fake/server.js +811 -0
  21. package/dist/chat/fake/xhr.d.ts +3 -0
  22. package/dist/chat/fake/xhr.js +104 -0
  23. package/dist/chat/index.d.ts +10 -0
  24. package/dist/chat/index.js +9 -0
  25. package/dist/chat/markdown.d.ts +29 -0
  26. package/dist/chat/markdown.js +161 -0
  27. package/dist/chat/react/Attachment.d.ts +39 -0
  28. package/dist/chat/react/Attachment.js +113 -0
  29. package/dist/chat/react/Chat.d.ts +48 -0
  30. package/dist/chat/react/Chat.js +139 -0
  31. package/dist/chat/react/Composer.d.ts +25 -0
  32. package/dist/chat/react/Composer.js +157 -0
  33. package/dist/chat/react/MessageRow.d.ts +21 -0
  34. package/dist/chat/react/MessageRow.js +114 -0
  35. package/dist/chat/react/NewDirectMessage.d.ts +23 -0
  36. package/dist/chat/react/NewDirectMessage.js +47 -0
  37. package/dist/chat/react/ThreadPanel.d.ts +25 -0
  38. package/dist/chat/react/ThreadPanel.js +17 -0
  39. package/dist/chat/react/Timeline.d.ts +27 -0
  40. package/dist/chat/react/Timeline.js +120 -0
  41. package/dist/chat/react/index.d.ts +7 -0
  42. package/dist/chat/react/index.js +6 -0
  43. package/dist/chat/react/mentions.d.ts +34 -0
  44. package/dist/chat/react/mentions.js +70 -0
  45. package/dist/chat/react/scroll.d.ts +26 -0
  46. package/dist/chat/react/scroll.js +27 -0
  47. package/dist/chat/react/timelineLayout.d.ts +26 -0
  48. package/dist/chat/react/timelineLayout.js +47 -0
  49. package/dist/chat/sanitize.d.ts +49 -0
  50. package/dist/chat/sanitize.js +264 -0
  51. package/dist/chat/store.d.ts +16 -0
  52. package/dist/chat/store.js +25 -0
  53. package/dist/chat/types.d.ts +340 -0
  54. package/dist/chat/types.js +1 -0
  55. package/package.json +88 -0
@@ -0,0 +1,9 @@
1
+ import type { ExchangeBody } from './types.ts';
2
+ /**
3
+ * Swap a current ZITADEL access token for a Matrix one, through the chat
4
+ * service's `POST /_chat/exchange` (`apps/chat-service/src/exchange.ts`).
5
+ *
6
+ * Never logs the ZITADEL token, the returned Matrix token, or the response
7
+ * body: a refusal is reported by status and reason code alone.
8
+ */
9
+ export declare function exchange(exchangeUrl: string, getAccessToken: () => string | Promise<string>, deviceId: string): Promise<ExchangeBody>;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Swap a current ZITADEL access token for a Matrix one, through the chat
3
+ * service's `POST /_chat/exchange` (`apps/chat-service/src/exchange.ts`).
4
+ *
5
+ * Never logs the ZITADEL token, the returned Matrix token, or the response
6
+ * body: a refusal is reported by status and reason code alone.
7
+ */
8
+ export async function exchange(exchangeUrl, getAccessToken, deviceId) {
9
+ const zitadelToken = await getAccessToken();
10
+ const response = await fetch(exchangeUrl, {
11
+ method: 'POST',
12
+ headers: {
13
+ Authorization: `Bearer ${zitadelToken}`,
14
+ 'Content-Type': 'application/json',
15
+ },
16
+ body: JSON.stringify({ device_id: deviceId }),
17
+ });
18
+ if (!response.ok) {
19
+ let reason;
20
+ try {
21
+ const problem = (await response.json());
22
+ reason = typeof problem.reason === 'string' ? problem.reason : undefined;
23
+ }
24
+ catch {
25
+ // The body was not JSON, or was empty. The status is still enough to
26
+ // report.
27
+ }
28
+ throw new Error(`chat exchange refused: ${response.status}${reason ? ` (${reason})` : ''}`);
29
+ }
30
+ return (await response.json());
31
+ }
@@ -0,0 +1,27 @@
1
+ import type { ChatClient } from '../types.ts';
2
+ import { FakeChatServer, type FakeChatServerOptions } from './server.ts';
3
+ export { FakeChatServer } from './server.ts';
4
+ export type { FakeChatServerOptions, FakeMember, FakeMessageSeed, FakeRoomSeed, } from './server.ts';
5
+ export { SAMPLE_ROOMS } from './sample.ts';
6
+ export type FakeChatOptions = FakeChatServerOptions & {
7
+ storeName?: string;
8
+ deviceId?: string;
9
+ };
10
+ export type FakeChat = {
11
+ /** A real `ChatClient`. Everything this package exports works against it
12
+ * unchanged, through the real `createChatClient`. */
13
+ client: ChatClient;
14
+ /** The homeserver behind it, to drive more rooms or a token refusal, or
15
+ * to assert on how many times the exchange was called. */
16
+ server: FakeChatServer;
17
+ /** Stops the client and uninstalls the fake. Call it when a story or a
18
+ * test is done. */
19
+ dispose: () => void;
20
+ };
21
+ /**
22
+ * A client and the fake exchange/homeserver behind it.
23
+ *
24
+ * Seeded with `SAMPLE_ROOMS` unless told otherwise, because a fake with no
25
+ * rooms demonstrates the empty state and nothing else.
26
+ */
27
+ export declare function fakeChat(options?: FakeChatOptions): FakeChat;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * `@wtfalch/chat/fake` -- a real `createChatClient`, wired to a
3
+ * fake exchange and a fake homeserver instead of the network, for stories
4
+ * and tests. See `server.ts`'s module comment for why it fakes the
5
+ * transport rather than the client.
6
+ *
7
+ * ```ts
8
+ * import { fakeChat } from '@wtfalch/chat/fake'
9
+ *
10
+ * const { client, dispose } = fakeChat()
11
+ * await client.start()
12
+ * client.rooms() // SAMPLE_ROOMS, joined
13
+ * dispose()
14
+ * ```
15
+ */
16
+ import { createChatClient } from "../client.js";
17
+ import { SAMPLE_ROOMS } from "./sample.js";
18
+ import { FakeChatServer } from "./server.js";
19
+ export { FakeChatServer } from "./server.js";
20
+ export { SAMPLE_ROOMS } from "./sample.js";
21
+ /**
22
+ * A client and the fake exchange/homeserver behind it.
23
+ *
24
+ * Seeded with `SAMPLE_ROOMS` unless told otherwise, because a fake with no
25
+ * rooms demonstrates the empty state and nothing else.
26
+ */
27
+ export function fakeChat(options = {}) {
28
+ const { storeName, deviceId, ...serverOptions } = options;
29
+ const server = new FakeChatServer({ rooms: SAMPLE_ROOMS, ...serverOptions });
30
+ const client = createChatClient({
31
+ exchangeUrl: server.exchangeUrl,
32
+ getAccessToken: () => 'fake-zitadel-token',
33
+ deviceId: deviceId ?? 'fake-device',
34
+ storeName: storeName ?? 'fake',
35
+ });
36
+ let disposed = false;
37
+ return {
38
+ client,
39
+ server,
40
+ dispose: () => {
41
+ if (disposed)
42
+ return;
43
+ disposed = true;
44
+ client.stop();
45
+ server.dispose();
46
+ },
47
+ };
48
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Global `fetch` interception, shared by every `FakeChatServer`.
3
+ *
4
+ * **A fake transport, not a fake API** -- the same choice `@wtfalch/email`'s
5
+ * `fakeMail()` makes. `createChatClient` and matrix-js-sdk run unchanged; only
6
+ * the network is answered by memory instead of a real homeserver.
7
+ *
8
+ * Unlike a single captured `route` callback, this keeps a list: two fakes --
9
+ * two companies' homeservers -- can be installed at once, each answering only
10
+ * its own origin and falling through to the next. The real `fetch` is
11
+ * restored once the last one is disposed.
12
+ */
13
+ export type FetchRoute = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> | null;
14
+ /** Registers `route`. Returns a function that unregisters it.
15
+ *
16
+ * `globalThis.fetch` stays patched once the first route is installed, and
17
+ * is never put back: a request made to a disposed fake is still in flight
18
+ * when its route goes, and restoring the real `fetch` underneath it sends
19
+ * that request to DNS. Everything but a `.example.test` host goes straight
20
+ * through to the real `fetch` either way, so nothing else is affected. */
21
+ export declare function installFetchRoute(route: FetchRoute): () => void;
@@ -0,0 +1,57 @@
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
+ }
@@ -0,0 +1,4 @@
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[];
@@ -0,0 +1,6 @@
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
+ ];
@@ -0,0 +1,168 @@
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
+ /** An `m.space` rather than a room -- the company space. Its `members`
10
+ * are what `client.people()` reads. Defaults to `false`. */
11
+ isSpace?: boolean;
12
+ /** Who else is joined, beyond the fake account itself. Defaults to none
13
+ * for a channel; a direct room with no `members` is recorded against
14
+ * the fake peer. */
15
+ members?: FakeMember[];
16
+ /** Who else is invited but has not joined -- a DM whose other side has
17
+ * not accepted yet. Defaults to none. */
18
+ invited?: FakeMember[];
19
+ /** Messages already in the room when the first sync lands, oldest first.
20
+ * Defaults to none. */
21
+ messages?: FakeMessageSeed[];
22
+ };
23
+ export type FakeMessageSeed = {
24
+ /** Defaults to a minted `$seeded-<n>`. Give one to reply to it. */
25
+ id?: string;
26
+ body: string;
27
+ /** Defaults to the fake peer. */
28
+ sender?: string;
29
+ /** The id of the message this replies to, making it a `m.thread` reply.
30
+ * Matrix threads are one level, so this is always the root's id. */
31
+ threadRootId?: string;
32
+ };
33
+ export type FakeMember = {
34
+ userId: string;
35
+ /** Their `m.room.member` display name. Defaults to the user id. */
36
+ name?: string;
37
+ };
38
+ export type FakeChatServerOptions = {
39
+ /** Defaults to a distinct `https://chat.<random>.example.test`, so two
40
+ * servers in one test never collide even if their callers forget to set
41
+ * one. */
42
+ homeserver?: string;
43
+ userId?: string;
44
+ rooms?: FakeRoomSeed[];
45
+ /** How long a minted Matrix token lasts, in ms. Long enough that a test
46
+ * which does not care about refresh timing never trips it by accident. */
47
+ tokenLifetimeMs?: number;
48
+ now?: () => number;
49
+ };
50
+ /**
51
+ * A fake exchange endpoint and a fake homeserver, both answered by
52
+ * intercepting `fetch` -- so `createChatClient`'s real wire code, and the
53
+ * real matrix-js-sdk underneath it, run exactly as they would against
54
+ * `apps/chat-service` and Synapse. See `intercept.ts`'s module comment.
55
+ *
56
+ * It implements only what `createChatClient`'s startup needs: `/versions`,
57
+ * `/pushrules/`, filter creation, and `/sync`. Anything else falls through
58
+ * to whatever else is installed, or the real network.
59
+ *
60
+ * `/sync` beyond the first request is a manual long-poll: it never answers
61
+ * on its own. A test drives it explicitly with `addRoom` and
62
+ * `invalidateCurrentToken`, after confirming the request has arrived with
63
+ * `waitForParkedPoll()`.
64
+ */
65
+ export declare class FakeChatServer {
66
+ #private;
67
+ readonly homeserver: string;
68
+ readonly exchangeUrl: string;
69
+ /** Controls for upload failure and in-flight UI scenarios. */
70
+ uploadBarrier: Promise<void> | null;
71
+ uploadStatus: number;
72
+ readonly userId: string;
73
+ /** The Matrix server name, as `userId` gives it -- what an `mxc://`
74
+ * reference from this homeserver names. */
75
+ readonly serverName: string;
76
+ /** How many times `/_chat/exchange` has been called. */
77
+ exchangeCount: number;
78
+ /** Every Matrix access token this server has ever minted, oldest first --
79
+ * for a test that asserts one was never logged. */
80
+ readonly mintedTokens: string[];
81
+ /** Every `m.read` receipt this server has answered, in arrival order --
82
+ * for a test that asserts `markRoomRead` actually called the wire. */
83
+ readonly receipts: Array<{
84
+ roomId: string;
85
+ eventId: string;
86
+ }>;
87
+ /** Every room `/createRoom` has made, in order -- for a test that asserts
88
+ * what shape a DM was created in. */
89
+ readonly createdRooms: Array<{
90
+ id: string;
91
+ isDirect: boolean;
92
+ invite: string[];
93
+ }>;
94
+ /** Every event this server has accepted from the client, in order -- for
95
+ * a test that asserts what relation a reply was sent with. */
96
+ readonly sent: Array<{
97
+ roomId: string;
98
+ type: string;
99
+ content: Record<string, unknown>;
100
+ }>;
101
+ /** Every file the client has uploaded, by media id -- so a test can
102
+ * assert what went up, and so the download route has something to
103
+ * answer with. */
104
+ readonly media: Map<string, {
105
+ bytes: ArrayBuffer;
106
+ contentType: string;
107
+ }>;
108
+ /** Every media download this server has answered, with the header the
109
+ * request carried -- for a test that asserts nothing reaches the
110
+ * legacy unauthenticated endpoints, and that the token was sent. */
111
+ readonly mediaRequests: Array<{
112
+ path: string;
113
+ authorised: boolean;
114
+ }>;
115
+ constructor(options?: FakeChatServerOptions);
116
+ dispose(): void;
117
+ /** Resolves once a `/sync` request is parked waiting for a test to drive
118
+ * it -- immediately if one already is. */
119
+ waitForParkedPoll(): Promise<void>;
120
+ /** Adds a room and, if a poll is parked, delivers it now. Throws if
121
+ * nothing is parked -- await `waitForParkedPoll()` first. */
122
+ addRoom(seed: FakeRoomSeed): void;
123
+ /** Answers a parked poll with nothing new -- proving the connection is
124
+ * healthy (a real incremental sync, just an empty one) without adding a
125
+ * room. Throws if nothing is parked. */
126
+ respondEmpty(): void;
127
+ /** Ends every currently-minted token, as if the person's session had been
128
+ * revoked or the token had simply expired server-side. If a poll is
129
+ * parked, it is answered with `M_UNKNOWN_TOKEN` immediately; otherwise
130
+ * the next request to arrive gets it. */
131
+ invalidateCurrentToken(): void;
132
+ /** Answers a parked poll with a `400`, as Synapse does when it refuses
133
+ * the client's stored `since` position (confirmed live after a long
134
+ * enough time offline). Throws if nothing is parked. */
135
+ refuseCurrentPoll(): void;
136
+ /** Delivers a parked poll as an existing, already-known room receiving
137
+ * one new message from the fake peer -- a timeline event and a bumped
138
+ * notification count together, the way a real incremental `/sync`
139
+ * carries both at once. Returns the minted event id, for a test that
140
+ * then calls `markRoomRead` against it. Throws if nothing is parked. */
141
+ receiveMessage(roomId: string, notificationCount?: number): string;
142
+ /** Delivers a parked poll renaming an already-known room -- an
143
+ * `m.room.name` state event, the way a real incremental `/sync` carries
144
+ * a rename. Throws if nothing is parked. */
145
+ renameRoom(roomId: string, name: string): void;
146
+ /** Delivers a parked poll with the fake account leaving `roomId` -- a
147
+ * `rooms.leave` block, the way a real incremental `/sync` reports a kick
148
+ * or a self-leave. Throws if nothing is parked. */
149
+ leaveRoom(roomId: string): void;
150
+ /** Delivers a parked poll as somebody else reacting to a message.
151
+ * Returns the minted event id, so a test can then redact it. Throws if
152
+ * nothing is parked. */
153
+ receiveReaction(roomId: string, targetId: string, key: string, sender?: string): string;
154
+ /** Delivers a parked poll as one more message arriving in an existing
155
+ * room -- threaded, when `threadRootId` is given. Returns the minted
156
+ * event id. Throws if nothing is parked. */
157
+ receiveThreadReply(roomId: string, threadRootId: string, body?: string): string;
158
+ /** Delivers a parked poll as somebody else editing one of their own
159
+ * messages: an `m.replace` carrying `m.new_content`, which is the whole
160
+ * of how Matrix edits a message. Returns the edit's own event id.
161
+ * Throws if nothing is parked. */
162
+ receiveEdit(roomId: string, targetId: string, body: string, sender?: string): string;
163
+ /** Delivers a parked poll as a message being redacted. The target keeps
164
+ * its place in the room's record with its content emptied, exactly as
165
+ * `#route`'s own redact endpoint does and as Synapse does -- a redacted
166
+ * event is still an event. Throws if nothing is parked. */
167
+ receiveRedaction(roomId: string, targetId: string, sender?: string): string;
168
+ }