@matrix-widget-toolkit/api 4.2.0 → 5.0.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,11 +1,12 @@
1
1
  export { generateRoomTimelineCapabilities } from './capabilities';
2
2
  export { getRoomMemberDisplayName } from './displayName';
3
- export { isRoomEvent, isStateEvent, isValidRoomEvent, isValidStateEvent as isValidStateEVent, isValidToDeviceMessageEvent, } from './events';
3
+ export { STATE_EVENT_CREATE, isRoomEvent, isStateEvent, isValidCreateEventSchema, isValidRoomEvent, isValidStateEvent as isValidStateEVent, isValidToDeviceMessageEvent, } from './events';
4
+ export type { PowerLevelsActions, PowerLevelsStateEvent, StateEventCreateContent, } from './events';
4
5
  export { WIDGET_CAPABILITY_NAVIGATE, navigateToRoom } from './navigateTo';
5
6
  export type { NavigateToRoomOptions } from './navigateTo';
6
7
  export { compareOriginServerTS } from './originServerTs';
7
8
  export { STATE_EVENT_POWER_LEVELS, calculateUserPowerLevel, hasActionPower, hasRoomEventPower, hasStateEventPower, isValidPowerLevelStateEvent, } from './powerLevel';
8
- export type { PowerLevelsActions, PowerLevelsStateEvent } from './powerLevel';
9
+ export type { ROOM_VERSION_12_CREATOR, UserPowerLevelType } from './powerLevel';
9
10
  export { ROOM_EVENT_REDACTION, isValidRedactionEvent, observeRedactionEvents, redactEvent, } from './redactions';
10
11
  export type { Redaction, RedactionRoomEvent } from './redactions';
11
12
  export { getContent, getOriginalEventId, isValidEventWithRelatesTo, } from './relatesTo';
@@ -1,55 +1,32 @@
1
1
  import { StateEvent } from '../types';
2
+ import type { PowerLevelsActions, PowerLevelsStateEvent, StateEventCreateContent } from './events';
3
+ export { isValidPowerLevelStateEvent, STATE_EVENT_POWER_LEVELS, } from './events';
2
4
  /**
3
- * The name of the power levels state event.
5
+ * Room version 12 requires us to have something larger than Max integer for room creators.
6
+ * This is a workaround to allow the room creator to always have the highest power level.
4
7
  */
5
- export declare const STATE_EVENT_POWER_LEVELS = "m.room.power_levels";
6
- /**
7
- * The types of actions.
8
- */
9
- export type PowerLevelsActions = 'invite' | 'kick' | 'ban' | 'redact';
10
- /**
11
- * The content of an `m.room.power_levels` event.
12
- */
13
- export type PowerLevelsStateEvent = {
14
- events?: {
15
- [key: string]: number;
16
- };
17
- state_default?: number;
18
- events_default?: number;
19
- users?: {
20
- [key: string]: number;
21
- };
22
- users_default?: number;
23
- ban?: number;
24
- invite?: number;
25
- kick?: number;
26
- redact?: number;
27
- };
28
- /**
29
- * Validates that `event` is has a valid structure for a
30
- * {@link PowerLevelsStateEvent}.
31
- * @param event - The event to validate.
32
- * @returns True, if the event is valid.
33
- */
34
- export declare function isValidPowerLevelStateEvent(event: StateEvent<unknown>): event is StateEvent<PowerLevelsStateEvent>;
8
+ export declare const ROOM_VERSION_12_CREATOR = "ROOM_VERSION_12_CREATOR";
9
+ export type UserPowerLevelType = number | typeof ROOM_VERSION_12_CREATOR;
35
10
  /**
36
11
  * Check if a user has the power to send a specific room event.
37
12
  *
38
13
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
14
+ * @param createRoomStateEvent - the `m.room.create` event for the room
39
15
  * @param userId - the id of the user
40
16
  * @param eventType - the type of room event
41
17
  * @returns if true, the user has the power
42
18
  */
43
- export declare function hasRoomEventPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, userId: string | undefined, eventType: string): boolean;
19
+ export declare function hasRoomEventPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, createRoomStateEvent: StateEvent<StateEventCreateContent> | undefined, userId: string | undefined, eventType: string): boolean;
44
20
  /**
45
21
  * Check if a user has the power to send a specific state event.
46
22
  *
47
23
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
24
+ * @param createRoomStateEvent - the `m.room.create` event for the room
48
25
  * @param userId - the id of the user
49
26
  * @param eventType - the type of state event
50
27
  * @returns if true, the user has the power
51
28
  */
