@eventuras/oratio-core 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.
package/LICENSE ADDED
@@ -0,0 +1,382 @@
1
+ oratio — a chat client for Matrix
2
+ Copyright (c) 2026 Losol AS.
3
+
4
+ oratio is licensed under the Mozilla Public License, Version 2.0 (MPL-2.0).
5
+ The full license text is reproduced below and is also available at
6
+ https://mozilla.org/MPL/2.0/.
7
+
8
+ --------------------------------------------------------------------------------
9
+
10
+ Mozilla Public License Version 2.0
11
+ ==================================
12
+
13
+ 1. Definitions
14
+ --------------
15
+
16
+ 1.1. "Contributor"
17
+ means each individual or legal entity that creates, contributes to
18
+ the creation of, or owns Covered Software.
19
+
20
+ 1.2. "Contributor Version"
21
+ means the combination of the Contributions of others (if any) used
22
+ by a Contributor and that particular Contributor's Contribution.
23
+
24
+ 1.3. "Contribution"
25
+ means Covered Software of a particular Contributor.
26
+
27
+ 1.4. "Covered Software"
28
+ means Source Code Form to which the initial Contributor has attached
29
+ the notice in Exhibit A, the Executable Form of such Source Code
30
+ Form, and Modifications of such Source Code Form, in each case
31
+ including portions thereof.
32
+
33
+ 1.5. "Incompatible With Secondary Licenses"
34
+ means
35
+
36
+ (a) that the initial Contributor has attached the notice described
37
+ in Exhibit B to the Covered Software; or
38
+
39
+ (b) that the Covered Software was made available under the terms of
40
+ version 1.1 or earlier of the License, but not also under the
41
+ terms of a Secondary License.
42
+
43
+ 1.6. "Executable Form"
44
+ means any form of the work other than Source Code Form.
45
+
46
+ 1.7. "Larger Work"
47
+ means a work that combines Covered Software with other material, in
48
+ a separate file or files, that is not Covered Software.
49
+
50
+ 1.8. "License"
51
+ means this document.
52
+
53
+ 1.9. "Licensable"
54
+ means having the right to grant, to the maximum extent possible,
55
+ whether at the time of the initial grant or subsequently, any and
56
+ all of the rights conveyed by this License.
57
+
58
+ 1.10. "Modifications"
59
+ means any of the following:
60
+
61
+ (a) any file in Source Code Form that results from an addition to,
62
+ deletion from, or modification of the contents of Covered
63
+ Software; or
64
+
65
+ (b) any new file in Source Code Form that contains any Covered
66
+ Software.
67
+
68
+ 1.11. "Patent Claims" of a Contributor
69
+ means any patent claim(s), including without limitation, method,
70
+ process, and apparatus claims, in any patent Licensable by such
71
+ Contributor that would be infringed, but for the grant of the
72
+ License, by the making, using, selling, offering for sale, having
73
+ made, import, or transfer of either its Contributions or its
74
+ Contributor Version.
75
+
76
+ 1.12. "Secondary License"
77
+ means either the GNU General Public License, Version 2.0, the GNU
78
+ Lesser General Public License, Version 2.1, the GNU Affero General
79
+ Public License, Version 3.0, or any later versions of those
80
+ licenses.
81
+
82
+ 1.13. "Source Code Form"
83
+ means the form of the work preferred for making modifications.
84
+
85
+ 1.14. "You" (or "Your")
86
+ means an individual or a legal entity exercising rights under this
87
+ License. For legal entities, "You" includes any entity that
88
+ controls, is controlled by, or is under common control with You. For
89
+ purposes of this definition, "control" means (a) the power, direct
90
+ or indirect, to cause the direction or management of such entity,
91
+ whether by contract or otherwise, or (b) ownership of more than
92
+ fifty percent (50%) of the outstanding shares or beneficial
93
+ ownership of such entity.
94
+
95
+ 2. License Grants and Conditions
96
+ --------------------------------
97
+
98
+ 2.1. Grants
99
+
100
+ Each Contributor hereby grants You a world-wide, royalty-free,
101
+ non-exclusive license:
102
+
103
+ (a) under intellectual property rights (other than patent or trademark)
104
+ Licensable by such Contributor to use, reproduce, make available,
105
+ modify, display, perform, distribute, and otherwise exploit its
106
+ Contributions, either on an unmodified basis, with Modifications, or
107
+ as part of a Larger Work; and
108
+
109
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
110
+ for sale, have made, import, and otherwise transfer either its
111
+ Contributions or its Contributor Version.
112
+
113
+ 2.2. Effective Date
114
+
115
+ The licenses granted in Section 2.1 with respect to any Contribution
116
+ become effective for each Contribution on the date the Contributor first
117
+ distributes such Contribution.
118
+
119
+ 2.3. Limitations on Grant Scope
120
+
121
+ The licenses granted in this Section 2 are the only rights granted under
122
+ this License. No additional rights or licenses will be implied from the
123
+ distribution or licensing of Covered Software under this License.
124
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
125
+ Contributor:
126
+
127
+ (a) for any code that a Contributor has removed from Covered Software;
128
+ or
129
+
130
+ (b) for infringements caused by: (i) Your and any other third party's
131
+ modifications of Covered Software, or (ii) the combination of its
132
+ Contributions with other software (except as part of its Contributor
133
+ Version); or
134
+
135
+ (c) under Patent Claims infringed by Covered Software in the absence of
136
+ its Contributions.
137
+
138
+ This License does not grant any rights in the trademarks, service marks,
139
+ or logos of any Contributor (except as may be necessary to comply with
140
+ the notice requirements in Section 3.4).
141
+
142
+ 2.4. Subsequent Licenses
143
+
144
+ No Contributor makes additional grants as a result of Your choice to
145
+ distribute the Covered Software under a subsequent version of this
146
+ License (see Section 10.2) or under the terms of a Secondary License (if
147
+ permitted under the terms of Section 3.3).
148
+
149
+ 2.5. Representation
150
+
151
+ Each Contributor represents that the Contributor believes its
152
+ Contributions are its original creation(s) or it has sufficient rights
153
+ to grant the rights to its Contributions conveyed by this License.
154
+
155
+ 2.6. Fair Use
156
+
157
+ This License is not intended to limit any rights You have under
158
+ applicable copyright doctrines of fair use, fair dealing, or other
159
+ equivalents.
160
+
161
+ 2.7. Conditions
162
+
163
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
164
+ in Section 2.1.
165
+
166
+ 3. Responsibilities
167
+ -------------------
168
+
169
+ 3.1. Distribution of Source Form
170
+
171
+ All distribution of Covered Software in Source Code Form, including any
172
+ Modifications that You create or to which You contribute, must be under
173
+ the terms of this License. You must inform recipients that the Source
174
+ Code Form of the Covered Software is governed by the terms of this
175
+ License, and how they can obtain a copy of this License. You may not
176
+ attempt to alter or restrict the recipients' rights in the Source Code
177
+ Form.
178
+
179
+ 3.2. Distribution of Executable Form
180
+
181
+ If You distribute Covered Software in Executable Form then:
182
+
183
+ (a) such Covered Software must also be made available in Source Code
184
+ Form, as described in Section 3.1, and You must inform recipients of
185
+ the Executable Form how they can obtain a copy of such Source Code
186
+ Form by reasonable means in a timely manner, at a charge no more
187
+ than the cost of distribution to the recipient; and
188
+
189
+ (b) You may distribute such Executable Form under the terms of this
190
+ License, or sublicense it under different terms, provided that the
191
+ license for the Executable Form does not attempt to limit or alter
192
+ the recipients' rights in the Source Code Form under this License.
193
+
194
+ 3.3. Distribution of a Larger Work
195
+
196
+ You may create and distribute a Larger Work under terms of Your choice,
197
+ provided that You also comply with the requirements of this License for
198
+ the Covered Software. If the Larger Work is a combination of Covered
199
+ Software with a work governed by one or more Secondary Licenses, and the
200
+ Covered Software is not Incompatible With Secondary Licenses, this
201
+ License permits You to additionally distribute such Covered Software
202
+ under the terms of such Secondary License(s), so that the recipient of
203
+ the Larger Work may, at their option, further distribute the Covered
204
+ Software under the terms of either this License or such Secondary
205
+ License(s).
206
+
207
+ 3.4. Notices
208
+
209
+ You may not remove or alter the substance of any license notices
210
+ (including copyright notices, patent notices, disclaimers of warranty,
211
+ or limitations of liability) contained within the Source Code Form of
212
+ the Covered Software, except that You may alter any license notices to
213
+ the extent required to remedy known factual inaccuracies.
214
+
215
+ 3.5. Application of Additional Terms
216
+
217
+ You may choose to offer, and to charge a fee for, warranty, support,
218
+ indemnity or liability obligations to one or more recipients of Covered
219
+ Software. However, You may do so only on Your own behalf, and not on
220
+ behalf of any Contributor. You must make it absolutely clear that any
221
+ such warranty, support, indemnity, or liability obligation is offered by
222
+ You alone, and You hereby agree to indemnify every Contributor for any
223
+ liability incurred by such Contributor as a result of warranty, support,
224
+ indemnity or liability terms You offer. You may include additional
225
+ disclaimers of warranty and limitations of liability specific to any
226
+ jurisdiction.
227
+
228
+ 4. Inability to Comply Due to Statute or Regulation
229
+ ---------------------------------------------------
230
+
231
+ If it is impossible for You to comply with any of the terms of this
232
+ License with respect to some or all of the Covered Software due to
233
+ statute, judicial order, or regulation then You must: (a) comply with
234
+ the terms of this License to the maximum extent possible; and (b)
235
+ describe the limitations and the code they affect. Such description must
236
+ be placed in a text file included with all distributions of the Covered
237
+ Software under this License. Except to the extent prohibited by statute
238
+ or regulation, such description must be sufficiently detailed for a
239
+ recipient of ordinary skill to be able to understand it.
240
+
241
+ 5. Termination
242
+ --------------
243
+
244
+ 5.1. The rights granted under this License will terminate automatically
245
+ if You fail to comply with any of its terms. However, if You become
246
+ compliant, then the rights granted under this License from a particular
247
+ Contributor are reinstated (a) provisionally, unless and until such
248
+ Contributor explicitly and finally terminates Your grants, and (b) on an
249
+ ongoing basis, if such Contributor fails to notify You of the
250
+ non-compliance by some reasonable means prior to 60 days after You have
251
+ come back into compliance. Moreover, Your grants from a particular
252
+ Contributor are reinstated on an ongoing basis if such Contributor
253
+ notifies You of the non-compliance by some reasonable means, this is the
254
+ first time You have received notice of non-compliance with this License
255
+ from such Contributor, and You become compliant prior to 30 days after
256
+ Your receipt of the notice.
257
+
258
+ 5.2. If You initiate litigation against any entity by asserting a patent
259
+ infringement claim (excluding declaratory judgment actions,
260
+ counter-claims, and cross-claims) alleging that a Contributor Version
261
+ directly or indirectly infringes any patent, then the rights granted to
262
+ You by any and all Contributors for the Covered Software under Section
263
+ 2.1 of this License shall terminate.
264
+
265
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
266
+ end user license agreements (excluding distributors and resellers) which
267
+ have been validly granted by You or Your distributors under this License
268
+ prior to termination shall survive termination.
269
+
270
+ ************************************************************************
271
+ * *
272
+ * 6. Disclaimer of Warranty *
273
+ * ------------------------- *
274
+ * *
275
+ * Covered Software is provided under this License on an "as is" *
276
+ * basis, without warranty of any kind, either expressed, implied, or *
277
+ * statutory, including, without limitation, warranties that the *
278
+ * Covered Software is free of defects, merchantable, fit for a *
279
+ * particular purpose or non-infringing. The entire risk as to the *
280
+ * quality and performance of the Covered Software is with You. *
281
+ * Should any Covered Software prove defective in any respect, You *
282
+ * (not any Contributor) assume the cost of any necessary servicing, *
283
+ * repair, or correction. This disclaimer of warranty constitutes an *
284
+ * essential part of this License. No use of any Covered Software is *
285
+ * authorized under this License except under this disclaimer. *
286
+ * *
287
+ ************************************************************************
288
+
289
+ ************************************************************************
290
+ * *
291
+ * 7. Limitation of Liability *
292
+ * -------------------------- *
293
+ * *
294
+ * Under no circumstances and under no legal theory, whether tort *
295
+ * (including negligence), contract, or otherwise, shall any *
296
+ * Contributor, or anyone who distributes Covered Software as *
297
+ * permitted above, be liable to You for any direct, indirect, *
298
+ * special, incidental, or consequential damages of any character *
299
+ * including, without limitation, damages for lost profits, loss of *
300
+ * goodwill, work stoppage, computer failure or malfunction, or any *
301
+ * and all other commercial damages or losses, even if such party *
302
+ * shall have been informed of the possibility of such damages. This *
303
+ * limitation of liability shall not apply to liability for death or *
304
+ * personal injury resulting from such party's negligence to the *
305
+ * extent applicable law prohibits such limitation. Some *
306
+ * jurisdictions do not allow the exclusion or limitation of *
307
+ * incidental or consequential damages, so this exclusion and *
308
+ * limitation may not apply to You. *
309
+ * *
310
+ ************************************************************************
311
+
312
+ 8. Litigation
313
+ -------------
314
+
315
+ Any litigation relating to this License may be brought only in the
316
+ courts of a jurisdiction where the defendant maintains its principal
317
+ place of business and such litigation shall be governed by laws of that
318
+ jurisdiction, without reference to its conflict-of-law provisions.
319
+ Nothing in this Section shall prevent a party's ability to bring
320
+ cross-claims or counter-claims.
321
+
322
+ 9. Miscellaneous
323
+ ----------------
324
+
325
+ This License represents the complete agreement concerning the subject
326
+ matter hereof. If any provision of this License is held to be
327
+ unenforceable, such provision shall be reformed only to the extent
328
+ necessary to make it enforceable. Any law or regulation which provides
329
+ that the language of a contract shall be construed against the drafter
330
+ shall not be used to construe this License against a Contributor.
331
+
332
+ 10. Versions of the License
333
+ ---------------------------
334
+
335
+ 10.1. New Versions
336
+
337
+ Mozilla Foundation is the license steward. Except as provided in Section
338
+ 10.3, no one other than the license steward has the right to modify or
339
+ publish new versions of this License. Each version will be given a
340
+ distinguishing version number.
341
+
342
+ 10.2. Effect of New Versions
343
+
344
+ You may distribute the Covered Software under the terms of the version
345
+ of the License under which You originally received the Covered Software,
346
+ or under the terms of any subsequent version published by the license
347
+ steward.
348
+
349
+ 10.3. Modified Versions
350
+
351
+ If you create software not governed by this License, and you want to
352
+ create a new license for such software, you may create and use a
353
+ modified version of this License if you rename the license and remove
354
+ any references to the name of the license steward (except to note that
355
+ such modified license differs from this License).
356
+
357
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary
358
+ Licenses
359
+
360
+ If You choose to distribute Source Code Form that is Incompatible With
361
+ Secondary Licenses under the terms of this version of the License, the
362
+ notice described in Exhibit B of this License must be attached.
363
+
364
+ Exhibit A - Source Code Form License Notice
365
+ -------------------------------------------
366
+
367
+ This Source Code Form is subject to the terms of the Mozilla Public
368
+ License, v. 2.0. If a copy of the MPL was not distributed with this
369
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
370
+
371
+ If it is not possible or desirable to put the notice in a particular
372
+ file, then You may include the notice in a location (such as a LICENSE
373
+ file in a relevant directory) where a recipient would be likely to look
374
+ for such a notice.
375
+
376
+ You may add additional accurate notices of copyright ownership.
377
+
378
+ Exhibit B - "Incompatible With Secondary Licenses" Notice
379
+ ---------------------------------------------------------
380
+
381
+ This Source Code Form is "Incompatible With Secondary Licenses", as
382
+ defined by the Mozilla Public License, v. 2.0.
package/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # @eventuras/oratio-core
2
+
3
+ Framework-agnostic core of the oratio Matrix client. Wraps
4
+ [matrix-js-sdk](https://github.com/matrix-org/matrix-js-sdk) and maps rooms,
5
+ timelines and members to the shapes that `@eventuras/ratio-ui/chat` renders.
6
+
7
+ No DOM dependencies: storage and other platform services are injected, so the
8
+ package can serve a web app, a Capacitor shell or React Native.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ pnpm add @eventuras/oratio-core
14
+ ```
15
+
16
+ ## Status
17
+
18
+ Early, 0.x: the API may change between minor versions. Signs in with a
19
+ password or through the homeserver's OIDC (MSC3861), syncs with token refresh,
20
+ and maps rooms and timelines. No end-to-end encryption.
21
+
22
+ ## Development
23
+
24
+ ```sh
25
+ pnpm --filter @eventuras/oratio-core build
26
+ pnpm --filter @eventuras/oratio-core test
27
+ ```
28
+
29
+ ## License
30
+
31
+ MPL-2.0
package/dist/ids.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ /** A Matrix user ID, `@localpart:server.name`, split into its parts. */
2
+ export interface MatrixUserId {
3
+ localpart: string;
4
+ serverName: string;
5
+ }
6
+ /**
7
+ * Splits a Matrix user ID into localpart and server name.
8
+ * The server name may carry a port (`localhost:8008`), so the first colon
9
+ * after `@` is the separator. Returns null when the input is not a user ID.
10
+ */
11
+ export declare function parseUserId(userId: string): MatrixUserId | null;
12
+ //# sourceMappingURL=ids.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ids.d.ts","sourceRoot":"","sources":["../src/ids.ts"],"names":[],"mappings":"AAIA,wEAAwE;AACxE,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAS/D"}
@@ -0,0 +1,7 @@
1
+ export { ClientEvent, EventType, type MatrixClient, Preset, RoomEvent } from 'matrix-js-sdk';
2
+ export { type MatrixUserId, parseUserId } from './ids';
3
+ export { beginOidcLogin, completeOidcLogin, type OidcLoginOptions, type PendingOidcLogin, } from './oidc';
4
+ export { directRoomIds, joinedRooms, type OratioRoom, type RoomLike, toOratioRoom, } from './rooms';
5
+ export { loginWithPassword, logout, type OratioSession, type PasswordLogin, type StartClientOptions, startClient, } from './session';
6
+ export { type EventLike, type OratioMessage, type TimelineOptions, toOratioMessages, } from './timeline';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,KAAK,YAAY,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC7F,OAAO,EAAE,KAAK,YAAY,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACvD,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,GACtB,MAAM,QAAQ,CAAC;AAChB,OAAO,EACL,aAAa,EACb,WAAW,EACX,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,YAAY,GACb,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,iBAAiB,EACjB,MAAM,EACN,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACvB,WAAW,GACZ,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,KAAK,SAAS,EACd,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,gBAAgB,GACjB,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,199 @@
1
+ import { ClientEvent, EventType, EventType as EventType$1, KnownMembership, MsgType, NotificationCountType, OAuth2, Preset, RoomEvent, TokenRefresher, createClient } from "matrix-js-sdk";
2
+ //#region src/ids.ts
3
+ /**
4
+ * Splits a Matrix user ID into localpart and server name.
5
+ * The server name may carry a port (`localhost:8008`), so the first colon
6
+ * after `@` is the separator. Returns null when the input is not a user ID.
7
+ */
8
+ function parseUserId(userId) {
9
+ if (!userId.startsWith("@")) return null;
10
+ const colon = userId.indexOf(":", 1);
11
+ if (colon < 2 || colon === userId.length - 1) return null;
12
+ return {
13
+ localpart: userId.slice(1, colon),
14
+ serverName: userId.slice(colon + 1)
15
+ };
16
+ }
17
+ //#endregion
18
+ //#region src/oidc.ts
19
+ async function authMetadata(homeserverUrl) {
20
+ return createClient({ baseUrl: homeserverUrl }).getAuthMetadata();
21
+ }
22
+ /** Registers the app with the homeserver and returns the URL to send the user to. */
23
+ async function beginOidcLogin(options) {
24
+ const metadata = await authMetadata(options.homeserverUrl);
25
+ const start = async (clientId) => {
26
+ const oauth = new OAuth2(metadata, {
27
+ clientId,
28
+ redirectUri: options.redirectUri
29
+ });
30
+ const state = crypto.randomUUID();
31
+ return {
32
+ url: await oauth.generateAuthorizationCodeGrantUrl(state),
33
+ pending: {
34
+ ...oauth.context,
35
+ homeserverUrl: options.homeserverUrl,
36
+ state
37
+ }
38
+ };
39
+ };
40
+ if (options.clientId) {
41
+ const attempt = await start(options.clientId);
42
+ if ((await fetch(attempt.url, { redirect: "manual" }).catch(() => null))?.status !== 404) return attempt;
43
+ }
44
+ return start(await OAuth2.registerClient(metadata, {
45
+ client_name: options.clientName ?? "oratio",
46
+ client_uri: options.clientUri,
47
+ redirect_uris: [options.redirectUri],
48
+ application_type: "web"
49
+ }));
50
+ }
51
+ /**
52
+ * Finishes sign-in from the URL the homeserver redirected to. The code comes in
53
+ * the fragment by default; the query string is read as a fallback.
54
+ */
55
+ async function completeOidcLogin(pending, callbackUrl) {
56
+ const url = new URL(callbackUrl);
57
+ const params = new URLSearchParams(url.hash.slice(1) || url.search);
58
+ const error = params.get("error");
59
+ if (error) throw new Error(params.get("error_description") ?? error);
60
+ if (params.get("state") !== pending.state) throw new Error("Sign-in state does not match. Start again.");
61
+ const code = params.get("code");
62
+ if (!code) throw new Error("The homeserver sent no authorization code.");
63
+ const metadata = await authMetadata(pending.homeserverUrl);
64
+ const tokens = await new OAuth2(metadata, pending).completeAuthorizationCodeGrant(code);
65
+ const { user_id } = await createClient({
66
+ baseUrl: pending.homeserverUrl,
67
+ accessToken: tokens.access_token
68
+ }).whoami();
69
+ return {
70
+ homeserverUrl: pending.homeserverUrl,
71
+ userId: user_id,
72
+ accessToken: tokens.access_token,
73
+ deviceId: pending.deviceId,
74
+ refreshToken: tokens.refresh_token,
75
+ oauthClientId: pending.clientId
76
+ };
77
+ }
78
+ /** An OAuth2 helper for a signed-in OIDC session, for token refresh and revocation. */
79
+ async function oauthForSession(session) {
80
+ if (!session.oauthClientId) return null;
81
+ const metadata = await authMetadata(session.homeserverUrl);
82
+ return new OAuth2(metadata, {
83
+ clientId: session.oauthClientId,
84
+ deviceId: session.deviceId,
85
+ redirectUri: ""
86
+ });
87
+ }
88
+ //#endregion
89
+ //#region src/rooms.ts
90
+ /**
91
+ * Maps a Matrix room to a room-list entry. `directRoomIds` comes from the
92
+ * user's `m.direct` account data: those rooms are direct messages.
93
+ */
94
+ function toOratioRoom(room, directRoomIds) {
95
+ const unread = room.getUnreadNotificationCount(NotificationCountType.Total);
96
+ const highlights = room.getUnreadNotificationCount(NotificationCountType.Highlight);
97
+ return {
98
+ id: room.roomId,
99
+ kind: directRoomIds.has(room.roomId) ? "dm" : "channel",
100
+ name: room.name,
101
+ ...unread > 0 && { unread },
102
+ ...highlights > 0 && { mention: true },
103
+ members: room.getJoinedMemberCount(),
104
+ ...room.hasEncryptionStateEvent() && { encrypted: true }
105
+ };
106
+ }
107
+ /** The room IDs listed in `m.direct`, which maps each user ID to their DM rooms. */
108
+ function directRoomIds(mDirect) {
109
+ return new Set(Object.values(mDirect ?? {}).flat());
110
+ }
111
+ /** Rooms the user has joined, sorted by name. Invites and left rooms are not listed yet. */
112
+ function joinedRooms(rooms) {
113
+ return rooms.filter((room) => room.getMyMembership() === KnownMembership.Join).sort((a, b) => a.name.localeCompare(b.name));
114
+ }
115
+ //#endregion
116
+ //#region src/session.ts
117
+ /** Signs in with a password and returns a new session. For development and password-only servers. */
118
+ async function loginWithPassword(login) {
119
+ const response = await createClient({ baseUrl: login.homeserverUrl }).loginRequest({
120
+ type: "m.login.password",
121
+ identifier: {
122
+ type: "m.id.user",
123
+ user: login.username
124
+ },
125
+ password: login.password,
126
+ initial_device_display_name: login.deviceName ?? "oratio"
127
+ });
128
+ return {
129
+ homeserverUrl: login.homeserverUrl,
130
+ userId: response.user_id,
131
+ accessToken: response.access_token,
132
+ deviceId: response.device_id
133
+ };
134
+ }
135
+ /**
136
+ * Creates a client for a session and starts syncing. OIDC sessions refresh
137
+ * their access token as it expires. No end-to-end encryption: encrypted rooms
138
+ * show up, but their messages cannot be read.
139
+ */
140
+ async function startClient(session, options = {}) {
141
+ let current = session;
142
+ const oauth = session.refreshToken ? await oauthForSession(session) : null;
143
+ const refresher = oauth ? new TokenRefresher(oauth, async ({ accessToken, refreshToken }) => {
144
+ current = {
145
+ ...current,
146
+ accessToken,
147
+ refreshToken
148
+ };
149
+ options.onSessionChange?.(current);
150
+ }) : null;
151
+ const client = createClient({
152
+ baseUrl: session.homeserverUrl,
153
+ userId: session.userId,
154
+ accessToken: session.accessToken,
155
+ deviceId: session.deviceId,
156
+ refreshToken: session.refreshToken,
157
+ tokenRefreshFunction: refresher?.tokenRefreshFunction,
158
+ disableVoip: true
159
+ });
160
+ await client.startClient({ initialSyncLimit: 50 });
161
+ return client;
162
+ }
163
+ /** Stops syncing and invalidates the access token on the server. */
164
+ async function logout(client) {
165
+ client.stopClient();
166
+ await client.logout(true);
167
+ }
168
+ //#endregion
169
+ //#region src/timeline.ts
170
+ /**
171
+ * Maps timeline events to log rows: text messages, notices and `/me` emotes.
172
+ * Everything else (state changes, reactions, encrypted events) is skipped for now.
173
+ */
174
+ function toOratioMessages(events, options = {}) {
175
+ const time = new Intl.DateTimeFormat(options.locale, {
176
+ hour: "2-digit",
177
+ minute: "2-digit"
178
+ });
179
+ const messages = [];
180
+ for (const event of events) {
181
+ const id = event.getId();
182
+ if (!id || event.getType() !== EventType$1.RoomMessage || event.isRedacted()) continue;
183
+ const content = event.getContent();
184
+ if (typeof content.body !== "string") continue;
185
+ const sender = event.getSender() ?? "";
186
+ messages.push({
187
+ id,
188
+ type: content.msgtype === MsgType.Emote ? "action" : "msg",
189
+ time: time.format(event.getTs()),
190
+ nick: event.sender?.name ?? parseUserId(sender)?.localpart ?? sender,
191
+ text: content.body
192
+ });
193
+ }
194
+ return messages;
195
+ }
196
+ //#endregion
197
+ export { ClientEvent, EventType, Preset, RoomEvent, beginOidcLogin, completeOidcLogin, directRoomIds, joinedRooms, loginWithPassword, logout, parseUserId, startClient, toOratioMessages, toOratioRoom };
198
+
199
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/ids.ts","../src/oidc.ts","../src/rooms.ts","../src/session.ts","../src/timeline.ts"],"sourcesContent":["// oratio · a chat client for Matrix\n// SPDX-FileCopyrightText: 2026 Losol AS\n// SPDX-License-Identifier: MPL-2.0\n\n/** A Matrix user ID, `@localpart:server.name`, split into its parts. */\nexport interface MatrixUserId {\n localpart: string;\n serverName: string;\n}\n\n/**\n * Splits a Matrix user ID into localpart and server name.\n * The server name may carry a port (`localhost:8008`), so the first colon\n * after `@` is the separator. Returns null when the input is not a user ID.\n */\nexport function parseUserId(userId: string): MatrixUserId | null {\n if (!userId.startsWith('@')) {\n return null;\n }\n const colon = userId.indexOf(':', 1);\n if (colon < 2 || colon === userId.length - 1) {\n return null;\n }\n return { localpart: userId.slice(1, colon), serverName: userId.slice(colon + 1) };\n}\n","// oratio · a chat client for Matrix\n// SPDX-FileCopyrightText: 2026 Losol AS\n// SPDX-License-Identifier: MPL-2.0\n\nimport { createClient, OAuth2 } from 'matrix-js-sdk';\nimport type { OratioSession } from './session';\n\n/**\n * Sign-in through the homeserver's OAuth 2.0 API (next-gen auth, MSC3861).\n * The homeserver hands the actual login to its identity provider, e.g. Keycloak.\n * Two halves, because a browser leaves the page in between:\n * {@link beginOidcLogin} before the redirect, {@link completeOidcLogin} after.\n */\nexport interface OidcLoginOptions {\n homeserverUrl: string;\n /** The app's https home page. Redirect URIs must share its host. */\n clientUri: string;\n /** Where the homeserver sends the user back, e.g. `https://chat.example/auth/callback`. */\n redirectUri: string;\n /** Shown to the user by the homeserver. @default 'oratio' */\n clientName?: string;\n /**\n * A client ID this app registered earlier with the same homeserver and\n * redirect URI. Reusing it means the user approves the app once, not at\n * every sign-in. Registers a new client when omitted or no longer known.\n */\n clientId?: string;\n}\n\n/** What {@link completeOidcLogin} needs. Keep it until the user comes back, then drop it. */\nexport interface PendingOidcLogin {\n homeserverUrl: string;\n clientId: string;\n deviceId: string;\n codeVerifier: string;\n redirectUri: string;\n state: string;\n}\n\nasync function authMetadata(homeserverUrl: string) {\n return createClient({ baseUrl: homeserverUrl }).getAuthMetadata();\n}\n\n/** Registers the app with the homeserver and returns the URL to send the user to. */\nexport async function beginOidcLogin(\n options: OidcLoginOptions,\n): Promise<{ url: string; pending: PendingOidcLogin }> {\n const metadata = await authMetadata(options.homeserverUrl);\n const start = async (clientId: string) => {\n const oauth = new OAuth2(metadata, { clientId, redirectUri: options.redirectUri });\n const state = crypto.randomUUID();\n const url = await oauth.generateAuthorizationCodeGrantUrl(state);\n return { url, pending: { ...oauth.context, homeserverUrl: options.homeserverUrl, state } };\n };\n\n if (options.clientId) {\n const attempt = await start(options.clientId);\n // A client the homeserver forgot, e.g. after a database reset, gets 404\n // here before any redirect. A known one redirects on to the identity\n // provider, which a manual-redirect fetch sees as an opaque response.\n const probe = await fetch(attempt.url, { redirect: 'manual' }).catch(() => null);\n if (probe?.status !== 404) {\n return attempt;\n }\n }\n\n const clientId = await OAuth2.registerClient(metadata, {\n client_name: options.clientName ?? 'oratio',\n client_uri: options.clientUri,\n redirect_uris: [options.redirectUri],\n application_type: 'web',\n });\n return start(clientId);\n}\n\n/**\n * Finishes sign-in from the URL the homeserver redirected to. The code comes in\n * the fragment by default; the query string is read as a fallback.\n */\nexport async function completeOidcLogin(\n pending: PendingOidcLogin,\n callbackUrl: string,\n): Promise<OratioSession> {\n const url = new URL(callbackUrl);\n const params = new URLSearchParams(url.hash.slice(1) || url.search);\n const error = params.get('error');\n if (error) {\n throw new Error(params.get('error_description') ?? error);\n }\n if (params.get('state') !== pending.state) {\n throw new Error('Sign-in state does not match. Start again.');\n }\n const code = params.get('code');\n if (!code) {\n throw new Error('The homeserver sent no authorization code.');\n }\n\n const metadata = await authMetadata(pending.homeserverUrl);\n const oauth = new OAuth2(metadata, pending);\n const tokens = await oauth.completeAuthorizationCodeGrant(code);\n const client = createClient({ baseUrl: pending.homeserverUrl, accessToken: tokens.access_token });\n const { user_id } = await client.whoami();\n return {\n homeserverUrl: pending.homeserverUrl,\n userId: user_id,\n accessToken: tokens.access_token,\n deviceId: pending.deviceId,\n refreshToken: tokens.refresh_token,\n oauthClientId: pending.clientId,\n };\n}\n\n/** An OAuth2 helper for a signed-in OIDC session, for token refresh and revocation. */\nexport async function oauthForSession(session: OratioSession): Promise<OAuth2 | null> {\n if (!session.oauthClientId) {\n return null;\n }\n const metadata = await authMetadata(session.homeserverUrl);\n return new OAuth2(metadata, {\n clientId: session.oauthClientId,\n deviceId: session.deviceId,\n redirectUri: '',\n });\n}\n","// oratio · a chat client for Matrix\n// SPDX-FileCopyrightText: 2026 Losol AS\n// SPDX-License-Identifier: MPL-2.0\n\nimport { KnownMembership, NotificationCountType, type Room } from 'matrix-js-sdk';\n\n/**\n * A room as the room list shows it, seen by the signed-in user: `unread`,\n * `mention` and a DM's `name` are that user's own, computed by the homeserver.\n * Same shape as `ChatRoom` in `@eventuras/ratio-ui/chat`, without depending on it.\n */\nexport interface OratioRoom {\n id: string;\n kind: 'channel' | 'group' | 'dm';\n name: string;\n /** Unread messages for this user, from the server's notification counts. */\n unread?: number;\n /** This user was mentioned or otherwise highlighted in an unread message. */\n mention?: boolean;\n members?: number;\n /** End-to-end encrypted. oratio cannot read or send in these rooms yet. */\n encrypted?: boolean;\n}\n\n/** The parts of a matrix-js-sdk `Room` the mapping reads. */\nexport type RoomLike = Pick<\n Room,\n | 'roomId'\n | 'name'\n | 'getJoinedMemberCount'\n | 'getUnreadNotificationCount'\n | 'hasEncryptionStateEvent'\n>;\n\n/**\n * Maps a Matrix room to a room-list entry. `directRoomIds` comes from the\n * user's `m.direct` account data: those rooms are direct messages.\n */\nexport function toOratioRoom(room: RoomLike, directRoomIds: ReadonlySet<string>): OratioRoom {\n const unread = room.getUnreadNotificationCount(NotificationCountType.Total);\n const highlights = room.getUnreadNotificationCount(NotificationCountType.Highlight);\n return {\n id: room.roomId,\n kind: directRoomIds.has(room.roomId) ? 'dm' : 'channel',\n name: room.name,\n ...(unread > 0 && { unread }),\n ...(highlights > 0 && { mention: true }),\n members: room.getJoinedMemberCount(),\n ...(room.hasEncryptionStateEvent() && { encrypted: true }),\n };\n}\n\n/** The room IDs listed in `m.direct`, which maps each user ID to their DM rooms. */\nexport function directRoomIds(mDirect: Record<string, string[]> | undefined): Set<string> {\n return new Set(Object.values(mDirect ?? {}).flat());\n}\n\n/** Rooms the user has joined, sorted by name. Invites and left rooms are not listed yet. */\nexport function joinedRooms(rooms: Room[]): Room[] {\n return rooms\n .filter((room) => room.getMyMembership() === KnownMembership.Join)\n .sort((a, b) => a.name.localeCompare(b.name));\n}\n","// oratio · a chat client for Matrix\n// SPDX-FileCopyrightText: 2026 Losol AS\n// SPDX-License-Identifier: MPL-2.0\n\nimport { createClient, type MatrixClient, TokenRefresher } from 'matrix-js-sdk';\nimport { oauthForSession } from './oidc';\n\n/** What it takes to resume a signed-in client. The caller decides where it is kept. */\nexport interface OratioSession {\n homeserverUrl: string;\n userId: string;\n accessToken: string;\n deviceId: string;\n /** Set for OIDC sign-ins: access tokens expire and are renewed with this. */\n refreshToken?: string;\n /** The client ID the homeserver registered for us, for OIDC sign-ins. */\n oauthClientId?: string;\n}\n\nexport interface PasswordLogin {\n homeserverUrl: string;\n /** Localpart (`ole`) or full user ID (`@ole:losol.no`). */\n username: string;\n password: string;\n /** Shown in the user's device list. @default 'oratio' */\n deviceName?: string;\n}\n\n/** Signs in with a password and returns a new session. For development and password-only servers. */\nexport async function loginWithPassword(login: PasswordLogin): Promise<OratioSession> {\n const client = createClient({ baseUrl: login.homeserverUrl });\n const response = await client.loginRequest({\n type: 'm.login.password',\n identifier: { type: 'm.id.user', user: login.username },\n password: login.password,\n initial_device_display_name: login.deviceName ?? 'oratio',\n });\n return {\n homeserverUrl: login.homeserverUrl,\n userId: response.user_id,\n accessToken: response.access_token,\n deviceId: response.device_id,\n };\n}\n\nexport interface StartClientOptions {\n /** Called with the updated session when tokens are refreshed. Store it. */\n onSessionChange?: (session: OratioSession) => void;\n}\n\n/**\n * Creates a client for a session and starts syncing. OIDC sessions refresh\n * their access token as it expires. No end-to-end encryption: encrypted rooms\n * show up, but their messages cannot be read.\n */\nexport async function startClient(\n session: OratioSession,\n options: StartClientOptions = {},\n): Promise<MatrixClient> {\n let current = session;\n const oauth = session.refreshToken ? await oauthForSession(session) : null;\n const refresher = oauth\n ? new TokenRefresher(oauth, async ({ accessToken, refreshToken }) => {\n current = { ...current, accessToken, refreshToken };\n options.onSessionChange?.(current);\n })\n : null;\n const client = createClient({\n baseUrl: session.homeserverUrl,\n userId: session.userId,\n accessToken: session.accessToken,\n deviceId: session.deviceId,\n refreshToken: session.refreshToken,\n tokenRefreshFunction: refresher?.tokenRefreshFunction,\n // No voice or video: skip the TURN server lookup that calls need.\n disableVoip: true,\n });\n await client.startClient({ initialSyncLimit: 50 });\n return client;\n}\n\n/** Stops syncing and invalidates the access token on the server. */\nexport async function logout(client: MatrixClient): Promise<void> {\n client.stopClient();\n await client.logout(true);\n}\n","// oratio · a chat client for Matrix\n// SPDX-FileCopyrightText: 2026 Losol AS\n// SPDX-License-Identifier: MPL-2.0\n\nimport { EventType, type MatrixEvent, MsgType } from 'matrix-js-sdk';\nimport { parseUserId } from './ids';\n\n/**\n * A timeline row. Same shape as `ChatLogMessage` in\n * `@eventuras/ratio-ui/chat`, without depending on it.\n */\nexport interface OratioMessage {\n id: string;\n type: 'msg' | 'action';\n time: string;\n nick: string;\n text: string;\n}\n\n/** The parts of a matrix-js-sdk `MatrixEvent` the mapping reads. */\nexport type EventLike = Pick<\n MatrixEvent,\n 'getId' | 'getType' | 'getContent' | 'getSender' | 'getTs' | 'isRedacted'\n> & { sender?: { name: string } | null };\n\nexport interface TimelineOptions {\n /** BCP 47 locale for message times. @default the runtime's */\n locale?: string;\n}\n\n/**\n * Maps timeline events to log rows: text messages, notices and `/me` emotes.\n * Everything else (state changes, reactions, encrypted events) is skipped for now.\n */\nexport function toOratioMessages(\n events: readonly EventLike[],\n options: TimelineOptions = {},\n): OratioMessage[] {\n const time = new Intl.DateTimeFormat(options.locale, { hour: '2-digit', minute: '2-digit' });\n const messages: OratioMessage[] = [];\n for (const event of events) {\n const id = event.getId();\n if (!id || event.getType() !== EventType.RoomMessage || event.isRedacted()) {\n continue;\n }\n const content = event.getContent<{ msgtype?: string; body?: unknown }>();\n if (typeof content.body !== 'string') {\n continue;\n }\n const sender = event.getSender() ?? '';\n messages.push({\n id,\n type: content.msgtype === MsgType.Emote ? 'action' : 'msg',\n time: time.format(event.getTs()),\n nick: event.sender?.name ?? parseUserId(sender)?.localpart ?? sender,\n text: content.body,\n });\n }\n return messages;\n}\n"],"mappings":"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"}
package/dist/oidc.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ import { OAuth2 } from 'matrix-js-sdk';
2
+ import type { OratioSession } from './session';
3
+ /**
4
+ * Sign-in through the homeserver's OAuth 2.0 API (next-gen auth, MSC3861).
5
+ * The homeserver hands the actual login to its identity provider, e.g. Keycloak.
6
+ * Two halves, because a browser leaves the page in between:
7
+ * {@link beginOidcLogin} before the redirect, {@link completeOidcLogin} after.
8
+ */
9
+ export interface OidcLoginOptions {
10
+ homeserverUrl: string;
11
+ /** The app's https home page. Redirect URIs must share its host. */
12
+ clientUri: string;
13
+ /** Where the homeserver sends the user back, e.g. `https://chat.example/auth/callback`. */
14
+ redirectUri: string;
15
+ /** Shown to the user by the homeserver. @default 'oratio' */
16
+ clientName?: string;
17
+ /**
18
+ * A client ID this app registered earlier with the same homeserver and
19
+ * redirect URI. Reusing it means the user approves the app once, not at
20
+ * every sign-in. Registers a new client when omitted or no longer known.
21
+ */
22
+ clientId?: string;
23
+ }
24
+ /** What {@link completeOidcLogin} needs. Keep it until the user comes back, then drop it. */
25
+ export interface PendingOidcLogin {
26
+ homeserverUrl: string;
27
+ clientId: string;
28
+ deviceId: string;
29
+ codeVerifier: string;
30
+ redirectUri: string;
31
+ state: string;
32
+ }
33
+ /** Registers the app with the homeserver and returns the URL to send the user to. */
34
+ export declare function beginOidcLogin(options: OidcLoginOptions): Promise<{
35
+ url: string;
36
+ pending: PendingOidcLogin;
37
+ }>;
38
+ /**
39
+ * Finishes sign-in from the URL the homeserver redirected to. The code comes in
40
+ * the fragment by default; the query string is read as a fallback.
41
+ */
42
+ export declare function completeOidcLogin(pending: PendingOidcLogin, callbackUrl: string): Promise<OratioSession>;
43
+ /** An OAuth2 helper for a signed-in OIDC session, for token refresh and revocation. */
44
+ export declare function oauthForSession(session: OratioSession): Promise<OAuth2 | null>;
45
+ //# sourceMappingURL=oidc.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc.d.ts","sourceRoot":"","sources":["../src/oidc.ts"],"names":[],"mappings":"AAIA,OAAO,EAAgB,MAAM,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAE/C;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,aAAa,EAAE,MAAM,CAAC;IACtB,oEAAoE;IACpE,SAAS,EAAE,MAAM,CAAC;IAClB,2FAA2F;IAC3F,WAAW,EAAE,MAAM,CAAC;IACpB,6DAA6D;IAC7D,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,6FAA6F;AAC7F,MAAM,WAAW,gBAAgB;IAC/B,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;CACf;AAMD,qFAAqF;AACrF,wBAAsB,cAAc,CAClC,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAAC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,gBAAgB,CAAA;CAAE,CAAC,CA2BrD;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,gBAAgB,EACzB,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,aAAa,CAAC,CA4BxB;AAED,uFAAuF;AACvF,wBAAsB,eAAe,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAUpF"}
@@ -0,0 +1,30 @@
1
+ import { type Room } from 'matrix-js-sdk';
2
+ /**
3
+ * A room as the room list shows it, seen by the signed-in user: `unread`,
4
+ * `mention` and a DM's `name` are that user's own, computed by the homeserver.
5
+ * Same shape as `ChatRoom` in `@eventuras/ratio-ui/chat`, without depending on it.
6
+ */
7
+ export interface OratioRoom {
8
+ id: string;
9
+ kind: 'channel' | 'group' | 'dm';
10
+ name: string;
11
+ /** Unread messages for this user, from the server's notification counts. */
12
+ unread?: number;
13
+ /** This user was mentioned or otherwise highlighted in an unread message. */
14
+ mention?: boolean;
15
+ members?: number;
16
+ /** End-to-end encrypted. oratio cannot read or send in these rooms yet. */
17
+ encrypted?: boolean;
18
+ }
19
+ /** The parts of a matrix-js-sdk `Room` the mapping reads. */
20
+ export type RoomLike = Pick<Room, 'roomId' | 'name' | 'getJoinedMemberCount' | 'getUnreadNotificationCount' | 'hasEncryptionStateEvent'>;
21
+ /**
22
+ * Maps a Matrix room to a room-list entry. `directRoomIds` comes from the
23
+ * user's `m.direct` account data: those rooms are direct messages.
24
+ */
25
+ export declare function toOratioRoom(room: RoomLike, directRoomIds: ReadonlySet<string>): OratioRoom;
26
+ /** The room IDs listed in `m.direct`, which maps each user ID to their DM rooms. */
27
+ export declare function directRoomIds(mDirect: Record<string, string[]> | undefined): Set<string>;
28
+ /** Rooms the user has joined, sorted by name. Invites and left rooms are not listed yet. */
29
+ export declare function joinedRooms(rooms: Room[]): Room[];
30
+ //# sourceMappingURL=rooms.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rooms.d.ts","sourceRoot":"","sources":["../src/rooms.ts"],"names":[],"mappings":"AAIA,OAAO,EAA0C,KAAK,IAAI,EAAE,MAAM,eAAe,CAAC;AAElF;;;;GAIG;AACH,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,SAAS,GAAG,OAAO,GAAG,IAAI,CAAC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,4EAA4E;IAC5E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,6EAA6E;IAC7E,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,2EAA2E;IAC3E,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,6DAA6D;AAC7D,MAAM,MAAM,QAAQ,GAAG,IAAI,CACzB,IAAI,EACF,QAAQ,GACR,MAAM,GACN,sBAAsB,GACtB,4BAA4B,GAC5B,yBAAyB,CAC5B,CAAC;AAEF;;;GAGG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,UAAU,CAY3F;AAED,oFAAoF;AACpF,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,SAAS,GAAG,GAAG,CAAC,MAAM,CAAC,CAExF;AAED,4FAA4F;AAC5F,wBAAgB,WAAW,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,CAIjD"}
@@ -0,0 +1,35 @@
1
+ import { type MatrixClient } from 'matrix-js-sdk';
2
+ /** What it takes to resume a signed-in client. The caller decides where it is kept. */
3
+ export interface OratioSession {
4
+ homeserverUrl: string;
5
+ userId: string;
6
+ accessToken: string;
7
+ deviceId: string;
8
+ /** Set for OIDC sign-ins: access tokens expire and are renewed with this. */
9
+ refreshToken?: string;
10
+ /** The client ID the homeserver registered for us, for OIDC sign-ins. */
11
+ oauthClientId?: string;
12
+ }
13
+ export interface PasswordLogin {
14
+ homeserverUrl: string;
15
+ /** Localpart (`ole`) or full user ID (`@ole:losol.no`). */
16
+ username: string;
17
+ password: string;
18
+ /** Shown in the user's device list. @default 'oratio' */
19
+ deviceName?: string;
20
+ }
21
+ /** Signs in with a password and returns a new session. For development and password-only servers. */
22
+ export declare function loginWithPassword(login: PasswordLogin): Promise<OratioSession>;
23
+ export interface StartClientOptions {
24
+ /** Called with the updated session when tokens are refreshed. Store it. */
25
+ onSessionChange?: (session: OratioSession) => void;
26
+ }
27
+ /**
28
+ * Creates a client for a session and starts syncing. OIDC sessions refresh
29
+ * their access token as it expires. No end-to-end encryption: encrypted rooms
30
+ * show up, but their messages cannot be read.
31
+ */
32
+ export declare function startClient(session: OratioSession, options?: StartClientOptions): Promise<MatrixClient>;
33
+ /** Stops syncing and invalidates the access token on the server. */
34
+ export declare function logout(client: MatrixClient): Promise<void>;
35
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAIA,OAAO,EAAgB,KAAK,YAAY,EAAkB,MAAM,eAAe,CAAC;AAGhF,uFAAuF;AACvF,MAAM,WAAW,aAAa;IAC5B,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,6EAA6E;IAC7E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,yEAAyE;IACzE,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,aAAa;IAC5B,aAAa,EAAE,MAAM,CAAC;IACtB,2DAA2D;IAC3D,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,yDAAyD;IACzD,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,qGAAqG;AACrG,wBAAsB,iBAAiB,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAcpF;AAED,MAAM,WAAW,kBAAkB;IACjC,2EAA2E;IAC3E,eAAe,CAAC,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,CAAC;CACpD;AAED;;;;GAIG;AACH,wBAAsB,WAAW,CAC/B,OAAO,EAAE,aAAa,EACtB,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,YAAY,CAAC,CAqBvB;AAED,oEAAoE;AACpE,wBAAsB,MAAM,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAGhE"}
@@ -0,0 +1,28 @@
1
+ import { type MatrixEvent } from 'matrix-js-sdk';
2
+ /**
3
+ * A timeline row. Same shape as `ChatLogMessage` in
4
+ * `@eventuras/ratio-ui/chat`, without depending on it.
5
+ */
6
+ export interface OratioMessage {
7
+ id: string;
8
+ type: 'msg' | 'action';
9
+ time: string;
10
+ nick: string;
11
+ text: string;
12
+ }
13
+ /** The parts of a matrix-js-sdk `MatrixEvent` the mapping reads. */
14
+ export type EventLike = Pick<MatrixEvent, 'getId' | 'getType' | 'getContent' | 'getSender' | 'getTs' | 'isRedacted'> & {
15
+ sender?: {
16
+ name: string;
17
+ } | null;
18
+ };
19
+ export interface TimelineOptions {
20
+ /** BCP 47 locale for message times. @default the runtime's */
21
+ locale?: string;
22
+ }
23
+ /**
24
+ * Maps timeline events to log rows: text messages, notices and `/me` emotes.
25
+ * Everything else (state changes, reactions, encrypted events) is skipped for now.
26
+ */
27
+ export declare function toOratioMessages(events: readonly EventLike[], options?: TimelineOptions): OratioMessage[];
28
+ //# sourceMappingURL=timeline.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timeline.d.ts","sourceRoot":"","sources":["../src/timeline.ts"],"names":[],"mappings":"AAIA,OAAO,EAAa,KAAK,WAAW,EAAW,MAAM,eAAe,CAAC;AAGrE;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,KAAK,GAAG,QAAQ,CAAC;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AAED,oEAAoE;AACpE,MAAM,MAAM,SAAS,GAAG,IAAI,CAC1B,WAAW,EACX,OAAO,GAAG,SAAS,GAAG,YAAY,GAAG,WAAW,GAAG,OAAO,GAAG,YAAY,CAC1E,GAAG;IAAE,MAAM,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAA;CAAE,CAAC;AAEzC,MAAM,WAAW,eAAe;IAC9B,8DAA8D;IAC9D,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,SAAS,SAAS,EAAE,EAC5B,OAAO,GAAE,eAAoB,GAC5B,aAAa,EAAE,CAsBjB"}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@eventuras/oratio-core",
3
+ "version": "0.1.0",
4
+ "description": "Framework-agnostic Matrix client core for oratio, on matrix-js-sdk",
5
+ "license": "MPL-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/losol/oratio.git",
9
+ "directory": "packages/oratio-core"
10
+ },
11
+ "type": "module",
12
+ "sideEffects": false,
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "devDependencies": {
25
+ "@eventuras/typescript-config": "^1.1.0",
26
+ "@eventuras/vite-config": "^0.4.0",
27
+ "typescript": "^6.0.2",
28
+ "vite": "^8.2.1",
29
+ "vitest": "^4.1.10"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "matrix-js-sdk": "^42.4.0"
36
+ },
37
+ "scripts": {
38
+ "build": "vite build && tsc --emitDeclarationOnly",
39
+ "dev": "vite build --watch",
40
+ "typecheck": "tsc --noEmit",
41
+ "test": "vitest run",
42
+ "test:watch": "vitest"
43
+ }
44
+ }