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