52
- export declare function hasStateEventPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, userId: string | undefined, eventType: string): boolean;
29
+ export declare function hasStateEventPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, createRoomStateEvent: StateEvent<StateEventCreateContent> | undefined, userId: string | undefined, eventType: string): boolean;
53
30
  /**
54
31
  * Check if a user has the power to perform a specific action.
55
32
  *
@@ -60,19 +37,25 @@ export declare function hasStateEventPower(powerLevelStateEvent: PowerLevelsStat
60
37
  * * redact: Redact a message from another user
61
38
  *
62
39
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
40
+ * @param createRoomStateEvent - the `m.room.create` event for the room
63
41
  * @param userId - the id of the user
64
42
  * @param action - the action
65
43
  * @returns if true, the user has the power
66
44
  */
67
- export declare function hasActionPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, userId: string | undefined, action: PowerLevelsActions): boolean;
45
+ export declare function hasActionPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, createRoomStateEvent: StateEvent<StateEventCreateContent> | undefined, userId: string | undefined, action: PowerLevelsActions): boolean;
68
46
  /**
69
47
  * Calculate the power level of the user based on a `m.room.power_levels` event.
70
48
  *
49
+ * Note that we return the @see UserPowerLevelType type instead of a number as Room Version 12
50
+ * gives a Room creator (and additionalCreators) always the highest power level regardless
51
+ * of the highest next Powerlevel number.
52
+ *
71
53
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event.
54
+ * @param createRoomStateEvent - the `m.room.create` event for the room.
72
55
  * @param userId - the ID of the user.
73
56
  * @returns the power level of the user.
74
57
  */
75
- export declare function calculateUserPowerLevel(powerLevelStateEvent: PowerLevelsStateEvent, userId?: string): number;
58
+ export declare function calculateUserPowerLevel(powerLevelStateEvent: PowerLevelsStateEvent | undefined, createRoomStateEvent: StateEvent<StateEventCreateContent> | undefined, userId: string): UserPowerLevelType;
76
59
  /**
77
60
  * Calculate the power level that a user needs send a specific room event.
78
61
  *
@@ -80,15 +63,16 @@ export declare function calculateUserPowerLevel(powerLevelStateEvent: PowerLevel
80
63
  * @param eventType - the type of room event
81
64
  * @returns the power level that is needed
82
65
  */
83
- export declare function calculateRoomEventPowerLevel(powerLevelStateEvent: PowerLevelsStateEvent, eventType: string): number;
66
+ export declare function calculateRoomEventPowerLevel(powerLevelStateEvent: PowerLevelsStateEvent | undefined, eventType: string): number;
84
67
  /**
85
68
  * Calculate the power level that a user needs send a specific state event.
86
69
  *
87
70
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
71
+ * @param createRoomStateEvent - the `m.room.create` event
88
72
  * @param eventType - the type of state event
89
73
  * @returns the power level that is needed
90
74
  */
91
- export declare function calculateStateEventPowerLevel(powerLevelStateEvent: PowerLevelsStateEvent, eventType: string): number;
75
+ export declare function calculateStateEventPowerLevel(powerLevelStateEvent: PowerLevelsStateEvent | undefined, createRoomStateEvent: StateEvent<StateEventCreateContent> | undefined, eventType: string): number;
92
76
  /**
93
77
  * Calculate the power level that a user needs to perform an action.
94
78
  *
@@ -102,4 +86,4 @@ export declare function calculateStateEventPowerLevel(powerLevelStateEvent: Powe
102
86
  * @param action - the action
103
87
  * @returns the power level that is needed
104
88
  */
105
- export declare function calculateActionPowerLevel(powerLevelStateEvent: PowerLevelsStateEvent, action: PowerLevelsActions): number;
89
+ export declare function calculateActionPowerLevel(powerLevelStateEvent: PowerLevelsStateEvent | undefined, action: PowerLevelsActions): number;
@@ -118,6 +118,14 @@ var __assign$2 = (undefined && undefined.__assign) || function () {
118
118
  };
119
119
  return __assign$2.apply(this, arguments);
120
120
  };
