@matrix-widget-toolkit/api 3.3.0 → 3.3.2

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,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  var matrixWidgetApi = require('matrix-widget-api');
4
- var rxjs = require('rxjs');
5
4
  var qs = require('qs');
5
+ var rxjs = require('rxjs');
6
6
 
7
7
  /*
8
8
  * Copyright 2022 Nordeck IT + Consulting GmbH
@@ -19,92 +19,112 @@ var qs = require('qs');
19
19
  * See the License for the specific language governing permissions and
20
20
  * limitations under the License.
21
21
  */
22
- var __assign$1 = (undefined && undefined.__assign) || function () {
23
- __assign$1 = Object.assign || function(t) {
24
- for (var s, i = 1, n = arguments.length; i < n; i++) {
25
- s = arguments[i];
26
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
27
- t[p] = s[p];
28
- }
29
- return t;
30
- };
31
- return __assign$1.apply(this, arguments);
32
- };
33
22
  /**
34
- * Extract the parameters used to initialize the widget API from the current
35
- * `window.location`.
36
- * @returns The parameters required for initializing the widget API.
23
+ * Generate a list of capabilities to access the timeline of other rooms.
24
+ * If enabled, all previously or future capabilities will apply to _all_
25
+ * selected rooms.
26
+ * If `Symbols.AnyRoom` is passed, this is expanded to all joined
27
+ * or invited rooms the client is able to see, current and future.
28
+ *
29
+ * @param roomIds - a list of room ids or `@link Symbols.AnyRoom`.
30
+ * @returns the generated capabilities.
37
31
  */
