@matrix-widget-toolkit/api 3.3.1 → 3.4.0

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