121
+ /**
122
+ * The type of the power levels state event.
123
+ */
124
+ var STATE_EVENT_POWER_LEVELS = 'm.room.power_levels';
125
+ /**
126
+ * The types of type of the create event.
127
+ */
128
+ var STATE_EVENT_CREATE = 'm.room.create';
121
129
  /**
122
130
  * Check if the given event is a {@link StateEvent}.
123
131
  *
@@ -145,7 +153,12 @@ function isRoomEvent(event) {
145
153
  // Allow any here, so that the validation works for every event
146
154
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
147
155
  function isValidRoomEvent(event) {
148
- return roomEventSchema.validate(event).error === undefined;
156
+ var result = roomEventSchema.validate(event);
157
+ if (result.error) {
158
+ console.warn('Invalid room event:', result.error.details, { event: event });
159
+ return false;
160
+ }
161
+ return true;
149
162
  }
150
163
  /**
151
164
  * Check if the given value is a valid {@link StateEvent}.
@@ -156,7 +169,12 @@ function isValidRoomEvent(event) {
156
169
  // Allow any here, so that the validation works for every event
157
170
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
158
171
  function isValidStateEvent(event) {
159
- return stateEventSchema.validate(event).error === undefined;
172
+ var result = stateEventSchema.validate(event);
173
+ if (result.error) {
174
+ console.warn('Invalid state event:', result.error.details, { event: event });
175
+ return false;
176
+ }
177
+ return true;
160
178
  }
161
179
  /**
162
180
  * Check if the given value is a valid {@link ToDeviceMessageEvent}.
@@ -165,19 +183,26 @@ function isValidStateEvent(event) {
165
183
  * @returns true if value is a valid to device message, else false.
166
184
  */
167
185
  function isValidToDeviceMessageEvent(event) {
168
- return toDeviceMessageSchema.validate(event).error === undefined;
186
+ var result = toDeviceMessageSchema.validate(event);
187
+ if (result.error) {
188
+ console.warn('Invalid to device message event:', result.error.details, {
189
+ event: event,
190
+ });
191
+ return false;
192
+ }
193
+ return true;
169
194
  }