38
- function extractWidgetApiParameters() {
39
- var query = qs.parse(window.location.search, { ignoreQueryPrefix: true });
40
- // If either parentUrl or widgetId is missing, we have no element context and
41
- // want to inform the user that the widget only works inside of element.
42
- if (typeof query.parentUrl !== 'string') {
43
- throw Error('Missing parameter "parentUrl"');
32
+ function generateRoomTimelineCapabilities(roomIds) {
33
+ if (roomIds === matrixWidgetApi.Symbols.AnyRoom) {
34
+ return ['org.matrix.msc2762.timeline:*'];
44
35
  }
45
- var clientOrigin = new URL(query.parentUrl).origin;
46
- if (typeof query.widgetId !== 'string') {
47
- throw Error('Missing parameter "widgetId"');
36
+ if (Array.isArray(roomIds)) {
37
+ return roomIds.map(function (id) { return "org.matrix.msc2762.timeline:".concat(id); });
48
38
  }
49
- var widgetId = query.widgetId;
50
- return { widgetId: widgetId, clientOrigin: clientOrigin };
39
+ return [];
51
40
  }
41
+
42
+ /*
43
+ * Copyright 2022 Nordeck IT + Consulting GmbH
44
+ *
45
+ * Licensed under the Apache License, Version 2.0 (the "License");
46
+ * you may not use this file except in compliance with the License.
47
+ * You may obtain a copy of the License at
48
+ *
49
+ * http://www.apache.org/licenses/LICENSE-2.0
50
+ *
51
+ * Unless required by applicable law or agreed to in writing, software
52
+ * distributed under the License is distributed on an "AS IS" BASIS,
53
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
54
+ * See the License for the specific language governing permissions and
55
+ * limitations under the License.
56
+ */
52
57
  /**
53
- * Extract the widget parameters from the current `window.location`.
54
- * @returns The all unprocessed raw widget parameters.
58
+ * Generate a unique displayname of a user that is consistent across Matrix clients.
59
+ *
60
+ * @remarks The algorithm is based on https://spec.matrix.org/v1.1/client-server-api/#calculating-the-display-name-for-a-user
61
+ *
62
+ * @param member - the member to generate a name for.
63
+ * @param allRoomMembers - a list of all members of the same room.
64
+ * @returns the displayname that is unique in given the set of all room members.
55
65
  */
56
- function extractRawWidgetParameters() {
57
- var hash = window.location.hash.substring(window.location.hash.indexOf('?') + 1);
58
- var params = __assign$1(__assign$1({}, qs.parse(window.location.search, { ignoreQueryPrefix: true })), qs.parse(hash));
59
- return Object.fromEntries(Object.entries(params).filter(
60
- // For now only use simple values, don't allow them to be specified more
61
- // than once.
62
- function (e) { return typeof e[1] === 'string'; }));
66
+ function getRoomMemberDisplayName(member, allRoomMembers) {
67
+ if (allRoomMembers === void 0) { allRoomMembers = []; }
68
+ // If the m.room.member state event has no displayname field, or if that field
69
+ // has a null value, use the raw user id as the display name.
70
+ if (typeof member.content.displayname !== 'string') {
71
+ return member.state_key;
72
+ }
73
+ // If the m.room.member event has a displayname which is unique among members of
74
+ // the room with membership: join or membership: invite, ...
75
+ var hasDuplicateDisplayName = allRoomMembers.some(function (m) {
76
+ // same room
77
+ return m.room_id === member.room_id &&
78
+ // not the own event
79
+ m.state_key !== member.state_key &&
80
+ // only join or invite state
81
+ ['join', 'invite'].includes(m.content.membership) &&
82
+ // same displayname
83
+ m.content.displayname === member.content.displayname;
84
+ });
85
+ if (!hasDuplicateDisplayName) {
86
+ // ... use the given displayname as the user-visible display name.
87
+ return member.content.displayname;
88
+ }
89
+ else {
90
+ // The m.room.member event has a non-unique displayname. This should be
91
+ // disambiguated using the user id, for example “display name (@id:homeserver.org)”.
92
+ return "".concat(member.content.displayname, " (").concat(member.state_key, ")");
93
+ }
63
94
  }
95
+
96
+ /*
97
+ * Copyright 2022 Nordeck IT + Consulting GmbH
98
+ *
99
+ * Licensed under the Apache License, Version 2.0 (the "License");
100
+ * you may not use this file except in compliance with the License.
101
+ * You may obtain a copy of the License at
102
+ *
103
+ * http://www.apache.org/licenses/LICENSE-2.0
104
+ *
105
+ * Unless required by applicable law or agreed to in writing, software
106
+ * distributed under the License is distributed on an "AS IS" BASIS,
107
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
108
+ * See the License for the specific language governing permissions and
109
+ * limitations under the License.
110
+ */
64
111
  /**
65
- * Extract the widget parameters from the current `window.location`.
66
- * @returns The widget parameters.
112
+ * Check if the given event is a {@link StateEvent}.
113
+ *
114
+ * @param event - An event that is either a {@link RoomEvent} or a {@link StateEvent}.
115
+ * @returns True, if the event is a {@link StateEvent}.
67
116
  */
68
- function extractWidgetParameters() {
69
- var params = extractRawWidgetParameters();
70
- // This is a hack to detect whether we are in a mobile client that supports widgets,
71
- // but not the widget API. Mobile clients are not passing the parameters required for
72
- // the widget API (like widgetId), but are passing the replaced placeholder values for
73
- // the widget parameters.
74
- var roomId = params['matrix_room_id'];
75
- var isOpenedByClient = typeof roomId === 'string' && roomId !== '$matrix_room_id';
76
- return {
77
- userId: params['matrix_user_id'],
78
- displayName: params['matrix_display_name'],
79
- avatarUrl: params['matrix_avatar_url'],
80
- roomId: roomId,
81
- theme: params['theme'],
82
- clientId: params['matrix_client_id'],
83
- clientLanguage: params['matrix_client_language'],
84
- isOpenedByClient: isOpenedByClient,
85
- };
117
+ function isStateEvent(event) {
118
+ return 'state_key' in event && typeof event.state_key === 'string';
86
119
  }
87
120
  /**
88
- * Parse a widget id into the individual fields.
89
- * @param widgetId - The widget id to parse.
90
- * @returns The individual fields encoded inside a widget id.
121
+ * Check if the given event is a {@link RoomEvent}.
122
+ *
123
+ * @param event - An event that is either a {@link RoomEvent} or a {@link StateEvent}.
124
+ * @returns True, if the event is a {@link RoomEvent}.
91
125
  */
92
- function parseWidgetId(widgetId) {
93
- // TODO: Is this whole parsing still working for user widgets?
94
- var mainWidgetId = decodeURIComponent(widgetId).replace(/^modal_/, '');
95
- var roomId = mainWidgetId.indexOf('_')
96
- ? decodeURIComponent(mainWidgetId.split('_')[0])
97
- : undefined;
98
- var creator = (mainWidgetId.match(/_/g) || []).length > 1
99
- ? decodeURIComponent(mainWidgetId.split('_')[1])
100
- : undefined;
101
- var isModal = decodeURIComponent(widgetId).startsWith('modal_');
102
- return {
103
- mainWidgetId: mainWidgetId,
104
- roomId: roomId,
105
- creator: creator,
106
- isModal: isModal,
107
- };
126
+ function isRoomEvent(event) {
127
+ return !('state_key' in event);
108
128
  }
109
129
 
110
130
  /*
@@ -122,17 +142,6 @@ function parseWidgetId(widgetId) {
122
142
  * See the License for the specific language governing permissions and
123
143
  * limitations under the License.
124
144
  */
125
- var __assign = (undefined && undefined.__assign) || function () {
126
- __assign = Object.assign || function(t) {
127
- for (var s, i = 1, n = arguments.length; i < n; i++) {
128
- s = arguments[i];
129
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
130
- t[p] = s[p];
131
- }
132
- return t;
133
- };
134
- return __assign.apply(this, arguments);
135
- };
136
145
  var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
137
146
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
138
147
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -169,124 +178,63 @@ var __generator$3 = (undefined && undefined.__generator) || function (thisArg, b
169
178
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
170
179
  }
171
180
  };
172
- var __rest = (undefined && undefined.__rest) || function (s, e) {
173
- var t = {};
174
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
175
- t[p] = s[p];
176
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
177
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
178
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
179
- t[p[i]] = s[p[i]];
180
- }
181
- return t;
182
- };
183
181
  /**
184
- * Checks whether all widget parameters were provided to the widget.
182
+ * The capability that needs to be requested in order to navigate to another room.
183
+ */
184
+ var WIDGET_CAPABILITY_NAVIGATE = 'org.matrix.msc2931.navigate';
185
+ /**
186
+ * Navigate the client to another matrix room.
185
187
  *
186
- * @param widgetApi - The widget api to read the parameters from
187
- * @returns True, if all parameters were provided.
188
+ * @remarks This requires the {@link WIDGET_CAPABILITY_NAVIGATE} capability.
189
+ *
190
+ * @param widgetApi - the {@link WidgetApi} instance.
191
+ * @param roomId - the room ID.
192
+ * @param opts - {@link NavigateToRoomOptions}
188
193
  */
189
- function hasRequiredWidgetParameters(widgetApi) {
190
- return (typeof widgetApi.widgetParameters.userId === 'string' &&
191
- typeof widgetApi.widgetParameters.displayName === 'string' &&
192
- typeof widgetApi.widgetParameters.avatarUrl === 'string' &&
193
- typeof widgetApi.widgetParameters.roomId === 'string' &&
194
- typeof widgetApi.widgetParameters.theme === 'string' &&
195
- typeof widgetApi.widgetParameters.clientId === 'string' &&
196
- typeof widgetApi.widgetParameters.clientLanguage === 'string');
194
+ function navigateToRoom(widgetApi_1, roomId_1) {
195
+ return __awaiter$3(this, arguments, void 0, function (widgetApi, roomId, opts) {
196
+ var _a, via, params, url;
197
+ if (opts === void 0) { opts = {}; }
198
+ return __generator$3(this, function (_b) {
199
+ switch (_b.label) {
200
+ case 0:
201
+ _a = opts.via, via = _a === void 0 ? [] : _a;
202
+ params = qs.stringify({ via: via }, { addQueryPrefix: true, arrayFormat: 'repeat' });
203
+ url = "https://matrix.to/#/".concat(encodeURIComponent(roomId)).concat(params);
204
+ return [4 /*yield*/, widgetApi.navigateTo(url)];
205
+ case 1:
206
+ _b.sent();
207
+ return [2 /*return*/];
208
+ }
209
+ });
210
+ });
197
211
  }
212
+
213
+ /*
214
+ * Copyright 2022 Nordeck IT + Consulting GmbH
215
+ *
216
+ * Licensed under the Apache License, Version 2.0 (the "License");
217
+ * you may not use this file except in compliance with the License.
218
+ * You may obtain a copy of the License at
219
+ *
220
+ * http://www.apache.org/licenses/LICENSE-2.0
221
+ *
222
+ * Unless required by applicable law or agreed to in writing, software
223
+ * distributed under the License is distributed on an "AS IS" BASIS,
224
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
225
+ * See the License for the specific language governing permissions and
226
+ * limitations under the License.
227
+ */
198
228
  /**
199
- * Generate a registration URL for the widget based on the current URL and
200
- * include all widget parameters (and their placeholders).
201
- * @param options - Options for generating the URL.
202
- * Use `pathName` to include an optional sub path in the URL.
203
- * Use `includeParameters` to append the widget parameters to
204
- * the URL, defaults to `true`.
205
- * @returns The generated URL.
229
+ * Compares two room events by their origin server timestamp.
230
+ *
231
+ * @param a - A room event
232
+ * @param b - A room event
233
+ * @returns Either zero if the timestamp is equal, \>0 if a is newer, or \<0 if
234
+ * b is newer.
206
235
  */
207
- function generateWidgetRegistrationUrl(options) {
208
- var _a, _b, _c, _d, _e, _f, _g;
209
- if (options === void 0) { options = {}; }
210
- var pathName = options.pathName, _h = options.includeParameters, includeParameters = _h === void 0 ? true : _h, widgetParameters = options.widgetParameters;
211
- // don't forward widgetId and parentUrl as they will be generated by the client
212
- var _j = extractRawWidgetParameters(); _j.widgetId; _j.parentUrl; var rawWidgetParameters = __rest(_j, ["widgetId", "parentUrl"]);
213
- var parameters = Object.entries(__assign(__assign({}, rawWidgetParameters), { theme: (_a = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.theme) !== null && _a !== void 0 ? _a : '$org.matrix.msc2873.client_theme', matrix_user_id: (_b = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.userId) !== null && _b !== void 0 ? _b : '$matrix_user_id', matrix_display_name: (_c = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.displayName) !== null && _c !== void 0 ? _c : '$matrix_display_name', matrix_avatar_url: (_d = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.avatarUrl) !== null && _d !== void 0 ? _d : '$matrix_avatar_url', matrix_room_id: (_e = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.roomId) !== null && _e !== void 0 ? _e : '$matrix_room_id', matrix_client_id: (_f = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.clientId) !== null && _f !== void 0 ? _f : '$org.matrix.msc2873.client_id', matrix_client_language: (_g = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.clientLanguage) !== null && _g !== void 0 ? _g : '$org.matrix.msc2873.client_language' }))
214
- .map(function (_a) {
215
- var k = _a[0], v = _a[1];
216
- return "".concat(k, "=").concat(v);
217
- })
218
- .join('&');
219
- var url = new URL(window.location.href);
220
- if (pathName) {
221
- url.pathname = pathName;
222
- }
223
- else {
224
- // ensure trailing '/'
225
- url.pathname = url.pathname.replace(/\/?$/, '/');
226
- }
227
- url.search = '';
228
- url.hash = includeParameters ? "#/?".concat(parameters) : '';
229
- return url.toString();
230
- }
231
- var STATE_EVENT_WIDGETS = 'im.vector.modular.widgets';
232
- /**
233
- * Repair/configure the registration of the current widget.
234
- * This steps make sure to include all the required widget parameters in the
235
- * URL. Support setting a widget name and additional parameters.
236
- *
237
- * @param widgetApi - The widget api of the current widget.
238
- * @param registration - Optional configuration options for the widget
239
- * registration, like the display name of the widget.
240
- */
241
- function repairWidgetRegistration(widgetApi, registration) {
242
- if (registration === void 0) { registration = {}; }
243
- return __awaiter$3(this, void 0, void 0, function () {
244
- var readResult, url, name, type, data;
245
- return __generator$3(this, function (_a) {
246
- switch (_a.label) {
247
- case 0: return [4 /*yield*/, widgetApi.requestCapabilities([
248
- matrixWidgetApi.WidgetEventCapability.forStateEvent(matrixWidgetApi.EventDirection.Send, STATE_EVENT_WIDGETS, widgetApi.widgetId),
249
- matrixWidgetApi.WidgetEventCapability.forStateEvent(matrixWidgetApi.EventDirection.Receive, STATE_EVENT_WIDGETS, widgetApi.widgetId),
250
- ])];
251
- case 1:
252
- _a.sent();
253
- return [4 /*yield*/, widgetApi.receiveSingleStateEvent(STATE_EVENT_WIDGETS, widgetApi.widgetId)];
254
- case 2:
255
- readResult = _a.sent();
256
- if (!readResult) {
257
- throw new Error("Error while repairing registration, can't find existing registration.");
258
- }
259
- url = generateWidgetRegistrationUrl();
260
- name = registration.name &&
261
- (!readResult.content.name ||
262
- readResult.content.name === 'Custom Widget' ||
263
- readResult.content.name === 'Custom')
264
- ? registration.name
265
- : readResult.content.name;
266
- type = registration.type &&
267
- (!readResult.content.type || readResult.content.type === 'm.custom')
268
- ? registration.type
269
- : readResult.content.type;
270
- data = registration.data
271
- ? __assign(__assign({}, readResult.content.data), registration.data) : readResult.content.data;
272
- // This is a workaround because changing the widget config is breaking the
273
- // widget API communication. However we need to fail in case the power level
274
- // for this change is missing. As the error happens quite fast, we just wait
275
- // a moment and then consider the operation as succeeded.
276
- return [4 /*yield*/, Promise.race([
277
- widgetApi.sendStateEvent(STATE_EVENT_WIDGETS, __assign(__assign({}, readResult.content), { url: url.toString(), name: name, type: type, data: data }), { stateKey: widgetApi.widgetId }),
278
- new Promise(function (resolve) { return setTimeout(resolve, 1000); }),
279
- ])];
280
- case 3:
281
- // This is a workaround because changing the widget config is breaking the
282
- // widget API communication. However we need to fail in case the power level
283
- // for this change is missing. As the error happens quite fast, we just wait
284
- // a moment and then consider the operation as succeeded.
285
- _a.sent();
286
- return [2 /*return*/];
287
- }
288
- });
289
- });
236
+ function compareOriginServerTS(a, b) {
237
+ return a.origin_server_ts - b.origin_server_ts;
290
238
  }
291
239
 
292
240
  /*
@@ -304,31 +252,176 @@ function repairWidgetRegistration(widgetApi, registration) {
304
252
  * See the License for the specific language governing permissions and
305
253
  * limitations under the License.
306
254
  */
307
- function convertToRawCapabilities(rawCapabilities) {
308
- return rawCapabilities.map(function (c) { return (typeof c === 'string' ? c : c.raw); });
255
+ /**
256
+ * The name of the power levels state event.
257
+ */
258
+ var STATE_EVENT_POWER_LEVELS = 'm.room.power_levels';
259
+ function isNumberOrUndefined(value) {
260
+ return value === undefined || typeof value === 'number';
309
261
  }
310
- function isDefined(arg) {
311
- return arg !== null && arg !== undefined;
262
+ function isStringToNumberMapOrUndefined(value) {
263
+ return (value === undefined ||
264
+ (value !== null &&
265
+ typeof value === 'object' &&
266
+ Object.entries(value).every(function (_a) {
267
+ var k = _a[0], v = _a[1];
268
+ return typeof k === 'string' && typeof v === 'number';
269
+ })));
312
270
  }
313
- function unique(items) {
314
- return Array.from(new Set(items));
271
+ /**
272
+ * Validates that `event` is has a valid structure for a
273
+ * {@link PowerLevelsStateEvent}.
274
+ * @param event - The event to validate.
275
+ * @returns True, if the event is valid.
276
+ */
277
+ function isValidPowerLevelStateEvent(event) {
278
+ if (event.type !== STATE_EVENT_POWER_LEVELS ||
279
+ typeof event.content !== 'object') {
280
+ return false;
281
+ }
282
+ var content = event.content;
283
+ if (!isStringToNumberMapOrUndefined(content.events)) {
284
+ return false;
285
+ }
286
+ if (!isNumberOrUndefined(content.state_default)) {
287
+ return false;
288
+ }
289
+ if (!isNumberOrUndefined(content.events_default)) {
290
+ return false;
291
+ }
292
+ if (!isStringToNumberMapOrUndefined(content.users)) {
293
+ return false;
294
+ }
295
+ if (!isNumberOrUndefined(content.users_default)) {
296
+ return false;
297
+ }
298
+ if (!isNumberOrUndefined(content.ban)) {
299
+ return false;
300
+ }
301
+ if (!isNumberOrUndefined(content.invite)) {
302
+ return false;
303
+ }
304
+ if (!isNumberOrUndefined(content.kick)) {
305
+ return false;
306
+ }
307
+ if (!isNumberOrUndefined(content.redact)) {
308
+ return false;
309
+ }
310
+ return true;
315
311
  }
316
- function subtractSet(as, bs) {
317
- var result = new Set(as);
318
- bs.forEach(function (v) { return result.delete(v); });
319
- return result;
312
+ /**
313
+ * Check if a user has the power to send a specific room event.
314
+ *
315
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
316
+ * @param userId - the id of the user
317
+ * @param eventType - the type of room event
318
+ * @returns if true, the user has the power
319
+ */
320
+ function hasRoomEventPower(powerLevelStateEvent, userId, eventType) {
321
+ if (!powerLevelStateEvent) {
322
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
323
+ return true;
324
+ }
325
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
326
+ var eventLevel = calculateRoomEventPowerLevel(powerLevelStateEvent, eventType);
327
+ return userLevel >= eventLevel;
320
328
  }
321
- function isInRoom(matrixEvent, currentRoomId, roomIds) {
322
- if (!roomIds) {
323
- return matrixEvent.room_id === currentRoomId;
329
+ /**
330
+ * Check if a user has the power to send a specific state event.
331
+ *
332
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
333
+ * @param userId - the id of the user
334
+ * @param eventType - the type of state event
335
+ * @returns if true, the user has the power
336
+ */
337
+ function hasStateEventPower(powerLevelStateEvent, userId, eventType) {
338
+ if (!powerLevelStateEvent) {
339
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
340
+ return true;
324
341
  }
325
- if (typeof roomIds === 'string') {
326
- if (roomIds !== matrixWidgetApi.Symbols.AnyRoom) {
327
- throw Error("Unknown room id symbol: ".concat(roomIds));
328
- }
342
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
343
+ var eventLevel = calculateStateEventPowerLevel(powerLevelStateEvent, eventType);
344
+ return userLevel >= eventLevel;
345
+ }
346
+ /**
347
+ * Check if a user has the power to perform a specific action.
348
+ *
349
+ * Supported actions:
350
+ * * invite: Invite a new user into the room
351
+ * * kick: Kick a user from the room
352
+ * * ban: Ban a user from the room
353
+ * * redact: Redact a message from another user
354
+ *
355
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
356
+ * @param userId - the id of the user
357
+ * @param action - the action
358
+ * @returns if true, the user has the power
359
+ */
360
+ function hasActionPower(powerLevelStateEvent, userId, action) {
361
+ if (!powerLevelStateEvent) {
362
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
329
363
  return true;
330
364
  }
331
- return roomIds.includes(matrixEvent.room_id);
365
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
366
+ var eventLevel = calculateActionPowerLevel(powerLevelStateEvent, action);
367
+ return userLevel >= eventLevel;
368
+ }
369
+ /**
370
+ * Calculate the power level of the user based on a `m.room.power_levels` event.
371
+ *
372
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event.
373
+ * @param userId - the ID of the user.
374
+ * @returns the power level of the user.
375
+ */
376
+ function calculateUserPowerLevel(powerLevelStateEvent, userId) {
377
+ var _a, _b, _c;
378
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L8-L12
379
+ return ((_c = (_b = (userId ? (_a = powerLevelStateEvent.users) === null || _a === void 0 ? void 0 : _a[userId] : undefined)) !== null && _b !== void 0 ? _b : powerLevelStateEvent.users_default) !== null && _c !== void 0 ? _c : 0);
380
+ }
381
+ /**
382
+ * Calculate the power level that a user needs send a specific room event.
383
+ *
384
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
385
+ * @param eventType - the type of room event
386
+ * @returns the power level that is needed
387
+ */
388
+ function calculateRoomEventPowerLevel(powerLevelStateEvent, eventType) {
389
+ var _a, _b, _c;
390
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
391
+ return ((_c = (_b = (_a = powerLevelStateEvent.events) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : powerLevelStateEvent.events_default) !== null && _c !== void 0 ? _c : 0);
392
+ }
393
+ /**
394
+ * Calculate the power level that a user needs send a specific state event.
395
+ *
396
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
397
+ * @param eventType - the type of state event
398
+ * @returns the power level that is needed
399
+ */
400
+ function calculateStateEventPowerLevel(powerLevelStateEvent, eventType) {
401
+ var _a, _b, _c;
402
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
403
+ return ((_c = (_b = (_a = powerLevelStateEvent.events) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : powerLevelStateEvent.state_default) !== null && _c !== void 0 ? _c : 50);
404
+ }
405
+ /**
406
+ * Calculate the power level that a user needs to perform an action.
407
+ *
408
+ * Supported actions:
409
+ * * invite: Invite a new user into the room
410
+ * * kick: Kick a user from the room
411
+ * * ban: Ban a user from the room
412
+ * * redact: Redact a message from another user
413
+ *
414
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
415
+ * @param action - the action
416
+ * @returns the power level that is needed
417
+ */
418
+ function calculateActionPowerLevel(powerLevelStateEvent, action) {
419
+ var _a, _b;
420
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L27-L32
421
+ if (action === 'invite') {
422
+ return (_a = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _a !== void 0 ? _a : 0;
423
+ }
424
+ return (_b = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _b !== void 0 ? _b : 50;
332
425
  }
333
426
 
334
427
  /*
@@ -382,672 +475,452 @@ var __generator$2 = (undefined && undefined.__generator) || function (thisArg, b
382
475
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
383
476
  }
384
477
  };
385
- var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
386
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
387
- if (ar || !(i in from)) {
388
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
389
- ar[i] = from[i];
390
- }
478
+ /**
479
+ * The name of the redaction room event.
480
+ */
481
+ var ROOM_EVENT_REDACTION = 'm.room.redaction';
482
+ /**
483
+ * Check whether the format of a redaction event is valid.
484
+ * @param event - The event to check.
485
+ * @returns True if the event format is valid, otherwise false.
486
+ */
487
+ function isValidRedactionEvent(event) {
488
+ if (event.type === ROOM_EVENT_REDACTION &&
489
+ typeof event.redacts === 'string') {
490
+ return true;
391
491
  }
392
- return to.concat(ar || Array.prototype.slice.call(from));
393
- };
492
+ return false;
493
+ }
394
494
  /**
395
- * Implementation of the API from the widget to the client.
396
- *
397
- * @remarks Widget API is specified here:
398
- * https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit#heading=h.9rn9lt6ctkgi
495
+ * Redacts an event in the current room.
496
+ * @param widgetApi - An instance of the widget API.
497
+ * @param eventId - The id of the event to redact.
498
+ * @returns The redaction event that was send to the room.
399
499
  */
400
- var WidgetApiImpl = /** @class */ (function () {
401
- function WidgetApiImpl(
402
- /**
403
- * Provide access to the underlying widget API from `matrix-widget-sdk`.
404
- *
405
- * @remarks Normally there is no need to use it, however if features are
406
- * missing from `WidgetApi` it can be handy to work with the
407
- * original API.
408
- */
409
- matrixWidgetApi$1,
410
- /** {@inheritDoc WidgetApi.widgetId} */
411
- widgetId,
412
- /** {@inheritDoc WidgetApi.widgetParameters} */
413
- widgetParameters, _a) {
414
- var _this = this;
415
- var _b = _a === void 0 ? {} : _a, _c = _b.capabilities, capabilities = _c === void 0 ? [] : _c, _d = _b.supportStandalone, supportStandalone = _d === void 0 ? false : _d;
416
- this.matrixWidgetApi = matrixWidgetApi$1;
417
- this.widgetId = widgetId;
418
- this.widgetParameters = widgetParameters;
419
- this.events$ = rxjs.fromEvent(this.matrixWidgetApi, "action:".concat(matrixWidgetApi.WidgetApiToWidgetAction.SendEvent), function (event) {
420
- event.preventDefault();
421
- try {
422
- _this.matrixWidgetApi.transport.reply(event.detail, {});
423
- }
424
- catch (_) {
425
- // Ignore errors while replying
426
- }
427
- return event;
428
- }).pipe(rxjs.share());
429
- this.toDeviceMessages$ = rxjs.fromEvent(this.matrixWidgetApi, 'action:send_to_device', function (event) {
430
- event.preventDefault();
431
- try {
432
- matrixWidgetApi$1.transport.reply(event.detail, {});
433
- }
434
- catch (_) {
435
- // Ignore errors while replying
500
+ function redactEvent(widgetApi, eventId) {
501
+ return __awaiter$2(this, void 0, void 0, function () {
502
+ var result;
503
+ return __generator$2(this, function (_a) {
504
+ switch (_a.label) {
505
+ case 0: return [4 /*yield*/, widgetApi.sendRoomEvent(ROOM_EVENT_REDACTION, { redacts: eventId })];
506
+ case 1:
507
+ result = _a.sent();
508
+ // The redaction event is special and needs to be casted, as the widget
509
+ // toolkit assumes that the content of an event is returned as we send it.
510
+ // However for redactions the content is copied directly into the event to
511
+ // make it available without decrypting the content.
512
+ return [2 /*return*/, result];
436
513
  }
437
- return event;
438
- }).pipe(rxjs.share());
439
- this.initialCapabilities = __spreadArray(__spreadArray([], capabilities, true), (supportStandalone ? [] : [matrixWidgetApi.MatrixCapabilities.RequiresClient]), true);
440
- }
441
- /**
442
- * Initialize a new widget API instance and wait till it is ready.
443
- * There should only be one instance of the widget API. The widget API should
444
- * be created as early as possible when starting the application. This is
445
- * required to match the timing of the API connection establishment with the
446
- * client, especially in Safari. Therefore it is recommended to create it
447
- * inside the entrypoint, before initializing rendering engines like react.
448
- *
449
- * @param param0 - {@link WidgetApiOptions}
450
- *
451
- * @returns A widget API instance ready to use.
452
- */
453
- WidgetApiImpl.create = function (_a) {
454
- var _b = _a === void 0 ? {} : _a, _c = _b.capabilities, capabilities = _c === void 0 ? [] : _c, _d = _b.supportStandalone, supportStandalone = _d === void 0 ? false : _d;
455
- return __awaiter$2(this, void 0, void 0, function () {
456
- var _e, clientOrigin, widgetId, widgetParameters, matrixWidgetApi$1, widgetApi;
457
- return __generator$2(this, function (_f) {
458
- switch (_f.label) {
459
- case 0:
460
- _e = extractWidgetApiParameters(), clientOrigin = _e.clientOrigin, widgetId = _e.widgetId;
461
- widgetParameters = extractWidgetParameters();
462
- matrixWidgetApi$1 = new matrixWidgetApi.WidgetApi(widgetId, clientOrigin);
463
- widgetApi = new WidgetApiImpl(matrixWidgetApi$1, widgetId, widgetParameters, { capabilities: capabilities, supportStandalone: supportStandalone });
464
- return [4 /*yield*/, widgetApi.initialize()];
465
- case 1:
466
- _f.sent();
467
- return [2 /*return*/, widgetApi];
468
- }
469
- });
470
514
  });
515
+ });
516
+ }
517
+ /**
518
+ * Observes redaction events in the current room.
519
+ * @param widgetApi - An instance of the widget API.
520
+ * @returns An observable of validated redaction events.
521
+ */
522
+ function observeRedactionEvents(widgetApi) {
523
+ return widgetApi
524
+ .observeRoomEvents(ROOM_EVENT_REDACTION)
525
+ .pipe(rxjs.filter(isValidRedactionEvent));
526
+ }
527
+
528
+ /*
529
+ * Copyright 2022 Nordeck IT + Consulting GmbH
530
+ *
531
+ * Licensed under the Apache License, Version 2.0 (the "License");
532
+ * you may not use this file except in compliance with the License.
533
+ * You may obtain a copy of the License at
534
+ *
535
+ * http://www.apache.org/licenses/LICENSE-2.0
536
+ *
537
+ * Unless required by applicable law or agreed to in writing, software
538
+ * distributed under the License is distributed on an "AS IS" BASIS,
539
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
540
+ * See the License for the specific language governing permissions and
541
+ * limitations under the License.
542
+ */
543
+ /**
544
+ * Get the original event id, or the event id of the current event if it
545
+ * doesn't relates to another event.
546
+ * @param event - The room event.
547
+ * @returns The event id of the original event, or the current event id.
548
+ */
549
+ function getOriginalEventId(event) {
550
+ var _a, _b, _c;
551
+ var newContentRelatesTo = event.content;
552
+ if (((_a = newContentRelatesTo['m.relates_to']) === null || _a === void 0 ? void 0 : _a.rel_type) === 'm.replace') {
553
+ return (_c = (_b = newContentRelatesTo['m.relates_to']) === null || _b === void 0 ? void 0 : _b.event_id) !== null && _c !== void 0 ? _c : event.event_id;
554
+ }
555
+ return event.event_id;
556
+ }
557
+ /**
558
+ * Get the content of the event, independent from whether it contains the
559
+ * content directly or contains a "m.new_content" key.
560
+ * @param event - The room event.
561
+ * @returns Only the content of the room event.
562
+ */
563
+ function getContent(event) {
564
+ var _a;
565
+ var newContentRelatesTo = event.content;
566
+ return (_a = newContentRelatesTo['m.new_content']) !== null && _a !== void 0 ? _a : event.content;
567
+ }
568
+ /**
569
+ * Validates that `event` has a valid structure for a
570
+ * {@link EventWithRelatesTo}.
571
+ * @param event - The event to validate.
572
+ * @returns True, if the event is valid.
573
+ */
574
+ function isValidEventWithRelatesTo(event) {
575
+ if (!event.content || typeof event.content !== 'object') {
576
+ return false;
577
+ }
578
+ var relatedEvent = event;
579
+ if (!relatedEvent.content['m.relates_to'] ||
580
+ typeof relatedEvent.content['m.relates_to'] !== 'object') {
581
+ return false;
582
+ }
583
+ if (typeof relatedEvent.content['m.relates_to'].rel_type !== 'string' ||
584
+ typeof relatedEvent.content['m.relates_to'].event_id !== 'string') {
585
+ return false;
586
+ }
587
+ return true;
588
+ }
589
+
590
+ /*
591
+ * Copyright 2022 Nordeck IT + Consulting GmbH
592
+ *
593
+ * Licensed under the Apache License, Version 2.0 (the "License");
594
+ * you may not use this file except in compliance with the License.
595
+ * You may obtain a copy of the License at
596
+ *
597
+ * http://www.apache.org/licenses/LICENSE-2.0
598
+ *
599
+ * Unless required by applicable law or agreed to in writing, software
600
+ * distributed under the License is distributed on an "AS IS" BASIS,
601
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
602
+ * See the License for the specific language governing permissions and
603
+ * limitations under the License.
604
+ */
605
+ /**
606
+ * The name of the room member state event.
607
+ */
608
+ var STATE_EVENT_ROOM_MEMBER = 'm.room.member';
609
+ function isStringUndefinedOrNull(value) {
610
+ return value === undefined || value === null || typeof value === 'string';
611
+ }
612
+ /**
613
+ * Validates that `event` is has a valid structure for a
614
+ * {@link RoomMemberStateEventContent}.
615
+ * @param event - The event to validate.
616
+ * @returns True, if the event is valid.
617
+ */
618
+ function isValidRoomMemberStateEvent(event) {
619
+ if (event.type !== STATE_EVENT_ROOM_MEMBER ||
620
+ typeof event.content !== 'object') {
621
+ return false;
622
+ }
623
+ var content = event.content;
624
+ if (typeof content.membership !== 'string') {
625
+ return false;
626
+ }
627
+ if (!isStringUndefinedOrNull(content.displayname)) {
628
+ return false;
629
+ }
630
+ // the avatar_url shouldn't be null, but some implementations
631
+ // set it as a valid value
632
+ if (!isStringUndefinedOrNull(content.avatar_url)) {
633
+ return false;
634
+ }
635
+ return true;
636
+ }
637
+
638
+ /*
639
+ * Copyright 2022 Nordeck IT + Consulting GmbH
640
+ *
641
+ * Licensed under the Apache License, Version 2.0 (the "License");
642
+ * you may not use this file except in compliance with the License.
643
+ * You may obtain a copy of the License at
644
+ *
645
+ * http://www.apache.org/licenses/LICENSE-2.0
646
+ *
647
+ * Unless required by applicable law or agreed to in writing, software
648
+ * distributed under the License is distributed on an "AS IS" BASIS,
649
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
650
+ * See the License for the specific language governing permissions and
651
+ * limitations under the License.
652
+ */
653
+ var __assign$1 = (undefined && undefined.__assign) || function () {
654
+ __assign$1 = Object.assign || function(t) {
655
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
656
+ s = arguments[i];
657
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
658
+ t[p] = s[p];
659
+ }
660
+ return t;
471
661
  };
472
- /**
473
- * Initialize the widget API and wait till a connection with the client is
474
- * fully established.
475
- *
476
- * Waits till the user has approved the initial set of capabilities. The
477
- * method doesn't fail if the user doesn't approve all of them. It is
478
- * required to check manually afterwards.
479
- * In case of modal widgets it waits till the `widgetConfig` is received.
480
- *
481
- * @remarks Should only be called once during startup.
482
- */
483
- WidgetApiImpl.prototype.initialize = function () {
484
- return __awaiter$2(this, void 0, void 0, function () {
485
- var ready, isModal, configReady, rawCapabilities;
486
- var _this = this;
487
- return __generator$2(this, function (_a) {
488
- switch (_a.label) {
489
- case 0:
490
- ready = new Promise(function (resolve) {
491
- _this.matrixWidgetApi.once('ready', function () { return resolve(); });
492
- });
493
- isModal = parseWidgetId(this.widgetId).isModal;
494
- configReady = isModal
495
- ? (function () { return __awaiter$2(_this, void 0, void 0, function () {
496
- var widgetConfig$, _a;
497
- var _this = this;
498
- return __generator$2(this, function (_b) {
499
- switch (_b.label) {
500
- case 0:
501
- widgetConfig$ = rxjs.fromEvent(this.matrixWidgetApi, "action:".concat(matrixWidgetApi.WidgetApiToWidgetAction.WidgetConfig), function (ev) {
502
- ev.preventDefault();
503
- _this.matrixWidgetApi.transport.reply(ev.detail, {});
504
- return ev.detail.data;
505
- });
506
- _a = this;
507
- return [4 /*yield*/, rxjs.firstValueFrom(widgetConfig$)];
508
- case 1:
509
- _a.widgetConfig = _b.sent();
510
- return [2 /*return*/];
511
- }
512
- });
513
- }); })()
514
- : undefined;
515
- rawCapabilities = unique(convertToRawCapabilities(this.initialCapabilities));
516
- this.matrixWidgetApi.requestCapabilities(rawCapabilities);
517
- this.matrixWidgetApi.start();
518
- return [4 /*yield*/, ready];
519
- case 1:
520
- _a.sent();
521
- if (!configReady) return [3 /*break*/, 3];
522
- return [4 /*yield*/, configReady];
523
- case 2:
524
- _a.sent();
525
- _a.label = 3;
526
- case 3: return [2 /*return*/];
527
- }
528
- });
529
- });
530
- };
531
- /** {@inheritDoc WidgetApi.getWidgetConfig} */
532
- WidgetApiImpl.prototype.getWidgetConfig = function () {
533
- return this.widgetConfig;
534
- };
535
- /** {@inheritDoc WidgetApi.rerequestInitialCapabilities} */
536
- WidgetApiImpl.prototype.rerequestInitialCapabilities = function () {
537
- return __awaiter$2(this, void 0, void 0, function () {
538
- return __generator$2(this, function (_a) {
539
- switch (_a.label) {
540
- case 0: return [4 /*yield*/, this.requestCapabilities(this.initialCapabilities)];
541
- case 1: return [2 /*return*/, _a.sent()];
542
- }
543
- });
544
- });
545
- };
546
- /** {@inheritDoc WidgetApi.hasInitialCapabilities} */
547
- WidgetApiImpl.prototype.hasInitialCapabilities = function () {
548
- return this.hasCapabilities(this.initialCapabilities);
662
+ return __assign$1.apply(this, arguments);
663
+ };
664
+ /**
665
+ * Extract the parameters used to initialize the widget API from the current
666
+ * `window.location`.
667
+ * @returns The parameters required for initializing the widget API.
668
+ */
669
+ function extractWidgetApiParameters() {
670
+ var query = qs.parse(window.location.search, { ignoreQueryPrefix: true });
671
+ // If either parentUrl or widgetId is missing, we have no element context and
672
+ // want to inform the user that the widget only works inside of element.
673
+ if (typeof query.parentUrl !== 'string') {
674
+ throw Error('Missing parameter "parentUrl"');
675
+ }
676
+ var clientOrigin = new URL(query.parentUrl).origin;
677
+ if (typeof query.widgetId !== 'string') {
678
+ throw Error('Missing parameter "widgetId"');
679
+ }
680
+ var widgetId = query.widgetId;
681
+ return { widgetId: widgetId, clientOrigin: clientOrigin };
682
+ }
683
+ /**
684
+ * Extract the widget parameters from the current `window.location`.
685
+ * @returns The all unprocessed raw widget parameters.
686
+ */
687
+ function extractRawWidgetParameters() {
688
+ var hash = window.location.hash.substring(window.location.hash.indexOf('?') + 1);
689
+ var params = __assign$1(__assign$1({}, qs.parse(window.location.search, { ignoreQueryPrefix: true })), qs.parse(hash));
690
+ return Object.fromEntries(Object.entries(params).filter(
691
+ // For now only use simple values, don't allow them to be specified more
692
+ // than once.
693
+ function (e) { return typeof e[1] === 'string'; }));
694
+ }
695
+ /**
696
+ * Extract the widget parameters from the current `window.location`.
697
+ * @returns The widget parameters.
698
+ */
699
+ function extractWidgetParameters() {
700
+ var params = extractRawWidgetParameters();
701
+ // This is a hack to detect whether we are in a mobile client that supports widgets,
702
+ // but not the widget API. Mobile clients are not passing the parameters required for
703
+ // the widget API (like widgetId), but are passing the replaced placeholder values for
704
+ // the widget parameters.
705
+ var roomId = params['matrix_room_id'];
706
+ var isOpenedByClient = typeof roomId === 'string' && roomId !== '$matrix_room_id';
707
+ return {
708
+ userId: params['matrix_user_id'],
709
+ displayName: params['matrix_display_name'],
710
+ avatarUrl: params['matrix_avatar_url'],
711
+ roomId: roomId,
712
+ theme: params['theme'],
713
+ clientId: params['matrix_client_id'],
714
+ clientLanguage: params['matrix_client_language'],
715
+ baseUrl: params['matrix_base_url'],
716
+ isOpenedByClient: isOpenedByClient,
549
717
  };
550
- /** {@inheritDoc WidgetApi.requestCapabilities} */
551
- WidgetApiImpl.prototype.requestCapabilities = function (capabilities) {
552
- return __awaiter$2(this, void 0, void 0, function () {
553
- return __generator$2(this, function (_b) {
554
- switch (_b.label) {
555
- case 0:
556
- if (!this.outstandingCapabilitiesRequest) return [3 /*break*/, 4];
557
- _b.label = 1;
558
- case 1:
559
- _b.trys.push([1, 3, , 4]);
560
- return [4 /*yield*/, this.outstandingCapabilitiesRequest];
561
- case 2:
562
- _b.sent();
563
- return [3 /*break*/, 4];
564
- case 3:
565
- _b.sent();
566
- return [3 /*break*/, 4];
567
- case 4:
568
- _b.trys.push([4, , 6, 7]);
569
- this.outstandingCapabilitiesRequest =
570
- this.requestCapabilitiesInternal(capabilities);
571
- return [4 /*yield*/, this.outstandingCapabilitiesRequest];
572
- case 5:
573
- _b.sent();
574
- return [3 /*break*/, 7];
575
- case 6:
576
- this.outstandingCapabilitiesRequest = undefined;
577
- return [7 /*endfinally*/];
578
- case 7: return [2 /*return*/];
579
- }
580
- });
581
- });
718
+ }
719
+ /**
720
+ * Parse a widget id into the individual fields.
721
+ * @param widgetId - The widget id to parse.
722
+ * @returns The individual fields encoded inside a widget id.
723
+ */
724
+ function parseWidgetId(widgetId) {
725
+ // TODO: Is this whole parsing still working for user widgets?
726
+ var mainWidgetId = decodeURIComponent(widgetId).replace(/^modal_/, '');
727
+ var roomId = mainWidgetId.indexOf('_')
728
+ ? decodeURIComponent(mainWidgetId.split('_')[0])
729
+ : undefined;
730
+ var creator = (mainWidgetId.match(/_/g) || []).length > 1
731
+ ? decodeURIComponent(mainWidgetId.split('_')[1])
732
+ : undefined;
733
+ var isModal = decodeURIComponent(widgetId).startsWith('modal_');
734
+ return {
735
+ mainWidgetId: mainWidgetId,
736
+ roomId: roomId,
737
+ creator: creator,
738
+ isModal: isModal,
582
739
  };
583
- WidgetApiImpl.prototype.requestCapabilitiesInternal = function (capabilities) {
584
- return __awaiter$2(this, void 0, void 0, function () {
585
- var rawCapabilities, requestedSet, capabilities$;
586
- var _this = this;
587
- return __generator$2(this, function (_a) {
588
- switch (_a.label) {
589
- case 0:
590
- rawCapabilities = unique(convertToRawCapabilities(capabilities));
591
- // Take shortcut if possible, that avoid extra roundtrips over the API.
592
- if (this.hasCapabilities(rawCapabilities)) {
593
- return [2 /*return*/];
594
- }
595
- requestedSet = new Set(rawCapabilities);
596
- capabilities$ = rxjs.fromEvent(this.matrixWidgetApi, "action:".concat(matrixWidgetApi.WidgetApiToWidgetAction.NotifyCapabilities), function (ev) { return ev; }).pipe(
597
- // TODO: `hasCapability` in the matrix-widget-api isn't consistent when capability
598
- // upgrades happened. But `updateRequestedCapabilities` will deduplicate already
599
- // approved capabilities, so the the `requested` field will be inconsistent.
600
- // If we would enable this check, the function will never resolve. This should
601
- // be reactivated once the capability upgrade is working correctly. See also:
602
- // https://github.com/matrix-org/matrix-widget-api/issues/52
603
- // Ignore events from other parallel capability requests
604
- //filter((ev) =>
605
- // equalsSet(new Set(ev.detail.data.requested), requestedSet)
606
- //),
607
- rxjs.map(function (ev) {
608
- var approvedSet = new Set(ev.detail.data.approved);
609
- var missingSet = subtractSet(requestedSet, approvedSet);
610
- if (missingSet.size > 0) {
611
- throw new Error("Capabilities rejected: ".concat(Array.from(missingSet).join(', ')));
612
- }
613
- }), rxjs.first());
614
- return [4 /*yield*/, new Promise(function (resolve, reject) { return __awaiter$2(_this, void 0, void 0, function () {
615
- var subscription, err_1;
616
- return __generator$2(this, function (_a) {
617
- switch (_a.label) {
618
- case 0:
619
- subscription = capabilities$.subscribe({
620
- next: resolve,
621
- error: reject,
622
- });
623
- _a.label = 1;
624
- case 1:
625
- _a.trys.push([1, 3, , 4]);
626
- this.matrixWidgetApi.requestCapabilities(rawCapabilities);
627
- return [4 /*yield*/, this.matrixWidgetApi.updateRequestedCapabilities()];
628
- case 2:
629
- _a.sent();
630
- return [3 /*break*/, 4];
631
- case 3:
632
- err_1 = _a.sent();
633
- subscription.unsubscribe();
634
- reject(err_1);
635
- return [3 /*break*/, 4];
636
- case 4: return [2 /*return*/];
637
- }
638
- });
639
- }); })];
640
- case 1:
641
- _a.sent();
642
- return [2 /*return*/];
643
- }
644
- });
645
- });
740
+ }
741
+
742
+ /*
743
+ * Copyright 2022 Nordeck IT + Consulting GmbH
744
+ *
745
+ * Licensed under the Apache License, Version 2.0 (the "License");
746
+ * you may not use this file except in compliance with the License.
747
+ * You may obtain a copy of the License at
748
+ *
749
+ * http://www.apache.org/licenses/LICENSE-2.0
750
+ *
751
+ * Unless required by applicable law or agreed to in writing, software
752
+ * distributed under the License is distributed on an "AS IS" BASIS,
753
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
754
+ * See the License for the specific language governing permissions and
755
+ * limitations under the License.
756
+ */
757
+ var __assign = (undefined && undefined.__assign) || function () {
758
+ __assign = Object.assign || function(t) {
759
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
760
+ s = arguments[i];
761
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
762
+ t[p] = s[p];
763
+ }
764
+ return t;
646
765
  };
647
- /** {@inheritDoc WidgetApi.hasCapabilities} */
648
- WidgetApiImpl.prototype.hasCapabilities = function (capabilities) {
649
- var _this = this;
650
- var rawCapabilities = convertToRawCapabilities(capabilities);
651
- return rawCapabilities.every(function (c) { return _this.matrixWidgetApi.hasCapability(c); });
652
- };
653
- /** {@inheritDoc WidgetApi.receiveSingleStateEvent} */
654
- WidgetApiImpl.prototype.receiveSingleStateEvent = function (eventType, stateKey) {
655
- if (stateKey === void 0) { stateKey = ''; }
656
- return __awaiter$2(this, void 0, void 0, function () {
657
- var events;
658
- return __generator$2(this, function (_a) {
659
- switch (_a.label) {
660
- case 0: return [4 /*yield*/, this.receiveStateEvents(eventType, { stateKey: stateKey })];
661
- case 1:
662
- events = _a.sent();
663
- return [2 /*return*/, events && events[0]];
664
- }
665
- });
666
- });
667
- };
668
- /** {@inheritDoc WidgetApi.receiveStateEvents} */
669
- WidgetApiImpl.prototype.receiveStateEvents = function (eventType, _a) {
670
- var _b = _a === void 0 ? {} : _a, stateKey = _b.stateKey, roomIds = _b.roomIds;
671
- return __awaiter$2(this, void 0, void 0, function () {
672
- return __generator$2(this, function (_c) {
673
- switch (_c.label) {
674
- case 0: return [4 /*yield*/, this.matrixWidgetApi.readStateEvents(eventType, Number.MAX_SAFE_INTEGER, stateKey, typeof roomIds === 'string' ? [matrixWidgetApi.Symbols.AnyRoom] : roomIds)];
675
- case 1: return [2 /*return*/, (_c.sent())];
676
- }
677
- });
678
- });
679
- };
680
- /** {@inheritDoc WidgetApi.observeStateEvents} */
681
- WidgetApiImpl.prototype.observeStateEvents = function (eventType, _a) {
682
- var _b = _a === void 0 ? {} : _a, stateKey = _b.stateKey, roomIds = _b.roomIds;
683
- var currentRoomId = this.widgetParameters.roomId;
684
- if (!currentRoomId) {
685
- return rxjs.throwError(function () { return new Error('Current room id is unknown'); });
686
- }
687
- var historyEvent$ = rxjs.from(this.receiveStateEvents(eventType, { stateKey: stateKey, roomIds: roomIds })).pipe(rxjs.mergeAll());
688
- var futureEvent$ = this.events$.pipe(rxjs.map(function (event) {
689
- var matrixEvent = event.detail.data;
690
- if (matrixEvent.type === eventType &&
691
- matrixEvent.state_key !== undefined &&
692
- (stateKey === undefined || matrixEvent.state_key === stateKey) &&
693
- isInRoom(matrixEvent, currentRoomId, roomIds)) {
694
- return event.detail.data;
766
+ return __assign.apply(this, arguments);
767
+ };
768
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
769
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
770
+ return new (P || (P = Promise))(function (resolve, reject) {
771
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
772
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
773
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
774
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
775
+ });
776
+ };
777
+ var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) {
778
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
779
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
780
+ function verb(n) { return function (v) { return step([n, v]); }; }
781
+ function step(op) {
782
+ if (f) throw new TypeError("Generator is already executing.");
783
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
784
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
785
+ if (y = 0, t) op = [op[0] & 2, t.value];
786
+ switch (op[0]) {
787
+ case 0: case 1: t = op; break;
788
+ case 4: _.label++; return { value: op[1], done: false };
789
+ case 5: _.label++; y = op[1]; op = [0]; continue;
790
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
791
+ default:
792
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
793
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
794
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
795
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
796
+ if (t[2]) _.ops.pop();
797
+ _.trys.pop(); continue;
695
798
  }
696
- return undefined;
697
- }), rxjs.filter(isDefined));
698
- return rxjs.concat(historyEvent$, futureEvent$);
699
- };
700
- /** {@inheritDoc WidgetApi.sendStateEvent} */
701
- WidgetApiImpl.prototype.sendStateEvent = function (eventType, content, _a) {
702
- var _b = _a === void 0 ? {} : _a, roomId = _b.roomId, _c = _b.stateKey, stateKey = _c === void 0 ? '' : _c;
703
- return __awaiter$2(this, void 0, void 0, function () {
704
- var subject, subscription, _d, event_id_1, room_id_1, event_1;
705
- return __generator$2(this, function (_e) {
706
- switch (_e.label) {
707
- case 0:
708
- subject = new rxjs.ReplaySubject();
709
- subscription = this.events$.subscribe(function (e) { return subject.next(e); });
710
- _e.label = 1;
711
- case 1:
712
- _e.trys.push([1, , 4, 5]);
713
- return [4 /*yield*/, this.matrixWidgetApi.sendStateEvent(eventType, stateKey, content, roomId)];
714
- case 2:
715
- _d = _e.sent(), event_id_1 = _d.event_id, room_id_1 = _d.room_id;
716
- return [4 /*yield*/, rxjs.firstValueFrom(subject.pipe(rxjs.filter(function (event) {
717
- var matrixEvent = event.detail.data;
718
- return (matrixEvent.event_id === event_id_1 &&
719
- matrixEvent.room_id === room_id_1);
720
- }), rxjs.map(function (event) { return event.detail.data; })))];
721
- case 3:
722
- event_1 = _e.sent();
723
- return [2 /*return*/, event_1];
724
- case 4:
725
- subscription.unsubscribe();
726
- return [7 /*endfinally*/];
727
- case 5: return [2 /*return*/];
728
- }
729
- });
730
- });
731
- };
732
- /** {@inheritDoc WidgetApi.receiveRoomEvents} */
733
- WidgetApiImpl.prototype.receiveRoomEvents = function (eventType, _a) {
734
- var _b = _a === void 0 ? {} : _a, messageType = _b.messageType, roomIds = _b.roomIds;
735
- return __awaiter$2(this, void 0, void 0, function () {
736
- return __generator$2(this, function (_c) {
737
- switch (_c.label) {
738
- case 0: return [4 /*yield*/, this.matrixWidgetApi.readRoomEvents(eventType, Number.MAX_SAFE_INTEGER, messageType, typeof roomIds === 'string' ? [matrixWidgetApi.Symbols.AnyRoom] : roomIds)];
739
- case 1: return [2 /*return*/, (_c.sent())];
740
- }
741
- });
742
- });
743
- };
744
- /** {@inheritDoc WidgetApi.observeRoomEvents} */
745
- WidgetApiImpl.prototype.observeRoomEvents = function (eventType, _a) {
746
- var _b = _a === void 0 ? {} : _a, messageType = _b.messageType, roomIds = _b.roomIds;
747
- var currentRoomId = this.widgetParameters.roomId;
748
- if (!currentRoomId) {
749
- return rxjs.throwError(function () { return new Error('Current room id is unknown'); });
799
+ op = body.call(thisArg, _);
800
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
801
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
802
+ }
803
+ };
804
+ var __rest = (undefined && undefined.__rest) || function (s, e) {
805
+ var t = {};
806
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
807
+ t[p] = s[p];
808
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
809
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
810
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
811
+ t[p[i]] = s[p[i]];
750
812
  }
751
- var historyEvent$ = rxjs.from(this.receiveRoomEvents(eventType, { messageType: messageType, roomIds: roomIds })).pipe(rxjs.mergeAll());
752
- var futureEvent$ = this.events$.pipe(rxjs.map(function (event) {
753
- var matrixEvent = event.detail.data;
754
- if (matrixEvent.type === eventType &&
755
- matrixEvent.state_key === undefined &&
756
- (!messageType || matrixEvent.content.msgtype === messageType) &&
757
- isInRoom(matrixEvent, currentRoomId, roomIds)) {
758
- return event.detail.data;
813
+ return t;
814
+ };
815
+ /**
816
+ * Checks whether all widget parameters were provided to the widget.
817
+ *
818
+ * @param widgetApi - The widget api to read the parameters from
819
+ * @returns True, if all parameters were provided.
820
+ */
821
+ function hasRequiredWidgetParameters(widgetApi) {
822
+ return (typeof widgetApi.widgetParameters.userId === 'string' &&
823
+ typeof widgetApi.widgetParameters.displayName === 'string' &&
824
+ typeof widgetApi.widgetParameters.avatarUrl === 'string' &&
825
+ typeof widgetApi.widgetParameters.roomId === 'string' &&
826
+ typeof widgetApi.widgetParameters.theme === 'string' &&
827
+ typeof widgetApi.widgetParameters.clientId === 'string' &&
828
+ typeof widgetApi.widgetParameters.clientLanguage === 'string' &&
829
+ typeof widgetApi.widgetParameters.baseUrl === 'string');
830
+ }
831
+ /**
832
+ * Generate a registration URL for the widget based on the current URL and
833
+ * include all widget parameters (and their placeholders).
834
+ * @param options - Options for generating the URL.
835
+ * Use `pathName` to include an optional sub path in the URL.
836
+ * Use `includeParameters` to append the widget parameters to
837
+ * the URL, defaults to `true`.
838
+ * @returns The generated URL.
839
+ */
840
+ function generateWidgetRegistrationUrl(options) {
841
+ var _a, _b, _c, _d, _e, _f, _g, _h;
842
+ if (options === void 0) { options = {}; }
843
+ var pathName = options.pathName, _j = options.includeParameters, includeParameters = _j === void 0 ? true : _j, widgetParameters = options.widgetParameters;
844
+ // don't forward widgetId and parentUrl as they will be generated by the client
845
+ var _k = extractRawWidgetParameters(); _k.widgetId; _k.parentUrl; var rawWidgetParameters = __rest(_k, ["widgetId", "parentUrl"]);
846
+ var parameters = Object.entries(__assign(__assign({}, rawWidgetParameters), { theme: (_a = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.theme) !== null && _a !== void 0 ? _a : '$org.matrix.msc2873.client_theme', matrix_user_id: (_b = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.userId) !== null && _b !== void 0 ? _b : '$matrix_user_id', matrix_display_name: (_c = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.displayName) !== null && _c !== void 0 ? _c : '$matrix_display_name', matrix_avatar_url: (_d = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.avatarUrl) !== null && _d !== void 0 ? _d : '$matrix_avatar_url', matrix_room_id: (_e = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.roomId) !== null && _e !== void 0 ? _e : '$matrix_room_id', matrix_client_id: (_f = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.clientId) !== null && _f !== void 0 ? _f : '$org.matrix.msc2873.client_id', matrix_client_language: (_g = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.clientLanguage) !== null && _g !== void 0 ? _g : '$org.matrix.msc2873.client_language', matrix_base_url: (_h = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.baseUrl) !== null && _h !== void 0 ? _h : '$org.matrix.msc4039.matrix_base_url' }))
847
+ .map(function (_a) {
848
+ var k = _a[0], v = _a[1];
849
+ return "".concat(k, "=").concat(v);
850
+ })
851
+ .join('&');
852
+ var url = new URL(window.location.href);
853
+ if (pathName) {
854
+ url.pathname = pathName;
855
+ }
856
+ else {
857
+ // ensure trailing '/'
858
+ url.pathname = url.pathname.replace(/\/?$/, '/');
859
+ }
860
+ url.search = '';
861
+ url.hash = includeParameters ? "#/?".concat(parameters) : '';
862
+ return url.toString();
863
+ }
864
+ var STATE_EVENT_WIDGETS = 'im.vector.modular.widgets';
865
+ /**
866
+ * Repair/configure the registration of the current widget.
867
+ * This steps make sure to include all the required widget parameters in the
868
+ * URL. Support setting a widget name and additional parameters.
869
+ *
870
+ * @param widgetApi - The widget api of the current widget.
871
+ * @param registration - Optional configuration options for the widget
872
+ * registration, like the display name of the widget.
873
+ */
874
+ function repairWidgetRegistration(widgetApi_1) {
875
+ return __awaiter$1(this, arguments, void 0, function (widgetApi, registration) {
876
+ var readResult, url, name, type, data;
877
+ if (registration === void 0) { registration = {}; }
878
+ return __generator$1(this, function (_a) {
879
+ switch (_a.label) {
880
+ case 0: return [4 /*yield*/, widgetApi.requestCapabilities([
881
+ matrixWidgetApi.WidgetEventCapability.forStateEvent(matrixWidgetApi.EventDirection.Send, STATE_EVENT_WIDGETS, widgetApi.widgetId),
882
+ matrixWidgetApi.WidgetEventCapability.forStateEvent(matrixWidgetApi.EventDirection.Receive, STATE_EVENT_WIDGETS, widgetApi.widgetId),
883
+ ])];
884
+ case 1:
885
+ _a.sent();
886
+ return [4 /*yield*/, widgetApi.receiveSingleStateEvent(STATE_EVENT_WIDGETS, widgetApi.widgetId)];
887
+ case 2:
888
+ readResult = _a.sent();
889
+ if (!readResult) {
890
+ throw new Error("Error while repairing registration, can't find existing registration.");
891
+ }
892
+ url = generateWidgetRegistrationUrl();
893
+ name = registration.name &&
894
+ (!readResult.content.name ||
895
+ readResult.content.name === 'Custom Widget' ||
896
+ readResult.content.name === 'Custom')
897
+ ? registration.name
898
+ : readResult.content.name;
899
+ type = registration.type &&
900
+ (!readResult.content.type || readResult.content.type === 'm.custom')
901
+ ? registration.type
902
+ : readResult.content.type;
903
+ data = registration.data
904
+ ? __assign(__assign({}, readResult.content.data), registration.data) : readResult.content.data;
905
+ // This is a workaround because changing the widget config is breaking the
906
+ // widget API communication. However we need to fail in case the power level
907
+ // for this change is missing. As the error happens quite fast, we just wait
908
+ // a moment and then consider the operation as succeeded.
909
+ return [4 /*yield*/, Promise.race([
910
+ widgetApi.sendStateEvent(STATE_EVENT_WIDGETS, __assign(__assign({}, readResult.content), { url: url.toString(), name: name, type: type, data: data }), { stateKey: widgetApi.widgetId }),
911
+ new Promise(function (resolve) { return setTimeout(resolve, 1000); }),
912
+ ])];
913
+ case 3:
914
+ // This is a workaround because changing the widget config is breaking the
915
+ // widget API communication. However we need to fail in case the power level
916
+ // for this change is missing. As the error happens quite fast, we just wait
917
+ // a moment and then consider the operation as succeeded.
918
+ _a.sent();
919
+ return [2 /*return*/];
759
920
  }
760
- return undefined;
761
- }), rxjs.filter(isDefined));
762
- return rxjs.concat(historyEvent$, futureEvent$);
763
- };
764
- /** {@inheritDoc WidgetApi.sendRoomEvent} */
765
- WidgetApiImpl.prototype.sendRoomEvent = function (eventType, content, _a) {
766
- var _b = _a === void 0 ? {} : _a, roomId = _b.roomId;
767
- return __awaiter$2(this, void 0, void 0, function () {
768
- var subject, subscription, _c, event_id_2, room_id_2, event_2;
769
- return __generator$2(this, function (_d) {
770
- switch (_d.label) {
771
- case 0:
772
- subject = new rxjs.ReplaySubject();
773
- subscription = this.events$.subscribe(function (e) { return subject.next(e); });
774
- _d.label = 1;
775
- case 1:
776
- _d.trys.push([1, , 4, 5]);
777
- return [4 /*yield*/, this.matrixWidgetApi.sendRoomEvent(eventType, content, roomId)];
778
- case 2:
779
- _c = _d.sent(), event_id_2 = _c.event_id, room_id_2 = _c.room_id;
780
- return [4 /*yield*/, rxjs.firstValueFrom(subject.pipe(rxjs.filter(function (event) {
781
- var matrixEvent = event.detail.data;
782
- return (matrixEvent.event_id === event_id_2 &&
783
- matrixEvent.room_id === room_id_2);
784
- }), rxjs.map(function (event) { return event.detail.data; })))];
785
- case 3:
786
- event_2 = _d.sent();
787
- return [2 /*return*/, event_2];
788
- case 4:
789
- subscription.unsubscribe();
790
- return [7 /*endfinally*/];
791
- case 5: return [2 /*return*/];
792
- }
793
- });
794
- });
795
- };
796
- /** {@inheritDoc WidgetApi.readEventRelations} */
797
- WidgetApiImpl.prototype.readEventRelations = function (eventId, options) {
798
- return __awaiter$2(this, void 0, void 0, function () {
799
- var _a, chunk, next_batch;
800
- return __generator$2(this, function (_b) {
801
- switch (_b.label) {
802
- case 0: return [4 /*yield*/, this.matrixWidgetApi.readEventRelations(eventId, options === null || options === void 0 ? void 0 : options.roomId, options === null || options === void 0 ? void 0 : options.relationType, options === null || options === void 0 ? void 0 : options.eventType, options === null || options === void 0 ? void 0 : options.limit, options === null || options === void 0 ? void 0 : options.from, undefined, options === null || options === void 0 ? void 0 : options.direction)];
803
- case 1:
804
- _a = _b.sent(), chunk = _a.chunk, next_batch = _a.next_batch;
805
- return [2 /*return*/, {
806
- chunk: chunk,
807
- nextToken: next_batch !== null && next_batch !== void 0 ? next_batch : undefined,
808
- }];
809
- }
810
- });
811
- });
812
- };
813
- /** {@inheritDoc WidgetApi.sendToDeviceMessage} */
814
- WidgetApiImpl.prototype.sendToDeviceMessage = function (eventType, encrypted, content) {
815
- return __awaiter$2(this, void 0, void 0, function () {
816
- return __generator$2(this, function (_a) {
817
- switch (_a.label) {
818
- case 0: return [4 /*yield*/, this.matrixWidgetApi.sendToDevice(eventType, encrypted, content)];
819
- case 1:
820
- _a.sent();
821
- return [2 /*return*/];
822
- }
823
- });
824
- });
825
- };
826
- /** {@inheritDoc WidgetApi.observeToDeviceMessages} */
827
- WidgetApiImpl.prototype.observeToDeviceMessages = function (eventType) {
828
- return this.toDeviceMessages$.pipe(rxjs.map(function (e) { return e.detail.data; }), rxjs.filter(function (e) { return e.type === eventType; }));
829
- };
830
- /** {@inheritDoc WidgetApi.openModal} */
831
- WidgetApiImpl.prototype.openModal = function (pathName, name, options) {
832
- return __awaiter$2(this, void 0, void 0, function () {
833
- var isModal, url, closeModalWidget$;
834
- var _this = this;
835
- return __generator$2(this, function (_a) {
836
- switch (_a.label) {
837
- case 0:
838
- isModal = parseWidgetId(this.widgetId).isModal;
839
- if (isModal) {
840
- throw new Error("Modals can't be opened from another modal widget");
841
- }
842
- url = generateWidgetRegistrationUrl({
843
- pathName: pathName,
844
- widgetParameters: this.widgetParameters,
845
- });
846
- return [4 /*yield*/, this.matrixWidgetApi.openModalWidget(url, name, options === null || options === void 0 ? void 0 : options.buttons, options === null || options === void 0 ? void 0 : options.data)];
847
- case 1:
848
- _a.sent();
849
- closeModalWidget$ = rxjs.fromEvent(this.matrixWidgetApi, "action:".concat(matrixWidgetApi.WidgetApiToWidgetAction.CloseModalWidget), function (event) {
850
- var _a;
851
- event.preventDefault();
852
- _this.matrixWidgetApi.transport.reply(event.detail, {});
853
- if (((_a = event.detail.data) === null || _a === void 0 ? void 0 : _a['m.exited']) === true) {
854
- return undefined;
855
- }
856
- return event.detail.data;
857
- });
858
- return [2 /*return*/, rxjs.firstValueFrom(closeModalWidget$)];
859
- }
860
- });
861
- });
862
- };
863
- /** {@inheritDoc WidgetApi.setModalButtonEnabled} */
864
- WidgetApiImpl.prototype.setModalButtonEnabled = function (buttonId, isEnabled) {
865
- return __awaiter$2(this, void 0, void 0, function () {
866
- var isModal;
867
- return __generator$2(this, function (_a) {
868
- switch (_a.label) {
869
- case 0:
870
- isModal = parseWidgetId(this.widgetId).isModal;
871
- if (!isModal) {
872
- throw new Error('Modal buttons can only be enabled from a modal widget');
873
- }
874
- return [4 /*yield*/, this.matrixWidgetApi.setModalButtonEnabled(buttonId, isEnabled)];
875
- case 1:
876
- _a.sent();
877
- return [2 /*return*/];
878
- }
879
- });
880
- });
881
- };
882
- /** {@inheritDoc WidgetApi.observeModalButtons} */
883
- WidgetApiImpl.prototype.observeModalButtons = function () {
884
- var _this = this;
885
- var isModal = parseWidgetId(this.widgetId).isModal;
886
- if (!isModal) {
887
- throw new Error('Modal buttons can only be observed from a modal widget');
888
- }
889
- return rxjs.fromEvent(this.matrixWidgetApi, "action:".concat(matrixWidgetApi.WidgetApiToWidgetAction.ButtonClicked), function (event) {
890
- event.preventDefault();
891
- _this.matrixWidgetApi.transport.reply(event.detail, {});
892
- return event.detail.data.id;
893
- });
894
- };
895
- /** {@inheritDoc WidgetApi.closeModal} */
896
- WidgetApiImpl.prototype.closeModal = function (data) {
897
- return __awaiter$2(this, void 0, void 0, function () {
898
- var isModal;
899
- return __generator$2(this, function (_a) {
900
- switch (_a.label) {
901
- case 0:
902
- isModal = parseWidgetId(this.widgetId).isModal;
903
- if (!isModal) {
904
- throw new Error('Modals can only be closed from a modal widget');
905
- }
906
- return [4 /*yield*/, this.matrixWidgetApi.closeModalWidget(data ? data : { 'm.exited': true })];
907
- case 1:
908
- _a.sent();
909
- return [2 /*return*/];
910
- }
911
- });
912
- });
913
- };
914
- /** {@inheritdoc WidgetApi.navigateTo} */
915
- WidgetApiImpl.prototype.navigateTo = function (uri) {
916
- return __awaiter$2(this, void 0, void 0, function () {
917
- return __generator$2(this, function (_a) {
918
- switch (_a.label) {
919
- case 0: return [4 /*yield*/, this.matrixWidgetApi.navigateTo(uri)];
920
- case 1:
921
- _a.sent();
922
- return [2 /*return*/];
923
- }
924
- });
925
- });
926
- };
927
- /** {@inheritdoc WidgetApi.requestOpenIDConnectToken} */
928
- WidgetApiImpl.prototype.requestOpenIDConnectToken = function () {
929
- return __awaiter$2(this, void 0, void 0, function () {
930
- return __generator$2(this, function (_b) {
931
- switch (_b.label) {
932
- case 0:
933
- if (!this.outstandingOpenIDConnectTokenRequest) return [3 /*break*/, 4];
934
- _b.label = 1;
935
- case 1:
936
- _b.trys.push([1, 3, , 4]);
937
- return [4 /*yield*/, this.outstandingOpenIDConnectTokenRequest];
938
- case 2:
939
- _b.sent();
940
- return [3 /*break*/, 4];
941
- case 3:
942
- _b.sent();
943
- return [3 /*break*/, 4];
944
- case 4:
945
- _b.trys.push([4, , 6, 7]);
946
- this.outstandingOpenIDConnectTokenRequest =
947
- this.requestOpenIDConnectTokenInternal();
948
- return [4 /*yield*/, this.outstandingOpenIDConnectTokenRequest];
949
- case 5: return [2 /*return*/, _b.sent()];
950
- case 6:
951
- this.outstandingOpenIDConnectTokenRequest = undefined;
952
- return [7 /*endfinally*/];
953
- case 7: return [2 /*return*/];
954
- }
955
- });
956
- });
957
- };
958
- WidgetApiImpl.prototype.requestOpenIDConnectTokenInternal = function () {
959
- var _a;
960
- return __awaiter$2(this, void 0, void 0, function () {
961
- var leywayMilliseconds, openIdToken, err_2;
962
- return __generator$2(this, function (_b) {
963
- switch (_b.label) {
964
- case 0:
965
- leywayMilliseconds = 30 * 1000;
966
- if (this.cachedOpenIdToken &&
967
- this.cachedOpenIdToken.expiresAt - leywayMilliseconds > Date.now()) {
968
- return [2 /*return*/, this.cachedOpenIdToken.openIdToken];
969
- }
970
- _b.label = 1;
971
- case 1:
972
- _b.trys.push([1, 3, , 4]);
973
- return [4 /*yield*/, this.matrixWidgetApi.requestOpenIDConnectToken()];
974
- case 2:
975
- openIdToken = _b.sent();
976
- this.cachedOpenIdToken = {
977
- openIdToken: openIdToken,
978
- expiresAt: Date.now() + ((_a = openIdToken.expires_in) !== null && _a !== void 0 ? _a : 0) * 1000,
979
- };
980
- return [2 /*return*/, openIdToken];
981
- case 3:
982
- err_2 = _b.sent();
983
- this.cachedOpenIdToken = undefined;
984
- throw err_2;
985
- case 4: return [2 /*return*/];
986
- }
987
- });
988
- });
989
- };
990
- /** {@inheritdoc WidgetApi.observeTurnServers} */
991
- WidgetApiImpl.prototype.observeTurnServers = function () {
992
- return rxjs.from(this.matrixWidgetApi.getTurnServers()).pipe(
993
- // For some reason a different naming was chosen for the API, but
994
- // we already convert them to the right type for WebRTC consumers.
995
- rxjs.map(function (_a) {
996
- var uris = _a.uris, username = _a.username, password = _a.password;
997
- return ({
998
- urls: uris,
999
- username: username,
1000
- credential: password,
1001
- });
1002
- }));
1003
- };
1004
- /** {@inheritdoc WidgetApi.searchUserDirectory} */
1005
- WidgetApiImpl.prototype.searchUserDirectory = function (searchTerm, options) {
1006
- return __awaiter$2(this, void 0, void 0, function () {
1007
- var results;
1008
- return __generator$2(this, function (_a) {
1009
- switch (_a.label) {
1010
- case 0: return [4 /*yield*/, this.matrixWidgetApi.searchUserDirectory(searchTerm, options === null || options === void 0 ? void 0 : options.limit)];
1011
- case 1:
1012
- results = (_a.sent()).results;
1013
- return [2 /*return*/, {
1014
- results: results.map(function (_a) {
1015
- var user_id = _a.user_id, display_name = _a.display_name, avatar_url = _a.avatar_url;
1016
- return ({
1017
- userId: user_id,
1018
- displayName: display_name,
1019
- avatarUrl: avatar_url,
1020
- });
1021
- }),
1022
- }];
1023
- }
1024
- });
1025
- });
1026
- };
1027
- /** {@inheritdoc WidgetApi.getMediaConfig} */
1028
- WidgetApiImpl.prototype.getMediaConfig = function () {
1029
- return __awaiter$2(this, void 0, void 0, function () {
1030
- return __generator$2(this, function (_a) {
1031
- switch (_a.label) {
1032
- case 0: return [4 /*yield*/, this.matrixWidgetApi.getMediaConfig()];
1033
- case 1: return [2 /*return*/, _a.sent()];
1034
- }
1035
- });
1036
- });
1037
- };
1038
- /** {@inheritdoc WidgetApi.uploadFile} */
1039
- WidgetApiImpl.prototype.uploadFile = function (file) {
1040
- return __awaiter$2(this, void 0, void 0, function () {
1041
- return __generator$2(this, function (_a) {
1042
- switch (_a.label) {
1043
- case 0: return [4 /*yield*/, this.matrixWidgetApi.uploadFile(file)];
1044
- case 1: return [2 /*return*/, _a.sent()];
1045
- }
1046
- });
1047
921
  });
1048
- };
1049
- return WidgetApiImpl;
1050
- }());
922
+ });
923
+ }
1051
924
 
1052
925
  /*
1053
926
  * Copyright 2022 Nordeck IT + Consulting GmbH
@@ -1064,112 +937,31 @@ var WidgetApiImpl = /** @class */ (function () {
1064
937
  * See the License for the specific language governing permissions and
1065
938
  * limitations under the License.
1066
939
  */
1067
- /**
1068
- * Generate a list of capabilities to access the timeline of other rooms.
1069
- * If enabled, all previously or future capabilities will apply to _all_
1070
- * selected rooms.
1071
- * If `Symbols.AnyRoom` is passed, this is expanded to all joined
1072
- * or invited rooms the client is able to see, current and future.
1073
- *
1074
- * @param roomIds - a list of room ids or `@link Symbols.AnyRoom`.
1075
- * @returns the generated capabilities.
1076
- */
1077
- function generateRoomTimelineCapabilities(roomIds) {
1078
- if (roomIds === matrixWidgetApi.Symbols.AnyRoom) {
1079
- return ['org.matrix.msc2762.timeline:*'];
1080
- }
1081
- if (Array.isArray(roomIds)) {
1082
- return roomIds.map(function (id) { return "org.matrix.msc2762.timeline:".concat(id); });
1083
- }
1084
- return [];
940
+ function convertToRawCapabilities(rawCapabilities) {
941
+ return rawCapabilities.map(function (c) { return (typeof c === 'string' ? c : c.raw); });
1085
942
  }
1086
-
1087
- /*
1088
- * Copyright 2022 Nordeck IT + Consulting GmbH
1089
- *
1090
- * Licensed under the Apache License, Version 2.0 (the "License");
1091
- * you may not use this file except in compliance with the License.
1092
- * You may obtain a copy of the License at
1093
- *
1094
- * http://www.apache.org/licenses/LICENSE-2.0
1095
- *
1096
- * Unless required by applicable law or agreed to in writing, software
1097
- * distributed under the License is distributed on an "AS IS" BASIS,
1098
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1099
- * See the License for the specific language governing permissions and
1100
- * limitations under the License.
1101
- */
1102
- /**
1103
- * Generate a unique displayname of a user that is consistent across Matrix clients.
1104
- *
1105
- * @remarks The algorithm is based on https://spec.matrix.org/v1.1/client-server-api/#calculating-the-display-name-for-a-user
1106
- *
1107
- * @param member - the member to generate a name for.
1108
- * @param allRoomMembers - a list of all members of the same room.
1109
- * @returns the displayname that is unique in given the set of all room members.
1110
- */
1111
- function getRoomMemberDisplayName(member, allRoomMembers) {
1112
- if (allRoomMembers === void 0) { allRoomMembers = []; }
1113
- // If the m.room.member state event has no displayname field, or if that field
1114
- // has a null value, use the raw user id as the display name.
1115
- if (typeof member.content.displayname !== 'string') {
1116
- return member.state_key;
1117
- }
1118
- // If the m.room.member event has a displayname which is unique among members of
1119
- // the room with membership: join or membership: invite, ...
1120
- var hasDuplicateDisplayName = allRoomMembers.some(function (m) {
1121
- // same room
1122
- return m.room_id === member.room_id &&
1123
- // not the own event
1124
- m.state_key !== member.state_key &&
1125
- // only join or invite state
1126
- ['join', 'invite'].includes(m.content.membership) &&
1127
- // same displayname
1128
- m.content.displayname === member.content.displayname;
1129
- });
1130
- if (!hasDuplicateDisplayName) {
1131
- // ... use the given displayname as the user-visible display name.
1132
- return member.content.displayname;
1133
- }
1134
- else {
1135
- // The m.room.member event has a non-unique displayname. This should be
1136
- // disambiguated using the user id, for example “display name (@id:homeserver.org)”.
1137
- return "".concat(member.content.displayname, " (").concat(member.state_key, ")");
1138
- }
943
+ function isDefined(arg) {
944
+ return arg !== null && arg !== undefined;
1139
945
  }
1140
-
1141
- /*
1142
- * Copyright 2022 Nordeck IT + Consulting GmbH
1143
- *
1144
- * Licensed under the Apache License, Version 2.0 (the "License");
1145
- * you may not use this file except in compliance with the License.
1146
- * You may obtain a copy of the License at
1147
- *
1148
- * http://www.apache.org/licenses/LICENSE-2.0
1149
- *
1150
- * Unless required by applicable law or agreed to in writing, software
1151
- * distributed under the License is distributed on an "AS IS" BASIS,
1152
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1153
- * See the License for the specific language governing permissions and
1154
- * limitations under the License.
1155
- */
1156
- /**
1157
- * Check if the given event is a {@link StateEvent}.
1158
- *
1159
- * @param event - An event that is either a {@link RoomEvent} or a {@link StateEvent}.
1160
- * @returns True, if the event is a {@link StateEvent}.
1161
- */
1162
- function isStateEvent(event) {
1163
- return 'state_key' in event && typeof event.state_key === 'string';
946
+ function unique(items) {
947
+ return Array.from(new Set(items));
1164
948
  }
1165
- /**
1166
- * Check if the given event is a {@link RoomEvent}.
1167
- *
1168
- * @param event - An event that is either a {@link RoomEvent} or a {@link StateEvent}.
1169
- * @returns True, if the event is a {@link RoomEvent}.
1170
- */
1171
- function isRoomEvent(event) {
1172
- return !('state_key' in event);
949
+ function subtractSet(as, bs) {
950
+ var result = new Set(as);
951
+ bs.forEach(function (v) { return result.delete(v); });
952
+ return result;
953
+ }
954
+ function isInRoom(matrixEvent, currentRoomId, roomIds) {
955
+ if (!roomIds) {
956
+ return matrixEvent.room_id === currentRoomId;
957
+ }
958
+ if (typeof roomIds === 'string') {
959
+ if (roomIds !== matrixWidgetApi.Symbols.AnyRoom) {
960
+ throw Error("Unknown room id symbol: ".concat(roomIds));
961
+ }
962
+ return true;
963
+ }
964
+ return roomIds.includes(matrixEvent.room_id);
1173
965
  }
1174
966
 
1175
967
  /*
@@ -1187,7 +979,7 @@ function isRoomEvent(event) {
1187
979
  * See the License for the specific language governing permissions and
1188
980
  * limitations under the License.
1189
981
  */
1190
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
982
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1191
983
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1192
984
  return new (P || (P = Promise))(function (resolve, reject) {
1193
985
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -1196,7 +988,7 @@ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _argu
1196
988
  step((generator = generator.apply(thisArg, _arguments || [])).next());
1197
989
  });
1198
990
  };
1199
- var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) {
991
+ var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
1200
992
  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1201
993
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1202
994
  function verb(n) { return function (v) { return step([n, v]); }; }
@@ -1223,462 +1015,672 @@ var __generator$1 = (undefined && undefined.__generator) || function (thisArg, b
1223
1015
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1224
1016
  }
1225
1017
  };
1018
+ var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
1019
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1020
+ if (ar || !(i in from)) {
1021
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1022
+ ar[i] = from[i];
1023
+ }
1024
+ }
1025
+ return to.concat(ar || Array.prototype.slice.call(from));
1026
+ };
1226
1027
  /**
1227
- * The capability that needs to be requested in order to navigate to another room.
1228
- */
1229
- var WIDGET_CAPABILITY_NAVIGATE = 'org.matrix.msc2931.navigate';
1230
- /**
1231
- * Navigate the client to another matrix room.
1232
- *
1233
- * @remarks This requires the {@link WIDGET_CAPABILITY_NAVIGATE} capability.
1028
+ * Implementation of the API from the widget to the client.
1234
1029
  *
1235
- * @param widgetApi - the {@link WidgetApi} instance.
1236
- * @param roomId - the room ID.
1237
- * @param opts - {@link NavigateToRoomOptions}
1030
+ * @remarks Widget API is specified here:
1031
+ * https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit#heading=h.9rn9lt6ctkgi
1238
1032
  */
1239
- function navigateToRoom(widgetApi, roomId, opts) {
1240
- if (opts === void 0) { opts = {}; }
1241
- return __awaiter$1(this, void 0, void 0, function () {
1242
- var _a, via, params, url;
1243
- return __generator$1(this, function (_b) {
1244
- switch (_b.label) {
1245
- case 0:
1246
- _a = opts.via, via = _a === void 0 ? [] : _a;
1247
- params = qs.stringify({ via: via }, { addQueryPrefix: true, arrayFormat: 'repeat' });
1248
- url = "https://matrix.to/#/".concat(encodeURIComponent(roomId)).concat(params);
1249
- return [4 /*yield*/, widgetApi.navigateTo(url)];
1250
- case 1:
1251
- _b.sent();
1252
- return [2 /*return*/];
1033
+ var WidgetApiImpl = /** @class */ (function () {
1034
+ function WidgetApiImpl(
1035
+ /**
1036
+ * Provide access to the underlying widget API from `matrix-widget-sdk`.
1037
+ *
1038
+ * @remarks Normally there is no need to use it, however if features are
1039
+ * missing from `WidgetApi` it can be handy to work with the
1040
+ * original API.
1041
+ */
1042
+ matrixWidgetApi$1,
1043
+ /** {@inheritDoc WidgetApi.widgetId} */
1044
+ widgetId,
1045
+ /** {@inheritDoc WidgetApi.widgetParameters} */
1046
+ widgetParameters, _a) {
1047
+ var _b = _a === void 0 ? {} : _a, _c = _b.capabilities, capabilities = _c === void 0 ? [] : _c, _d = _b.supportStandalone, supportStandalone = _d === void 0 ? false : _d;
1048
+ var _this = this;
1049
+ this.matrixWidgetApi = matrixWidgetApi$1;
1050
+ this.widgetId = widgetId;
1051
+ this.widgetParameters = widgetParameters;
1052
+ this.events$ = rxjs.fromEvent(this.matrixWidgetApi, "action:".concat(matrixWidgetApi.WidgetApiToWidgetAction.SendEvent), function (event) {
1053
+ event.preventDefault();
1054
+ try {
1055
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1056
+ }
1057
+ catch (_) {
1058
+ // Ignore errors while replying
1059
+ }
1060
+ return event;
1061
+ }).pipe(rxjs.share());
1062
+ this.toDeviceMessages$ = rxjs.fromEvent(this.matrixWidgetApi, 'action:send_to_device', function (event) {
1063
+ event.preventDefault();
1064
+ try {
1065
+ matrixWidgetApi$1.transport.reply(event.detail, {});
1066
+ }
1067
+ catch (_) {
1068
+ // Ignore errors while replying
1253
1069
  }
1070
+ return event;
1071
+ }).pipe(rxjs.share());
1072
+ this.initialCapabilities = __spreadArray(__spreadArray([], capabilities, true), (supportStandalone ? [] : [matrixWidgetApi.MatrixCapabilities.RequiresClient]), true);
1073
+ }
1074
+ /**
1075
+ * Initialize a new widget API instance and wait till it is ready.
1076
+ * There should only be one instance of the widget API. The widget API should
1077
+ * be created as early as possible when starting the application. This is
1078
+ * required to match the timing of the API connection establishment with the
1079
+ * client, especially in Safari. Therefore it is recommended to create it
1080
+ * inside the entrypoint, before initializing rendering engines like react.
1081
+ *
1082
+ * @param param0 - {@link WidgetApiOptions}
1083
+ *
1084
+ * @returns A widget API instance ready to use.
1085
+ */
1086
+ WidgetApiImpl.create = function () {
1087
+ return __awaiter(this, arguments, void 0, function (_a) {
1088
+ var _b, clientOrigin, widgetId, widgetParameters, matrixWidgetApi$1, widgetApi;
1089
+ var _c = _a === void 0 ? {} : _a, _d = _c.capabilities, capabilities = _d === void 0 ? [] : _d, _e = _c.supportStandalone, supportStandalone = _e === void 0 ? false : _e;
1090
+ return __generator(this, function (_f) {
1091
+ switch (_f.label) {
1092
+ case 0:
1093
+ _b = extractWidgetApiParameters(), clientOrigin = _b.clientOrigin, widgetId = _b.widgetId;
1094
+ widgetParameters = extractWidgetParameters();
1095
+ matrixWidgetApi$1 = new matrixWidgetApi.WidgetApi(widgetId, clientOrigin);
1096
+ widgetApi = new WidgetApiImpl(matrixWidgetApi$1, widgetId, widgetParameters, { capabilities: capabilities, supportStandalone: supportStandalone });
1097
+ return [4 /*yield*/, widgetApi.initialize()];
1098
+ case 1:
1099
+ _f.sent();
1100
+ return [2 /*return*/, widgetApi];
1101
+ }
1102
+ });
1254
1103
  });
1255
- });
1256
- }
1257
-
1258
- /*
1259
- * Copyright 2022 Nordeck IT + Consulting GmbH
1260
- *
1261
- * Licensed under the Apache License, Version 2.0 (the "License");
1262
- * you may not use this file except in compliance with the License.
1263
- * You may obtain a copy of the License at
1264
- *
1265
- * http://www.apache.org/licenses/LICENSE-2.0
1266
- *
1267
- * Unless required by applicable law or agreed to in writing, software
1268
- * distributed under the License is distributed on an "AS IS" BASIS,
1269
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1270
- * See the License for the specific language governing permissions and
1271
- * limitations under the License.
1272
- */
1273
- /**
1274
- * Compares two room events by their origin server timestamp.
1275
- *
1276
- * @param a - A room event
1277
- * @param b - A room event
1278
- * @returns Either zero if the timestamp is equal, \>0 if a is newer, or \<0 if
1279
- * b is newer.
1280
- */
1281
- function compareOriginServerTS(a, b) {
1282
- return a.origin_server_ts - b.origin_server_ts;
1283
- }
1284
-
1285
- /*
1286
- * Copyright 2022 Nordeck IT + Consulting GmbH
1287
- *
1288
- * Licensed under the Apache License, Version 2.0 (the "License");
1289
- * you may not use this file except in compliance with the License.
1290
- * You may obtain a copy of the License at
1291
- *
1292
- * http://www.apache.org/licenses/LICENSE-2.0
1293
- *
1294
- * Unless required by applicable law or agreed to in writing, software
1295
- * distributed under the License is distributed on an "AS IS" BASIS,
1296
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1297
- * See the License for the specific language governing permissions and
1298
- * limitations under the License.
1299
- */
1300
- /**
1301
- * The name of the power levels state event.
1302
- */
1303
- var STATE_EVENT_POWER_LEVELS = 'm.room.power_levels';
1304
- function isNumberOrUndefined(value) {
1305
- return value === undefined || typeof value === 'number';
1306
- }
1307
- function isStringToNumberMapOrUndefined(value) {
1308
- return (value === undefined ||
1309
- (value !== null &&
1310
- typeof value === 'object' &&
1311
- Object.entries(value).every(function (_a) {
1312
- var k = _a[0], v = _a[1];
1313
- return typeof k === 'string' && typeof v === 'number';
1314
- })));
1315
- }
1316
- /**
1317
- * Validates that `event` is has a valid structure for a
1318
- * {@link PowerLevelsStateEvent}.
1319
- * @param event - The event to validate.
1320
- * @returns True, if the event is valid.
1321
- */
1322
- function isValidPowerLevelStateEvent(event) {
1323
- if (event.type !== STATE_EVENT_POWER_LEVELS ||
1324
- typeof event.content !== 'object') {
1325
- return false;
1326
- }
1327
- var content = event.content;
1328
- if (!isStringToNumberMapOrUndefined(content.events)) {
1329
- return false;
1330
- }
1331
- if (!isNumberOrUndefined(content.state_default)) {
1332
- return false;
1333
- }
1334
- if (!isNumberOrUndefined(content.events_default)) {
1335
- return false;
1336
- }
1337
- if (!isStringToNumberMapOrUndefined(content.users)) {
1338
- return false;
1339
- }
1340
- if (!isNumberOrUndefined(content.users_default)) {
1341
- return false;
1342
- }
1343
- if (!isNumberOrUndefined(content.ban)) {
1344
- return false;
1345
- }
1346
- if (!isNumberOrUndefined(content.invite)) {
1347
- return false;
1348
- }
1349
- if (!isNumberOrUndefined(content.kick)) {
1350
- return false;
1351
- }
1352
- if (!isNumberOrUndefined(content.redact)) {
1353
- return false;
1354
- }
1355
- return true;
1356
- }
1357
- /**
1358
- * Check if a user has the power to send a specific room event.
1359
- *
1360
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1361
- * @param userId - the id of the user
1362
- * @param eventType - the type of room event
1363
- * @returns if true, the user has the power
1364
- */
1365
- function hasRoomEventPower(powerLevelStateEvent, userId, eventType) {
1366
- if (!powerLevelStateEvent) {
1367
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
1368
- return true;
1369
- }
1370
- var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
1371
- var eventLevel = calculateRoomEventPowerLevel(powerLevelStateEvent, eventType);
1372
- return userLevel >= eventLevel;
1373
- }
1374
- /**
1375
- * Check if a user has the power to send a specific state event.
1376
- *
1377
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1378
- * @param userId - the id of the user
1379
- * @param eventType - the type of state event
1380
- * @returns if true, the user has the power
1381
- */
1382
- function hasStateEventPower(powerLevelStateEvent, userId, eventType) {
1383
- if (!powerLevelStateEvent) {
1384
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
1385
- return true;
1386
- }
1387
- var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
1388
- var eventLevel = calculateStateEventPowerLevel(powerLevelStateEvent, eventType);
1389
- return userLevel >= eventLevel;
1390
- }
1391
- /**
1392
- * Check if a user has the power to perform a specific action.
1393
- *
1394
- * Supported actions:
1395
- * * invite: Invite a new user into the room
1396
- * * kick: Kick a user from the room
1397
- * * ban: Ban a user from the room
1398
- * * redact: Redact a message from another user
1399
- *
1400
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1401
- * @param userId - the id of the user
1402
- * @param action - the action
1403
- * @returns if true, the user has the power
1404
- */
1405
- function hasActionPower(powerLevelStateEvent, userId, action) {
1406
- if (!powerLevelStateEvent) {
1407
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
1408
- return true;
1409
- }
1410
- var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
1411
- var eventLevel = calculateActionPowerLevel(powerLevelStateEvent, action);
1412
- return userLevel >= eventLevel;
1413
- }
1414
- /**
1415
- * Calculate the power level of the user based on a `m.room.power_levels` event.
1416
- *
1417
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event.
1418
- * @param userId - the ID of the user.
1419
- * @returns the power level of the user.
1420
- */
1421
- function calculateUserPowerLevel(powerLevelStateEvent, userId) {
1422
- var _a, _b, _c;
1423
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L8-L12
1424
- return ((_c = (_b = (userId ? (_a = powerLevelStateEvent.users) === null || _a === void 0 ? void 0 : _a[userId] : undefined)) !== null && _b !== void 0 ? _b : powerLevelStateEvent.users_default) !== null && _c !== void 0 ? _c : 0);
1425
- }
1426
- /**
1427
- * Calculate the power level that a user needs send a specific room event.
1428
- *
1429
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1430
- * @param eventType - the type of room event
1431
- * @returns the power level that is needed
1432
- */
1433
- function calculateRoomEventPowerLevel(powerLevelStateEvent, eventType) {
1434
- var _a, _b, _c;
1435
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
1436
- return ((_c = (_b = (_a = powerLevelStateEvent.events) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : powerLevelStateEvent.events_default) !== null && _c !== void 0 ? _c : 0);
1437
- }
1438
- /**
1439
- * Calculate the power level that a user needs send a specific state event.
1440
- *
1441
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1442
- * @param eventType - the type of state event
1443
- * @returns the power level that is needed
1444
- */
1445
- function calculateStateEventPowerLevel(powerLevelStateEvent, eventType) {
1446
- var _a, _b, _c;
1447
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
1448
- return ((_c = (_b = (_a = powerLevelStateEvent.events) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : powerLevelStateEvent.state_default) !== null && _c !== void 0 ? _c : 50);
1449
- }
1450
- /**
1451
- * Calculate the power level that a user needs to perform an action.
1452
- *
1453
- * Supported actions:
1454
- * * invite: Invite a new user into the room
1455
- * * kick: Kick a user from the room
1456
- * * ban: Ban a user from the room
1457
- * * redact: Redact a message from another user
1458
- *
1459
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1460
- * @param action - the action
1461
- * @returns the power level that is needed
1462
- */
1463
- function calculateActionPowerLevel(powerLevelStateEvent, action) {
1464
- var _a, _b;
1465
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L27-L32
1466
- if (action === 'invite') {
1467
- return (_a = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _a !== void 0 ? _a : 0;
1468
- }
1469
- return (_b = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _b !== void 0 ? _b : 50;
1470
- }
1471
-
1472
- /*
1473
- * Copyright 2022 Nordeck IT + Consulting GmbH
1474
- *
1475
- * Licensed under the Apache License, Version 2.0 (the "License");
1476
- * you may not use this file except in compliance with the License.
1477
- * You may obtain a copy of the License at
1478
- *
1479
- * http://www.apache.org/licenses/LICENSE-2.0
1480
- *
1481
- * Unless required by applicable law or agreed to in writing, software
1482
- * distributed under the License is distributed on an "AS IS" BASIS,
1483
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1484
- * See the License for the specific language governing permissions and
1485
- * limitations under the License.
1486
- */
1487
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1488
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1489
- return new (P || (P = Promise))(function (resolve, reject) {
1490
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1491
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1492
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1493
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1494
- });
1495
- };
1496
- var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
1497
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1498
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1499
- function verb(n) { return function (v) { return step([n, v]); }; }
1500
- function step(op) {
1501
- if (f) throw new TypeError("Generator is already executing.");
1502
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
1503
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1504
- if (y = 0, t) op = [op[0] & 2, t.value];
1505
- switch (op[0]) {
1506
- case 0: case 1: t = op; break;
1507
- case 4: _.label++; return { value: op[1], done: false };
1508
- case 5: _.label++; y = op[1]; op = [0]; continue;
1509
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
1510
- default:
1511
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1512
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1513
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1514
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1515
- if (t[2]) _.ops.pop();
1516
- _.trys.pop(); continue;
1104
+ };
1105
+ /**
1106
+ * Initialize the widget API and wait till a connection with the client is
1107
+ * fully established.
1108
+ *
1109
+ * Waits till the user has approved the initial set of capabilities. The
1110
+ * method doesn't fail if the user doesn't approve all of them. It is
1111
+ * required to check manually afterwards.
1112
+ * In case of modal widgets it waits till the `widgetConfig` is received.
1113
+ *
1114
+ * @remarks Should only be called once during startup.
1115
+ */
1116
+ WidgetApiImpl.prototype.initialize = function () {
1117
+ return __awaiter(this, void 0, void 0, function () {
1118
+ var ready, isModal, configReady, rawCapabilities;
1119
+ var _this = this;
1120
+ return __generator(this, function (_a) {
1121
+ switch (_a.label) {
1122
+ case 0:
1123
+ ready = new Promise(function (resolve) {
1124
+ _this.matrixWidgetApi.once('ready', function () { return resolve(); });
1125
+ });
1126
+ isModal = parseWidgetId(this.widgetId).isModal;
1127
+ configReady = isModal
1128
+ ? (function () { return __awaiter(_this, void 0, void 0, function () {
1129
+ var widgetConfig$, _a;
1130
+ var _this = this;
1131
+ return __generator(this, function (_b) {
1132
+ switch (_b.label) {
1133
+ case 0:
1134
+ widgetConfig$ = rxjs.fromEvent(this.matrixWidgetApi, "action:".concat(matrixWidgetApi.WidgetApiToWidgetAction.WidgetConfig), function (ev) {
1135
+ ev.preventDefault();
1136
+ _this.matrixWidgetApi.transport.reply(ev.detail, {});
1137
+ return ev.detail.data;
1138
+ });
1139
+ _a = this;
1140
+ return [4 /*yield*/, rxjs.firstValueFrom(widgetConfig$)];
1141
+ case 1:
1142
+ _a.widgetConfig = _b.sent();
1143
+ return [2 /*return*/];
1144
+ }
1145
+ });
1146
+ }); })()
1147
+ : undefined;
1148
+ rawCapabilities = unique(convertToRawCapabilities(this.initialCapabilities));
1149
+ this.matrixWidgetApi.requestCapabilities(rawCapabilities);
1150
+ this.matrixWidgetApi.start();
1151
+ return [4 /*yield*/, ready];
1152
+ case 1:
1153
+ _a.sent();
1154
+ if (!configReady) return [3 /*break*/, 3];
1155
+ return [4 /*yield*/, configReady];
1156
+ case 2:
1157
+ _a.sent();
1158
+ _a.label = 3;
1159
+ case 3: return [2 /*return*/];
1160
+ }
1161
+ });
1162
+ });
1163
+ };
1164
+ /** {@inheritDoc WidgetApi.getWidgetConfig} */
1165
+ WidgetApiImpl.prototype.getWidgetConfig = function () {
1166
+ return this.widgetConfig;
1167
+ };
1168
+ /** {@inheritDoc WidgetApi.rerequestInitialCapabilities} */
1169
+ WidgetApiImpl.prototype.rerequestInitialCapabilities = function () {
1170
+ return __awaiter(this, void 0, void 0, function () {
1171
+ return __generator(this, function (_a) {
1172
+ switch (_a.label) {
1173
+ case 0: return [4 /*yield*/, this.requestCapabilities(this.initialCapabilities)];
1174
+ case 1: return [2 /*return*/, _a.sent()];
1175
+ }
1176
+ });
1177
+ });
1178
+ };
1179
+ /** {@inheritDoc WidgetApi.hasInitialCapabilities} */
1180
+ WidgetApiImpl.prototype.hasInitialCapabilities = function () {
1181
+ return this.hasCapabilities(this.initialCapabilities);
1182
+ };
1183
+ /** {@inheritDoc WidgetApi.requestCapabilities} */
1184
+ WidgetApiImpl.prototype.requestCapabilities = function (capabilities) {
1185
+ return __awaiter(this, void 0, void 0, function () {
1186
+ return __generator(this, function (_b) {
1187
+ switch (_b.label) {
1188
+ case 0:
1189
+ if (!this.outstandingCapabilitiesRequest) return [3 /*break*/, 4];
1190
+ _b.label = 1;
1191
+ case 1:
1192
+ _b.trys.push([1, 3, , 4]);
1193
+ return [4 /*yield*/, this.outstandingCapabilitiesRequest];
1194
+ case 2:
1195
+ _b.sent();
1196
+ return [3 /*break*/, 4];
1197
+ case 3:
1198
+ _b.sent();
1199
+ return [3 /*break*/, 4];
1200
+ case 4:
1201
+ _b.trys.push([4, , 6, 7]);
1202
+ this.outstandingCapabilitiesRequest =
1203
+ this.requestCapabilitiesInternal(capabilities);
1204
+ return [4 /*yield*/, this.outstandingCapabilitiesRequest];
1205
+ case 5:
1206
+ _b.sent();
1207
+ return [3 /*break*/, 7];
1208
+ case 6:
1209
+ this.outstandingCapabilitiesRequest = undefined;
1210
+ return [7 /*endfinally*/];
1211
+ case 7: return [2 /*return*/];
1212
+ }
1213
+ });
1214
+ });
1215
+ };
1216
+ WidgetApiImpl.prototype.requestCapabilitiesInternal = function (capabilities) {
1217
+ return __awaiter(this, void 0, void 0, function () {
1218
+ var rawCapabilities, requestedSet, capabilities$;
1219
+ var _this = this;
1220
+ return __generator(this, function (_a) {
1221
+ switch (_a.label) {
1222
+ case 0:
1223
+ rawCapabilities = unique(convertToRawCapabilities(capabilities));
1224
+ // Take shortcut if possible, that avoid extra roundtrips over the API.
1225
+ if (this.hasCapabilities(rawCapabilities)) {
1226
+ return [2 /*return*/];
1227
+ }
1228
+ requestedSet = new Set(rawCapabilities);
1229
+ capabilities$ = rxjs.fromEvent(this.matrixWidgetApi, "action:".concat(matrixWidgetApi.WidgetApiToWidgetAction.NotifyCapabilities), function (ev) { return ev; }).pipe(
1230
+ // TODO: `hasCapability` in the matrix-widget-api isn't consistent when capability
1231
+ // upgrades happened. But `updateRequestedCapabilities` will deduplicate already
1232
+ // approved capabilities, so the the `requested` field will be inconsistent.
1233
+ // If we would enable this check, the function will never resolve. This should
1234
+ // be reactivated once the capability upgrade is working correctly. See also:
1235
+ // https://github.com/matrix-org/matrix-widget-api/issues/52
1236
+ // Ignore events from other parallel capability requests
1237
+ //filter((ev) =>
1238
+ // equalsSet(new Set(ev.detail.data.requested), requestedSet)
1239
+ //),
1240
+ rxjs.map(function (ev) {
1241
+ var approvedSet = new Set(ev.detail.data.approved);
1242
+ var missingSet = subtractSet(requestedSet, approvedSet);
1243
+ if (missingSet.size > 0) {
1244
+ throw new Error("Capabilities rejected: ".concat(Array.from(missingSet).join(', ')));
1245
+ }
1246
+ }), rxjs.first());
1247
+ return [4 /*yield*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1248
+ var subscription, err_1;
1249
+ return __generator(this, function (_a) {
1250
+ switch (_a.label) {
1251
+ case 0:
1252
+ subscription = capabilities$.subscribe({
1253
+ next: resolve,
1254
+ error: reject,
1255
+ });
1256
+ _a.label = 1;
1257
+ case 1:
1258
+ _a.trys.push([1, 3, , 4]);
1259
+ this.matrixWidgetApi.requestCapabilities(rawCapabilities);
1260
+ return [4 /*yield*/, this.matrixWidgetApi.updateRequestedCapabilities()];
1261
+ case 2:
1262
+ _a.sent();
1263
+ return [3 /*break*/, 4];
1264
+ case 3:
1265
+ err_1 = _a.sent();
1266
+ subscription.unsubscribe();
1267
+ reject(err_1);
1268
+ return [3 /*break*/, 4];
1269
+ case 4: return [2 /*return*/];
1270
+ }
1271
+ });
1272
+ }); })];
1273
+ case 1:
1274
+ _a.sent();
1275
+ return [2 /*return*/];
1276
+ }
1277
+ });
1278
+ });
1279
+ };
1280
+ /** {@inheritDoc WidgetApi.hasCapabilities} */
1281
+ WidgetApiImpl.prototype.hasCapabilities = function (capabilities) {
1282
+ var _this = this;
1283
+ var rawCapabilities = convertToRawCapabilities(capabilities);
1284
+ return rawCapabilities.every(function (c) { return _this.matrixWidgetApi.hasCapability(c); });
1285
+ };
1286
+ /** {@inheritDoc WidgetApi.receiveSingleStateEvent} */
1287
+ WidgetApiImpl.prototype.receiveSingleStateEvent = function (eventType_1) {
1288
+ return __awaiter(this, arguments, void 0, function (eventType, stateKey) {
1289
+ var events;
1290
+ if (stateKey === void 0) { stateKey = ''; }
1291
+ return __generator(this, function (_a) {
1292
+ switch (_a.label) {
1293
+ case 0: return [4 /*yield*/, this.receiveStateEvents(eventType, { stateKey: stateKey })];
1294
+ case 1:
1295
+ events = _a.sent();
1296
+ return [2 /*return*/, events && events[0]];
1297
+ }
1298
+ });
1299
+ });
1300
+ };
1301
+ /** {@inheritDoc WidgetApi.receiveStateEvents} */
1302
+ WidgetApiImpl.prototype.receiveStateEvents = function (eventType_1) {
1303
+ return __awaiter(this, arguments, void 0, function (eventType, _a) {
1304
+ var _b = _a === void 0 ? {} : _a, stateKey = _b.stateKey, roomIds = _b.roomIds;
1305
+ return __generator(this, function (_c) {
1306
+ switch (_c.label) {
1307
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.readStateEvents(eventType, Number.MAX_SAFE_INTEGER, stateKey, typeof roomIds === 'string' ? [matrixWidgetApi.Symbols.AnyRoom] : roomIds)];
1308
+ case 1: return [2 /*return*/, (_c.sent())];
1309
+ }
1310
+ });
1311
+ });
1312
+ };
1313
+ /** {@inheritDoc WidgetApi.observeStateEvents} */
1314
+ WidgetApiImpl.prototype.observeStateEvents = function (eventType, _a) {
1315
+ var _b = _a === void 0 ? {} : _a, stateKey = _b.stateKey, roomIds = _b.roomIds;
1316
+ var currentRoomId = this.widgetParameters.roomId;
1317
+ if (!currentRoomId) {
1318
+ return rxjs.throwError(function () { return new Error('Current room id is unknown'); });
1319
+ }
1320
+ var historyEvent$ = rxjs.from(this.receiveStateEvents(eventType, { stateKey: stateKey, roomIds: roomIds })).pipe(rxjs.mergeAll());
1321
+ var futureEvent$ = this.events$.pipe(rxjs.map(function (event) {
1322
+ var matrixEvent = event.detail.data;
1323
+ if (matrixEvent.type === eventType &&
1324
+ matrixEvent.state_key !== undefined &&
1325
+ (stateKey === undefined || matrixEvent.state_key === stateKey) &&
1326
+ isInRoom(matrixEvent, currentRoomId, roomIds)) {
1327
+ return event.detail.data;
1517
1328
  }
1518
- op = body.call(thisArg, _);
1519
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1520
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1521
- }
1522
- };
1523
- /**
1524
- * The name of the redaction room event.
1525
- */
1526
- var ROOM_EVENT_REDACTION = 'm.room.redaction';
1527
- /**
1528
- * Check whether the format of a redaction event is valid.
1529
- * @param event - The event to check.
1530
- * @returns True if the event format is valid, otherwise false.
1531
- */
1532
- function isValidRedactionEvent(event) {
1533
- if (event.type === ROOM_EVENT_REDACTION &&
1534
- typeof event.redacts === 'string') {
1535
- return true;
1536
- }
1537
- return false;
1538
- }
1539
- /**
1540
- * Redacts an event in the current room.
1541
- * @param widgetApi - An instance of the widget API.
1542
- * @param eventId - The id of the event to redact.
1543
- * @returns The redaction event that was send to the room.
1544
- */
1545
- function redactEvent(widgetApi, eventId) {
1546
- return __awaiter(this, void 0, void 0, function () {
1547
- var result;
1548
- return __generator(this, function (_a) {
1549
- switch (_a.label) {
1550
- case 0: return [4 /*yield*/, widgetApi.sendRoomEvent(ROOM_EVENT_REDACTION, { redacts: eventId })];
1551
- case 1:
1552
- result = _a.sent();
1553
- // The redaction event is special and needs to be casted, as the widget
1554
- // toolkit assumes that the content of an event is returned as we send it.
1555
- // However for redactions the content is copied directly into the event to
1556
- // make it available without decrypting the content.
1557
- return [2 /*return*/, result];
1329
+ return undefined;
1330
+ }), rxjs.filter(isDefined));
1331
+ return rxjs.concat(historyEvent$, futureEvent$);
1332
+ };
1333
+ /** {@inheritDoc WidgetApi.sendStateEvent} */
1334
+ WidgetApiImpl.prototype.sendStateEvent = function (eventType_1, content_1) {
1335
+ return __awaiter(this, arguments, void 0, function (eventType, content, _a) {
1336
+ var subject, subscription, _b, event_id_1, room_id_1, event_1;
1337
+ var _c = _a === void 0 ? {} : _a, roomId = _c.roomId, _d = _c.stateKey, stateKey = _d === void 0 ? '' : _d;
1338
+ return __generator(this, function (_e) {
1339
+ switch (_e.label) {
1340
+ case 0:
1341
+ subject = new rxjs.ReplaySubject();
1342
+ subscription = this.events$.subscribe(function (e) { return subject.next(e); });
1343
+ _e.label = 1;
1344
+ case 1:
1345
+ _e.trys.push([1, , 4, 5]);
1346
+ return [4 /*yield*/, this.matrixWidgetApi.sendStateEvent(eventType, stateKey, content, roomId)];
1347
+ case 2:
1348
+ _b = _e.sent(), event_id_1 = _b.event_id, room_id_1 = _b.room_id;
1349
+ return [4 /*yield*/, rxjs.firstValueFrom(subject.pipe(rxjs.filter(function (event) {
1350
+ var matrixEvent = event.detail.data;
1351
+ return (matrixEvent.event_id === event_id_1 &&
1352
+ matrixEvent.room_id === room_id_1);
1353
+ }), rxjs.map(function (event) { return event.detail.data; })))];
1354
+ case 3:
1355
+ event_1 = _e.sent();
1356
+ return [2 /*return*/, event_1];
1357
+ case 4:
1358
+ subscription.unsubscribe();
1359
+ return [7 /*endfinally*/];
1360
+ case 5: return [2 /*return*/];
1361
+ }
1362
+ });
1363
+ });
1364
+ };
1365
+ /** {@inheritDoc WidgetApi.receiveRoomEvents} */
1366
+ WidgetApiImpl.prototype.receiveRoomEvents = function (eventType_1) {
1367
+ return __awaiter(this, arguments, void 0, function (eventType, _a) {
1368
+ var _b = _a === void 0 ? {} : _a, messageType = _b.messageType, roomIds = _b.roomIds;
1369
+ return __generator(this, function (_c) {
1370
+ switch (_c.label) {
1371
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.readRoomEvents(eventType, Number.MAX_SAFE_INTEGER, messageType, typeof roomIds === 'string' ? [matrixWidgetApi.Symbols.AnyRoom] : roomIds)];
1372
+ case 1: return [2 /*return*/, (_c.sent())];
1373
+ }
1374
+ });
1375
+ });
1376
+ };
1377
+ /** {@inheritDoc WidgetApi.observeRoomEvents} */
1378
+ WidgetApiImpl.prototype.observeRoomEvents = function (eventType, _a) {
1379
+ var _b = _a === void 0 ? {} : _a, messageType = _b.messageType, roomIds = _b.roomIds;
1380
+ var currentRoomId = this.widgetParameters.roomId;
1381
+ if (!currentRoomId) {
1382
+ return rxjs.throwError(function () { return new Error('Current room id is unknown'); });
1383
+ }
1384
+ var historyEvent$ = rxjs.from(this.receiveRoomEvents(eventType, { messageType: messageType, roomIds: roomIds })).pipe(rxjs.mergeAll());
1385
+ var futureEvent$ = this.events$.pipe(rxjs.map(function (event) {
1386
+ var matrixEvent = event.detail.data;
1387
+ if (matrixEvent.type === eventType &&
1388
+ matrixEvent.state_key === undefined &&
1389
+ (!messageType || matrixEvent.content.msgtype === messageType) &&
1390
+ isInRoom(matrixEvent, currentRoomId, roomIds)) {
1391
+ return event.detail.data;
1558
1392
  }
1393
+ return undefined;
1394
+ }), rxjs.filter(isDefined));
1395
+ return rxjs.concat(historyEvent$, futureEvent$);
1396
+ };
1397
+ /** {@inheritDoc WidgetApi.sendRoomEvent} */
1398
+ WidgetApiImpl.prototype.sendRoomEvent = function (eventType_1, content_1) {
1399
+ return __awaiter(this, arguments, void 0, function (eventType, content, _a) {
1400
+ var subject, subscription, _b, event_id_2, room_id_2, event_2;
1401
+ var _c = _a === void 0 ? {} : _a, roomId = _c.roomId;
1402
+ return __generator(this, function (_d) {
1403
+ switch (_d.label) {
1404
+ case 0:
1405
+ subject = new rxjs.ReplaySubject();
1406
+ subscription = this.events$.subscribe(function (e) { return subject.next(e); });
1407
+ _d.label = 1;
1408
+ case 1:
1409
+ _d.trys.push([1, , 4, 5]);
1410
+ return [4 /*yield*/, this.matrixWidgetApi.sendRoomEvent(eventType, content, roomId)];
1411
+ case 2:
1412
+ _b = _d.sent(), event_id_2 = _b.event_id, room_id_2 = _b.room_id;
1413
+ return [4 /*yield*/, rxjs.firstValueFrom(subject.pipe(rxjs.filter(function (event) {
1414
+ var matrixEvent = event.detail.data;
1415
+ return (matrixEvent.event_id === event_id_2 &&
1416
+ matrixEvent.room_id === room_id_2);
1417
+ }), rxjs.map(function (event) { return event.detail.data; })))];
1418
+ case 3:
1419
+ event_2 = _d.sent();
1420
+ return [2 /*return*/, event_2];
1421
+ case 4:
1422
+ subscription.unsubscribe();
1423
+ return [7 /*endfinally*/];
1424
+ case 5: return [2 /*return*/];
1425
+ }
1426
+ });
1427
+ });
1428
+ };
1429
+ /** {@inheritDoc WidgetApi.readEventRelations} */
1430
+ WidgetApiImpl.prototype.readEventRelations = function (eventId, options) {
1431
+ return __awaiter(this, void 0, void 0, function () {
1432
+ var _a, chunk, next_batch;
1433
+ return __generator(this, function (_b) {
1434
+ switch (_b.label) {
1435
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.readEventRelations(eventId, options === null || options === void 0 ? void 0 : options.roomId, options === null || options === void 0 ? void 0 : options.relationType, options === null || options === void 0 ? void 0 : options.eventType, options === null || options === void 0 ? void 0 : options.limit, options === null || options === void 0 ? void 0 : options.from, undefined, options === null || options === void 0 ? void 0 : options.direction)];
1436
+ case 1:
1437
+ _a = _b.sent(), chunk = _a.chunk, next_batch = _a.next_batch;
1438
+ return [2 /*return*/, {
1439
+ chunk: chunk,
1440
+ nextToken: next_batch !== null && next_batch !== void 0 ? next_batch : undefined,
1441
+ }];
1442
+ }
1443
+ });
1444
+ });
1445
+ };
1446
+ /** {@inheritDoc WidgetApi.sendToDeviceMessage} */
1447
+ WidgetApiImpl.prototype.sendToDeviceMessage = function (eventType, encrypted, content) {
1448
+ return __awaiter(this, void 0, void 0, function () {
1449
+ return __generator(this, function (_a) {
1450
+ switch (_a.label) {
1451
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.sendToDevice(eventType, encrypted, content)];
1452
+ case 1:
1453
+ _a.sent();
1454
+ return [2 /*return*/];
1455
+ }
1456
+ });
1457
+ });
1458
+ };
1459
+ /** {@inheritDoc WidgetApi.observeToDeviceMessages} */
1460
+ WidgetApiImpl.prototype.observeToDeviceMessages = function (eventType) {
1461
+ return this.toDeviceMessages$.pipe(rxjs.map(function (e) { return e.detail.data; }), rxjs.filter(function (e) { return e.type === eventType; }));
1462
+ };
1463
+ /** {@inheritDoc WidgetApi.openModal} */
1464
+ WidgetApiImpl.prototype.openModal = function (pathName, name, options) {
1465
+ return __awaiter(this, void 0, void 0, function () {
1466
+ var isModal, url, closeModalWidget$;
1467
+ var _this = this;
1468
+ return __generator(this, function (_a) {
1469
+ switch (_a.label) {
1470
+ case 0:
1471
+ isModal = parseWidgetId(this.widgetId).isModal;
1472
+ if (isModal) {
1473
+ throw new Error("Modals can't be opened from another modal widget");
1474
+ }
1475
+ url = generateWidgetRegistrationUrl({
1476
+ pathName: pathName,
1477
+ widgetParameters: this.widgetParameters,
1478
+ });
1479
+ return [4 /*yield*/, this.matrixWidgetApi.openModalWidget(url, name, options === null || options === void 0 ? void 0 : options.buttons, options === null || options === void 0 ? void 0 : options.data)];
1480
+ case 1:
1481
+ _a.sent();
1482
+ closeModalWidget$ = rxjs.fromEvent(this.matrixWidgetApi, "action:".concat(matrixWidgetApi.WidgetApiToWidgetAction.CloseModalWidget), function (event) {
1483
+ var _a;
1484
+ event.preventDefault();
1485
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1486
+ if (((_a = event.detail.data) === null || _a === void 0 ? void 0 : _a['m.exited']) === true) {
1487
+ return undefined;
1488
+ }
1489
+ return event.detail.data;
1490
+ });
1491
+ return [2 /*return*/, rxjs.firstValueFrom(closeModalWidget$)];
1492
+ }
1493
+ });
1494
+ });
1495
+ };
1496
+ /** {@inheritDoc WidgetApi.setModalButtonEnabled} */
1497
+ WidgetApiImpl.prototype.setModalButtonEnabled = function (buttonId, isEnabled) {
1498
+ return __awaiter(this, void 0, void 0, function () {
1499
+ var isModal;
1500
+ return __generator(this, function (_a) {
1501
+ switch (_a.label) {
1502
+ case 0:
1503
+ isModal = parseWidgetId(this.widgetId).isModal;
1504
+ if (!isModal) {
1505
+ throw new Error('Modal buttons can only be enabled from a modal widget');
1506
+ }
1507
+ return [4 /*yield*/, this.matrixWidgetApi.setModalButtonEnabled(buttonId, isEnabled)];
1508
+ case 1:
1509
+ _a.sent();
1510
+ return [2 /*return*/];
1511
+ }
1512
+ });
1513
+ });
1514
+ };
1515
+ /** {@inheritDoc WidgetApi.observeModalButtons} */
1516
+ WidgetApiImpl.prototype.observeModalButtons = function () {
1517
+ var _this = this;
1518
+ var isModal = parseWidgetId(this.widgetId).isModal;
1519
+ if (!isModal) {
1520
+ throw new Error('Modal buttons can only be observed from a modal widget');
1521
+ }
1522
+ return rxjs.fromEvent(this.matrixWidgetApi, "action:".concat(matrixWidgetApi.WidgetApiToWidgetAction.ButtonClicked), function (event) {
1523
+ event.preventDefault();
1524
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1525
+ return event.detail.data.id;
1526
+ });
1527
+ };
1528
+ /** {@inheritDoc WidgetApi.closeModal} */
1529
+ WidgetApiImpl.prototype.closeModal = function (data) {
1530
+ return __awaiter(this, void 0, void 0, function () {
1531
+ var isModal;
1532
+ return __generator(this, function (_a) {
1533
+ switch (_a.label) {
1534
+ case 0:
1535
+ isModal = parseWidgetId(this.widgetId).isModal;
1536
+ if (!isModal) {
1537
+ throw new Error('Modals can only be closed from a modal widget');
1538
+ }
1539
+ return [4 /*yield*/, this.matrixWidgetApi.closeModalWidget(data ? data : { 'm.exited': true })];
1540
+ case 1:
1541
+ _a.sent();
1542
+ return [2 /*return*/];
1543
+ }
1544
+ });
1559
1545
  });
1560
- });
1561
- }
1562
- /**
1563
- * Observes redaction events in the current room.
1564
- * @param widgetApi - An instance of the widget API.
1565
- * @returns An observable of validated redaction events.
1566
- */
1567
- function observeRedactionEvents(widgetApi) {
1568
- return widgetApi
1569
- .observeRoomEvents(ROOM_EVENT_REDACTION)
1570
- .pipe(rxjs.filter(isValidRedactionEvent));
1571
- }
1572
-
1573
- /*
1574
- * Copyright 2022 Nordeck IT + Consulting GmbH
1575
- *
1576
- * Licensed under the Apache License, Version 2.0 (the "License");
1577
- * you may not use this file except in compliance with the License.
1578
- * You may obtain a copy of the License at
1579
- *
1580
- * http://www.apache.org/licenses/LICENSE-2.0
1581
- *
1582
- * Unless required by applicable law or agreed to in writing, software
1583
- * distributed under the License is distributed on an "AS IS" BASIS,
1584
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1585
- * See the License for the specific language governing permissions and
1586
- * limitations under the License.
1587
- */
1588
- /**
1589
- * Get the original event id, or the event id of the current event if it
1590
- * doesn't relates to another event.
1591
- * @param event - The room event.
1592
- * @returns The event id of the original event, or the current event id.
1593
- */
1594
- function getOriginalEventId(event) {
1595
- var _a, _b, _c;
1596
- var newContentRelatesTo = event.content;
1597
- if (((_a = newContentRelatesTo['m.relates_to']) === null || _a === void 0 ? void 0 : _a.rel_type) === 'm.replace') {
1598
- return (_c = (_b = newContentRelatesTo['m.relates_to']) === null || _b === void 0 ? void 0 : _b.event_id) !== null && _c !== void 0 ? _c : event.event_id;
1599
- }
1600
- return event.event_id;
1601
- }
1602
- /**
1603
- * Get the content of the event, independent from whether it contains the
1604
- * content directly or contains a "m.new_content" key.
1605
- * @param event - The room event.
1606
- * @returns Only the content of the room event.
1607
- */
1608
- function getContent(event) {
1609
- var _a;
1610
- var newContentRelatesTo = event.content;
1611
- return (_a = newContentRelatesTo['m.new_content']) !== null && _a !== void 0 ? _a : event.content;
1612
- }
1613
- /**
1614
- * Validates that `event` has a valid structure for a
1615
- * {@link EventWithRelatesTo}.
1616
- * @param event - The event to validate.
1617
- * @returns True, if the event is valid.
1618
- */
1619
- function isValidEventWithRelatesTo(event) {
1620
- if (!event.content || typeof event.content !== 'object') {
1621
- return false;
1622
- }
1623
- var relatedEvent = event;
1624
- if (!relatedEvent.content['m.relates_to'] ||
1625
- typeof relatedEvent.content['m.relates_to'] !== 'object') {
1626
- return false;
1627
- }
1628
- if (typeof relatedEvent.content['m.relates_to'].rel_type !== 'string' ||
1629
- typeof relatedEvent.content['m.relates_to'].event_id !== 'string') {
1630
- return false;
1631
- }
1632
- return true;
1633
- }
1634
-
1635
- /*
1636
- * Copyright 2022 Nordeck IT + Consulting GmbH
1637
- *
1638
- * Licensed under the Apache License, Version 2.0 (the "License");
1639
- * you may not use this file except in compliance with the License.
1640
- * You may obtain a copy of the License at
1641
- *
1642
- * http://www.apache.org/licenses/LICENSE-2.0
1643
- *
1644
- * Unless required by applicable law or agreed to in writing, software
1645
- * distributed under the License is distributed on an "AS IS" BASIS,
1646
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1647
- * See the License for the specific language governing permissions and
1648
- * limitations under the License.
1649
- */
1650
- /**
1651
- * The name of the room member state event.
1652
- */
1653
- var STATE_EVENT_ROOM_MEMBER = 'm.room.member';
1654
- function isStringUndefinedOrNull(value) {
1655
- return value === undefined || value === null || typeof value === 'string';
1656
- }
1657
- /**
1658
- * Validates that `event` is has a valid structure for a
1659
- * {@link RoomMemberStateEventContent}.
1660
- * @param event - The event to validate.
1661
- * @returns True, if the event is valid.
1662
- */
1663
- function isValidRoomMemberStateEvent(event) {
1664
- if (event.type !== STATE_EVENT_ROOM_MEMBER ||
1665
- typeof event.content !== 'object') {
1666
- return false;
1667
- }
1668
- var content = event.content;
1669
- if (typeof content.membership !== 'string') {
1670
- return false;
1671
- }
1672
- if (!isStringUndefinedOrNull(content.displayname)) {
1673
- return false;
1674
- }
1675
- // the avatar_url shouldn't be null, but some implementations
1676
- // set it as a valid value
1677
- if (!isStringUndefinedOrNull(content.avatar_url)) {
1678
- return false;
1679
- }
1680
- return true;
1681
- }
1546
+ };
1547
+ /** {@inheritdoc WidgetApi.navigateTo} */
1548
+ WidgetApiImpl.prototype.navigateTo = function (uri) {
1549
+ return __awaiter(this, void 0, void 0, function () {
1550
+ return __generator(this, function (_a) {
1551
+ switch (_a.label) {
1552
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.navigateTo(uri)];
1553
+ case 1:
1554
+ _a.sent();
1555
+ return [2 /*return*/];
1556
+ }
1557
+ });
1558
+ });
1559
+ };
1560
+ /** {@inheritdoc WidgetApi.requestOpenIDConnectToken} */
1561
+ WidgetApiImpl.prototype.requestOpenIDConnectToken = function () {
1562
+ return __awaiter(this, void 0, void 0, function () {
1563
+ return __generator(this, function (_b) {
1564
+ switch (_b.label) {
1565
+ case 0:
1566
+ if (!this.outstandingOpenIDConnectTokenRequest) return [3 /*break*/, 4];
1567
+ _b.label = 1;
1568
+ case 1:
1569
+ _b.trys.push([1, 3, , 4]);
1570
+ return [4 /*yield*/, this.outstandingOpenIDConnectTokenRequest];
1571
+ case 2:
1572
+ _b.sent();
1573
+ return [3 /*break*/, 4];
1574
+ case 3:
1575
+ _b.sent();
1576
+ return [3 /*break*/, 4];
1577
+ case 4:
1578
+ _b.trys.push([4, , 6, 7]);
1579
+ this.outstandingOpenIDConnectTokenRequest =
1580
+ this.requestOpenIDConnectTokenInternal();
1581
+ return [4 /*yield*/, this.outstandingOpenIDConnectTokenRequest];
1582
+ case 5: return [2 /*return*/, _b.sent()];
1583
+ case 6:
1584
+ this.outstandingOpenIDConnectTokenRequest = undefined;
1585
+ return [7 /*endfinally*/];
1586
+ case 7: return [2 /*return*/];
1587
+ }
1588
+ });
1589
+ });
1590
+ };
1591
+ WidgetApiImpl.prototype.requestOpenIDConnectTokenInternal = function () {
1592
+ return __awaiter(this, void 0, void 0, function () {
1593
+ var leywayMilliseconds, openIdToken, err_2;
1594
+ var _a;
1595
+ return __generator(this, function (_b) {
1596
+ switch (_b.label) {
1597
+ case 0:
1598
+ leywayMilliseconds = 30 * 1000;
1599
+ if (this.cachedOpenIdToken &&
1600
+ this.cachedOpenIdToken.expiresAt - leywayMilliseconds > Date.now()) {
1601
+ return [2 /*return*/, this.cachedOpenIdToken.openIdToken];
1602
+ }
1603
+ _b.label = 1;
1604
+ case 1:
1605
+ _b.trys.push([1, 3, , 4]);
1606
+ return [4 /*yield*/, this.matrixWidgetApi.requestOpenIDConnectToken()];
1607
+ case 2:
1608
+ openIdToken = _b.sent();
1609
+ this.cachedOpenIdToken = {
1610
+ openIdToken: openIdToken,
1611
+ expiresAt: Date.now() + ((_a = openIdToken.expires_in) !== null && _a !== void 0 ? _a : 0) * 1000,
1612
+ };
1613
+ return [2 /*return*/, openIdToken];
1614
+ case 3:
1615
+ err_2 = _b.sent();
1616
+ this.cachedOpenIdToken = undefined;
1617
+ throw err_2;
1618
+ case 4: return [2 /*return*/];
1619
+ }
1620
+ });
1621
+ });
1622
+ };
1623
+ /** {@inheritdoc WidgetApi.observeTurnServers} */
1624
+ WidgetApiImpl.prototype.observeTurnServers = function () {
1625
+ return rxjs.from(this.matrixWidgetApi.getTurnServers()).pipe(
1626
+ // For some reason a different naming was chosen for the API, but
1627
+ // we already convert them to the right type for WebRTC consumers.
1628
+ rxjs.map(function (_a) {
1629
+ var uris = _a.uris, username = _a.username, password = _a.password;
1630
+ return ({
1631
+ urls: uris,
1632
+ username: username,
1633
+ credential: password,
1634
+ });
1635
+ }));
1636
+ };
1637
+ /** {@inheritdoc WidgetApi.searchUserDirectory} */
1638
+ WidgetApiImpl.prototype.searchUserDirectory = function (searchTerm, options) {
1639
+ return __awaiter(this, void 0, void 0, function () {
1640
+ var results;
1641
+ return __generator(this, function (_a) {
1642
+ switch (_a.label) {
1643
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.searchUserDirectory(searchTerm, options === null || options === void 0 ? void 0 : options.limit)];
1644
+ case 1:
1645
+ results = (_a.sent()).results;
1646
+ return [2 /*return*/, {
1647
+ results: results.map(function (_a) {
1648
+ var user_id = _a.user_id, display_name = _a.display_name, avatar_url = _a.avatar_url;
1649
+ return ({
1650
+ userId: user_id,
1651
+ displayName: display_name,
1652
+ avatarUrl: avatar_url,
1653
+ });
1654
+ }),
1655
+ }];
1656
+ }
1657
+ });
1658
+ });
1659
+ };
1660
+ /** {@inheritdoc WidgetApi.getMediaConfig} */
1661
+ WidgetApiImpl.prototype.getMediaConfig = function () {
1662
+ return __awaiter(this, void 0, void 0, function () {
1663
+ return __generator(this, function (_a) {
1664
+ switch (_a.label) {
1665
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.getMediaConfig()];
1666
+ case 1: return [2 /*return*/, _a.sent()];
1667
+ }
1668
+ });
1669
+ });
1670
+ };
1671
+ /** {@inheritdoc WidgetApi.uploadFile} */
1672
+ WidgetApiImpl.prototype.uploadFile = function (file) {
1673
+ return __awaiter(this, void 0, void 0, function () {
1674
+ return __generator(this, function (_a) {
1675
+ switch (_a.label) {
1676
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.uploadFile(file)];
1677
+ case 1: return [2 /*return*/, _a.sent()];
1678
+ }
1679
+ });
1680
+ });
1681
+ };
1682
+ return WidgetApiImpl;
1683
+ }());
1682
1684
 
1683
1685
  exports.ROOM_EVENT_REDACTION = ROOM_EVENT_REDACTION;
1684
1686
  exports.STATE_EVENT_POWER_LEVELS = STATE_EVENT_POWER_LEVELS;