170
- /**
171
- * Base properties to validate for all events.
172
- */
173
- var eventSchemaProps = {
174
- type: Joi.string().required(),
195
+ var eventSchemaBasicProps = {
175
196
  // Do roughly check against the format
176
197
  // https://spec.matrix.org/v1.13/appendices/#common-identifier-format
177
198
  sender: Joi.string().pattern(new RegExp('^@[^\\s:]*:\\S*$')).required(),
178
- room_id: Joi.string().pattern(new RegExp('^![^:]*:\\S*')).required(),
179
- content: Joi.object().required(),
199
+ // Prior versions of the code had checked for a server_name. However in room version 12+ this got dropped. There is no way for us to check this here.
200
+ room_id: Joi.string().pattern(new RegExp('^!')).required(),
180
201
  };
202
+ /**
203
+ * Base properties to validate for all events.
204
+ */
205
+ var eventSchemaProps = __assign$2({ type: Joi.string().required(), content: Joi.object().required() }, eventSchemaBasicProps);
181
206
  var roomEventSchema = Joi.object(__assign$2(__assign$2({}, eventSchemaProps), { event_id: Joi.string().pattern(new RegExp('^\\$.*')).required(), origin_server_ts: Joi.date().timestamp('javascript').required() })).unknown();
182
207
  var stateEventSchema = Joi.object(__assign$2(__assign$2({}, eventSchemaProps), { event_id: Joi.string().pattern(new RegExp('^\\$.*')), origin_server_ts: Joi.date().timestamp('javascript'), state_key: Joi.string().allow('').required() })).unknown();
183
208
  var toDeviceMessageSchema = Joi.object({
@@ -186,6 +211,71 @@ var toDeviceMessageSchema = Joi.object({
186
211
  encrypted: Joi.boolean().required(),
187
212
  content: Joi.object().required(),
188
213
  }).unknown();
214
+ var createEventSchema = Joi.object(__assign$2(__assign$2({}, eventSchemaBasicProps), { type: Joi.string().equal(STATE_EVENT_CREATE).required(), content: Joi.object({
215
+ // Room version 1 does not have a room version, so we allow it to be undefined.
216
+ room_version: Joi.string().optional(),
217
+ // The user ID of the creator of the room. (only from 1-10. after that we must use the sender field)
218
+ creator: Joi.string().optional(),
219
+ // Room version 12 introduces the additional_creators field.
220
+ additional_creators: Joi.array().items(Joi.string()).optional(),
221
+ })
222
+ .unknown()
223
+ .required() })).unknown();
224
+ /**
225
+ * Validates that `event` is has a valid structure for a
226
+ * {@link StateEventCreateContent}.
227
+ * @param event - The event to validate.
228
+ * @returns True, if the event is valid.
229
+ */
230
+ function isValidCreateEventSchema(event) {
231
+ if (!event) {
232
+ return true;
233
+ }
234
+ var result = createEventSchema.validate(event);
235
+ if (result.error) {
236
+ console.warn('Invalid room create message event:', result.error.details, {
237
+ event: event,
238
+ });
239
+ return false;
240
+ }
241
+ return true;
242
+ }
243
+ var powerLevelsEventSchema = Joi.object(__assign$2(__assign$2({}, eventSchemaBasicProps), {
244
+ // Strictly require to match the power levels event type
245
+ type: Joi.string().equal(STATE_EVENT_POWER_LEVELS).required(), content: Joi.object({
246
+ ban: Joi.number().optional().default(50),
247
+ events: Joi.object().pattern(Joi.string(), Joi.number()).optional(),
248
+ events_default: Joi.number().optional().default(0),
249
+ invite: Joi.number().optional().default(0),
250
+ kick: Joi.number().optional().default(50),
251
+ notifications: Joi.object({
252
+ room: Joi.number().optional().default(50),
253
+ })
254
+ .unknown()
255
+ .optional(),
256
+ redact: Joi.number().optional().default(50),
257
+ state_default: Joi.number().optional().default(50),
258
+ users: Joi.object().pattern(Joi.string(), Joi.number()).optional(),
259
+ users_default: Joi.number().optional().default(0),
260
+ })
261
+ .unknown()
262
+ .required() })).unknown();
263
+ /**
264
+ * Validates that `event` is has a valid structure for a
265
+ * {@link PowerLevelsStateEvent}.
266
+ * @param event - The event to validate.
267
+ * @returns True, if the event is valid.
268
+ */
269
+ function isValidPowerLevelStateEvent(event) {
270
+ var result = powerLevelsEventSchema.validate(event);
271
+ if (result.error) {
272
+ console.warn('Invalid powerlevel event:', result.error.details, {
273
+ event: event,
274
+ });
275
+ return false;
276
+ }
277
+ return true;
278
+ }
189
279
 
190
280
  /*
191
281
  * Copyright 2022 Nordeck IT + Consulting GmbH
@@ -313,95 +403,57 @@ function compareOriginServerTS(a, b) {
313
403
  * limitations under the License.
314
404
  */
315
405
  /**
316
- * The name of the power levels state event.
406
+ * Room version 12 requires us to have something larger than Max integer for room creators.
407
+ * This is a workaround to allow the room creator to always have the highest power level.
317
408
  */
318
- var STATE_EVENT_POWER_LEVELS = 'm.room.power_levels';
319
- function isNumberOrUndefined(value) {
320
- return value === undefined || typeof value === 'number';
321
- }
322
- function isStringToNumberMapOrUndefined(value) {
323
- return (value === undefined ||
324
- (value !== null &&
325
- typeof value === 'object' &&
326
- Object.entries(value).every(function (_a) {
327
- var k = _a[0], v = _a[1];
328
- return typeof k === 'string' && typeof v === 'number';
329
- })));
330
- }
331
- /**
332
- * Validates that `event` is has a valid structure for a
333
- * {@link PowerLevelsStateEvent}.
334
- * @param event - The event to validate.
335
- * @returns True, if the event is valid.
336
- */
337
- function isValidPowerLevelStateEvent(event) {
338
- if (event.type !== STATE_EVENT_POWER_LEVELS ||
339
- typeof event.content !== 'object') {
340
- return false;
341
- }
342
- var content = event.content;
343
- if (!isStringToNumberMapOrUndefined(content.events)) {
344
- return false;
345
- }
346
- if (!isNumberOrUndefined(content.state_default)) {
347
- return false;
348
- }
349
- if (!isNumberOrUndefined(content.events_default)) {
350
- return false;
351
- }
352
- if (!isStringToNumberMapOrUndefined(content.users)) {
353
- return false;
354
- }
355
- if (!isNumberOrUndefined(content.users_default)) {
356
- return false;
357
- }
358
- if (!isNumberOrUndefined(content.ban)) {
359
- return false;
360
- }
361
- if (!isNumberOrUndefined(content.invite)) {
362
- return false;
363
- }
364
- if (!isNumberOrUndefined(content.kick)) {
365
- return false;
409
+ var ROOM_VERSION_12_CREATOR = 'ROOM_VERSION_12_CREATOR';
410
+ function compareUserPowerLevelToNormalPowerLevel(userPowerLevel, normalPowerLevel) {
411
+ if (userPowerLevel === ROOM_VERSION_12_CREATOR) {
412
+ // Room version 12 creator has the highest power level.
413
+ return true;
366
414
  }
367
- if (!isNumberOrUndefined(content.redact)) {
415
+ if (typeof userPowerLevel !== 'number') {
416
+ // If the user power level is not a number, we cannot compare it to a normal power level.
368
417
  return false;
369
418
  }
370
- return true;
419
+ // Compare the user power level to the normal power level.
420
+ return userPowerLevel >= normalPowerLevel;
371
421
  }
372
422
  /**
373
423
  * Check if a user has the power to send a specific room event.
374
424
  *
375
425
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
426
+ * @param createRoomStateEvent - the `m.room.create` event for the room
376
427
  * @param userId - the id of the user
377
428
  * @param eventType - the type of room event
378
429
  * @returns if true, the user has the power
379
430
  */
380
- function hasRoomEventPower(powerLevelStateEvent, userId, eventType) {
381
- if (!powerLevelStateEvent) {
382
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
383
- return true;
431
+ function hasRoomEventPower(powerLevelStateEvent, createRoomStateEvent, userId, eventType) {
432
+ if (!userId) {
433
+ // This is invalid but required to be checked due to widget API which may not know it
434
+ throw new Error('Cannot check action power without a user ID. Please provide a user ID.');
384
435
  }
385
- var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
436
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, createRoomStateEvent, userId);
386
437
  var eventLevel = calculateRoomEventPowerLevel(powerLevelStateEvent, eventType);
387
- return userLevel >= eventLevel;
438
+ return compareUserPowerLevelToNormalPowerLevel(userLevel, eventLevel);
388
439
  }
389
440
  /**
390
441
  * Check if a user has the power to send a specific state event.
391
442
  *
392
443
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
444
+ * @param createRoomStateEvent - the `m.room.create` event for the room
393
445
  * @param userId - the id of the user
394
446
  * @param eventType - the type of state event
395
447
  * @returns if true, the user has the power
396
448
  */
397
- function hasStateEventPower(powerLevelStateEvent, userId, eventType) {
398
- if (!powerLevelStateEvent) {
399
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
400
- return true;
449
+ function hasStateEventPower(powerLevelStateEvent, createRoomStateEvent, userId, eventType) {
450
+ if (!userId) {
451
+ // This is invalid but required to be checked due to widget API which may not know it
452
+ throw new Error('Cannot check action power without a user ID. Please provide a user ID.');
401
453
  }
402
- var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
403
- var eventLevel = calculateStateEventPowerLevel(powerLevelStateEvent, eventType);
404
- return userLevel >= eventLevel;
454
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, createRoomStateEvent, userId);
455
+ var eventLevel = calculateStateEventPowerLevel(powerLevelStateEvent, createRoomStateEvent, eventType);
456
+ return compareUserPowerLevelToNormalPowerLevel(userLevel, eventLevel);
405
457
  }
406
458
  /**
407
459
  * Check if a user has the power to perform a specific action.
@@ -413,30 +465,74 @@ function hasStateEventPower(powerLevelStateEvent, userId, eventType) {
413
465
  * * redact: Redact a message from another user
414
466
  *
415
467
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
468
+ * @param createRoomStateEvent - the `m.room.create` event for the room
416
469
  * @param userId - the id of the user
417
470
  * @param action - the action
418
471
  * @returns if true, the user has the power
419
472
  */
420
- function hasActionPower(powerLevelStateEvent, userId, action) {
421
- if (!powerLevelStateEvent) {
422
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
423
- return true;
473
+ function hasActionPower(powerLevelStateEvent, createRoomStateEvent, userId, action) {
474
+ if (!userId) {
475
+ // This is invalid but required to be checked due to widget API which may not know it
476
+ throw new Error('Cannot check action power without a user ID. Please provide a user ID.');
424
477
  }
425
- var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
478
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, createRoomStateEvent, userId);
426
479
  var eventLevel = calculateActionPowerLevel(powerLevelStateEvent, action);
427
- return userLevel >= eventLevel;
480
+ return compareUserPowerLevelToNormalPowerLevel(userLevel, eventLevel);
428
481
  }
429
482
  /**
430
483
  * Calculate the power level of the user based on a `m.room.power_levels` event.
431
484
  *
485
+ * Note that we return the @see UserPowerLevelType type instead of a number as Room Version 12
486
+ * gives a Room creator (and additionalCreators) always the highest power level regardless
487
+ * of the highest next Powerlevel number.
488
+ *
432
489
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event.
490
+ * @param createRoomStateEvent - the `m.room.create` event for the room.
433
491
  * @param userId - the ID of the user.
434
492
  * @returns the power level of the user.
435
493
  */
436
- function calculateUserPowerLevel(powerLevelStateEvent, userId) {
437
- var _a, _b, _c;
438
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L8-L12
439
- 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);
494
+ function calculateUserPowerLevel(powerLevelStateEvent, createRoomStateEvent, userId) {
495
+ var _a, _b, _c, _d, _e, _f;
496
+ // This is practically not allowed and therefor not covered by the spec. However a js consumer could still pass an undefined userId so we handle it gracefully.
497
+ if (!userId) {
498
+ // If no user ID is provided, we return the default user power level or 0 if not set.
499
+ return 0;
500
+ }
501
+ // If we have room version 12 we must check if the user is the creator of the room and needs to have the highest power level.
502
+ if (((_a = createRoomStateEvent === null || createRoomStateEvent === void 0 ? void 0 : createRoomStateEvent.content) === null || _a === void 0 ? void 0 : _a.room_version) === '12' ||
503
+ ((_b = createRoomStateEvent === null || createRoomStateEvent === void 0 ? void 0 : createRoomStateEvent.content) === null || _b === void 0 ? void 0 : _b.room_version) === 'org.matrix.hydra.11') {
504
+ // If the user is the creator of the room, we return the special ROOM_VERSION_12_CREATOR value.
505
+ if (createRoomStateEvent.sender === userId) {
506
+ return ROOM_VERSION_12_CREATOR;
507
+ }
508
+ if ((_c = createRoomStateEvent.content.additional_creators) === null || _c === void 0 ? void 0 : _c.includes(userId)) {
509
+ // If the user is an additional creator of the room, we return the special ROOM_VERSION_12_CREATOR value.
510
+ return ROOM_VERSION_12_CREATOR;
511
+ }
512
+ }
513
+ // If there is no power level state event, we assume the user has no power unless they are the room creator in which case they get PL 100.
514
+ if (!powerLevelStateEvent) {
515
+ if (['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'].includes((_e = (_d = createRoomStateEvent === null || createRoomStateEvent === void 0 ? void 0 : createRoomStateEvent.content) === null || _d === void 0 ? void 0 : _d.room_version) !== null && _e !== void 0 ? _e : '1')) {
516
+ // Room version 1-10 does not have a room version, so we assume the creator has power level 100.
517
+ return ((_f = createRoomStateEvent === null || createRoomStateEvent === void 0 ? void 0 : createRoomStateEvent.content) === null || _f === void 0 ? void 0 : _f.creator) === userId ? 100 : 0;
518
+ }
519
+ else {
520
+ // For room versions 11 and above, we assume the sender has power level 100.
521
+ return (createRoomStateEvent === null || createRoomStateEvent === void 0 ? void 0 : createRoomStateEvent.sender) === userId ? 100 : 0;
522
+ }
523
+ }
524
+ if (powerLevelStateEvent.users && userId in powerLevelStateEvent.users) {
525
+ // If the user is explicitly listed in the users map, return their power level.
526
+ return powerLevelStateEvent.users[userId];
527
+ }
528
+ else if (powerLevelStateEvent.users_default !== undefined) {
529
+ // If the user is not explicitly listed, return the default user power level.
530
+ return powerLevelStateEvent.users_default;
531
+ }
532
+ else {
533
+ // If no users or default is set, return 0.
534
+ return 0;
535
+ }
440
536
  }
441
537
  /**
442
538
  * Calculate the power level that a user needs send a specific room event.
@@ -448,19 +544,26 @@ function calculateUserPowerLevel(powerLevelStateEvent, userId) {
448
544
  function calculateRoomEventPowerLevel(powerLevelStateEvent, eventType) {
449
545
  var _a, _b, _c;
450
546
  // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
451
- 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);
547
+ return ((_c = (_b = (_a = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent.events) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent.events_default) !== null && _c !== void 0 ? _c : 0);
452
548
  }
453
549
  /**
454
550
  * Calculate the power level that a user needs send a specific state event.
455
551
  *
456
552
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
553
+ * @param createRoomStateEvent - the `m.room.create` event
457
554
  * @param eventType - the type of state event
458
555
  * @returns the power level that is needed
459
556
  */
460
- function calculateStateEventPowerLevel(powerLevelStateEvent, eventType) {
461
- var _a, _b, _c;
557
+ function calculateStateEventPowerLevel(powerLevelStateEvent, createRoomStateEvent, eventType) {
558
+ var _a, _b, _c, _d, _e;
559
+ // In room version 12 (and the beta org.matrix.hydra.11 version) we need 150 for m.room.tombstone events and it cant be changed by the user.
560
+ if ((((_a = createRoomStateEvent === null || createRoomStateEvent === void 0 ? void 0 : createRoomStateEvent.content) === null || _a === void 0 ? void 0 : _a.room_version) === '12' ||
561
+ ((_b = createRoomStateEvent === null || createRoomStateEvent === void 0 ? void 0 : createRoomStateEvent.content) === null || _b === void 0 ? void 0 : _b.room_version) === 'org.matrix.hydra.11') &&
562
+ eventType === 'm.room.tombstone') {
563
+ return 150;
564
+ }
462
565
  // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
463
- 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);
566
+ return ((_e = (_d = (_c = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent.events) === null || _c === void 0 ? void 0 : _c[eventType]) !== null && _d !== void 0 ? _d : powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent.state_default) !== null && _e !== void 0 ? _e : 50);
464
567
  }
465
568
  /**
466
569
  * Calculate the power level that a user needs to perform an action.
@@ -1907,4 +2010,4 @@ var WidgetApiImpl = /** @class */ (function () {
1907
2010
  return WidgetApiImpl;
1908
2011
  }());
1909
2012
 
1910
- export { ROOM_EVENT_REDACTION, STATE_EVENT_POWER_LEVELS, STATE_EVENT_ROOM_MEMBER, WIDGET_CAPABILITY_NAVIGATE, WidgetApiImpl, WidgetParameter, calculateUserPowerLevel, compareOriginServerTS, extractRawWidgetParameters, extractWidgetApiParameters, extractWidgetParameters, generateRoomTimelineCapabilities, generateWidgetRegistrationUrl, getContent, getOriginalEventId, getRoomMemberDisplayName, hasActionPower, hasRoomEventPower, hasStateEventPower, hasWidgetParameters, isRoomEvent, isStateEvent, isValidEventWithRelatesTo, isValidPowerLevelStateEvent, isValidRedactionEvent, isValidRoomEvent, isValidRoomMemberStateEvent, isValidStateEvent as isValidStateEVent, isValidToDeviceMessageEvent, makeEventFromSendStateEventResult, navigateToRoom, observeRedactionEvents, parseWidgetId, redactEvent, repairWidgetRegistration, sendStateEventWithEventResult };
2013
+ export { ROOM_EVENT_REDACTION, STATE_EVENT_CREATE, STATE_EVENT_POWER_LEVELS, STATE_EVENT_ROOM_MEMBER, WIDGET_CAPABILITY_NAVIGATE, WidgetApiImpl, WidgetParameter, calculateUserPowerLevel, compareOriginServerTS, extractRawWidgetParameters, extractWidgetApiParameters, extractWidgetParameters, generateRoomTimelineCapabilities, generateWidgetRegistrationUrl, getContent, getOriginalEventId, getRoomMemberDisplayName, hasActionPower, hasRoomEventPower, hasStateEventPower, hasWidgetParameters, isRoomEvent, isStateEvent, isValidCreateEventSchema, isValidEventWithRelatesTo, isValidPowerLevelStateEvent, isValidRedactionEvent, isValidRoomEvent, isValidRoomMemberStateEvent, isValidStateEvent as isValidStateEVent, isValidToDeviceMessageEvent, makeEventFromSendStateEventResult, navigateToRoom, observeRedactionEvents, parseWidgetId, redactEvent, repairWidgetRegistration, sendStateEventWithEventResult };
package/build/index.d.ts CHANGED
@@ -26,11 +26,16 @@ import { WidgetEventCapability } from 'matrix-widget-api';
26
26
  /**
27
27
  * Calculate the power level of the user based on a `m.room.power_levels` event.
28
28
  *
29
+ * Note that we return the @see UserPowerLevelType type instead of a number as Room Version 12
30
+ * gives a Room creator (and additionalCreators) always the highest power level regardless
31
+ * of the highest next Powerlevel number.
32
+ *
29
33
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event.
34
+ * @param createRoomStateEvent - the `m.room.create` event for the room.
30
35
  * @param userId - the ID of the user.
31
36
  * @returns the power level of the user.
32
37
  */
33
- export declare function calculateUserPowerLevel(powerLevelStateEvent: PowerLevelsStateEvent, userId?: string): number;
38
+ export declare function calculateUserPowerLevel(powerLevelStateEvent: PowerLevelsStateEvent | undefined, createRoomStateEvent: StateEvent<StateEventCreateContent> | undefined, userId: string): UserPowerLevelType;
34
39
 
35
40
  /**
36
41
  * Compares two room events by their origin server timestamp.
@@ -135,31 +140,34 @@ export declare function getRoomMemberDisplayName(member: StateEvent<RoomMemberSt
135
140
  * * redact: Redact a message from another user
136
141
  *
137
142
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
143
+ * @param createRoomStateEvent - the `m.room.create` event for the room
138
144
  * @param userId - the id of the user
139
145
  * @param action - the action
140
146
  * @returns if true, the user has the power
141
147
  */
142
- export declare function hasActionPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, userId: string | undefined, action: PowerLevelsActions): boolean;
148
+ export declare function hasActionPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, createRoomStateEvent: StateEvent<StateEventCreateContent> | undefined, userId: string | undefined, action: PowerLevelsActions): boolean;
143
149
 
144
150
  /**
145
151
  * Check if a user has the power to send a specific room event.
146
152
  *
147
153
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
154
+ * @param createRoomStateEvent - the `m.room.create` event for the room
148
155
  * @param userId - the id of the user
149
156
  * @param eventType - the type of room event
150
157
  * @returns if true, the user has the power
151
158
  */
152
- export declare function hasRoomEventPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, userId: string | undefined, eventType: string): boolean;
159
+ export declare function hasRoomEventPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, createRoomStateEvent: StateEvent<StateEventCreateContent> | undefined, userId: string | undefined, eventType: string): boolean;
153
160
 
154
161
  /**
155
162
  * Check if a user has the power to send a specific state event.
156
163
  *
157
164
  * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
165
+ * @param createRoomStateEvent - the `m.room.create` event for the room
158
166
  * @param userId - the id of the user
159
167
  * @param eventType - the type of state event
160
168
  * @returns if true, the user has the power
161
169
  */
162
- export declare function hasStateEventPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, userId: string | undefined, eventType: string): boolean;
170
+ export declare function hasStateEventPower(powerLevelStateEvent: PowerLevelsStateEvent | undefined, createRoomStateEvent: StateEvent<StateEventCreateContent> | undefined, userId: string | undefined, eventType: string): boolean;
163
171
 
164
172
  /**
165
173
  * Checks whether the necessary widget parameters were provided to the widget.
@@ -185,6 +193,14 @@ export declare function isRoomEvent(event: RoomEvent | StateEvent): event is Roo
185
193
  */
186
194
  export declare function isStateEvent(event: RoomEvent | StateEvent): event is StateEvent;
187
195
 
196
+ /**
197
+ * Validates that `event` is has a valid structure for a
198
+ * {@link StateEventCreateContent}.
199
+ * @param event - The event to validate.
200
+ * @returns True, if the event is valid.
201
+ */
202
+ export declare function isValidCreateEventSchema(event: StateEvent<unknown> | undefined): event is StateEvent<StateEventCreateContent>;
203
+
188
204
  /**
189
205
  * Validates that `event` has a valid structure for a
190
206
  * {@link EventWithRelatesTo}.
@@ -380,6 +396,12 @@ export declare function repairWidgetRegistration(widgetApi: WidgetApi, registrat
380
396
  */
381
397
  export declare const ROOM_EVENT_REDACTION = "m.room.redaction";
382
398
 
399
+ /**
400
+ * Room version 12 requires us to have something larger than Max integer for room creators.
401
+ * This is a workaround to allow the room creator to always have the highest power level.
402
+ */
403
+ export declare const ROOM_VERSION_12_CREATOR = "ROOM_VERSION_12_CREATOR";
404
+
383
405
  /**
384
406
  * Generic type for room events.
385
407
  */
@@ -421,7 +443,12 @@ export declare type RoomMemberStateEventContent = {
421
443
  export declare function sendStateEventWithEventResult<T>(widgetApi: WidgetApi, type: string, stateKey: string, content: T): Promise<StateEvent<T>>;
422
444
 
423
445
  /**
424
- * The name of the power levels state event.
446
+ * The types of type of the create event.
447
+ */
448
+ export declare const STATE_EVENT_CREATE = "m.room.create";
449
+
450
+ /**
451
+ * The type of the power levels state event.
425
452
  */
426
453
  export declare const STATE_EVENT_POWER_LEVELS = "m.room.power_levels";
427
454
 
@@ -438,6 +465,12 @@ export declare type StateEvent<T = unknown> = Omit<IRoomEvent, 'content' | 'unsi
438
465
  content: T;
439
466
  };
440
467
 
468
+ export declare type StateEventCreateContent = {
469
+ room_version?: string;
470
+ creator?: string;
471
+ additional_creators?: string[];
472
+ };
473
+
441
474
  /**
442
475
  * Generic type for to device message events.
443
476
  */
@@ -461,6 +494,8 @@ export declare type TurnServer = {
461
494
  credential: string;
462
495
  };
463
496
 
497
+ export declare type UserPowerLevelType = number | typeof ROOM_VERSION_12_CREATOR;
498
+
464
499
  /**
465
500
  * The capability that needs to be requested in order to navigate to another room.
466
501
  */