@devanachat/sdk 0.0.0-stage → 0.7.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.
Files changed (196) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/LICENSE +21 -0
  3. package/README.md +418 -2
  4. package/build/index.cjs.js +3656 -0
  5. package/build/index.cjs.js.map +1 -0
  6. package/build/index.mjs +3613 -0
  7. package/build/index.mjs.map +1 -0
  8. package/build/index.umd.js +2 -0
  9. package/build/index.umd.js.map +1 -0
  10. package/build/types/AbstractChatClient.d.ts +184 -0
  11. package/build/types/AbstractRestClient.d.ts +21 -0
  12. package/build/types/EventTarget.d.ts +32 -0
  13. package/build/types/FilesClient.d.ts +16 -0
  14. package/build/types/IndexedObjectCollection.d.ts +66 -0
  15. package/build/types/Permissions.d.ts +117 -0
  16. package/build/types/WebApiChatClient.d.ts +38 -0
  17. package/build/types/WebSocketChatClient.d.ts +110 -0
  18. package/build/types/index.d.ts +19 -0
  19. package/build/types/protocol/index.d.ts +165 -0
  20. package/build/types/protocol/schemes/BanObject.d.ts +14 -0
  21. package/build/types/protocol/schemes/ChatLocation.d.ts +5 -0
  22. package/build/types/protocol/schemes/Emoticon.d.ts +9 -0
  23. package/build/types/protocol/schemes/Entitlements.d.ts +92 -0
  24. package/build/types/protocol/schemes/Envelope.d.ts +5 -0
  25. package/build/types/protocol/schemes/FollowedTopic.d.ts +10 -0
  26. package/build/types/protocol/schemes/LeaveReason.d.ts +9 -0
  27. package/build/types/protocol/schemes/Message.d.ts +32 -0
  28. package/build/types/protocol/schemes/MessagePoll.d.ts +10 -0
  29. package/build/types/protocol/schemes/PermissionOverwritesTarget.d.ts +5 -0
  30. package/build/types/protocol/schemes/PermissionOverwritesValue.d.ts +4 -0
  31. package/build/types/protocol/schemes/Reaction.d.ts +13 -0
  32. package/build/types/protocol/schemes/Role.d.ts +20 -0
  33. package/build/types/protocol/schemes/Room.d.ts +17 -0
  34. package/build/types/protocol/schemes/RoomHistory.d.ts +5 -0
  35. package/build/types/protocol/schemes/RoomMember.d.ts +11 -0
  36. package/build/types/protocol/schemes/RoomStream.d.ts +5 -0
  37. package/build/types/protocol/schemes/RoomSummary.d.ts +15 -0
  38. package/build/types/protocol/schemes/SessionData.d.ts +10 -0
  39. package/build/types/protocol/schemes/Space.d.ts +19 -0
  40. package/build/types/protocol/schemes/SpaceMember.d.ts +7 -0
  41. package/build/types/protocol/schemes/SpaceSummary.d.ts +8 -0
  42. package/build/types/protocol/schemes/Topic.d.ts +8 -0
  43. package/build/types/protocol/schemes/User.d.ts +23 -0
  44. package/build/types/protocol/schemes/UserData.d.ts +10 -0
  45. package/build/types/protocol/schemes/UserInformation.d.ts +11 -0
  46. package/build/types/protocol/schemes/UserRelationship.d.ts +6 -0
  47. package/build/types/protocol/schemes/UserState.d.ts +6 -0
  48. package/build/types/protocol/schemes/commands/Ack.d.ts +5 -0
  49. package/build/types/protocol/schemes/commands/AssignRole.d.ts +6 -0
  50. package/build/types/protocol/schemes/commands/Ban.d.ts +10 -0
  51. package/build/types/protocol/schemes/commands/CreateAccessTicket.d.ts +13 -0
  52. package/build/types/protocol/schemes/commands/CreateEmoticon.d.ts +5 -0
  53. package/build/types/protocol/schemes/commands/CreateMessage.d.ts +11 -0
  54. package/build/types/protocol/schemes/commands/CreateOwner.d.ts +5 -0
  55. package/build/types/protocol/schemes/commands/CreateRelationship.d.ts +5 -0
  56. package/build/types/protocol/schemes/commands/CreateRole.d.ts +6 -0
  57. package/build/types/protocol/schemes/commands/CreateRoom.d.ts +9 -0
  58. package/build/types/protocol/schemes/commands/CreateSpace.d.ts +6 -0
  59. package/build/types/protocol/schemes/commands/CreateTopic.d.ts +11 -0
  60. package/build/types/protocol/schemes/commands/DeassignRole.d.ts +6 -0
  61. package/build/types/protocol/schemes/commands/DeleteEmoticon.d.ts +3 -0
  62. package/build/types/protocol/schemes/commands/DeleteOwner.d.ts +5 -0
  63. package/build/types/protocol/schemes/commands/DeleteRelationship.d.ts +5 -0
  64. package/build/types/protocol/schemes/commands/DeleteRole.d.ts +4 -0
  65. package/build/types/protocol/schemes/commands/DeleteRoom.d.ts +3 -0
  66. package/build/types/protocol/schemes/commands/DeleteSpace.d.ts +3 -0
  67. package/build/types/protocol/schemes/commands/DeleteTopic.d.ts +4 -0
  68. package/build/types/protocol/schemes/commands/FollowTopic.d.ts +4 -0
  69. package/build/types/protocol/schemes/commands/GetBans.d.ts +6 -0
  70. package/build/types/protocol/schemes/commands/GetClientData.d.ts +2 -0
  71. package/build/types/protocol/schemes/commands/GetComputedPermissions.d.ts +10 -0
  72. package/build/types/protocol/schemes/commands/GetDiscoverableSpaces.d.ts +2 -0
  73. package/build/types/protocol/schemes/commands/GetEmoticons.d.ts +3 -0
  74. package/build/types/protocol/schemes/commands/GetEntitlements.d.ts +8 -0
  75. package/build/types/protocol/schemes/commands/GetFollowedTopics.d.ts +4 -0
  76. package/build/types/protocol/schemes/commands/GetInvited.d.ts +3 -0
  77. package/build/types/protocol/schemes/commands/GetMessages.d.ts +13 -0
  78. package/build/types/protocol/schemes/commands/GetOwners.d.ts +4 -0
  79. package/build/types/protocol/schemes/commands/GetPermissionOverwriteTargets.d.ts +4 -0
  80. package/build/types/protocol/schemes/commands/GetPermissionOverwrites.d.ts +6 -0
  81. package/build/types/protocol/schemes/commands/GetReactionDetails.d.ts +8 -0
  82. package/build/types/protocol/schemes/commands/GetRelationships.d.ts +2 -0
  83. package/build/types/protocol/schemes/commands/GetRoomMembers.d.ts +3 -0
  84. package/build/types/protocol/schemes/commands/GetRoomSummary.d.ts +4 -0
  85. package/build/types/protocol/schemes/commands/GetSession.d.ts +2 -0
  86. package/build/types/protocol/schemes/commands/GetSessionData.d.ts +2 -0
  87. package/build/types/protocol/schemes/commands/GetSpaceMembers.d.ts +3 -0
  88. package/build/types/protocol/schemes/commands/GetSpaceRooms.d.ts +3 -0
  89. package/build/types/protocol/schemes/commands/GetSpaceSummary.d.ts +3 -0
  90. package/build/types/protocol/schemes/commands/GetTopics.d.ts +4 -0
  91. package/build/types/protocol/schemes/commands/GetUserData.d.ts +2 -0
  92. package/build/types/protocol/schemes/commands/GetUserInfo.d.ts +3 -0
  93. package/build/types/protocol/schemes/commands/Invite.d.ts +5 -0
  94. package/build/types/protocol/schemes/commands/JoinRoom.d.ts +13 -0
  95. package/build/types/protocol/schemes/commands/JoinSpace.d.ts +3 -0
  96. package/build/types/protocol/schemes/commands/Kick.d.ts +7 -0
  97. package/build/types/protocol/schemes/commands/LeaveRoom.d.ts +3 -0
  98. package/build/types/protocol/schemes/commands/LeaveSpace.d.ts +3 -0
  99. package/build/types/protocol/schemes/commands/Ping.d.ts +2 -0
  100. package/build/types/protocol/schemes/commands/React.d.ts +6 -0
  101. package/build/types/protocol/schemes/commands/RedactMessages.d.ts +3 -0
  102. package/build/types/protocol/schemes/commands/ReportAbuse.d.ts +9 -0
  103. package/build/types/protocol/schemes/commands/SearchMessages.d.ts +18 -0
  104. package/build/types/protocol/schemes/commands/SetClientData.d.ts +1 -0
  105. package/build/types/protocol/schemes/commands/SetPermissionOverwrites.d.ts +8 -0
  106. package/build/types/protocol/schemes/commands/SetSessionData.d.ts +17 -0
  107. package/build/types/protocol/schemes/commands/SetUserData.d.ts +6 -0
  108. package/build/types/protocol/schemes/commands/Unban.d.ts +3 -0
  109. package/build/types/protocol/schemes/commands/UnfollowTopic.d.ts +4 -0
  110. package/build/types/protocol/schemes/commands/Uninvite.d.ts +5 -0
  111. package/build/types/protocol/schemes/commands/Unreact.d.ts +6 -0
  112. package/build/types/protocol/schemes/commands/UpdateFollowedTopic.d.ts +6 -0
  113. package/build/types/protocol/schemes/commands/UpdateRole.d.ts +8 -0
  114. package/build/types/protocol/schemes/commands/UpdateRoom.d.ts +10 -0
  115. package/build/types/protocol/schemes/commands/UpdateRoomMember.d.ts +8 -0
  116. package/build/types/protocol/schemes/commands/UpdateSpace.d.ts +12 -0
  117. package/build/types/protocol/schemes/commands/UpdateSpaceMember.d.ts +6 -0
  118. package/build/types/protocol/schemes/commands/UpdateTopic.d.ts +5 -0
  119. package/build/types/protocol/schemes/events/AccessTicket.d.ts +14 -0
  120. package/build/types/protocol/schemes/events/Bans.d.ts +6 -0
  121. package/build/types/protocol/schemes/events/Bye.d.ts +4 -0
  122. package/build/types/protocol/schemes/events/ClientData.d.ts +1 -0
  123. package/build/types/protocol/schemes/events/ComputedPermissions.d.ts +9 -0
  124. package/build/types/protocol/schemes/events/DiscoverableSpaces.d.ts +4 -0
  125. package/build/types/protocol/schemes/events/EmoticonDeleted.d.ts +4 -0
  126. package/build/types/protocol/schemes/events/Emoticons.d.ts +6 -0
  127. package/build/types/protocol/schemes/events/EntitlementUsage.d.ts +11 -0
  128. package/build/types/protocol/schemes/events/Entitlements.d.ts +12 -0
  129. package/build/types/protocol/schemes/events/Error.d.ts +14 -0
  130. package/build/types/protocol/schemes/events/FollowedTopicUpdated.d.ts +4 -0
  131. package/build/types/protocol/schemes/events/FollowedTopics.d.ts +6 -0
  132. package/build/types/protocol/schemes/events/FoundMessages.d.ts +16 -0
  133. package/build/types/protocol/schemes/events/Invited.d.ts +10 -0
  134. package/build/types/protocol/schemes/events/Messages.d.ts +9 -0
  135. package/build/types/protocol/schemes/events/MessagesRedacted.d.ts +5 -0
  136. package/build/types/protocol/schemes/events/NewEmoticon.d.ts +4 -0
  137. package/build/types/protocol/schemes/events/NewMessage.d.ts +4 -0
  138. package/build/types/protocol/schemes/events/NewRelationship.d.ts +4 -0
  139. package/build/types/protocol/schemes/events/NewRole.d.ts +5 -0
  140. package/build/types/protocol/schemes/events/NewRoom.d.ts +5 -0
  141. package/build/types/protocol/schemes/events/NewTopic.d.ts +5 -0
  142. package/build/types/protocol/schemes/events/Ok.d.ts +2 -0
  143. package/build/types/protocol/schemes/events/Owners.d.ts +8 -0
  144. package/build/types/protocol/schemes/events/PermissionOverwriteTargets.d.ts +10 -0
  145. package/build/types/protocol/schemes/events/PermissionOverwrites.d.ts +8 -0
  146. package/build/types/protocol/schemes/events/PermissionOverwritesUpdated.d.ts +8 -0
  147. package/build/types/protocol/schemes/events/Pong.d.ts +2 -0
  148. package/build/types/protocol/schemes/events/Reacted.d.ts +9 -0
  149. package/build/types/protocol/schemes/events/ReactionDetails.d.ts +11 -0
  150. package/build/types/protocol/schemes/events/ReactionUpdated.d.ts +8 -0
  151. package/build/types/protocol/schemes/events/RelationshipDeleted.d.ts +4 -0
  152. package/build/types/protocol/schemes/events/Relationships.d.ts +4 -0
  153. package/build/types/protocol/schemes/events/RoleDeleted.d.ts +4 -0
  154. package/build/types/protocol/schemes/events/RoleUpdated.d.ts +5 -0
  155. package/build/types/protocol/schemes/events/RoomDeleted.d.ts +3 -0
  156. package/build/types/protocol/schemes/events/RoomJoined.d.ts +4 -0
  157. package/build/types/protocol/schemes/events/RoomLeft.d.ts +5 -0
  158. package/build/types/protocol/schemes/events/RoomMemberLeft.d.ts +4 -0
  159. package/build/types/protocol/schemes/events/RoomMemberUpdated.d.ts +6 -0
  160. package/build/types/protocol/schemes/events/RoomMembers.d.ts +5 -0
  161. package/build/types/protocol/schemes/events/RoomMembersJoined.d.ts +9 -0
  162. package/build/types/protocol/schemes/events/RoomSummary.d.ts +4 -0
  163. package/build/types/protocol/schemes/events/RoomSummaryUpdated.d.ts +8 -0
  164. package/build/types/protocol/schemes/events/RoomUpdated.d.ts +4 -0
  165. package/build/types/protocol/schemes/events/Session.d.ts +9 -0
  166. package/build/types/protocol/schemes/events/SpaceDeleted.d.ts +3 -0
  167. package/build/types/protocol/schemes/events/SpaceJoined.d.ts +4 -0
  168. package/build/types/protocol/schemes/events/SpaceLeft.d.ts +5 -0
  169. package/build/types/protocol/schemes/events/SpaceMemberJoined.d.ts +5 -0
  170. package/build/types/protocol/schemes/events/SpaceMemberLeft.d.ts +4 -0
  171. package/build/types/protocol/schemes/events/SpaceMemberUpdated.d.ts +6 -0
  172. package/build/types/protocol/schemes/events/SpaceMembers.d.ts +5 -0
  173. package/build/types/protocol/schemes/events/SpaceRooms.d.ts +5 -0
  174. package/build/types/protocol/schemes/events/SpaceSummary.d.ts +4 -0
  175. package/build/types/protocol/schemes/events/SpaceUpdated.d.ts +4 -0
  176. package/build/types/protocol/schemes/events/TopicDeleted.d.ts +4 -0
  177. package/build/types/protocol/schemes/events/TopicFollowed.d.ts +4 -0
  178. package/build/types/protocol/schemes/events/TopicUnfollowed.d.ts +4 -0
  179. package/build/types/protocol/schemes/events/TopicUpdated.d.ts +6 -0
  180. package/build/types/protocol/schemes/events/Topics.d.ts +6 -0
  181. package/build/types/protocol/schemes/events/UserInfo.d.ts +4 -0
  182. package/build/types/protocol/schemes/events/UserUpdated.d.ts +4 -0
  183. package/build/types/state-tracker/AsyncUtils.d.ts +15 -0
  184. package/build/types/state-tracker/ChatStateTracker.d.ts +41 -0
  185. package/build/types/state-tracker/EmoticonsManager.d.ts +15 -0
  186. package/build/types/state-tracker/FollowedTopicsManager.d.ts +85 -0
  187. package/build/types/state-tracker/MessagesManager.d.ts +27 -0
  188. package/build/types/state-tracker/PermissionsManager.d.ts +51 -0
  189. package/build/types/state-tracker/RelationshipsManager.d.ts +15 -0
  190. package/build/types/state-tracker/RoomMessagesHistory.d.ts +72 -0
  191. package/build/types/state-tracker/RoomsManager.d.ts +72 -0
  192. package/build/types/state-tracker/SpacesManager.d.ts +63 -0
  193. package/build/types/state-tracker/TopicHistoryWindow.d.ts +191 -0
  194. package/build/types/state-tracker/UsersManager.d.ts +23 -0
  195. package/build/types/state-tracker/functions.d.ts +6 -0
  196. package/package.json +67 -4
@@ -0,0 +1,3613 @@
1
+ /******/ // The require scope
2
+ /******/ var __webpack_require__ = {};
3
+ /******/
4
+ /************************************************************************/
5
+ /******/ /* webpack/runtime/define property getters */
6
+ /******/ (() => {
7
+ /******/ // define getter functions for harmony exports
8
+ /******/ __webpack_require__.d = (exports, definition) => {
9
+ /******/ for(var key in definition) {
10
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
11
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
12
+ /******/ }
13
+ /******/ }
14
+ /******/ };
15
+ /******/ })();
16
+ /******/
17
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
18
+ /******/ (() => {
19
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
20
+ /******/ })();
21
+ /******/
22
+ /************************************************************************/
23
+ var __webpack_exports__ = {};
24
+
25
+ ;// ./src/EventTarget.ts
26
+ class EventTarget {
27
+ events = new Map();
28
+ onceEvents = new Map();
29
+ on(eventName, handler) {
30
+ this.addHandler(this.events, eventName, handler);
31
+ return this;
32
+ }
33
+ once(eventName, handler) {
34
+ this.addHandler(this.onceEvents, eventName, handler);
35
+ return this;
36
+ }
37
+ off(eventName, handler) {
38
+ this.removeHandler(this.events, eventName, handler);
39
+ this.removeHandler(this.onceEvents, eventName, handler);
40
+ return this;
41
+ }
42
+ emit(eventName, event) {
43
+ this.callHandlers(this.events, eventName, event);
44
+ this.callHandlers(this.onceEvents, eventName, event);
45
+ this.onceEvents.delete(eventName);
46
+ return this;
47
+ }
48
+ addHandler(map, eventName, handler) {
49
+ const handlers = map.get(eventName) ?? [];
50
+ handlers.push(handler);
51
+ map.set(eventName, handlers);
52
+ }
53
+ removeHandler(map, eventName, handler) {
54
+ const handlers = map.get(eventName);
55
+ const index = handlers?.indexOf(handler) ?? -1;
56
+ if (index >= 0) {
57
+ handlers.splice(index, 1);
58
+ }
59
+ }
60
+ callHandlers(map, eventName, event) {
61
+ map.get(eventName)?.forEach(callback => callback(event));
62
+ }
63
+ }
64
+ ;// ./src/AbstractChatClient.ts
65
+
66
+ class AbstractChatClient extends EventTarget {
67
+ awaitingResponse = new Map();
68
+ sentCounter = 0;
69
+ createEnvelope(type, data) {
70
+ return {
71
+ type,
72
+ data,
73
+ ref: (++this.sentCounter).toString()
74
+ };
75
+ }
76
+ createPromiseFromCommandEnvelope(envelope) {
77
+ return new Promise((...args) => this.awaitingResponse.set(envelope.ref, args));
78
+ }
79
+ handleIncomingEnvelope(envelope) {
80
+ if (!this.awaitingResponse.has(envelope.ref)) {
81
+ return;
82
+ }
83
+ const isError = envelope.type === 'Error';
84
+ this.awaitingResponse.get(envelope.ref)[0]({
85
+ data: isError ? null : envelope.data,
86
+ error: isError ? envelope.data : null
87
+ });
88
+ this.awaitingResponse.delete(envelope.ref);
89
+ }
90
+ handleEnvelopeSendError(envelope, error) {
91
+ if (!this.awaitingResponse.has(envelope.ref)) {
92
+ return;
93
+ }
94
+ this.awaitingResponse.get(envelope.ref)[1](error);
95
+ this.awaitingResponse.delete(envelope.ref);
96
+ }
97
+
98
+ /**
99
+ * Reject every command that is still waiting for a response.
100
+ * Call this whenever the transport can no longer deliver an answer (the
101
+ * connection dropped).
102
+ */
103
+ failAwaitingResponses(error) {
104
+ if (!this.awaitingResponse.size) {
105
+ return;
106
+ }
107
+ const pending = Array.from(this.awaitingResponse.values());
108
+ this.awaitingResponse.clear();
109
+ for (const [, reject] of pending) {
110
+ reject(error);
111
+ }
112
+ }
113
+ }
114
+
115
+ /**
116
+ * The answer to a command: either `data` or the server `error`, never both.
117
+ * Check `error` first and TypeScript knows `data` is there.
118
+ */
119
+
120
+ /**
121
+ * Map of incoming events.
122
+ */
123
+
124
+ /**
125
+ * Map of commands and their corresponding events.
126
+ */
127
+ ;// ./src/IndexedObjectCollection.ts
128
+
129
+ class IndexedCollection {
130
+ _items = new Map();
131
+ constructor(items = []) {
132
+ this.set(...items);
133
+ }
134
+ get items() {
135
+ return this._items;
136
+ }
137
+ get length() {
138
+ return this._items.size;
139
+ }
140
+ set(...items) {
141
+ for (const item of items) {
142
+ this._items.set(item[0], item[1]);
143
+ }
144
+ }
145
+ get(id) {
146
+ return this.items.get(id);
147
+ }
148
+ has(id) {
149
+ return this.items.has(id);
150
+ }
151
+ delete(...ids) {
152
+ for (const id of ids) {
153
+ this.items.delete(id);
154
+ }
155
+ }
156
+ deleteAll() {
157
+ this.items.clear();
158
+ }
159
+ findBy(field, valueToFind, limit = Infinity) {
160
+ const result = new IndexedCollection();
161
+ for (const [key, value] of this.items.entries()) {
162
+ if (result.length >= limit) {
163
+ break;
164
+ }
165
+ if (value[field] === valueToFind) {
166
+ result.set([key, value]);
167
+ }
168
+ }
169
+ return result;
170
+ }
171
+ createMirror() {
172
+ const copy = new IndexedCollection();
173
+ copy._items = this._items;
174
+ return copy;
175
+ }
176
+ }
177
+ class IndexedObjectCollection {
178
+ _items;
179
+ constructor(id, items = []) {
180
+ this.id = id;
181
+ this._items = new IndexedCollection();
182
+ this.set(...items);
183
+ }
184
+ get items() {
185
+ return Array.from(this._items.items.values());
186
+ }
187
+ get length() {
188
+ return this._items.length;
189
+ }
190
+ set(...items) {
191
+ this._items.set(...items.map(item => [this.getId(item), item]));
192
+ }
193
+ get(id) {
194
+ return this._items.get(id);
195
+ }
196
+ getAt(index) {
197
+ if (index < 0 || index >= this.length) {
198
+ return undefined;
199
+ }
200
+ let current = 0;
201
+ for (const item of this._items.items.values()) {
202
+ if (current++ === index) {
203
+ return item;
204
+ }
205
+ }
206
+ return undefined;
207
+ }
208
+ has(id) {
209
+ return this._items.has(id);
210
+ }
211
+ delete(...ids) {
212
+ this._items.delete(...ids);
213
+ }
214
+ deleteAll() {
215
+ this._items.deleteAll();
216
+ }
217
+ findBy(field, valueToFind, limit = null) {
218
+ const result = new IndexedObjectCollection(this.id);
219
+ for (const value of this.items) {
220
+ if (limit && result.length === limit) {
221
+ break;
222
+ }
223
+ if (value[field] === valueToFind) {
224
+ result.set(value);
225
+ }
226
+ }
227
+ return result;
228
+ }
229
+ createMirror() {
230
+ const copy = new IndexedObjectCollection(this.id);
231
+ copy._items = this._items;
232
+ return copy;
233
+ }
234
+ getId(item) {
235
+ return typeof this.id === 'function' ? this.id(item) : item[this.id];
236
+ }
237
+ }
238
+ class ObservableIndexedCollection extends IndexedCollection {
239
+ eventTarget;
240
+ constructor(items = []) {
241
+ super();
242
+ this.eventTarget = new EventTarget();
243
+ this.set(...items);
244
+ }
245
+ set(...items) {
246
+ if (items.length) {
247
+ super.set(...items);
248
+ this.eventTarget.emit('change', {
249
+ setItems: items.map(item => item[0])
250
+ });
251
+ }
252
+ }
253
+ delete(...ids) {
254
+ if (ids.length) {
255
+ super.delete(...ids);
256
+ this.eventTarget.emit('change', {
257
+ deletedItems: ids
258
+ });
259
+ }
260
+ }
261
+ deleteAll() {
262
+ if (this.length) {
263
+ const ids = Array.from(this._items.keys());
264
+ super.deleteAll();
265
+ this.eventTarget.emit('change', {
266
+ deletedItems: Array.from(ids)
267
+ });
268
+ }
269
+ }
270
+ createMirror() {
271
+ const copy = new ObservableIndexedCollection();
272
+ copy.eventTarget = this.eventTarget;
273
+ copy._items = this._items;
274
+ return copy;
275
+ }
276
+ on(eventName, handler) {
277
+ this.eventTarget.on(eventName, handler);
278
+ return this;
279
+ }
280
+ once(eventName, handler) {
281
+ this.eventTarget.once(eventName, handler);
282
+ return this;
283
+ }
284
+ off(eventName, handler) {
285
+ this.eventTarget.off(eventName, handler);
286
+ return this;
287
+ }
288
+ }
289
+ class ObservableIndexedObjectCollection extends IndexedObjectCollection {
290
+ eventTarget;
291
+ constructor(id, items = []) {
292
+ super(id);
293
+ this.eventTarget = new EventTarget();
294
+ this.set(...items);
295
+ }
296
+ set(...items) {
297
+ if (items.length) {
298
+ super.set(...items);
299
+ this.eventTarget.emit('change', {
300
+ setItems: items.map(item => this.getId(item))
301
+ });
302
+ }
303
+ }
304
+ delete(...ids) {
305
+ if (ids.length) {
306
+ super.delete(...ids);
307
+ this.eventTarget.emit('change', {
308
+ deletedItems: ids
309
+ });
310
+ }
311
+ }
312
+ deleteAll() {
313
+ if (this.length) {
314
+ const ids = this.items.map(item => this.getId(item));
315
+ super.deleteAll();
316
+ this.eventTarget.emit('change', {
317
+ deletedItems: ids
318
+ });
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Bring the collection to exactly match the provided items: upsert every
324
+ * provided item and remove any existing item whose id is not present in the
325
+ * provided set. Emits at most a single `change` event describing both the
326
+ * set and the deleted ids, so bound consumers can update in place without
327
+ * ever observing an intermediate empty state (unlike deleteAll + set).
328
+ */
329
+ reconcile(...items) {
330
+ const incomingIds = new Set(items.map(item => this.getId(item)));
331
+ const deletedItems = [];
332
+ for (const existing of this.items) {
333
+ const id = this.getId(existing);
334
+ if (!incomingIds.has(id)) {
335
+ deletedItems.push(id);
336
+ }
337
+ }
338
+ if (!items.length && !deletedItems.length) {
339
+ return;
340
+ }
341
+ this._items.delete(...deletedItems);
342
+ super.set(...items);
343
+ this.eventTarget.emit('change', {
344
+ setItems: items.map(item => this.getId(item)),
345
+ deletedItems
346
+ });
347
+ }
348
+ createMirror() {
349
+ const copy = new ObservableIndexedObjectCollection(this.id);
350
+ copy.eventTarget = this.eventTarget;
351
+ copy._items = this._items;
352
+ return copy;
353
+ }
354
+ on(eventName, handler) {
355
+ this.eventTarget.on(eventName, handler);
356
+ return this;
357
+ }
358
+ once(eventName, handler) {
359
+ this.eventTarget.once(eventName, handler);
360
+ return this;
361
+ }
362
+ off(eventName, handler) {
363
+ this.eventTarget.off(eventName, handler);
364
+ return this;
365
+ }
366
+ }
367
+ ;// ./src/state-tracker/AsyncUtils.ts
368
+
369
+ class DeferredTask {
370
+ promise;
371
+ resolve;
372
+ constructor() {
373
+ this.promise = new Promise(resolve => this.resolve = resolve);
374
+ }
375
+ }
376
+ class PromiseRegistry {
377
+ promises = new IndexedCollection();
378
+ register(promise, key) {
379
+ this.promises.set([key, promise]);
380
+ promise.catch(() => {
381
+ if (this.promises.get(key) === promise) {
382
+ this.promises.delete(key);
383
+ }
384
+ });
385
+ }
386
+ registerByFunction(fn, key) {
387
+ this.register(fn(), key);
388
+ }
389
+ get(key) {
390
+ return this.promises.get(key);
391
+ }
392
+ has(key) {
393
+ return this.promises.has(key);
394
+ }
395
+ notExist(key) {
396
+ return !this.has(key);
397
+ }
398
+ forget(...keys) {
399
+ this.promises.delete(...keys);
400
+ }
401
+ forgetAll() {
402
+ this.promises.deleteAll();
403
+ }
404
+ }
405
+ ;// ./src/state-tracker/TopicHistoryWindow.ts
406
+
407
+ let WindowState = /*#__PURE__*/function (WindowState) {
408
+ /**
409
+ * The latest messages (those received live) are available in the history window, history has not been fetched.
410
+ */
411
+ WindowState[WindowState["LIVE"] = 0] = "LIVE";
412
+ /**
413
+ * The latest messages has been fetched and are available in the history window.
414
+ */
415
+ WindowState[WindowState["LATEST"] = 1] = "LATEST";
416
+ /**
417
+ * The historical messages have been fetched and are available in the history window.
418
+ * Latest messages are not available and will not be available.
419
+ */
420
+ WindowState[WindowState["PAST"] = 2] = "PAST";
421
+ /**
422
+ * The oldest messages have been fetched and are available in the history window.
423
+ * Next attempts to fetch previous messages will result with no-op.
424
+ */
425
+ WindowState[WindowState["OLDEST"] = 3] = "OLDEST";
426
+ return WindowState;
427
+ }({});
428
+ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
429
+ /**
430
+ * Current mode od collection window. To change mode, call one of available fetch methods.
431
+ */
432
+ get state() {
433
+ return this.internalState.current;
434
+ }
435
+ internalState = {
436
+ current: WindowState.LIVE,
437
+ ongoing: undefined,
438
+ limit: 1000,
439
+ retainRatio: 1,
440
+ fetchLimit: 50,
441
+ lastFetchCount: 0,
442
+ oldestId: null
443
+ };
444
+
445
+ /**
446
+ * Number of items to fetch per request.
447
+ */
448
+ get fetchLimit() {
449
+ return this.internalState.fetchLimit;
450
+ }
451
+
452
+ /**
453
+ * Sets number of items to fetch per request.
454
+ */
455
+ set fetchLimit(value) {
456
+ this.internalState.fetchLimit = value;
457
+ }
458
+
459
+ /**
460
+ * Maximum number of items stored in window (High Watermark).
461
+ * Null for unlimited.
462
+ */
463
+ get limit() {
464
+ return this.internalState.limit;
465
+ }
466
+
467
+ /**
468
+ * Maximum number of items stored in window (High Watermark).
469
+ * Null for unlimited. Lowering it below the current length drops the oldest items right away.
470
+ */
471
+ set limit(value) {
472
+ this.internalState.limit = value;
473
+ const deletedItems = this.trimHead(value);
474
+ if (deletedItems.length) {
475
+ this.eventTarget.emit('change', {
476
+ deletedItems
477
+ });
478
+ }
479
+ }
480
+
481
+ /**
482
+ * Percentage of limit to keep when trimming.
483
+ */
484
+ get retainRatio() {
485
+ return this.internalState.retainRatio;
486
+ }
487
+
488
+ /**
489
+ * Percentage of limit to keep when trimming.
490
+ */
491
+ set retainRatio(value) {
492
+ this.internalState.retainRatio = value;
493
+ }
494
+ get hasLatest() {
495
+ return [WindowState.LATEST, WindowState.LIVE].includes(this.state);
496
+ }
497
+ get hasOldest() {
498
+ return this.state === WindowState.OLDEST || this.state === WindowState.LATEST && this.length < this.fetchLimit || this.internalState.oldestId !== null && this.has(this.internalState.oldestId);
499
+ }
500
+ async resetToLatest(force = false) {
501
+ if (this.internalState.ongoing || !force && this.internalState.current === WindowState.LATEST) {
502
+ return;
503
+ }
504
+ let result;
505
+ const originalState = this.state;
506
+ this.internalState.ongoing = WindowState.LATEST;
507
+ try {
508
+ result = await this.fetchLatestItems();
509
+ this.internalState.lastFetchCount = result.length;
510
+ } finally {
511
+ this.internalState.ongoing = undefined;
512
+ }
513
+ this._items.deleteAll(); // Directly call deleteAll to prevent event emit.
514
+ this.addItems(result, 'tail');
515
+ this.internalState.current = WindowState.LATEST;
516
+ this.emitChangeWithDiff(true, originalState);
517
+ }
518
+ async fetchPrevious() {
519
+ if (this.internalState.ongoing || this.hasOldest) {
520
+ return;
521
+ }
522
+ let result;
523
+ const originalState = this.state;
524
+ this.internalState.ongoing = WindowState.PAST;
525
+ try {
526
+ result = await this.fetchItemsBefore();
527
+ this.internalState.lastFetchCount = result ? result.length : 0;
528
+ } finally {
529
+ this.internalState.ongoing = undefined;
530
+ }
531
+ if (!result) {
532
+ return this.resetToLatest();
533
+ }
534
+ if (!result.length) {
535
+ const firstItem = this.getAt(0);
536
+ this.internalState.oldestId = firstItem ? this.getId(firstItem) : null;
537
+ await this.refreshFetchedState();
538
+
539
+ // LATEST state has priority over OLDEST
540
+ if (this.internalState.current === WindowState.PAST) {
541
+ this.internalState.current = WindowState.OLDEST;
542
+ }
543
+ this.emitChangeWithDiff(false, originalState);
544
+ return;
545
+ }
546
+ this.addItems(result, 'head');
547
+ await this.refreshFetchedState();
548
+ this.emitChangeWithDiff(true, originalState);
549
+ }
550
+ async fetchNext() {
551
+ if (this.hasLatest) {
552
+ return;
553
+ }
554
+ return this.fetchAfterLast();
555
+ }
556
+
557
+ /**
558
+ * Append the items that follow the last one in the window; an empty window gets the latest items.
559
+ */
560
+ async fetchAfterLast() {
561
+ if (this.internalState.ongoing) {
562
+ return;
563
+ }
564
+ let result;
565
+ const originalState = this.state;
566
+ this.internalState.ongoing = WindowState.PAST;
567
+ try {
568
+ result = await this.fetchItemsAfter();
569
+ this.internalState.lastFetchCount = result ? result.length : 0;
570
+ } finally {
571
+ this.internalState.ongoing = undefined;
572
+ }
573
+ if (!result) {
574
+ await this.resetToLatest(true);
575
+ return;
576
+ }
577
+ if (result.length) {
578
+ this.addItems(result, 'tail');
579
+ await this.refreshFetchedState();
580
+ this.emitChangeWithDiff(true, originalState);
581
+ return;
582
+ }
583
+ }
584
+ async jumpTo(id) {
585
+ if (this.internalState.ongoing || this.state !== WindowState.LIVE && this._items.has(id)) {
586
+ return;
587
+ }
588
+ let result;
589
+ const originalState = this.state;
590
+ this.internalState.ongoing = WindowState.PAST;
591
+ try {
592
+ result = await this.fetchItemsAround(id);
593
+ this.internalState.lastFetchCount = result ? result.length : 0;
594
+ if (result) {
595
+ this._items.deleteAll(); // Directly call deleteAll to prevent event emit.
596
+ this.addItems(result, 'tail');
597
+ await this.refreshFetchedState();
598
+ }
599
+ } finally {
600
+ this.internalState.ongoing = undefined;
601
+ }
602
+ this.emitChangeWithDiff(!!result, originalState);
603
+ }
604
+ async refreshFetchedState() {
605
+ this.internalState.current = (await this.isLatestItemLoaded()) ? WindowState.LATEST : WindowState.PAST;
606
+ }
607
+
608
+ /**
609
+ * Add items without emitting an event, trimming the window from the opposite end using the
610
+ * High/Low Watermark strategy. An item already in the window keeps its position.
611
+ * @return Ids of the items trimmed out.
612
+ */
613
+ addItems(newItems, to, highWatermark = this.limit) {
614
+ const entries = newItems.map(item => [this.getId(item), item]);
615
+ if (to === 'tail') {
616
+ this._items.set(...entries);
617
+ return this.trimHead(this.getLowWatermark(highWatermark));
618
+ }
619
+
620
+ // Prepending has to rebuild the map; a duplicate keeps the already loaded version of the item.
621
+ const loaded = Array.from(this._items.items);
622
+ this._items.deleteAll();
623
+ this._items.set(...entries, ...loaded);
624
+ return this.trimTail(this.getLowWatermark(highWatermark));
625
+ }
626
+ emitChangeWithDiff(itemChanged, originalState) {
627
+ if (itemChanged || originalState !== this.state) {
628
+ this.eventTarget.emit('change', {
629
+ setItems: Array.from(this._items.items.keys())
630
+ });
631
+ }
632
+ }
633
+
634
+ /**
635
+ * Drop the oldest items, so that at most `keep` remain. The newest items stay, so whether the window holds the
636
+ * latest ones does not change - but the oldest it held are gone.
637
+ * @return Ids of the dropped items.
638
+ */
639
+ trimHead(keep) {
640
+ if (keep === null || this._items.length <= keep) {
641
+ return [];
642
+ }
643
+ const deletedItems = [];
644
+ const deleteCount = this._items.length - keep;
645
+ for (const id of this._items.items.keys()) {
646
+ if (deletedItems.length === deleteCount) {
647
+ break;
648
+ }
649
+ deletedItems.push(id);
650
+ }
651
+ this._items.delete(...deletedItems);
652
+ if (this.internalState.current === WindowState.OLDEST) {
653
+ this.internalState.current = WindowState.PAST;
654
+ }
655
+ return deletedItems;
656
+ }
657
+ trimTail(keep) {
658
+ if (keep === null || this._items.length <= keep) {
659
+ return [];
660
+ }
661
+ const deletedItems = Array.from(this._items.items.keys()).slice(keep);
662
+ this._items.delete(...deletedItems);
663
+ return deletedItems;
664
+ }
665
+
666
+ /**
667
+ * Number of items left after trimming a window that went over the given High Watermark.
668
+ */
669
+ getLowWatermark(highWatermark) {
670
+ if (highWatermark === null || this._items.length <= highWatermark) {
671
+ return null;
672
+ }
673
+ return Math.floor(highWatermark * this.internalState.retainRatio);
674
+ }
675
+ }
676
+ class TopicHistoryWindow extends TraversableRemoteCollection {
677
+ /**
678
+ * Reexported available window modes enum.
679
+ */
680
+ WindowState = WindowState;
681
+ /**
682
+ * The window does not subscribe to the client itself - the messages manager routes the events of its topic to it.
683
+ */
684
+ constructor(roomId, topicId, tracker, preview = false) {
685
+ super('id');
686
+ this.roomId = roomId;
687
+ this.topicId = topicId;
688
+ this.tracker = tracker;
689
+ this.preview = preview;
690
+ this.internalState.traverseLock = false;
691
+ this.internalState.includeMyReactions = !preview;
692
+ this.internalState.myReactions = {};
693
+ this.internalState.liveLimit = 50;
694
+ }
695
+ createMirror() {
696
+ const copy = new TopicHistoryWindow(this.roomId, this.topicId, this.tracker, this.preview);
697
+ copy.eventTarget = this.eventTarget;
698
+ copy._items = this._items;
699
+ copy.internalState = this.internalState;
700
+ return copy;
701
+ }
702
+
703
+ /**
704
+ * Window of a room you have not joined. It gets no live messages - at the latest ones fetchNext() fetches the newer.
705
+ */
706
+ get isPreview() {
707
+ return this.preview;
708
+ }
709
+ get isTraverseLocked() {
710
+ return this.internalState.traverseLock;
711
+ }
712
+
713
+ /**
714
+ * What the connected user has reacted with, keyed by message id. Kept apart from
715
+ * the messages, so the history itself is identical for every user.
716
+ */
717
+ get myReactions() {
718
+ return this.internalState.myReactions;
719
+ }
720
+
721
+ /**
722
+ * Whether the history is fetched together with the reactions of the connected
723
+ * user. Turn it off only where the active state of a reaction is never rendered.
724
+ */
725
+ get includeMyReactions() {
726
+ return this.internalState.includeMyReactions;
727
+ }
728
+ set includeMyReactions(value) {
729
+ this.internalState.includeMyReactions = value;
730
+ }
731
+
732
+ /**
733
+ * Maximum number of items a window that has not been fetched yet (LIVE state) collects from the incoming
734
+ * messages. Null for the same as {@link limit}. It keeps the windows of topics nobody looks at small;
735
+ * the windows of ephemeral topics are exempt, as the live messages are all the history they have.
736
+ */
737
+ get liveLimit() {
738
+ return this.internalState.liveLimit;
739
+ }
740
+ set liveLimit(value) {
741
+ this.internalState.liveLimit = value;
742
+ }
743
+ async setTraverseLock(lock) {
744
+ this.internalState.traverseLock = lock;
745
+ if (lock && this.state !== WindowState.LIVE && this.state !== WindowState.LATEST) {
746
+ await super.resetToLatest();
747
+ }
748
+ }
749
+ async resetToLatest(force = false) {
750
+ if (this.internalState.traverseLock) {
751
+ return;
752
+ }
753
+ return super.resetToLatest(force);
754
+ }
755
+ async fetchNext() {
756
+ if (this.internalState.traverseLock) {
757
+ return;
758
+ }
759
+ if (this.preview && this.hasLatest) {
760
+ return this.fetchAfterLast(); // No events reach a preview
761
+ }
762
+ return super.fetchNext();
763
+ }
764
+ async fetchPrevious() {
765
+ if (this.internalState.traverseLock) {
766
+ return;
767
+ }
768
+ return super.fetchPrevious();
769
+ }
770
+ async jumpTo(id) {
771
+ if (this.internalState.traverseLock) {
772
+ return;
773
+ }
774
+ return super.jumpTo(id);
775
+ }
776
+
777
+ /**
778
+ * For internal use.
779
+ * @internal
780
+ */
781
+ _updateMessageReference(refTopic) {
782
+ const refMessage = this.get(refTopic.refMessage.id);
783
+ if (refMessage) {
784
+ // Update referenced topic ID in message
785
+ this.set({
786
+ ...refMessage,
787
+ topicRef: refTopic.id
788
+ });
789
+ }
790
+ }
791
+ async fetchItemsAfter() {
792
+ const afterId = this.getAt(this.length - 1)?.id;
793
+
794
+ // If there is no message to refer, fetch latest
795
+ return afterId ? this.fetchMessages({
796
+ after: afterId
797
+ }) : null;
798
+ }
799
+ async fetchItemsAround(id) {
800
+ return this.fetchMessages({
801
+ around: id
802
+ });
803
+ }
804
+ async fetchItemsBefore() {
805
+ const beforeId = this.getAt(0)?.id;
806
+
807
+ // If there is no message to refer, fetch latest
808
+ return beforeId ? this.fetchMessages({
809
+ before: beforeId
810
+ }) : null;
811
+ }
812
+ async fetchLatestItems() {
813
+ return this.fetchMessages({});
814
+ }
815
+ async fetchMessages(criteria) {
816
+ const result = await this.tracker.client.send('GetMessages', {
817
+ location: {
818
+ roomId: this.roomId,
819
+ topicId: this.topicId
820
+ },
821
+ limit: this.internalState.fetchLimit,
822
+ includeMyReactions: this.internalState.includeMyReactions,
823
+ ...criteria
824
+ });
825
+ if (result.error) {
826
+ throw new Error(`Cannot fetch messages: ${result.error.message}`);
827
+ }
828
+ this.storeMyReactions(result.data.messages, result.data.myReactions);
829
+ return result.data.messages;
830
+ }
831
+
832
+ /**
833
+ * The response is the truth for every message it covers, so a message it does not
834
+ * mention has no reaction of this user left on it.
835
+ */
836
+ storeMyReactions(messages, myReactions) {
837
+ if (!this.internalState.includeMyReactions) {
838
+ return;
839
+ }
840
+ const next = {
841
+ ...this.internalState.myReactions
842
+ };
843
+ for (const message of messages) {
844
+ const own = myReactions?.[message.id];
845
+ if (own?.length) {
846
+ next[message.id] = own;
847
+ } else {
848
+ delete next[message.id];
849
+ }
850
+ }
851
+ this.internalState.myReactions = next;
852
+ }
853
+ async getTopic() {
854
+ if (this.preview) {
855
+ // The tracker holds the topics of the joined rooms only
856
+ const result = await this.tracker.client.send('GetTopics', {
857
+ roomId: this.roomId,
858
+ topicIds: [this.topicId]
859
+ });
860
+ if (result.error) {
861
+ throw new Error(`Cannot fetch topic: ${result.error.message}`);
862
+ }
863
+ return result.data.topics.find(topic => topic.id === this.topicId);
864
+ }
865
+ return (await this.tracker.rooms.getTopics(this.roomId, [this.topicId])).get(this.topicId);
866
+ }
867
+ async getLatestMessageId() {
868
+ return (await this.getTopic())?.lastMessage?.id;
869
+ }
870
+ async isLatestItemLoaded() {
871
+ const lastMessageId = await this.getLatestMessageId();
872
+ return lastMessageId ? this.has(lastMessageId) : true;
873
+ }
874
+
875
+ /**
876
+ * For internal use.
877
+ * @internal
878
+ */
879
+ _handleNewMessage(ev) {
880
+ if (!this.hasLatest) {
881
+ return;
882
+ }
883
+ const limit = this.state === WindowState.LIVE && !this.internalState.traverseLock ? this.internalState.liveLimit ?? this.limit : this.limit;
884
+ const deletedItems = this.addItems([ev.message], 'tail', limit);
885
+ this.eventTarget.emit('change', deletedItems.length ? {
886
+ setItems: [ev.message.id],
887
+ deletedItems
888
+ } : {
889
+ setItems: [ev.message.id]
890
+ });
891
+ }
892
+
893
+ /**
894
+ * The counter arrives as the global source of truth - only it is overwritten, and
895
+ * a reaction nobody holds any more (count 0) leaves the message.
896
+ * For internal use.
897
+ * @internal
898
+ */
899
+ _handleReactionUpdated(ev) {
900
+ const message = this.get(ev.messageId);
901
+ if (!message) {
902
+ return;
903
+ }
904
+ const index = message.reactions.findIndex(reaction => reaction.type === ev.reaction.type && reaction.value === ev.reaction.value);
905
+ if (index === -1 && !ev.reaction.count) {
906
+ return;
907
+ }
908
+ const reactions = [...message.reactions];
909
+ if (index === -1) {
910
+ reactions.push(ev.reaction);
911
+ } else if (ev.reaction.count) {
912
+ reactions[index] = ev.reaction; // In place - a pill must not jump around as its counter moves
913
+ } else {
914
+ reactions.splice(index, 1);
915
+ }
916
+ this.set({
917
+ ...message,
918
+ reactions
919
+ });
920
+ }
921
+
922
+ /**
923
+ * For internal use.
924
+ * @internal
925
+ */
926
+ _handleReacted(ev) {
927
+ if (!this.has(ev.messageId)) {
928
+ return;
929
+ }
930
+ const {
931
+ type,
932
+ value,
933
+ isAdded
934
+ } = ev.reaction;
935
+ const own = (this.internalState.myReactions[ev.messageId] ?? []).filter(reaction => reaction.type !== type || reaction.value !== value);
936
+ if (isAdded) {
937
+ own.push({
938
+ type,
939
+ value
940
+ });
941
+ }
942
+ const {
943
+ [ev.messageId]: _previous,
944
+ ...myReactions
945
+ } = this.internalState.myReactions;
946
+ if (own.length) {
947
+ myReactions[ev.messageId] = own;
948
+ }
949
+ this.internalState.myReactions = myReactions;
950
+ this.eventTarget.emit('change', {
951
+ setItems: [ev.messageId]
952
+ });
953
+ }
954
+
955
+ /**
956
+ * For internal use.
957
+ * @internal
958
+ */
959
+ async _handleMessagesRedacted(ev) {
960
+ const refTopicIds = this.items.filter(msg => msg.topicRef && ev.ids.includes(msg.id)).map(msg => msg.topicRef);
961
+ this.delete(...ev.ids);
962
+ if (this.length === 0) {
963
+ await this.resetToLatest();
964
+ }
965
+ if (refTopicIds.length > 0) {
966
+ this.eventTarget.emit('reftopicsdeleted', refTopicIds);
967
+ }
968
+ }
969
+ }
970
+ ;// ./src/state-tracker/RoomMessagesHistory.ts
971
+
972
+
973
+
974
+ /**
975
+ * Does not subscribe to the client itself - the messages manager routes the events of its room to it, so a history
976
+ * dropped together with its room stops receiving them.
977
+ */
978
+ class RoomMessagesHistory {
979
+ isPreview;
980
+ roomId;
981
+ historyWindows = new IndexedCollection();
982
+ traverseLock = false;
983
+ room;
984
+ constructor(room, tracker) {
985
+ this.tracker = tracker;
986
+ this.roomId = typeof room === 'string' ? room : room.id;
987
+ this.room = typeof room === 'string' ? null : room;
988
+ this.isPreview = this.room === null;
989
+ if (this.room) {
990
+ this.updateTraverseLock(this.room);
991
+ }
992
+ if (this.room?.defaultTopic) {
993
+ this.createHistoryWindowForTopic(this.room.defaultTopic);
994
+ }
995
+ }
996
+
997
+ /**
998
+ * Returns a history window object for the given topic ID, allowing you to view message history.
999
+ * @param topicId
1000
+ * @param peek If true, do not create a cache for this topic and do not allow it to collect new messages.
1001
+ */
1002
+ async getMessagesWindow(topicId, peek = false) {
1003
+ if (!this.historyWindows.has(topicId) && !peek) {
1004
+ if (this.isPreview) {
1005
+ this.createHistoryWindow(topicId);
1006
+ } else {
1007
+ const topic = (await this.tracker.rooms.getTopics(this.roomId, [topicId])).get(topicId);
1008
+ if (topic) {
1009
+ this.createHistoryWindowForTopic(topic);
1010
+ }
1011
+ }
1012
+ }
1013
+ return this.historyWindows.get(topicId);
1014
+ }
1015
+
1016
+ /**
1017
+ * Re-synchronise this room's history after a reconnect without discarding
1018
+ * the existing window objects (which would blank the UI and, for ephemeral
1019
+ * rooms, permanently drop live-only history).
1020
+ *
1021
+ * The window bindings are preserved; only windows that the application had
1022
+ * actually pulled to the latest page (state === LATEST) are refreshed, with
1023
+ * a single resetToLatest instead of a chain of catch-up requests. Windows
1024
+ * that were never pulled (LIVE) or belong to an ephemeral room are left
1025
+ * untouched so their in-memory context survives the reconnect.
1026
+ */
1027
+ async resync(room) {
1028
+ this.room = room;
1029
+ this.updateTraverseLock(room);
1030
+ if (this.room.defaultTopic) {
1031
+ this.createHistoryWindowForTopic(this.room.defaultTopic);
1032
+ }
1033
+ for (const [, window] of Array.from(this.historyWindows.items)) {
1034
+ try {
1035
+ await window.setTraverseLock(this.traverseLock);
1036
+
1037
+ // Ephemeral history lives only in memory (the server does not
1038
+ // persist it), so never refetch/replace it on reconnect.
1039
+ if (this.traverseLock) {
1040
+ continue;
1041
+ }
1042
+ if (window.state === WindowState.LATEST) {
1043
+ await window.resetToLatest(true);
1044
+ }
1045
+ } catch (_e) {
1046
+ // Best effort: the connection can drop again mid-resync. The
1047
+ // window keeps its current content and stays usable, so the
1048
+ // application can refresh it on demand.
1049
+ }
1050
+ }
1051
+ }
1052
+
1053
+ /**
1054
+ * For internal use.
1055
+ * @internal
1056
+ */
1057
+ async _handleRoomUpdated(ev) {
1058
+ this.room = ev.room;
1059
+ this.updateTraverseLock(ev.room);
1060
+ if (ev.room.defaultTopic) {
1061
+ this.createHistoryWindowForTopic(ev.room.defaultTopic);
1062
+ }
1063
+ for (const [, window] of Array.from(this.historyWindows.items)) {
1064
+ await window.setTraverseLock(this.traverseLock);
1065
+ }
1066
+ }
1067
+
1068
+ /**
1069
+ * For internal use.
1070
+ * @internal
1071
+ */
1072
+ _handleNewTopic(ev) {
1073
+ this.createHistoryWindowForTopic(ev.topic);
1074
+ }
1075
+
1076
+ /**
1077
+ * For internal use.
1078
+ * @internal
1079
+ */
1080
+ _handleTopicDeleted(ev) {
1081
+ this.historyWindows.delete(ev.location.topicId);
1082
+ }
1083
+
1084
+ /**
1085
+ * For internal use.
1086
+ * @internal
1087
+ */
1088
+ _handleNewMessage(ev) {
1089
+ this.historyWindows.get(ev.message.location.topicId)?._handleNewMessage(ev);
1090
+ }
1091
+
1092
+ /**
1093
+ * For internal use.
1094
+ * @internal
1095
+ */
1096
+ _handleMessagesRedacted(ev) {
1097
+ void this.historyWindows.get(ev.location.topicId)?._handleMessagesRedacted(ev);
1098
+ }
1099
+
1100
+ /**
1101
+ * For internal use.
1102
+ * @internal
1103
+ */
1104
+ _handleReactionUpdated(ev) {
1105
+ for (const window of this.historyWindows.items.values()) {
1106
+ window._handleReactionUpdated(ev);
1107
+ }
1108
+ }
1109
+
1110
+ /**
1111
+ * For internal use.
1112
+ * @internal
1113
+ */
1114
+ _handleReacted(ev) {
1115
+ for (const window of this.historyWindows.items.values()) {
1116
+ window._handleReacted(ev);
1117
+ }
1118
+ }
1119
+ createHistoryWindowForTopic(topic) {
1120
+ if (this.historyWindows.has(topic.id)) {
1121
+ return;
1122
+ }
1123
+ this.createHistoryWindow(topic.id);
1124
+
1125
+ // If new topic refers to some message from this room, update other structures
1126
+ if (topic.refMessage) {
1127
+ const refHistoryWindow = this.historyWindows.get(topic.refMessage.location.topicId);
1128
+ refHistoryWindow?._updateMessageReference(topic);
1129
+ }
1130
+ }
1131
+ createHistoryWindow(topicId) {
1132
+ const historyWindow = new TopicHistoryWindow(this.roomId, topicId, this.tracker, this.isPreview);
1133
+ void historyWindow.setTraverseLock(this.traverseLock);
1134
+ this.historyWindows.set([topicId, historyWindow]);
1135
+
1136
+ // Current behavior of deletion a message with referenced topic is to delete the whole side topic
1137
+ // So we need to listen for topic deletions here
1138
+ historyWindow.on('reftopicsdeleted', deletedTopicIds => {
1139
+ for (const topicId of deletedTopicIds) {
1140
+ this.historyWindows.delete(topicId);
1141
+ }
1142
+ this.tracker.rooms._deleteTopicsFromRoom(this.roomId, ...deletedTopicIds);
1143
+ });
1144
+ }
1145
+ updateTraverseLock(room) {
1146
+ this.traverseLock = room.history.mode === 'Ephemeral';
1147
+ }
1148
+ }
1149
+ ;// ./src/state-tracker/MessagesManager.ts
1150
+
1151
+
1152
+
1153
+ class MessagesManager {
1154
+ roomHistories = new IndexedCollection();
1155
+ previewHistories = new IndexedCollection();
1156
+ deferredSession = new DeferredTask();
1157
+ constructor(tracker) {
1158
+ this.tracker = tracker;
1159
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
1160
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoin(ev));
1161
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
1162
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
1163
+
1164
+ // One subscription for all the histories, routed by location: a message costs the same however many rooms
1165
+ // and topics are tracked, and nothing stays subscribed after its room or topic is gone.
1166
+ this.tracker.client.on('RoomUpdated', ev => void this.roomHistories.get(ev.room.id)?._handleRoomUpdated(ev));
1167
+ this.tracker.client.on('NewTopic', ev => this.roomHistories.get(ev.roomId)?._handleNewTopic(ev));
1168
+ this.tracker.client.on('TopicDeleted', ev => this.roomHistories.get(ev.location.roomId)?._handleTopicDeleted(ev));
1169
+ this.tracker.client.on('NewMessage', ev => this.roomHistories.get(ev.message.location.roomId)?._handleNewMessage(ev));
1170
+ this.tracker.client.on('MessagesRedacted', ev => this.roomHistories.get(ev.location.roomId)?._handleMessagesRedacted(ev));
1171
+ this.tracker.client.on('ReactionUpdated', ev => this.forEachRoomHistory(history => history._handleReactionUpdated(ev)));
1172
+ this.tracker.client.on('Reacted', ev => this.forEachRoomHistory(history => history._handleReacted(ev)));
1173
+ }
1174
+
1175
+ /**
1176
+ * Get history manager for given room ID. For a room you have not joined it is a preview (requires `PreviewRooms`),
1177
+ * kept until {@link forgetRoomPreview} or until you join the room.
1178
+ */
1179
+ async getRoomHistory(roomId) {
1180
+ await this.deferredSession.promise;
1181
+ if (this.roomHistories.has(roomId)) {
1182
+ return this.roomHistories.get(roomId);
1183
+ }
1184
+ if (!this.previewHistories.has(roomId)) {
1185
+ this.previewHistories.set([roomId, new RoomMessagesHistory(roomId, this.tracker)]);
1186
+ }
1187
+ return this.previewHistories.get(roomId);
1188
+ }
1189
+ forgetRoomPreview(roomId) {
1190
+ this.previewHistories.delete(roomId);
1191
+ }
1192
+
1193
+ /**
1194
+ * For internal use.
1195
+ * @internal
1196
+ */
1197
+ async _resolveLastMessage(location) {
1198
+ // Try to get last message from history window (if cached); not getRoomHistory(), it would create a preview
1199
+ await this.deferredSession.promise;
1200
+ const historyWindow = await this.roomHistories.get(location.roomId)?.getMessagesWindow(location.topicId, true);
1201
+ let message = historyWindow?.hasLatest && historyWindow.getAt(historyWindow.length - 1);
1202
+ if (!message) {
1203
+ const result = await this.tracker.client.send('GetMessages', {
1204
+ location,
1205
+ limit: 1
1206
+ });
1207
+ message = result.data?.messages[0];
1208
+ }
1209
+ return message || null;
1210
+ }
1211
+ forEachRoomHistory(callback) {
1212
+ for (const history of this.roomHistories.items.values()) {
1213
+ callback(history);
1214
+ }
1215
+ }
1216
+ createHistoryForNewRoom(room) {
1217
+ this.previewHistories.delete(room.id);
1218
+ this.roomHistories.set([room.id, new RoomMessagesHistory(room, this.tracker)]);
1219
+ }
1220
+ handleRoomDeleted(ev) {
1221
+ this.roomHistories.delete(ev.id);
1222
+ }
1223
+ handleRoomJoin(ev) {
1224
+ this.createHistoryForNewRoom(ev.room);
1225
+ }
1226
+ handleRoomLeft(ev) {
1227
+ this.roomHistories.delete(ev.id);
1228
+ }
1229
+ handleSession(ev) {
1230
+ const stateRoomIds = new Set(ev.state.rooms.map(room => room.id));
1231
+
1232
+ // Drop histories only for rooms that no longer exist server-side.
1233
+ for (const roomId of Array.from(this.roomHistories.items.keys())) {
1234
+ if (!stateRoomIds.has(roomId)) {
1235
+ this.roomHistories.delete(roomId);
1236
+ }
1237
+ }
1238
+
1239
+ // Keep existing histories (preserving loaded messages and, crucially,
1240
+ // live-only ephemeral history), create histories for newly joined
1241
+ // rooms, and resync survivors against the fresh room snapshot.
1242
+ for (const room of ev.state.rooms) {
1243
+ const history = this.roomHistories.get(room.id);
1244
+ if (history) {
1245
+ void history.resync(room);
1246
+ } else {
1247
+ this.createHistoryForNewRoom(room);
1248
+ }
1249
+ }
1250
+ this.deferredSession.resolve();
1251
+ }
1252
+ }
1253
+ ;// ./src/state-tracker/FollowedTopicsManager.ts
1254
+
1255
+
1256
+
1257
+ class FollowedTopicsManager extends EventTarget {
1258
+ followedTopics = new IndexedCollection();
1259
+ followedTopicsPromises = new PromiseRegistry();
1260
+ deferredSession = new DeferredTask();
1261
+ summariesCache = new Map();
1262
+
1263
+ /**
1264
+ * Rooms whose cached followed-topics are stale after a reconnect and must
1265
+ * be refetched (and reconciled in place) the next time they are accessed.
1266
+ */
1267
+ staleRooms = new Set();
1268
+ constructor(tracker) {
1269
+ super();
1270
+ this.tracker = tracker;
1271
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
1272
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoin(ev));
1273
+ this.tracker.client.on('NewTopic', ev => this.handleNewTopic(ev));
1274
+ this.tracker.client.on('FollowedTopicUpdated', ev => this.handleFollowedTopicUpdated(ev));
1275
+ this.tracker.client.on('TopicFollowed', ev => this.handleTopicFollowed(ev));
1276
+ this.tracker.client.on('TopicUnfollowed', ev => this.handleTopicUnfollowed(ev));
1277
+ this.tracker.client.on('NewMessage', ev => this.handleNewMessage(ev));
1278
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
1279
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
1280
+ this.tracker.client.on('TopicDeleted', ev => this.handleTopicDeleted(ev));
1281
+ }
1282
+
1283
+ /**
1284
+ * Cache followed topics for all joined rooms in a space and fetch them in bulk if necessary.
1285
+ * Then you can get them using getRoomFollowedTopics().
1286
+ * @see getForRoom
1287
+ */
1288
+ async cacheForSpace(spaceId) {
1289
+ if (spaceId && !(await this.tracker.spaces.get()).has(spaceId)) {
1290
+ throw new Error(`You are not in space ${spaceId}`);
1291
+ }
1292
+ const rooms = await this.tracker.rooms.get();
1293
+ const roomIds = spaceId ? rooms.findBy('spaceId', spaceId).items.map(r => r.id) : rooms.items.filter(r => !r.spaceId).map(r => r.id);
1294
+ if (!roomIds.length) {
1295
+ return;
1296
+ }
1297
+ const needsFetch = roomIds.some(roomId => !this.followedTopics.has(roomId) || this.staleRooms.has(roomId));
1298
+ if (!needsFetch) {
1299
+ return;
1300
+ }
1301
+ const spaceRegistryKey = `space_fetch_${spaceId || 'spaceless'}`;
1302
+ if (this.followedTopicsPromises.notExist(spaceRegistryKey)) {
1303
+ this.followedTopicsPromises.registerByFunction(async () => {
1304
+ const result = await this.tracker.client.send('GetFollowedTopics', {
1305
+ location: {
1306
+ spaceId
1307
+ }
1308
+ });
1309
+ if (result.error) throw result.error;
1310
+ this.reconcileRoomsFollowedTopics(roomIds, result.data.followedTopics);
1311
+ }, spaceRegistryKey);
1312
+ }
1313
+ await this.followedTopicsPromises.get(spaceRegistryKey);
1314
+ }
1315
+
1316
+ /**
1317
+ * Get followed topics for the given room.
1318
+ * @return Undefined if you are not in the room, collection otherwise.
1319
+ */
1320
+ async getForRoom(roomId) {
1321
+ if (!(await this.tracker.rooms.get()).has(roomId)) {
1322
+ return undefined;
1323
+ }
1324
+ if (!this.followedTopics.has(roomId) || this.staleRooms.has(roomId)) {
1325
+ if (this.followedTopicsPromises.notExist(roomId)) {
1326
+ this.followedTopicsPromises.registerByFunction(async () => {
1327
+ const result = await this.tracker.client.send('GetFollowedTopics', {
1328
+ location: {
1329
+ roomId
1330
+ }
1331
+ });
1332
+ if (result.error) {
1333
+ throw result.error;
1334
+ }
1335
+ this.applyRoomFollowedTopics(roomId, result.data.followedTopics);
1336
+ this.invalidateUnreadSummaries(roomId);
1337
+ }, roomId);
1338
+ }
1339
+ await this.followedTopicsPromises.get(roomId);
1340
+ }
1341
+ return this.followedTopics.get(roomId);
1342
+ }
1343
+
1344
+ /**
1345
+ * Batch acknowledge all messages for given room.
1346
+ */
1347
+ async ackRoom(roomId) {
1348
+ const collection = await this.getForRoom(roomId);
1349
+ if (!collection) {
1350
+ return;
1351
+ }
1352
+ for (const followedTopic of collection.items) {
1353
+ if (followedTopic.isUnread) {
1354
+ await this.tracker.client.send('Ack', {
1355
+ location: followedTopic.location
1356
+ });
1357
+ }
1358
+ }
1359
+ }
1360
+
1361
+ /**
1362
+ * Summarize all unread messages or mentions from any topic in given location.
1363
+ * This method uses an internal cache, so it's ok to call it multiple times.
1364
+ * Capture the 'change' event to determine when it's worth calling this method again due to data changes.
1365
+ * @return Undefined if you are not in room.
1366
+ */
1367
+ async summarize(location) {
1368
+ const cacheKey = location.topicId ? `topic:${location.roomId}:${location.topicId}` : location.roomId ? `room:${location.roomId}` : location.spaceId ? `space:${location.spaceId}` : 'spaceless';
1369
+ if (this.summariesCache.has(cacheKey)) {
1370
+ return this.summariesCache.get(cacheKey);
1371
+ }
1372
+ let roomIds = [];
1373
+ let targetTopicId;
1374
+ const rooms = await this.tracker.rooms.get();
1375
+ if (location.topicId) {
1376
+ if (!location.roomId) {
1377
+ throw new Error("roomId is required when querying by topicId");
1378
+ }
1379
+ roomIds = [location.roomId];
1380
+ targetTopicId = location.topicId;
1381
+ } else if (location.roomId) {
1382
+ roomIds = [location.roomId];
1383
+ } else if (location.spaceId) {
1384
+ await this.cacheForSpace(location.spaceId);
1385
+ roomIds = rooms.findBy('spaceId', location.spaceId).items.map(r => r.id);
1386
+ } else {
1387
+ await this.cacheForSpace(null);
1388
+ roomIds = rooms.items.filter(r => !r.spaceId).map(r => r.id);
1389
+ }
1390
+ let mentionCount = 0;
1391
+ let unreadTopicCount = 0;
1392
+ let unreadRoomCount = 0;
1393
+ for (const roomId of roomIds) {
1394
+ const collection = await this.getForRoom(roomId);
1395
+ if (!collection) {
1396
+ continue;
1397
+ }
1398
+ let isRoomUnreadCount = false;
1399
+ for (const topic of collection.items) {
1400
+ if (targetTopicId && topic.location.topicId !== targetTopicId) {
1401
+ continue;
1402
+ }
1403
+ if (topic.isUnread) {
1404
+ if (!isRoomUnreadCount) {
1405
+ unreadRoomCount++;
1406
+ isRoomUnreadCount = true;
1407
+ }
1408
+ unreadTopicCount++;
1409
+ }
1410
+ mentionCount += topic.mentionCount ?? 0;
1411
+ }
1412
+ }
1413
+ const result = {
1414
+ mentionCount,
1415
+ unreadTopicCount,
1416
+ unreadRoomCount,
1417
+ isUnread: unreadTopicCount > 0
1418
+ };
1419
+ this.summariesCache.set(cacheKey, result);
1420
+ return result;
1421
+ }
1422
+
1423
+ /**
1424
+ * For internal use. If you want to delete the message, execute a proper command on client object.
1425
+ * @internal
1426
+ */
1427
+ _deleteByTopicIds(roomId, ...topicIds) {
1428
+ this.followedTopics.get(roomId)?.delete(...topicIds);
1429
+ topicIds.forEach(topicId => this.invalidateUnreadSummaries(roomId, topicId));
1430
+ }
1431
+ handleSession(ev) {
1432
+ // Keep cached followed-topic collections (they drive unread indicators
1433
+ // that would otherwise blank on reconnect), but mark them stale and drop
1434
+ // the fetch guards so the next access/caching refetches and reconciles
1435
+ // them in place.
1436
+ for (const roomId of this.followedTopics.items.keys()) {
1437
+ this.staleRooms.add(roomId);
1438
+ }
1439
+ this.followedTopicsPromises.forgetAll();
1440
+ this.invalidateUnreadSummaries();
1441
+ this.deferredSession.resolve();
1442
+ }
1443
+ handleNewMessage(ev) {
1444
+ void this.updateLocallyFollowedTopicOnNewMessage(ev);
1445
+ }
1446
+ handleFollowedTopicUpdated(ev) {
1447
+ this.followedTopics.get(ev.followedTopic.location.roomId)?.set(ev.followedTopic);
1448
+ this.invalidateUnreadSummaries(ev.followedTopic.location.roomId, ev.followedTopic.location.topicId);
1449
+ }
1450
+ handleTopicFollowed(ev) {
1451
+ this.setFollowedTopicsArray([ev.followedTopic.location.roomId], [ev.followedTopic]);
1452
+ this.invalidateUnreadSummaries(ev.followedTopic.location.roomId, ev.followedTopic.location.topicId);
1453
+ }
1454
+ handleTopicUnfollowed(ev) {
1455
+ this.followedTopics.get(ev.location.roomId)?.delete(ev.location.topicId);
1456
+ this.invalidateUnreadSummaries(ev.location.roomId, ev.location.topicId);
1457
+ }
1458
+ handleRoomDeleted(ev) {
1459
+ this.clearRoomFollowedTopicsStructures(ev.id);
1460
+ }
1461
+ handleRoomJoin(ev) {
1462
+ this.clearRoomFollowedTopicsStructures(ev.room.id);
1463
+ }
1464
+ handleRoomLeft(ev) {
1465
+ this.clearRoomFollowedTopicsStructures(ev.id);
1466
+ }
1467
+ async handleNewTopic(ev) {
1468
+ if (this.followedTopics.has(ev.roomId)) {
1469
+ // Check if the new topic is followed by user
1470
+ // only if client asked for followed topics list before for this room
1471
+ const result = await this.tracker.client.send('GetFollowedTopics', {
1472
+ location: {
1473
+ roomId: ev.roomId,
1474
+ topicId: ev.topic.id
1475
+ }
1476
+ });
1477
+ const followedTopic = result.data.followedTopics[0];
1478
+ if (followedTopic) {
1479
+ this.followedTopics.get(ev.roomId).set(followedTopic);
1480
+ this.invalidateUnreadSummaries(ev.roomId, ev.topic.id);
1481
+ }
1482
+ }
1483
+ }
1484
+ handleTopicDeleted(ev) {
1485
+ this.followedTopics.get(ev.location.roomId)?.delete(ev.location.topicId);
1486
+ this.invalidateUnreadSummaries(ev.location.roomId, ev.location.topicId);
1487
+ }
1488
+
1489
+ /**
1490
+ * Invalidate the summaries cache intentionally, only for the locations affected by the change.
1491
+ */
1492
+ invalidateUnreadSummaries(roomId, topicId) {
1493
+ if (roomId) {
1494
+ this.summariesCache.delete(`room:${roomId}`);
1495
+ if (topicId) {
1496
+ this.summariesCache.delete(`topic:${roomId}:${topicId}`);
1497
+ } else {
1498
+ for (const key of this.summariesCache.keys()) {
1499
+ if (key.startsWith(`topic:${roomId}:`)) {
1500
+ this.summariesCache.delete(key);
1501
+ }
1502
+ }
1503
+ }
1504
+ const room = this.tracker.rooms?._getRoom(roomId);
1505
+ if (room) {
1506
+ this.summariesCache.delete(room.spaceId ? `space:${room.spaceId}` : 'spaceless');
1507
+ } else {
1508
+ for (const key of this.summariesCache.keys()) {
1509
+ if (key.startsWith('space:') || key === 'spaceless') {
1510
+ this.summariesCache.delete(key);
1511
+ }
1512
+ }
1513
+ }
1514
+ } else {
1515
+ this.summariesCache.clear();
1516
+ }
1517
+ this.emit('change');
1518
+ }
1519
+ invalidateUnreadSummariesForRooms(roomIds) {
1520
+ const roomIdsSet = new Set(roomIds);
1521
+ roomIds.forEach(roomId => {
1522
+ this.summariesCache.delete(`room:${roomId}`);
1523
+ });
1524
+ for (const key of this.summariesCache.keys()) {
1525
+ if (key.startsWith('space:') || key === 'spaceless') {
1526
+ this.summariesCache.delete(key);
1527
+ continue;
1528
+ }
1529
+ if (key.startsWith('topic:')) {
1530
+ const parts = key.split(':');
1531
+ if (parts.length >= 2 && roomIdsSet.has(parts[1])) {
1532
+ this.summariesCache.delete(key);
1533
+ }
1534
+ }
1535
+ }
1536
+ this.emit('change');
1537
+ }
1538
+ async updateLocallyFollowedTopicOnNewMessage(ev) {
1539
+ const roomFollowedTopics = this.followedTopics.get(ev.message.location.roomId);
1540
+ const followedTopic = roomFollowedTopics?.get(ev.message.location.topicId);
1541
+ if (!roomFollowedTopics || !followedTopic || ev.message.type === 'Ephemeral') {
1542
+ // Skip if we don't follow this room or message is ephemeral
1543
+ return;
1544
+ }
1545
+ const me = await this.tracker.getMe();
1546
+ const isMe = ev.message.author.user.id === me.id;
1547
+ let update;
1548
+ if (isMe) {
1549
+ // Reset missed messages count if new message is authored by me
1550
+ update = {
1551
+ missed: 0,
1552
+ lastAckMessageId: ev.message.id
1553
+ };
1554
+ } else if (ev.message.type === 'Text') {
1555
+ // ...check for mentions if it's text message...
1556
+ const member = await this.tracker.rooms.getMe(ev.message.location.roomId);
1557
+ const roleIds = [...(member.spaceMember?.roles ?? []), ...(member.roles ?? [])];
1558
+ const mentionHandlers = [...roleIds.map(id => `<@&${id}>`), `<@${me.id}>`];
1559
+ const mentionExists = mentionHandlers.some(handler => ev.message.content.includes(handler));
1560
+ update = {
1561
+ missed: followedTopic.missed === null ? null : followedTopic.missed + 1,
1562
+ isUnread: true,
1563
+ mentionCount: followedTopic.mentionCount + (mentionExists ? 1 : 0)
1564
+ };
1565
+ } else {
1566
+ // ...or just mark as unread.
1567
+ update = {
1568
+ missed: followedTopic.missed === null ? null : followedTopic.missed + 1,
1569
+ isUnread: true
1570
+ };
1571
+ }
1572
+ roomFollowedTopics.set({
1573
+ ...followedTopic,
1574
+ ...update
1575
+ });
1576
+ this.invalidateUnreadSummaries(ev.message.location.roomId, ev.message.location.topicId);
1577
+ }
1578
+
1579
+ /**
1580
+ * Reconcile the followed-topics collection for a single room to exactly
1581
+ * match the provided list (upsert present, drop absent) without emitting an
1582
+ * intermediate empty state, and clear its stale marker. Does not touch the
1583
+ * unread summaries cache - callers decide how to invalidate it.
1584
+ */
1585
+ applyRoomFollowedTopics(roomId, followedTopics) {
1586
+ if (!this.followedTopics.has(roomId)) {
1587
+ this.followedTopics.set([roomId, new ObservableIndexedObjectCollection(followedTopic => followedTopic.location.topicId)]);
1588
+ }
1589
+ this.followedTopics.get(roomId).reconcile(...followedTopics);
1590
+ this.staleRooms.delete(roomId);
1591
+ }
1592
+
1593
+ /**
1594
+ * Reconcile a batch of rooms from a single bulk GetFollowedTopics response.
1595
+ * Rooms with no followed topics in the response are reconciled to empty, so
1596
+ * topics unfollowed/removed during the downtime are correctly dropped.
1597
+ */
1598
+ reconcileRoomsFollowedTopics(roomIds, followedTopics) {
1599
+ const roomToTopics = {};
1600
+ followedTopics.forEach(followedTopic => {
1601
+ (roomToTopics[followedTopic.location.roomId] ??= []).push(followedTopic);
1602
+ });
1603
+ roomIds.forEach(roomId => this.applyRoomFollowedTopics(roomId, roomToTopics[roomId] ?? []));
1604
+ this.invalidateUnreadSummariesForRooms(roomIds);
1605
+ }
1606
+ setFollowedTopicsArray(roomIds, followedTopics) {
1607
+ const roomToTopics = {};
1608
+
1609
+ // Reassign followed topics to limit collection change event emit
1610
+ followedTopics.forEach(followedTopic => {
1611
+ roomToTopics[followedTopic.location.roomId] ??= [];
1612
+ roomToTopics[followedTopic.location.roomId].push(followedTopic);
1613
+ });
1614
+ roomIds.forEach(roomId => {
1615
+ if (!this.followedTopics.has(roomId)) {
1616
+ this.followedTopics.set([roomId, new ObservableIndexedObjectCollection(followedTopic => followedTopic.location.topicId)]);
1617
+ }
1618
+ if (roomToTopics[roomId]) {
1619
+ this.followedTopics.get(roomId).set(...roomToTopics[roomId]);
1620
+ }
1621
+ });
1622
+ this.invalidateUnreadSummariesForRooms(roomIds);
1623
+ }
1624
+ clearRoomFollowedTopicsStructures(roomId) {
1625
+ this.followedTopics.delete(roomId);
1626
+ this.followedTopicsPromises.forget(roomId);
1627
+ this.staleRooms.delete(roomId);
1628
+ this.invalidateUnreadSummaries(roomId);
1629
+ }
1630
+ }
1631
+ ;// ./src/state-tracker/RoomsManager.ts
1632
+
1633
+
1634
+
1635
+
1636
+ class RoomsManager {
1637
+ messages;
1638
+ followedTopics;
1639
+ list = new ObservableIndexedObjectCollection('id');
1640
+ topics = new IndexedCollection();
1641
+ members = new IndexedCollection();
1642
+ deferredSession = new DeferredTask();
1643
+ membersPromises = new PromiseRegistry();
1644
+ topicsPromises = new PromiseRegistry();
1645
+ constructor(tracker) {
1646
+ this.tracker = tracker;
1647
+ this.messages = new MessagesManager(tracker);
1648
+ this.followedTopics = new FollowedTopicsManager(tracker);
1649
+ this.tracker.client.on('NewMessage', ev => this.handleNewMessage(ev));
1650
+ this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
1651
+ this.tracker.client.on('NewTopic', ev => this.handleNewTopic(ev));
1652
+ this.tracker.client.on('TopicDeleted', ev => this.handleTopicDeleted(ev));
1653
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
1654
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
1655
+ this.tracker.client.on('RoomUpdated', ev => this.handleRoomUpdated(ev));
1656
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
1657
+ this.tracker.client.on('TopicUpdated', ev => this.handleTopicUpdated(ev));
1658
+ this.tracker.client.on('RoomMembersJoined', ev => this.handleRoomMembersJoined(ev));
1659
+ this.tracker.client.on('RoomMemberLeft', ev => this.handleRoomMemberLeft(ev));
1660
+ this.tracker.client.on('RoomMembers', ev => this.handleRoomMembers(ev));
1661
+ this.tracker.client.on('RoomMemberUpdated', ev => this.handleRoomMemberUpdated(ev));
1662
+ this.tracker.client.on('SpaceMemberLeft', ev => this.handleSpaceMemberLeft(ev));
1663
+ this.tracker.client.on('SpaceMemberUpdated', ev => this.handleSpaceMemberUpdated(ev));
1664
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceDeleted(ev));
1665
+ this.tracker.client.on('SpaceLeft', ev => this.handleSpaceDeleted(ev));
1666
+ this.tracker.client.on('UserUpdated', ev => this.handleUserUpdated(ev));
1667
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
1668
+ }
1669
+
1670
+ /**
1671
+ * Get collection of room members.
1672
+ */
1673
+ async getMembers(roomId) {
1674
+ if (this.membersPromises.notExist(roomId)) {
1675
+ this.membersPromises.registerByFunction(async () => {
1676
+ const result = await this.tracker.client.send('GetRoomMembers', {
1677
+ id: roomId
1678
+ });
1679
+ if (result.error) {
1680
+ throw result.error;
1681
+ }
1682
+ this.handleRoomMembers(result.data);
1683
+ }, roomId);
1684
+ }
1685
+ await this.membersPromises.get(roomId);
1686
+ return this.members.get(roomId);
1687
+ }
1688
+
1689
+ /**
1690
+ * Get a room member representing the current user.
1691
+ */
1692
+ async getMe(roomId) {
1693
+ const userId = (await this.tracker.getMe()).id;
1694
+ if (!this.list.has(roomId)) {
1695
+ // User is not in passed room.
1696
+ return undefined;
1697
+ }
1698
+ const members = await this.getMembers(roomId);
1699
+ return members?.items.find(member => (member.user?.id ?? member.spaceMember.user.id) === userId);
1700
+ }
1701
+
1702
+ /**
1703
+ * Get collection of all the rooms you are in.
1704
+ */
1705
+ async get() {
1706
+ await this.deferredSession.promise;
1707
+ return this.list;
1708
+ }
1709
+
1710
+ /**
1711
+ * Get a collection of locally cached Topic objects for given room.
1712
+ * You can pass topic ids as second argument, to try to fetch them from the server.
1713
+ */
1714
+ async getTopics(roomId, tryToFetchTopicIds) {
1715
+ await this.deferredSession.promise;
1716
+ if (tryToFetchTopicIds?.length) {
1717
+ // Topic can be fetched if it isn't already cached and fetch is not already in progress
1718
+ const canFetch = topicId => !this.topics.get(roomId)?.has(topicId) && !this.topicsPromises.has(roomId + topicId);
1719
+ const idsToFetch = tryToFetchTopicIds.filter(canFetch);
1720
+ if (idsToFetch.length) {
1721
+ const promise = this.tracker.client.send('GetTopics', {
1722
+ roomId,
1723
+ topicIds: idsToFetch
1724
+ }).then(result => this.topics.get(result.data.location.roomId)?.set(...result.data.topics));
1725
+ idsToFetch.forEach(topicId => this.topicsPromises.register(promise, roomId + topicId));
1726
+ }
1727
+ for (const topicId of tryToFetchTopicIds) {
1728
+ await this.topicsPromises.get(roomId + topicId);
1729
+ }
1730
+ }
1731
+ return this.topics.get(roomId);
1732
+ }
1733
+
1734
+ /**
1735
+ * For internal use.
1736
+ * @internal
1737
+ */
1738
+ _getRoom(roomId) {
1739
+ return this.list.get(roomId);
1740
+ }
1741
+
1742
+ /**
1743
+ * For internal use. If you want to delete topic, execute a proper command on client object.
1744
+ * @internal
1745
+ */
1746
+ _deleteTopicsFromRoom(roomId, ...topicIds) {
1747
+ this.topics.get(roomId)?.delete(...topicIds);
1748
+ }
1749
+ deleteRoom(...roomIds) {
1750
+ this.list.delete(...roomIds);
1751
+ this.members.delete(...roomIds);
1752
+ this.membersPromises.forget(...roomIds);
1753
+ for (const roomId of roomIds) {
1754
+ const topicIds = this.topics.get(roomId)?.items.map(topic => topic.id) ?? [];
1755
+ this.followedTopics._deleteByTopicIds(roomId, ...topicIds);
1756
+ }
1757
+ this.topics.delete(...roomIds);
1758
+ }
1759
+ deleteRoomsBySpaceId(spaceId) {
1760
+ this.deleteRoom(...this.list.findBy('spaceId', spaceId).items.map(room => room.id));
1761
+ }
1762
+ handleSpaceMemberUpdated(ev) {
1763
+ // Update members of rooms related to this space
1764
+ for (const room of this.list.findBy('spaceId', ev.spaceId).items) {
1765
+ const roomMembers = this.members.get(room.id);
1766
+ if (!roomMembers || !roomMembers.has(ev.userId)) {
1767
+ // Skip update if member list for this room is not loaded
1768
+ // or user is not in room
1769
+ continue;
1770
+ }
1771
+
1772
+ // Update space member in roomMember, but first fill the user object (it's null in event)
1773
+ const roomMember = roomMembers.get(ev.userId);
1774
+ roomMembers.set({
1775
+ ...roomMember,
1776
+ spaceMember: {
1777
+ ...ev.member,
1778
+ user: roomMember.spaceMember.user
1779
+ }
1780
+ });
1781
+ }
1782
+ }
1783
+ handleSpaceMemberLeft(ev) {
1784
+ this.list.findBy('spaceId', ev.spaceId).items.forEach(room => this.members.get(room.id)?.delete(ev.userId));
1785
+ }
1786
+ handleRoomMemberUpdated(ev) {
1787
+ if (!this.members.has(ev.roomId)) {
1788
+ // We do not track member list for this room.
1789
+ return;
1790
+ }
1791
+ const members = this.members.get(ev.roomId);
1792
+ const member = members.get(ev.userId);
1793
+ const user = member.spaceMember?.user ?? member.user;
1794
+
1795
+ // Preserving user object, because it's not included in event
1796
+ members.set(ev.member.spaceMember ? {
1797
+ ...ev.member,
1798
+ spaceMember: {
1799
+ ...ev.member.spaceMember,
1800
+ user
1801
+ }
1802
+ } : {
1803
+ ...ev.member,
1804
+ user
1805
+ });
1806
+ }
1807
+ handleSpaceDeleted(ev) {
1808
+ this.deleteRoomsBySpaceId(ev.id);
1809
+ }
1810
+ handleTopicDeleted(ev) {
1811
+ const collection = this.topics.get(ev.location.roomId);
1812
+ collection.delete(ev.location.topicId);
1813
+ const room = this.list.get(ev.location.roomId);
1814
+ if (room.defaultTopic?.id === ev.location.topicId) {
1815
+ this.list.set({
1816
+ ...room,
1817
+ defaultTopic: null
1818
+ });
1819
+ }
1820
+ }
1821
+ handleNewTopic(ev) {
1822
+ this.addJoinedRoomTopics(ev.roomId, ev.topic);
1823
+ }
1824
+ addJoinedRoomTopics(roomId, ...topics) {
1825
+ if (this.topics.has(roomId)) {
1826
+ this.topics.get(roomId).set(...topics);
1827
+ } else {
1828
+ this.topics.set([roomId, new ObservableIndexedObjectCollection('id', topics)]);
1829
+ }
1830
+ }
1831
+ handleRoomJoined(ev) {
1832
+ this.addJoinedRooms(ev.room);
1833
+ }
1834
+ handleRoomUpdated(ev) {
1835
+ if (this.list.has(ev.room.id)) {
1836
+ this.list.set(ev.room);
1837
+ }
1838
+ }
1839
+ handleRoomDeleted(ev) {
1840
+ this.deleteRoom(ev.id);
1841
+ }
1842
+ handleTopicUpdated(ev) {
1843
+ const room = this.list.get(ev.location.roomId);
1844
+ if (this.topics.get(ev.location.roomId)?.has(ev.topic.id)) {
1845
+ this.topics.get(ev.location.roomId).set(ev.topic);
1846
+ }
1847
+ if (room.defaultTopic.id === ev.topic.id) {
1848
+ const newRoom = {
1849
+ ...room
1850
+ };
1851
+ newRoom.defaultTopic = ev.topic;
1852
+ this.list.set(newRoom);
1853
+ }
1854
+ }
1855
+ addJoinedRooms(...rooms) {
1856
+ for (const room of rooms) {
1857
+ if (room.defaultTopic) {
1858
+ this.addJoinedRoomTopics(room.id, room.defaultTopic);
1859
+ }
1860
+ if (room.type === 'Pm' && room.recipients) {
1861
+ // Treat PM recipients as normal room members.
1862
+ // We are registering fake promise in `memberPromises`
1863
+ // because GetMembers are not supported for PM rooms.
1864
+ this.handleRoomMembers({
1865
+ id: room.id,
1866
+ members: room.recipients.map(user => ({
1867
+ user,
1868
+ spaceMember: null,
1869
+ roles: null,
1870
+ customColor: null,
1871
+ customNick: null,
1872
+ customAvatar: null,
1873
+ extras: ''
1874
+ }))
1875
+ });
1876
+ this.membersPromises.register(Promise.resolve(), room.id);
1877
+ }
1878
+ }
1879
+ this.list.set(...rooms);
1880
+ }
1881
+ handleRoomLeft(ev) {
1882
+ this.deleteRoom(ev.id);
1883
+ }
1884
+ handleRoomMembersJoined(ev) {
1885
+ if (this.members.has(ev.roomId)) {
1886
+ this.members.get(ev.roomId).set(...ev.members);
1887
+ }
1888
+ }
1889
+ handleRoomMemberLeft(ev) {
1890
+ if (this.members.has(ev.roomId)) {
1891
+ this.members.get(ev.roomId).delete(ev.userId);
1892
+ }
1893
+ }
1894
+ handleRoomMembers(ev) {
1895
+ if (!this.members.has(ev.id)) {
1896
+ this.members.set([ev.id, new ObservableIndexedObjectCollection(member => member.user?.id ?? member.spaceMember.user.id, ev.members)]);
1897
+ } else {
1898
+ // Reconcile into the existing (bound) collection so a reconnect
1899
+ // refetch updates it in place instead of leaving stale members.
1900
+ this.members.get(ev.id).reconcile(...ev.members);
1901
+ }
1902
+ }
1903
+ handleSession(ev) {
1904
+ const stateRoomIds = new Set(ev.state.rooms.map(room => room.id));
1905
+
1906
+ // Remove only rooms that were left/deleted on the server during the
1907
+ // downtime, reusing the cascade cleanup (members, topics, followed
1908
+ // topics). Surviving rooms keep their identity and bindings.
1909
+ const removedRoomIds = this.list.items.filter(room => !stateRoomIds.has(room.id)).map(room => room.id);
1910
+ if (removedRoomIds.length) {
1911
+ this.deleteRoom(...removedRoomIds);
1912
+ }
1913
+
1914
+ // Invalidate lazy caches so the next access refetches fresh data, but
1915
+ // keep the collection objects: handleRoomMembers reconciles into them,
1916
+ // so bound views refresh in place without blanking.
1917
+ this.membersPromises.forgetAll();
1918
+ this.topicsPromises.forgetAll();
1919
+
1920
+ // Upsert surviving/new rooms from the authoritative snapshot.
1921
+ this.addJoinedRooms(...ev.state.rooms);
1922
+ this.deferredSession.resolve();
1923
+ }
1924
+ handleUserUpdated(ev) {
1925
+ // Update room members users
1926
+ this.members.items.forEach(members => {
1927
+ const member = members.get(ev.user.id);
1928
+ if (!member) {
1929
+ // Skip room; updated user is not here
1930
+ return;
1931
+ }
1932
+ members.set(member.user ? {
1933
+ ...member,
1934
+ user: ev.user
1935
+ } : {
1936
+ ...member,
1937
+ spaceMember: {
1938
+ ...member.spaceMember,
1939
+ user: ev.user
1940
+ }
1941
+ });
1942
+ });
1943
+
1944
+ // Update recipients users
1945
+ const newRooms = [];
1946
+ this.list.items.forEach(room => {
1947
+ if (room.recipients?.some(user => user.id === ev.user.id)) {
1948
+ newRooms.push({
1949
+ ...room,
1950
+ recipients: room.recipients.map(user => user.id === ev.user.id ? ev.user : user)
1951
+ });
1952
+ }
1953
+ });
1954
+ this.list.set(...newRooms);
1955
+ }
1956
+ handleNewMessage(ev) {
1957
+ const topics = this.topics.get(ev.message.location.roomId);
1958
+ const topic = topics?.get(ev.message.location.topicId);
1959
+ if (!topic) {
1960
+ return; // No topic found, nothing to update
1961
+ }
1962
+ const newTopic = {
1963
+ ...topic,
1964
+ messageCount: topic.messageCount + 1,
1965
+ lastMessage: ev.message
1966
+ };
1967
+ topics.set(newTopic);
1968
+ this.updatePmDefaultTopic(ev.message.location.roomId, newTopic);
1969
+ }
1970
+ async handleMessagesRedacted(ev) {
1971
+ // Remove redacted messages from topic and update metadata
1972
+ const topics = this.topics.get(ev.location.roomId);
1973
+ const topic = topics?.get(ev.location.topicId);
1974
+ if (topic) {
1975
+ const messageCount = Math.max(topic.messageCount - ev.ids.length, 0);
1976
+ const lastMessage = messageCount > 0 ? await this.messages._resolveLastMessage(ev.location) : null;
1977
+ const newTopic = {
1978
+ ...topic,
1979
+ messageCount,
1980
+ lastMessage
1981
+ };
1982
+ topics.set(newTopic);
1983
+ this.updatePmDefaultTopic(ev.location.roomId, newTopic);
1984
+ }
1985
+ }
1986
+
1987
+ /**
1988
+ * The topics collection is where the message counters of a topic are kept up to date; a room in the list
1989
+ * is not replaced on every message, as everything bound to the room would be rendered anew with it.
1990
+ * Private conversations are the exception - they are listed by their last message.
1991
+ */
1992
+ updatePmDefaultTopic(roomId, topic) {
1993
+ const room = this.list.get(roomId);
1994
+ if (room?.type === 'Pm' && room.defaultTopic?.id === topic.id) {
1995
+ this.list.set({
1996
+ ...room,
1997
+ defaultTopic: topic
1998
+ });
1999
+ }
2000
+ }
2001
+ }
2002
+ ;// ./src/state-tracker/functions.ts
2003
+ /**
2004
+ * @return New objects of the other roles whose priority has to move; the given roles are left intact.
2005
+ */
2006
+ function reorderRolesOnPriorityUpdate(allRoles, oldRole, updatedRole) {
2007
+ // If the priority has changed, adjust the rest of roles
2008
+ const increased = updatedRole.priority - oldRole.priority > 0;
2009
+ const decreased = !increased;
2010
+ const changedRoles = [];
2011
+ allRoles.forEach(role => {
2012
+ if (role.id === updatedRole.id) {
2013
+ // Skip the updated role
2014
+ return;
2015
+ }
2016
+ if (increased && oldRole.priority <= role.priority) {
2017
+ changedRoles.push({
2018
+ ...role,
2019
+ priority: role.priority - 1
2020
+ });
2021
+ }
2022
+ if (decreased && updatedRole.priority <= role.priority) {
2023
+ changedRoles.push({
2024
+ ...role,
2025
+ priority: role.priority + 1
2026
+ });
2027
+ }
2028
+ });
2029
+ return changedRoles;
2030
+ }
2031
+ function extractUserFromMember(member) {
2032
+ return member.user ?? member.spaceMember?.user;
2033
+ }
2034
+ ;// ./src/state-tracker/SpacesManager.ts
2035
+
2036
+
2037
+
2038
+ class SpacesManager {
2039
+ list = new ObservableIndexedObjectCollection('id');
2040
+ roles = new IndexedCollection();
2041
+ rooms = new IndexedCollection();
2042
+ roomIdToSpaceId = new IndexedCollection();
2043
+ members = new IndexedCollection();
2044
+ deferredSession = new DeferredTask();
2045
+ roomsPromises = new PromiseRegistry();
2046
+ membersPromises = new PromiseRegistry();
2047
+ constructor(tracker) {
2048
+ this.tracker = tracker;
2049
+ this.tracker.client.on('NewRoom', ev => this.handleNewRoom(ev));
2050
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
2051
+ this.tracker.client.on('RoomUpdated', ev => this.handleRoomUpdated(ev));
2052
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceDeleted(ev));
2053
+ this.tracker.client.on('SpaceUpdated', ev => this.handleSpaceUpdated(ev));
2054
+ this.tracker.client.on('SpaceJoined', ev => this.handleSpaceJoined(ev));
2055
+ this.tracker.client.on('SpaceLeft', ev => this.handleSpaceDeleted(ev));
2056
+ this.tracker.client.on('SpaceMemberJoined', ev => this.handleSpaceMemberJoined(ev));
2057
+ this.tracker.client.on('SpaceMemberLeft', ev => this.handleSpaceMemberLeft(ev));
2058
+ this.tracker.client.on('SpaceMembers', ev => this.handleSpaceMembers(ev));
2059
+ this.tracker.client.on('SpaceRooms', ev => this.handleSpaceRooms(ev));
2060
+ this.tracker.client.on('RoomSummaryUpdated', ev => this.handleRoomSummaryUpdated(ev));
2061
+ this.tracker.client.on('SpaceMemberUpdated', ev => this.handleSpaceMemberUpdated(ev));
2062
+ this.tracker.client.on('UserUpdated', ev => this.handleUserUpdated(ev));
2063
+ this.tracker.client.on('NewRole', ev => this.handleNewRole(ev));
2064
+ this.tracker.client.on('RoleDeleted', ev => this.handleRoleDeleted(ev));
2065
+ this.tracker.client.on('RoleUpdated', ev => this.handleRoleUpdated(ev));
2066
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
2067
+ }
2068
+
2069
+ /**
2070
+ * Get collection of all the spaces you are in.
2071
+ */
2072
+ async get() {
2073
+ await this.deferredSession.promise;
2074
+ return this.list;
2075
+ }
2076
+
2077
+ /**
2078
+ * Get collection of space roles.
2079
+ */
2080
+ async getRoles(spaceId) {
2081
+ await this.deferredSession.promise;
2082
+ return this.roles.get(spaceId);
2083
+ }
2084
+
2085
+ /**
2086
+ * Get collection of the all available rooms inside given space.
2087
+ */
2088
+ async getRooms(spaceId) {
2089
+ if (this.roomsPromises.notExist(spaceId)) {
2090
+ this.roomsPromises.registerByFunction(async () => {
2091
+ const result = await this.tracker.client.send('GetSpaceRooms', {
2092
+ id: spaceId
2093
+ });
2094
+ if (result.error) {
2095
+ throw result.error;
2096
+ }
2097
+ this.handleSpaceRooms(result.data);
2098
+ }, spaceId);
2099
+ }
2100
+ await this.roomsPromises.get(spaceId);
2101
+ return this.rooms.get(spaceId);
2102
+ }
2103
+
2104
+ /**
2105
+ * Drop the cached room listing of the space and fetch it again from the server.
2106
+ * Room visibility depends on things this client is not notified about (invitations,
2107
+ * permission changes), so the listing needs a way to be pulled anew on demand.
2108
+ */
2109
+ async refreshRooms(spaceId) {
2110
+ this.roomsPromises.forget(spaceId);
2111
+ return this.getRooms(spaceId);
2112
+ }
2113
+
2114
+ /**
2115
+ * Get collection of space members.
2116
+ */
2117
+ async getMembers(spaceId) {
2118
+ if (this.membersPromises.notExist(spaceId)) {
2119
+ this.membersPromises.registerByFunction(async () => {
2120
+ const result = await this.tracker.client.send('GetSpaceMembers', {
2121
+ id: spaceId
2122
+ });
2123
+ if (result.error) {
2124
+ throw result.error;
2125
+ }
2126
+ this.handleSpaceMembers(result.data);
2127
+ }, spaceId);
2128
+ }
2129
+ await this.membersPromises.get(spaceId);
2130
+ return this.members.get(spaceId);
2131
+ }
2132
+
2133
+ /**
2134
+ * Get a space member representing the current user.
2135
+ */
2136
+ async getMe(spaceId) {
2137
+ const userId = (await this.tracker.getMe()).id;
2138
+ if (!this.list.has(spaceId)) {
2139
+ // User is not in passed space.
2140
+ return undefined;
2141
+ }
2142
+ const members = await this.getMembers(spaceId);
2143
+ return members?.items.find(member => member.user.id === userId);
2144
+ }
2145
+ handleNewRole(ev) {
2146
+ this.roles.get(ev.spaceId).set(ev.role);
2147
+ this.syncSpaceRoles(ev.spaceId);
2148
+ }
2149
+ handleNewRoom(ev) {
2150
+ this.rooms.get(ev.spaceId)?.set(ev.summary);
2151
+ this.roomIdToSpaceId.set([ev.summary.id, ev.spaceId]);
2152
+ }
2153
+ handleRoomUpdated(ev) {
2154
+ if (ev.room.spaceId && this.rooms.has(ev.room.spaceId)) {
2155
+ const rooms = this.rooms.get(ev.room.spaceId);
2156
+ rooms.set({
2157
+ ...rooms.get(ev.room.id),
2158
+ name: ev.room.name,
2159
+ description: ev.room.description
2160
+ });
2161
+ }
2162
+ }
2163
+ async handleRoomDeleted(ev) {
2164
+ const spaceId = this.roomIdToSpaceId.get(ev.id);
2165
+ this.roomIdToSpaceId.delete(ev.id);
2166
+ if (!spaceId) {
2167
+ return;
2168
+ }
2169
+ const space = this.list.get(spaceId);
2170
+ this.rooms.get(spaceId)?.delete(ev.id);
2171
+ if (space && (space.systemRoom === ev.id || space.defaultRooms.includes(ev.id))) {
2172
+ this.list.set({
2173
+ ...space,
2174
+ systemRoom: space.systemRoom === ev.id ? null : space.systemRoom,
2175
+ defaultRooms: space.defaultRooms.filter(roomId => roomId !== ev.id)
2176
+ });
2177
+ }
2178
+ }
2179
+ handleRoleDeleted(ev) {
2180
+ this.roles.get(ev.spaceId).delete(ev.id);
2181
+ this.syncSpaceRoles(ev.spaceId);
2182
+ }
2183
+
2184
+ /**
2185
+ * Keep the roles listed on the space object in line with the roles collection.
2186
+ */
2187
+ syncSpaceRoles(spaceId) {
2188
+ const space = this.list.get(spaceId);
2189
+ if (space) {
2190
+ this.list.set({
2191
+ ...space,
2192
+ roles: this.roles.get(spaceId).items
2193
+ });
2194
+ }
2195
+ }
2196
+ handleSpaceUpdated(ev) {
2197
+ this.list.set(ev.space);
2198
+ }
2199
+ handleSpaceDeleted(ev) {
2200
+ const roomIds = this.rooms.get(ev.id)?.items.map(item => item.id) ?? [];
2201
+ this.roomIdToSpaceId.delete(...roomIds);
2202
+ this.roles.delete(ev.id);
2203
+ this.members.delete(ev.id);
2204
+ this.membersPromises.forget(ev.id);
2205
+ this.rooms.delete(ev.id);
2206
+ this.roomsPromises.forget(ev.id);
2207
+ this.list.delete(ev.id);
2208
+ }
2209
+ handleSpaceJoined(ev) {
2210
+ this.addJoinedSpaces(ev.space);
2211
+ }
2212
+ addJoinedSpaces(...spaces) {
2213
+ this.roles.set(...spaces.map(space => [space.id, new ObservableIndexedObjectCollection('id', space.roles)]));
2214
+ this.list.set(...spaces);
2215
+ }
2216
+ handleSpaceMemberJoined(ev) {
2217
+ if (this.members.has(ev.spaceId)) {
2218
+ this.members.get(ev.spaceId).set(ev.member);
2219
+ }
2220
+ }
2221
+ handleSpaceMemberLeft(ev) {
2222
+ if (this.members.has(ev.spaceId)) {
2223
+ this.members.get(ev.spaceId).delete(ev.userId);
2224
+ }
2225
+ }
2226
+ handleSpaceMembers(ev) {
2227
+ if (!this.members.has(ev.id)) {
2228
+ this.members.set([ev.id, new ObservableIndexedObjectCollection(member => member?.user.id, ev.members)]);
2229
+ } else {
2230
+ // Reconcile into the existing (bound) collection so a reconnect
2231
+ // refetch updates it in place instead of leaving stale members.
2232
+ this.members.get(ev.id).reconcile(...ev.members);
2233
+ }
2234
+ }
2235
+ handleSpaceRooms(ev) {
2236
+ if (!this.rooms.has(ev.id)) {
2237
+ this.rooms.set([ev.id, new ObservableIndexedObjectCollection('id', ev.summaries)]);
2238
+ } else {
2239
+ this.rooms.get(ev.id).reconcile(...ev.summaries);
2240
+ }
2241
+ ev.summaries.forEach(summary => this.roomIdToSpaceId.set([summary.id, ev.id]));
2242
+ }
2243
+ async handleRoomSummaryUpdated(ev) {
2244
+ const spaceId = this.roomIdToSpaceId.get(ev.summary.id);
2245
+ const summariesPromise = this.roomsPromises.get(spaceId);
2246
+
2247
+ /**
2248
+ * Update summary only if the list was already loaded.
2249
+ * RoomSummaryUpdated event has a partial summary, so we need to update the existing summary by merging it.
2250
+ */
2251
+ if (spaceId && summariesPromise) {
2252
+ await summariesPromise;
2253
+ const summaries = this.rooms.get(spaceId);
2254
+ const oldSummary = summaries.get(ev.summary.id);
2255
+ let newSummary;
2256
+ if (oldSummary) {
2257
+ newSummary = {
2258
+ ...oldSummary,
2259
+ ...ev.summary
2260
+ };
2261
+ } else {
2262
+ newSummary = ev.summary;
2263
+ }
2264
+ summaries.set(newSummary);
2265
+ }
2266
+ }
2267
+ handleSpaceMemberUpdated(ev) {
2268
+ if (this.members.has(ev.spaceId)) {
2269
+ const members = this.members.get(ev.spaceId);
2270
+ const member = members.get(ev.userId);
2271
+ members.set({
2272
+ ...ev.member,
2273
+ user: member.user
2274
+ });
2275
+ }
2276
+ }
2277
+ handleRoleUpdated(ev) {
2278
+ const roles = this.roles.get(ev.spaceId);
2279
+ const oldRole = roles.get(ev.role.id);
2280
+ const newRole = ev.role;
2281
+ const rolesToUpdate = [newRole];
2282
+ if (oldRole.priority !== newRole.priority) {
2283
+ rolesToUpdate.push(...reorderRolesOnPriorityUpdate(roles.items, oldRole, newRole));
2284
+ }
2285
+ this.roles.get(ev.spaceId).set(...rolesToUpdate);
2286
+ this.syncSpaceRoles(ev.spaceId);
2287
+ }
2288
+ handleSession(ev) {
2289
+ const stateSpaceIds = new Set(ev.state.spaces.map(space => space.id));
2290
+
2291
+ // Remove only spaces that were left/deleted on the server during the
2292
+ // downtime, reusing the cascade cleanup (roles, rooms, members, index).
2293
+ const removedSpaceIds = this.list.items.filter(space => !stateSpaceIds.has(space.id)).map(space => space.id);
2294
+ for (const spaceId of removedSpaceIds) {
2295
+ this.handleSpaceDeleted({
2296
+ id: spaceId
2297
+ });
2298
+ }
2299
+
2300
+ // Invalidate lazy caches (rooms/members) but keep their objects so the
2301
+ // next access refetches and reconciles them in place.
2302
+ this.roomsPromises.forgetAll();
2303
+ this.membersPromises.forgetAll();
2304
+
2305
+ // Reconcile roles in place (kept, possibly bound object) and upsert the
2306
+ // spaces from the authoritative snapshot.
2307
+ for (const space of ev.state.spaces) {
2308
+ if (this.roles.has(space.id)) {
2309
+ this.roles.get(space.id).reconcile(...space.roles);
2310
+ } else {
2311
+ this.roles.set([space.id, new ObservableIndexedObjectCollection('id', space.roles)]);
2312
+ }
2313
+ }
2314
+ this.list.set(...ev.state.spaces);
2315
+ this.deferredSession.resolve();
2316
+ }
2317
+ handleUserUpdated(ev) {
2318
+ this.members.items.forEach(members => {
2319
+ const member = members.get(ev.user.id);
2320
+ if (!member) {
2321
+ // Skip space; updated user is not here
2322
+ return;
2323
+ }
2324
+ members.set({
2325
+ ...member,
2326
+ user: ev.user
2327
+ });
2328
+ });
2329
+ }
2330
+ }
2331
+ ;// ./src/Permissions.ts
2332
+ let Layer = /*#__PURE__*/function (Layer) {
2333
+ Layer[Layer["Global"] = 0] = "Global";
2334
+ Layer[Layer["Space"] = 1] = "Space";
2335
+ Layer[Layer["Room"] = 2] = "Room";
2336
+ Layer[Layer["Topic"] = 3] = "Topic";
2337
+ return Layer;
2338
+ }({});
2339
+ class PermissionDefinition {
2340
+ value;
2341
+ maxLayer;
2342
+ }
2343
+ class Permissions {
2344
+ static list = {
2345
+ Root: {
2346
+ value: 1 << 0,
2347
+ maxLayer: Layer.Room
2348
+ },
2349
+ CreateSpaces: {
2350
+ value: 1 << 1,
2351
+ maxLayer: Layer.Global
2352
+ },
2353
+ ManageSpace: {
2354
+ value: 1 << 2,
2355
+ maxLayer: Layer.Space
2356
+ },
2357
+ ManageRoles: {
2358
+ value: 1 << 3,
2359
+ maxLayer: Layer.Space
2360
+ },
2361
+ //ManageRoom: {value: 1 << 4, maxLayer: Layer.Room},
2362
+ CreateTopics: {
2363
+ value: 1 << 5,
2364
+ maxLayer: Layer.Room
2365
+ },
2366
+ ManageTopic: {
2367
+ value: 1 << 6,
2368
+ maxLayer: Layer.Topic
2369
+ },
2370
+ ManageMemberProfiles: {
2371
+ value: 1 << 7,
2372
+ maxLayer: Layer.Space
2373
+ },
2374
+ ManageMemberRoles: {
2375
+ value: 1 << 8,
2376
+ maxLayer: Layer.Room
2377
+ },
2378
+ CreateMessages: {
2379
+ value: 1 << 9,
2380
+ maxLayer: Layer.Topic
2381
+ },
2382
+ ManagePermissions: {
2383
+ value: 1 << 10,
2384
+ maxLayer: Layer.Topic
2385
+ },
2386
+ CreateRooms: {
2387
+ value: 1 << 11,
2388
+ maxLayer: Layer.Space
2389
+ },
2390
+ ManageRoom: {
2391
+ value: 1 << 12,
2392
+ maxLayer: Layer.Room
2393
+ },
2394
+ CreateEmoticons: {
2395
+ value: 1 << 13,
2396
+ maxLayer: Layer.Space
2397
+ },
2398
+ ManageEmoticons: {
2399
+ value: 1 << 14,
2400
+ maxLayer: Layer.Space
2401
+ },
2402
+ ManageBans: {
2403
+ value: 1 << 15,
2404
+ maxLayer: Layer.Room
2405
+ },
2406
+ Kick: {
2407
+ value: 1 << 16,
2408
+ maxLayer: Layer.Room
2409
+ },
2410
+ ChangeOwnProfile: {
2411
+ value: 1 << 17,
2412
+ maxLayer: Layer.Space
2413
+ },
2414
+ ChangeOwnColor: {
2415
+ value: 1 << 18,
2416
+ maxLayer: Layer.Room
2417
+ },
2418
+ RedactMessages: {
2419
+ value: 1 << 19,
2420
+ maxLayer: Layer.Topic
2421
+ },
2422
+ AddMembers: {
2423
+ value: 1 << 20,
2424
+ maxLayer: Layer.Space
2425
+ },
2426
+ React: {
2427
+ value: 1 << 21,
2428
+ maxLayer: Layer.Topic
2429
+ },
2430
+ CreatePolls: {
2431
+ value: 1 << 22,
2432
+ maxLayer: Layer.Topic
2433
+ },
2434
+ MentionAllRoles: {
2435
+ value: 1 << 23,
2436
+ maxLayer: Layer.Topic
2437
+ },
2438
+ PreviewRooms: {
2439
+ value: 1 << 24,
2440
+ maxLayer: Layer.Room
2441
+ },
2442
+ SearchMessages: {
2443
+ value: 1 << 25,
2444
+ maxLayer: Layer.Room
2445
+ }
2446
+ };
2447
+ static getNames() {
2448
+ return Object.keys(this.list);
2449
+ }
2450
+ static getByName(name) {
2451
+ return this.list[name];
2452
+ }
2453
+ static canBeDefinedOnLayer(permissionName, layer) {
2454
+ const def = this.getByName(permissionName);
2455
+ if (!def) {
2456
+ throw new Error(`Invalid permission name: ${permissionName}`);
2457
+ }
2458
+ return layer <= this.getByName(permissionName).maxLayer;
2459
+ }
2460
+ }
2461
+ ;// ./src/state-tracker/PermissionsManager.ts
2462
+
2463
+
2464
+
2465
+
2466
+ const getOvId = (location, target) => [location.spaceId, location.roomId, location.topicId, target?.type, target?.userId, target?.roleId].filter(Boolean).join('/');
2467
+ const getOvIdByObject = overwrites => getOvId(overwrites.location, overwrites.target);
2468
+ class PermissionsManager extends EventTarget {
2469
+ overwrites = new IndexedCollection();
2470
+ overwritesPromises = new PromiseRegistry();
2471
+ constructor(tracker) {
2472
+ super();
2473
+ this.tracker = tracker;
2474
+ this.tracker.client.on('PermissionOverwrites', ev => this.handlePermissionOverwrites(ev));
2475
+ this.tracker.client.on('PermissionOverwritesUpdated', ev => this.handlePermissionOverwrites(ev));
2476
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceDeleted(ev));
2477
+ this.tracker.client.on('SpaceLeft', ev => this.handleSpaceDeleted(ev));
2478
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
2479
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomDeleted(ev));
2480
+ this.tracker.client.on('TopicDeleted', ev => this.handleTopicDeleted(ev));
2481
+ this.tracker.client.on('RoleDeleted', ev => this.handleRoleDeleted(ev));
2482
+ this.tracker.client.on('SpaceMemberUpdated', ev => this.handleSpaceMemberUpdated(ev));
2483
+ this.tracker.client.on('RoomMemberUpdated', ev => this.handleRoomMemberUpdated(ev));
2484
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
2485
+ }
2486
+ async getOverwrites(location, target) {
2487
+ this.validateLocation(location);
2488
+ const id = getOvId(location, target);
2489
+ if (this.overwritesPromises.notExist(id)) {
2490
+ this.overwritesPromises.registerByFunction(async () => {
2491
+ const result = await this.tracker.client.send('GetPermissionOverwrites', {
2492
+ location,
2493
+ target
2494
+ });
2495
+ if (result.error) {
2496
+ throw result.error;
2497
+ }
2498
+ this.handlePermissionOverwrites(result.data);
2499
+ }, id);
2500
+ }
2501
+ await this.overwritesPromises.get(id);
2502
+ return this.overwrites.get(id);
2503
+ }
2504
+ async check(permissionNames, location) {
2505
+ if (!permissionNames.length) {
2506
+ throw new Error('Permission names array cannot be empty');
2507
+ }
2508
+ const ownedPermissions = await this.calculatePermissions(location);
2509
+ const missing = [];
2510
+ permissionNames.forEach(name => {
2511
+ if (~ownedPermissions & Permissions.getByName(name).value) {
2512
+ missing.push(name);
2513
+ }
2514
+ });
2515
+ return {
2516
+ ok: missing.length === 0,
2517
+ hasAll: missing.length === 0,
2518
+ hasAny: missing.length < permissionNames.length,
2519
+ missing
2520
+ };
2521
+ }
2522
+
2523
+ /**
2524
+ * For a room or a space you have not joined the permissions are fetched from the server, on every call.
2525
+ */
2526
+ async calculatePermissions(location) {
2527
+ const room = location.roomId ? (await this.tracker.rooms.get()).get(location.roomId) : null;
2528
+ location = {
2529
+ spaceId: location.spaceId ?? room?.spaceId,
2530
+ roomId: location.roomId,
2531
+ topicId: location.topicId
2532
+ };
2533
+ this.validateLocation(location);
2534
+ if (location.roomId && !room || location.spaceId && !(await this.tracker.spaces.get())?.has(location.spaceId)) {
2535
+ return this.fetchComputedPermissions(location);
2536
+ }
2537
+ const userId = (await this.tracker.getMe()).id;
2538
+ const [spaceMember, roomMember] = await this.fetchMembersOrFail(location);
2539
+ const userRoles = [...(spaceMember?.roles ?? []), ...(roomMember?.roles ?? [])];
2540
+ const promises = [
2541
+ // Global user overwrites
2542
+ this.getOverwrites({}, {
2543
+ type: 'User',
2544
+ userId
2545
+ }).then(v => v.overwrites)];
2546
+ if (location.spaceId && (await this.tracker.spaces.get())?.has(location.spaceId)) {
2547
+ const filterLocation = {
2548
+ spaceId: location.spaceId
2549
+ };
2550
+ promises.push(this.collectRoleOverwrites(filterLocation, userRoles));
2551
+ promises.push(this.getOverwrites(filterLocation, {
2552
+ type: 'User',
2553
+ userId
2554
+ }).then(v => v.overwrites));
2555
+ }
2556
+ if (room) {
2557
+ const filterLocation = {
2558
+ spaceId: location.spaceId,
2559
+ roomId: location.roomId
2560
+ };
2561
+ if (userRoles.length) {
2562
+ promises.push(this.collectRoleOverwrites(filterLocation, userRoles));
2563
+ }
2564
+ promises.push(this.getOverwrites(filterLocation, {
2565
+ type: 'User',
2566
+ userId
2567
+ }).then(v => v.overwrites));
2568
+ }
2569
+ if (location.topicId && (await this.tracker.rooms.getTopics(location.roomId))?.has(location.topicId)) {
2570
+ if (userRoles.length) {
2571
+ promises.push(this.collectRoleOverwrites(location, userRoles));
2572
+ }
2573
+ promises.push(this.getOverwrites(location, {
2574
+ type: 'User',
2575
+ userId
2576
+ }).then(v => v.overwrites));
2577
+ }
2578
+ return this.resolveOverwritesHierarchy(await Promise.all(promises));
2579
+ }
2580
+
2581
+ /**
2582
+ * Arriving overwrites change the permissions only when they replace different ones. The first ones fetched for a
2583
+ * key have not been part of any result yet - every calculation needing them awaits their fetch - and a fetch
2584
+ * response arrives twice, as the command result and as an event.
2585
+ */
2586
+ handlePermissionOverwrites(ev) {
2587
+ const id = getOvIdByObject(ev);
2588
+ const previous = this.overwrites.get(id);
2589
+ this.overwrites.set([id, ev]);
2590
+ if (previous && (previous.overwrites.allow !== ev.overwrites.allow || previous.overwrites.deny !== ev.overwrites.deny)) {
2591
+ this.emit('change');
2592
+ }
2593
+ }
2594
+ handleSpaceDeleted(ev) {
2595
+ const ids = this.deleteOverwritesByIdPrefix(getOvId({
2596
+ spaceId: ev.id
2597
+ }));
2598
+ this.overwritesPromises.forget(...ids);
2599
+ }
2600
+ async handleRoomDeleted(ev) {
2601
+ const room = (await this.tracker.rooms.get()).get(ev.id);
2602
+ if (room) {
2603
+ const ids = this.deleteOverwritesByIdPrefix(getOvId({
2604
+ spaceId: room.spaceId,
2605
+ roomId: room.id
2606
+ }));
2607
+ this.overwritesPromises.forget(...ids);
2608
+ }
2609
+ }
2610
+ handleTopicDeleted(ev) {
2611
+ const ids = this.deleteOverwritesByIdPrefix(getOvId(ev.location));
2612
+ this.overwritesPromises.forget(...ids);
2613
+ }
2614
+ handleRoleDeleted(ev) {
2615
+ const ids = this.deleteOverwritesByIdPrefix(getOvId({
2616
+ spaceId: ev.spaceId
2617
+ }, {
2618
+ type: 'Role',
2619
+ roleId: ev.id
2620
+ }));
2621
+ this.overwritesPromises.forget(...ids);
2622
+ }
2623
+ handleSpaceMemberUpdated(ev) {
2624
+ if (ev.userId === this.tracker.me?.id) {
2625
+ // User roles in space could potentially have changed
2626
+ this.emit('change');
2627
+ }
2628
+ }
2629
+ handleRoomMemberUpdated(ev) {
2630
+ if (ev.userId === this.tracker.me?.id) {
2631
+ // User roles in room could potentially have changed
2632
+ this.emit('change');
2633
+ }
2634
+ }
2635
+
2636
+ /**
2637
+ * @return Matched and deleted ids
2638
+ */
2639
+ deleteOverwritesByIdPrefix(prefix) {
2640
+ const ids = [];
2641
+ this.overwrites.items.forEach(overwrites => {
2642
+ const id = getOvIdByObject(overwrites);
2643
+ if (id.startsWith(prefix)) {
2644
+ ids.push(id);
2645
+ this.overwrites.delete(id);
2646
+ }
2647
+ });
2648
+ return ids;
2649
+ }
2650
+ async collectRoleOverwrites(location, userRoles) {
2651
+ const roleOverwrites = await Promise.all(userRoles.map(roleId => this.getOverwrites(location, {
2652
+ type: 'Role',
2653
+ roleId
2654
+ })));
2655
+ return this.resolveOverwritesFromRolesByOrder(location.spaceId, roleOverwrites);
2656
+ }
2657
+ async resolveOverwritesFromRolesByOrder(spaceId, overwrites) {
2658
+ let allows = 0,
2659
+ denies = 0;
2660
+ const roles = await this.tracker.spaces.getRoles(spaceId);
2661
+ const sortedOverwrites = overwrites.sort((a, b) => roles.get(a.target.roleId).priority - roles.get(b.target.roleId).priority);
2662
+
2663
+ // Max length of bit word
2664
+ const permissionsLength = overwrites.reduce((previousValue, currentValue) => Math.max(previousValue, currentValue.overwrites.allow?.toString(2).length ?? 0, currentValue.overwrites.deny?.toString(2).length ?? 0), 0);
2665
+ sortedOverwrites.forEach(overwriteEvent => {
2666
+ const overwrites = overwriteEvent.overwrites;
2667
+ const revDecDenies = overwrites.deny?.toString(2).split('').reverse().join('') ?? '';
2668
+ const revDecAllows = overwrites.allow?.toString(2).split('').reverse().join('') ?? '';
2669
+ for (let i = 0; i < permissionsLength; i++) {
2670
+ const deny = parseInt(revDecDenies[i] ?? '0');
2671
+ const allow = parseInt(revDecAllows[i] ?? '0');
2672
+ if (deny) {
2673
+ denies |= 1 << i;
2674
+ }
2675
+ if (allow) {
2676
+ allows |= 1 << i;
2677
+ }
2678
+ }
2679
+ });
2680
+ return {
2681
+ allow: allows,
2682
+ deny: denies
2683
+ };
2684
+ }
2685
+ resolveOverwritesHierarchy(permissionOverwritesValues) {
2686
+ let result = 0;
2687
+ for (const value of permissionOverwritesValues) {
2688
+ if (value.allow & Permissions.getByName('Root').value) {
2689
+ return this.getRootAccessValue();
2690
+ }
2691
+ result = result & ~value.deny | value.allow;
2692
+ }
2693
+ return result;
2694
+ }
2695
+ getRootAccessValue() {
2696
+ let result = 0;
2697
+ for (const name of Permissions.getNames()) {
2698
+ result |= Permissions.getByName(name).value;
2699
+ }
2700
+ return result;
2701
+ }
2702
+ async fetchComputedPermissions(location) {
2703
+ const result = await this.tracker.client.send('GetComputedPermissions', {
2704
+ location
2705
+ });
2706
+ if (result.error) {
2707
+ throw result.error;
2708
+ }
2709
+ return result.data.permissions;
2710
+ }
2711
+ async fetchMembersOrFail(location) {
2712
+ const results = await Promise.all([location.spaceId ? this.tracker.spaces.getMe(location.spaceId) : null, location.roomId ? this.tracker.rooms.getMe(location.roomId) : null]);
2713
+ const spaceFail = location.spaceId && !results[0];
2714
+ const roomFail = location.roomId && !results[1];
2715
+ if (spaceFail || roomFail) {
2716
+ const layer = spaceFail ? `space (${location.spaceId})` : `room (${location.roomId})`;
2717
+ throw new Error(`Attempting to calculate permissions for a ${layer} that the user does not belong to`);
2718
+ }
2719
+ return results;
2720
+ }
2721
+ validateLocation(location) {
2722
+ if (location.topicId && !location.roomId) {
2723
+ throw new Error('Corrupted arguments hierarchy');
2724
+ }
2725
+ }
2726
+ handleSession(ev) {
2727
+ // Drop the fetch guards so permission checks recompute against fresh
2728
+ // overwrites (getOverwrites refetches and upserts on the next access),
2729
+ // and notify consumers to recompute so bound permission UI is never
2730
+ // left showing stale results after a reconnect.
2731
+ this.overwritesPromises.forgetAll();
2732
+ this.emit('change');
2733
+ }
2734
+ }
2735
+ ;// ./src/state-tracker/EmoticonsManager.ts
2736
+
2737
+
2738
+ const GLOBAL_KEY = 'global';
2739
+ class EmoticonsManager {
2740
+ list = new IndexedCollection();
2741
+ emoticonsPromises = new PromiseRegistry();
2742
+ constructor(tracker) {
2743
+ this.tracker = tracker;
2744
+ this.tracker.client.on('Emoticons', ev => this.handleEmoticons(ev));
2745
+ this.tracker.client.on('NewEmoticon', ev => this.handleNewEmoticon(ev));
2746
+ this.tracker.client.on('EmoticonDeleted', ev => this.handleEmoticonDeleted(ev));
2747
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceDeleted(ev));
2748
+ this.tracker.client.on('Session', () => this.handleSession());
2749
+ }
2750
+ async get(spaceId) {
2751
+ const key = spaceId ?? GLOBAL_KEY;
2752
+ if (this.emoticonsPromises.notExist(key)) {
2753
+ this.emoticonsPromises.registerByFunction(async () => {
2754
+ const result = await this.tracker.client.send('GetEmoticons', {
2755
+ spaceId
2756
+ });
2757
+ if (result.error) {
2758
+ throw result.error;
2759
+ }
2760
+ this.handleEmoticons(result.data);
2761
+ }, key);
2762
+ }
2763
+ await this.emoticonsPromises.get(key);
2764
+ return this.list.get(key);
2765
+ }
2766
+ handleEmoticons(event) {
2767
+ const spaceId = event.location.spaceId ?? GLOBAL_KEY;
2768
+ if (!this.list.has(spaceId)) {
2769
+ this.list.set([spaceId, new ObservableIndexedObjectCollection('id')]);
2770
+ }
2771
+
2772
+ // handleEmoticons always carries the full list for a location, so
2773
+ // reconcile in place: a reconnect refetch drops removed emoticons and
2774
+ // adds new ones without blanking a bound (visible) collection.
2775
+ this.list.get(spaceId).reconcile(...event.emoticons);
2776
+ }
2777
+ handleNewEmoticon(ev) {
2778
+ const collection = this.list.get(ev.emoticon.spaceId ?? GLOBAL_KEY);
2779
+ collection?.set(ev.emoticon);
2780
+ }
2781
+ handleEmoticonDeleted(ev) {
2782
+ const collection = this.list.get(ev.spaceId ?? GLOBAL_KEY);
2783
+ collection?.delete(ev.emoticonId);
2784
+ }
2785
+ handleSpaceDeleted(event) {
2786
+ this.list.delete(event.id);
2787
+ }
2788
+ handleSession() {
2789
+ // Keep cached emoticon collections (they may be bound to visible
2790
+ // pickers); just drop the fetch guards so the next access refetches and
2791
+ // reconciles them in place.
2792
+ this.emoticonsPromises.forgetAll();
2793
+ }
2794
+ }
2795
+ ;// ./src/state-tracker/UsersManager.ts
2796
+
2797
+
2798
+
2799
+ class UsersManager {
2800
+ onlineStatus = new EventTarget();
2801
+ users = new ObservableIndexedObjectCollection('id');
2802
+ constructor(tracker) {
2803
+ this.tracker = tracker;
2804
+ // RoomMemberUpdated & SpaceMemberUpdated events are not contains user object
2805
+ tracker.client.on('UserUpdated', event => this.handleUsers([event.user]));
2806
+ tracker.client.on('RoomMembersJoined', event => this.handleMembers(event.members));
2807
+ tracker.client.on('SpaceMemberJoined', event => this.handleMembers([event.member]));
2808
+ tracker.client.on('SpaceMembers', event => this.handleMembers(event.members));
2809
+ tracker.client.on('RoomMembers', event => this.handleMembers(event.members));
2810
+ tracker.client.on('Messages', event => this.handleUsers(event.messages.map(message => message.author.user)));
2811
+ tracker.client.on('NewMessage', event => this.handleUsers([event.message.author.user]));
2812
+ tracker.client.on('Session', event => this.handleSession(event));
2813
+ }
2814
+
2815
+ /**
2816
+ * Get all available (cached) user objects at once.
2817
+ */
2818
+ async getAvailable() {
2819
+ return this.users;
2820
+ }
2821
+ handleMembers(members) {
2822
+ this.handleUsers(members.map(extractUserFromMember));
2823
+ }
2824
+ handleSession(session) {
2825
+ // Keep the "seen users" cache across reconnects so bound user lists do
2826
+ // not blank out; just ensure our own user is present/updated. Stale
2827
+ // entries are refreshed as member/message collections refetch.
2828
+ this.handleUsers([session.user]);
2829
+ }
2830
+
2831
+ /**
2832
+ * Every message carries its author, so most of what arrives here is already known - only the users that actually
2833
+ * changed are stored, and the collection does not report a change for each message.
2834
+ */
2835
+ handleUsers(users) {
2836
+ const changedUsers = [];
2837
+ for (const newUser of users) {
2838
+ const oldUser = this.users.get(newUser.id);
2839
+ if (oldUser && isSameUser(oldUser, newUser)) {
2840
+ continue;
2841
+ }
2842
+ if (oldUser && oldUser.status !== newUser.status) {
2843
+ this.onlineStatus.emit('change', newUser);
2844
+ }
2845
+ changedUsers.push(newUser);
2846
+ }
2847
+ this.users.set(...changedUsers);
2848
+ }
2849
+ }
2850
+ function isSameUser(a, b) {
2851
+ const keys = Object.keys(a);
2852
+ if (keys.length !== Object.keys(b).length) {
2853
+ return false;
2854
+ }
2855
+ return keys.every(key => {
2856
+ const valueA = a[key];
2857
+ const valueB = b[key];
2858
+ if (Array.isArray(valueA) && Array.isArray(valueB)) {
2859
+ return valueA.length === valueB.length && valueA.every((item, index) => item === valueB[index]);
2860
+ }
2861
+ return valueA === valueB;
2862
+ });
2863
+ }
2864
+ ;// ./src/state-tracker/RelationshipsManager.ts
2865
+
2866
+
2867
+ const getId = (refUserId, type) => `${refUserId}-${type}`;
2868
+ const getIdFromRelationship = relationship => getId(relationship.refUser.id, relationship.type);
2869
+ class RelationshipsManager {
2870
+ relationships = new ObservableIndexedObjectCollection(getIdFromRelationship);
2871
+ promises = new PromiseRegistry();
2872
+ constructor(tracker) {
2873
+ this.tracker = tracker;
2874
+ this.tracker.client.on('Relationships', ev => this.handleRelationships(ev));
2875
+ this.tracker.client.on('NewRelationship', ev => this.handleNewRelationship(ev));
2876
+ this.tracker.client.on('RelationshipDeleted', ev => this.handleRelationshipDeleted(ev));
2877
+ this.tracker.client.on('Session', () => this.handleSession());
2878
+ }
2879
+ async get() {
2880
+ if (this.promises.notExist('all')) {
2881
+ this.promises.registerByFunction(async () => {
2882
+ const result = await this.tracker.client.send('GetRelationships', {});
2883
+ if (result.error) {
2884
+ throw result.error;
2885
+ }
2886
+ }, 'all');
2887
+ }
2888
+ await this.promises.get('all');
2889
+ return this.relationships;
2890
+ }
2891
+ async exists(refUserId, type) {
2892
+ await this.get();
2893
+ return this.relationships.has(getId(refUserId, type));
2894
+ }
2895
+ handleRelationships(ev) {
2896
+ // Full list from the server: reconcile in place so a reconnect refetch
2897
+ // updates a bound (visible) list without an intermediate empty state.
2898
+ this.relationships.reconcile(...ev.relationships);
2899
+ }
2900
+ handleNewRelationship(ev) {
2901
+ if (this.promises.has('all')) {
2902
+ this.relationships.set(ev.relationship);
2903
+ }
2904
+ }
2905
+ handleRelationshipDeleted(ev) {
2906
+ if (this.promises.has('all')) {
2907
+ this.relationships.delete(getIdFromRelationship(ev.relationship));
2908
+ }
2909
+ }
2910
+ handleSession() {
2911
+ // Keep the (possibly bound) collection; just drop the fetch guard so the
2912
+ // next get() refetches and reconciles it in place.
2913
+ this.promises.forgetAll();
2914
+ }
2915
+ }
2916
+ ;// ./src/state-tracker/ChatStateTracker.ts
2917
+
2918
+
2919
+
2920
+
2921
+
2922
+
2923
+
2924
+ class ChatStateTracker {
2925
+ client;
2926
+
2927
+ /**
2928
+ * State of your permissions.
2929
+ */
2930
+ permissions;
2931
+
2932
+ /**
2933
+ * State of the rooms you are in.
2934
+ */
2935
+ rooms;
2936
+
2937
+ /**
2938
+ * State of the spaces you are in.
2939
+ */
2940
+ spaces;
2941
+
2942
+ /**
2943
+ * State of the emoticons (global and space-related).
2944
+ */
2945
+ emoticons;
2946
+
2947
+ /**
2948
+ * Users related state.
2949
+ */
2950
+ users;
2951
+
2952
+ /**
2953
+ * State of relationships with other users.
2954
+ */
2955
+ relationships;
2956
+ _me = null;
2957
+ deferredSession = new DeferredTask();
2958
+ constructor(client) {
2959
+ this.client = client;
2960
+ this.client.on('Session', ev => this.handleSession(ev));
2961
+ this.permissions = new PermissionsManager(this);
2962
+ this.rooms = new RoomsManager(this);
2963
+ this.spaces = new SpacesManager(this);
2964
+ this.emoticons = new EmoticonsManager(this);
2965
+ this.users = new UsersManager(this);
2966
+ this.relationships = new RelationshipsManager(this);
2967
+ }
2968
+ get me() {
2969
+ return this._me;
2970
+ }
2971
+ async getMe() {
2972
+ await this.deferredSession.promise;
2973
+ return this._me;
2974
+ }
2975
+ handleSession(ev) {
2976
+ this._me = ev.user;
2977
+ this.deferredSession.resolve();
2978
+ }
2979
+ }
2980
+ ;// ./src/WebSocketChatClient.ts
2981
+
2982
+
2983
+ var WebSocketChatClientEvent = /*#__PURE__*/function (WebSocketChatClientEvent) {
2984
+ WebSocketChatClientEvent["connect"] = "connect";
2985
+ WebSocketChatClientEvent["disconnect"] = "disconnect";
2986
+ WebSocketChatClientEvent["message"] = "message";
2987
+ WebSocketChatClientEvent["error"] = "error";
2988
+ return WebSocketChatClientEvent;
2989
+ }(WebSocketChatClientEvent || {});
2990
+ class WebSocketChatClient extends AbstractChatClient {
2991
+ Event = WebSocketChatClientEvent;
2992
+ state;
2993
+ ws = null;
2994
+ sendQueue = [];
2995
+ connectingTimeoutId;
2996
+ authenticated;
2997
+ authenticatedResolvers = null;
2998
+ connectPromise = null;
2999
+ pingMonitorInterval;
3000
+ inFlightPingTimeout;
3001
+ lastReceivedMessageAt;
3002
+ reconnectEnabled = false;
3003
+ reconnectTimeoutId;
3004
+ reconnectAttempts = 0;
3005
+ constructor(options) {
3006
+ super();
3007
+ this.options = options;
3008
+ if (this.options.stateTracking ?? true) {
3009
+ this.state = new ChatStateTracker(this);
3010
+ }
3011
+ options.ping ??= {};
3012
+ options.ping.enabled ??= true;
3013
+ options.ping.noActivityTimeoutMs ??= 15000;
3014
+ options.ping.pongBackTimeoutMs ??= 5000;
3015
+ }
3016
+ async connect() {
3017
+ this.reconnectEnabled = true;
3018
+ // A manual call does not wait for a scheduled retry.
3019
+ this.cancelScheduledReconnect();
3020
+ if (this.isOpenWsState() || this.isConnectingWsState()) {
3021
+ return this.connectPromise ?? undefined;
3022
+ }
3023
+
3024
+ // Reuse the promise of an attempt that has not settled yet (an
3025
+ // automatic reconnect), so the caller that started connecting is
3026
+ // resolved by whichever attempt eventually authenticates.
3027
+ if (!this.connectPromise) {
3028
+ this.connectPromise = new Promise((...args) => this.authenticatedResolvers = args);
3029
+ // Automatic reconnects create this promise with no one awaiting it,
3030
+ // so its rejection must not surface as an unhandled one. Callers
3031
+ // awaiting it still receive the rejection.
3032
+ this.connectPromise.catch(() => undefined);
3033
+ }
3034
+ const connectPromise = this.connectPromise;
3035
+ this.openSocket();
3036
+ return connectPromise;
3037
+ }
3038
+ disconnect() {
3039
+ const wasActive = this.ws !== null || this.reconnectTimeoutId !== undefined;
3040
+ this.reconnectEnabled = false;
3041
+ this.reconnectAttempts = 0;
3042
+ this.cancelScheduledReconnect();
3043
+ this.releaseSocket(1000); // Normal closure
3044
+ this.failPendingCommands(new Error('Client disconnected before the command was answered'));
3045
+ this.settleConnect(new Error('Client disconnected before authentication'));
3046
+ if (wasActive) {
3047
+ this.emit(this.Event.disconnect, false);
3048
+ }
3049
+ }
3050
+ async send(commandType, commandData) {
3051
+ const envelope = this.createEnvelope(commandType, commandData);
3052
+ const promise = this.createPromiseFromCommandEnvelope(envelope);
3053
+ if (this.isConnectingWsState() || !this.authenticated && this.isOpenWsState()) {
3054
+ this.sendQueue.push(envelope);
3055
+ return promise;
3056
+ }
3057
+ this.sendEnvelope(envelope);
3058
+ return promise;
3059
+ }
3060
+ get isReady() {
3061
+ return this.isOpenWsState() && this.authenticated;
3062
+ }
3063
+ openSocket() {
3064
+ // Never leave a previous socket attached (e.g. one still closing).
3065
+ this.releaseSocket(1000);
3066
+ const params = new URLSearchParams(this.options.queryParams ?? {});
3067
+ params.set('token', this.options.token);
3068
+ let ws;
3069
+ try {
3070
+ ws = new WebSocket(`${this.options.url}?${params}`);
3071
+ } catch (error) {
3072
+ // Invalid URL - no retry can fix that.
3073
+ this.settleConnect(error);
3074
+ return;
3075
+ }
3076
+
3077
+ // Events of an abandoned socket must not touch the current connection.
3078
+ ws.onmessage = ev => ws === this.ws && this.onMessage(ev);
3079
+ ws.onclose = ev => ws === this.ws && this.onClose(ev);
3080
+ // Not every implementation follows a failed handshake with a close
3081
+ // event (e.g. Node.js), so an error alone means the connection is lost.
3082
+ ws.onerror = () => ws === this.ws && this.handleConnectionLoss(true);
3083
+ this.ws = ws;
3084
+ this.authenticated = false;
3085
+ this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), this.options.connectingTimeoutMs ?? 10000);
3086
+ }
3087
+ sendEnvelope(envelope) {
3088
+ if (this.isReady) {
3089
+ this.ws.send(JSON.stringify(envelope));
3090
+ return;
3091
+ }
3092
+ this.handleEnvelopeSendError(envelope, new Error(`Cannot send - client is not ready (state=${this.ws?.readyState ?? '[no connection]'}; authenticated=${this.authenticated})`));
3093
+ }
3094
+ onMessage(event) {
3095
+ this.lastReceivedMessageAt = Date.now();
3096
+ const envelope = JSON.parse(event.data);
3097
+ this.handleIncomingEnvelope(envelope);
3098
+ this.emit(envelope.type, envelope.data);
3099
+ this.emit(this.Event.message, envelope);
3100
+
3101
+ // Login successfully
3102
+ if (!this.authenticated) {
3103
+ const isAuthenticated = envelope.type !== 'Bye';
3104
+ this.authenticated = isAuthenticated;
3105
+ if (isAuthenticated) {
3106
+ this.reconnectAttempts = 0;
3107
+ this.startConnectionMonitor();
3108
+ this.settleConnect();
3109
+ this.emit(this.Event.connect);
3110
+ this.sendFromQueue();
3111
+ } else {
3112
+ this.settleConnect(envelope.data);
3113
+ const error = envelope.data?.reason?.error;
3114
+ if (error?.code === 'AuthenticationException') {
3115
+ // Invalid token - retrying would be rejected the same way.
3116
+ this.handleConnectionLoss(false);
3117
+ this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
3118
+ }
3119
+ }
3120
+ }
3121
+ }
3122
+ onClose(event) {
3123
+ // Connection was closed because of error
3124
+ this.handleConnectionLoss(event.code !== 1000);
3125
+ }
3126
+
3127
+ /**
3128
+ * Abandon the current socket without waiting for its close event (which
3129
+ * may never come, or take minutes on a dead TCP connection), settle
3130
+ * everything that depended on it and schedule a retry when requested.
3131
+ */
3132
+ handleConnectionLoss(reconnect) {
3133
+ this.releaseSocket(reconnect ? 3000 : 1000);
3134
+
3135
+ // The server can no longer answer anything that was queued or in
3136
+ // flight, so settle those promises instead of leaving them pending.
3137
+ this.failPendingCommands(new Error('Connection closed before the command was answered'));
3138
+ reconnect &&= this.reconnectEnabled;
3139
+ if (reconnect) {
3140
+ // Keep a pending connect() promise unsettled - the retry below is
3141
+ // expected to authenticate and will resolve it.
3142
+ this.scheduleReconnect();
3143
+ } else {
3144
+ this.reconnectEnabled = false;
3145
+ this.settleConnect(new Error('Connection closed before authentication'));
3146
+ }
3147
+ this.emit(this.Event.disconnect, reconnect);
3148
+ }
3149
+
3150
+ /**
3151
+ * Detach the current socket from the client and close it if it is still
3152
+ * alive, together with all timers bound to it.
3153
+ */
3154
+ releaseSocket(closeCode) {
3155
+ this.stopConnectionMonitor();
3156
+ clearTimeout(this.connectingTimeoutId);
3157
+ this.connectingTimeoutId = undefined;
3158
+ this.authenticated = false;
3159
+ const ws = this.ws;
3160
+ this.ws = null;
3161
+ if (!ws) {
3162
+ return;
3163
+ }
3164
+ ws.onmessage = ws.onclose = ws.onerror = null;
3165
+ if (ws.readyState === ws.CONNECTING || ws.readyState === ws.OPEN) {
3166
+ try {
3167
+ ws.close(closeCode);
3168
+ } catch {
3169
+ // Nothing more can be done with a broken socket.
3170
+ }
3171
+ }
3172
+ }
3173
+ scheduleReconnect() {
3174
+ this.cancelScheduledReconnect();
3175
+ const minDelay = Math.max(0, this.options.reconnect?.minDelayMs ?? 1000);
3176
+ const maxDelay = Math.max(minDelay, this.options.reconnect?.maxDelayMs ?? 30000);
3177
+ const delay = Math.min(maxDelay, minDelay * 2 ** Math.min(this.reconnectAttempts, 30));
3178
+ this.reconnectAttempts++;
3179
+
3180
+ // Random jitter (50-100% of the delay) keeps clients from reconnecting
3181
+ // in lockstep after a server restart.
3182
+ this.reconnectTimeoutId = setTimeout(() => {
3183
+ this.reconnectTimeoutId = undefined;
3184
+ this.connect().catch(() => undefined);
3185
+ }, delay / 2 + Math.random() * delay / 2);
3186
+ }
3187
+ cancelScheduledReconnect() {
3188
+ clearTimeout(this.reconnectTimeoutId);
3189
+ this.reconnectTimeoutId = undefined;
3190
+ }
3191
+
3192
+ /**
3193
+ * Resolve (or reject, when an error is given) a pending connect() promise.
3194
+ * No-op when there is nothing pending.
3195
+ */
3196
+ settleConnect(error) {
3197
+ const resolvers = this.authenticatedResolvers;
3198
+ this.authenticatedResolvers = null;
3199
+ this.connectPromise = null;
3200
+ if (!resolvers) {
3201
+ return;
3202
+ }
3203
+ error ? resolvers[1](error) : resolvers[0]();
3204
+ }
3205
+
3206
+ /**
3207
+ * Reject every command that has not been answered yet - both the ones still
3208
+ * waiting in the send queue and the ones already sent to the server.
3209
+ */
3210
+ failPendingCommands(error) {
3211
+ const queued = this.sendQueue;
3212
+ this.sendQueue = [];
3213
+ for (const envelope of queued) {
3214
+ this.handleEnvelopeSendError(envelope, error);
3215
+ }
3216
+ this.failAwaitingResponses(error);
3217
+ }
3218
+ sendFromQueue() {
3219
+ // Send awaiting data to server
3220
+ let lastDelay = 0;
3221
+ for (const dataIndex in this.sendQueue) {
3222
+ const envelope = this.sendQueue[dataIndex];
3223
+ setTimeout(() => this.sendEnvelope(envelope), lastDelay);
3224
+ lastDelay += this.options.awaitQueueSendDelayMs ?? 500;
3225
+ }
3226
+ this.sendQueue = [];
3227
+ clearTimeout(this.connectingTimeoutId);
3228
+ }
3229
+ triggerConnectionTimeout() {
3230
+ this.handleConnectionLoss(true);
3231
+ this.emit(this.Event.error, new Error('Connection timeout'));
3232
+ }
3233
+ isConnectingWsState() {
3234
+ return this.ws && this.ws.readyState === this.ws.CONNECTING;
3235
+ }
3236
+ isOpenWsState() {
3237
+ return this.ws && this.ws.readyState === this.ws.OPEN;
3238
+ }
3239
+ startConnectionMonitor() {
3240
+ this.stopConnectionMonitor();
3241
+ if (!this.options.ping.enabled) {
3242
+ return;
3243
+ }
3244
+ this.lastReceivedMessageAt = Date.now();
3245
+ this.pingMonitorInterval = setInterval(async () => {
3246
+ if (!this.isReady || this.inFlightPingTimeout) {
3247
+ return;
3248
+ }
3249
+ if (Date.now() - this.lastReceivedMessageAt < this.options.ping.noActivityTimeoutMs) {
3250
+ return;
3251
+ }
3252
+ this.inFlightPingTimeout = setTimeout(() => {
3253
+ this.inFlightPingTimeout = undefined;
3254
+ // Closing a dead connection can hang in CLOSING for minutes,
3255
+ // so drop it right away instead of waiting for the close event.
3256
+ this.handleConnectionLoss(true);
3257
+ }, this.options.ping.pongBackTimeoutMs);
3258
+
3259
+ // A rejection here means the connection dropped while the ping was
3260
+ // in flight; the loss is already handled, so just stop waiting.
3261
+ this.send('Ping', {}).catch(() => undefined).then(() => {
3262
+ clearTimeout(this.inFlightPingTimeout);
3263
+ this.inFlightPingTimeout = undefined;
3264
+ });
3265
+ }, 1000);
3266
+ }
3267
+ stopConnectionMonitor() {
3268
+ if (this.inFlightPingTimeout) {
3269
+ clearTimeout(this.inFlightPingTimeout);
3270
+ this.inFlightPingTimeout = undefined;
3271
+ }
3272
+ if (this.pingMonitorInterval) {
3273
+ clearInterval(this.pingMonitorInterval);
3274
+ this.pingMonitorInterval = undefined;
3275
+ }
3276
+ }
3277
+ }
3278
+ ;// ./src/WebApiChatClient.ts
3279
+
3280
+ var WebApiChatClientEvent = /*#__PURE__*/function (WebApiChatClientEvent) {
3281
+ WebApiChatClientEvent["message"] = "message";
3282
+ WebApiChatClientEvent["error"] = "error";
3283
+ WebApiChatClientEvent["destroy"] = "destroy";
3284
+ return WebApiChatClientEvent;
3285
+ }(WebApiChatClientEvent || {});
3286
+ class WebApiChatClient extends AbstractChatClient {
3287
+ Event = WebApiChatClientEvent;
3288
+ sendStack = [];
3289
+ constructor(options) {
3290
+ super();
3291
+ this.options = options;
3292
+ }
3293
+ async send(commandType, commandData) {
3294
+ const envelope = this.createEnvelope(commandType, commandData);
3295
+ const item = {
3296
+ data: envelope,
3297
+ attempts: 0,
3298
+ lastTimeoutId: null
3299
+ };
3300
+ this.sendStack.push(item);
3301
+ this.makeApiCall(item);
3302
+ return this.createPromiseFromCommandEnvelope(envelope);
3303
+ }
3304
+ destroy() {
3305
+ // Cancel all awaiting requests, rejecting their promises so no caller
3306
+ // is left awaiting forever
3307
+ const pending = this.sendStack;
3308
+ this.sendStack = [];
3309
+ pending.forEach(item => {
3310
+ if (item.lastTimeoutId) {
3311
+ clearTimeout(item.lastTimeoutId);
3312
+ }
3313
+ this.handleEnvelopeSendError(item.data, new Error('Client destroyed'));
3314
+ });
3315
+ this.emit(this.Event.destroy, false);
3316
+ }
3317
+ async onMessage(item, response) {
3318
+ let envelope;
3319
+ try {
3320
+ envelope = await response.json();
3321
+ } catch (e) {
3322
+ // Non-envelope response (e.g. a proxy error page) - failed attempt
3323
+ this.onError(item, `envelope ${item.data.ref} (HTTP ${response.status}, unparsable body)`);
3324
+ return;
3325
+ }
3326
+ if (!this.removeFromStack(item)) {
3327
+ return; // Destroyed in the meantime - the promise is already rejected
3328
+ }
3329
+ this.handleIncomingEnvelope(envelope);
3330
+ this.emit(envelope.type, envelope.data);
3331
+ this.emit(this.Event.message, envelope);
3332
+ }
3333
+ onError(item, body) {
3334
+ if (!this.sendStack.includes(item)) {
3335
+ return; // Destroyed in the meantime
3336
+ }
3337
+ if (item.attempts >= (this.options.attemptsToSend ?? 10)) {
3338
+ this.removeFromStack(item);
3339
+ this.handleEnvelopeSendError(item.data, new Error(`Cannot send ${body}; aborting after reaching the maximum connection errors`));
3340
+ return;
3341
+ }
3342
+ item.lastTimeoutId = setTimeout(() => this.makeApiCall(item), this.options.attemptDelayMs ?? 3000);
3343
+ }
3344
+ makeApiCall(item) {
3345
+ if (!this.sendStack.includes(item)) {
3346
+ return; // Destroyed before this (re)try fired
3347
+ }
3348
+ item.attempts++;
3349
+ item.lastTimeoutId = null;
3350
+ const bodyJson = JSON.stringify(item.data);
3351
+ const headers = {
3352
+ 'Content-Type': 'application/json',
3353
+ Accept: 'application/json'
3354
+ };
3355
+ headers.Authorization = `Bearer ${this.options.token}`;
3356
+ const query = new URLSearchParams(this.options.queryParams ?? {}).toString();
3357
+ const url = query ? `${this.options.url}?${query}` : this.options.url;
3358
+ fetch(url, {
3359
+ headers,
3360
+ body: bodyJson,
3361
+ method: 'POST'
3362
+ }).then(response => this.onMessage(item, response)).catch(() => this.onError(item, bodyJson));
3363
+ }
3364
+ removeFromStack(item) {
3365
+ const index = this.sendStack.indexOf(item);
3366
+ if (index === -1) {
3367
+ return false;
3368
+ }
3369
+ this.sendStack.splice(index, 1);
3370
+ return true;
3371
+ }
3372
+ }
3373
+ ;// ./src/AbstractRestClient.ts
3374
+ class AbstractRestClient {
3375
+ constructor(options) {
3376
+ this.options = options;
3377
+ }
3378
+ async send(method, uri, data = undefined, additionalHeaders = {}) {
3379
+ let url = this.getUrl(uri);
3380
+ let body = undefined;
3381
+ if (data) {
3382
+ if (['GET', 'DELETE'].includes(method)) {
3383
+ url += '?' + new URLSearchParams(data).toString();
3384
+ } else {
3385
+ body = JSON.stringify(data);
3386
+ }
3387
+ }
3388
+ const headers = {
3389
+ 'Content-Type': 'application/json',
3390
+ Accept: 'application/json',
3391
+ ...additionalHeaders,
3392
+ ...this.getAuthHeaders()
3393
+ };
3394
+ const result = await fetch(url, {
3395
+ method,
3396
+ body,
3397
+ headers
3398
+ });
3399
+ return this.convertFetchResponse(result);
3400
+ }
3401
+ getAuthHeaders() {
3402
+ const headers = {};
3403
+ if (this.options.token) {
3404
+ headers.Authorization = `Bearer ${this.options.token}`;
3405
+ }
3406
+ return headers;
3407
+ }
3408
+ getUrl(uri) {
3409
+ return this.removeEndingSlash(this.options.url ?? this.defaultUrl) + '/' + this.removeStartingSlash(uri);
3410
+ }
3411
+ async convertFetchResponse(result) {
3412
+ return {
3413
+ ok: result.ok,
3414
+ status: result.status,
3415
+ data: result.headers.get('content-type')?.includes('json') ? await result.json() : await result.text()
3416
+ };
3417
+ }
3418
+ removeStartingSlash(text) {
3419
+ return text.replace(/^\/+/, '');
3420
+ }
3421
+ removeEndingSlash(text) {
3422
+ return text.replace(/\/+$/, '');
3423
+ }
3424
+ }
3425
+ ;// ./src/FilesClient.ts
3426
+
3427
+ class FilesClient extends AbstractRestClient {
3428
+ defaultUrl = 'https://files.devana.pl';
3429
+ async uploadFile(file) {
3430
+ const name = encodeURIComponent(file.name ?? '');
3431
+ let headers = {
3432
+ ...this.getAuthHeaders(),
3433
+ Accept: 'application/json',
3434
+ 'Content-Disposition': `attachment; filename="${name}"`,
3435
+ 'Content-Length': file.size
3436
+ };
3437
+ const response = await fetch(this.getUrl('files'), {
3438
+ method: 'POST',
3439
+ body: file,
3440
+ headers
3441
+ });
3442
+ return this.convertFetchResponse(response);
3443
+ }
3444
+ async getFileMeta(id) {
3445
+ return this.send('GET', 'files/' + id);
3446
+ }
3447
+ async getFileMetaBulk(ids) {
3448
+ const searchParams = new URLSearchParams();
3449
+ ids.forEach(id => searchParams.append('id[]', id));
3450
+ return this.send('GET', 'files?' + searchParams);
3451
+ }
3452
+ }
3453
+ ;// ./src/protocol/schemes/events/Error.ts
3454
+ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
3455
+ ErrorCode["Authentication"] = "AuthenticationException";
3456
+ ErrorCode["CommandRateLimitExceeded"] = "CommandRateLimitExceededException";
3457
+ ErrorCode["InvalidSearchQuery"] = "InvalidSearchQueryException";
3458
+ ErrorCode["MessageSearchUnavailable"] = "MessageSearchUnavailableException";
3459
+ ErrorCode["MessageNotFound"] = "MessageNotFoundException";
3460
+ ErrorCode["RoomNotFound"] = "RoomNotFoundException";
3461
+ ErrorCode["TopicNotFound"] = "TopicNotFoundException";
3462
+ ErrorCode["UserNotFound"] = "UserNotFoundException";
3463
+ return ErrorCode;
3464
+ }({});
3465
+ ;// ./src/protocol/schemes/User.ts
3466
+ /**
3467
+ * Availability of a user, aggregated over all of their sessions.
3468
+ *
3469
+ * - `Offline` - no session is connected and none can be reached asynchronously.
3470
+ * - `Online` - at least one session holds a live connection.
3471
+ * - `OnlineAsync` - no live connection, but a push-registered device was active
3472
+ * recently, so a message will still reach the user.
3473
+ */
3474
+ let UserStatus = /*#__PURE__*/function (UserStatus) {
3475
+ UserStatus[UserStatus["Offline"] = 0] = "Offline";
3476
+ UserStatus[UserStatus["Online"] = 1] = "Online";
3477
+ UserStatus[UserStatus["OnlineAsync"] = 2] = "OnlineAsync";
3478
+ return UserStatus;
3479
+ }({});
3480
+ ;// ./src/protocol/schemes/Role.ts
3481
+ /**
3482
+ * Bit flags of a role, stored in {@link Role.flags}.
3483
+ *
3484
+ * - `SeparateOnMembersList` - available holders of the role are listed in their
3485
+ * own group of the members list, headed by the role name.
3486
+ * - `MentionableByEveryone` - anybody may mention the role with notification
3487
+ * effects; without it the mention is decorative only, unless the author holds
3488
+ * the `MentionAllRoles` permission.
3489
+ */
3490
+ let RoleFlag = /*#__PURE__*/function (RoleFlag) {
3491
+ RoleFlag[RoleFlag["SeparateOnMembersList"] = 1] = "SeparateOnMembersList";
3492
+ RoleFlag[RoleFlag["MentionableByEveryone"] = 2] = "MentionableByEveryone";
3493
+ return RoleFlag;
3494
+ }({});
3495
+ ;// ./src/protocol/schemes/Entitlements.ts
3496
+ /**
3497
+ * What a package is attached to. A space package and a user package never describe the same
3498
+ * feature, so entitlements of the two targets are never merged, summed or prioritised.
3499
+ */
3500
+
3501
+ /**
3502
+ * Subject the entitlements belong to, as the billing service knows it.
3503
+ */
3504
+
3505
+ /**
3506
+ * Value of a single entitlement: a flag, a numeric limit ({@link NO_LIMIT} means unlimited)
3507
+ * or a dictionary value. A dictionary states its numbers as strings.
3508
+ */
3509
+
3510
+ /**
3511
+ * Entitlement keys granted by the package, keyed by {@link SpaceFeature} or {@link UserFeature}.
3512
+ * A feature the package does not grant is simply absent.
3513
+ */
3514
+
3515
+ /**
3516
+ * What the modules of the chat server add to the answer of `GetEntitlements`. The package says
3517
+ * how much a subject may take, these say how much of it is already gone.
3518
+ */
3519
+
3520
+ /**
3521
+ * Value of a numeric limit that is not limited at all.
3522
+ */
3523
+ const NO_LIMIT = -1;
3524
+
3525
+ /**
3526
+ * Entitlement keys of space packages.
3527
+ */
3528
+ let SpaceFeature = /*#__PURE__*/function (SpaceFeature) {
3529
+ SpaceFeature["MembersLimit"] = "space.members.limit";
3530
+ SpaceFeature["MembersGuests"] = "space.members.guests";
3531
+ SpaceFeature["RoomsLimit"] = "space.rooms.limit";
3532
+ SpaceFeature["RoomsPrivateLimit"] = "space.rooms.private_limit";
3533
+ SpaceFeature["RoomsArchive"] = "space.rooms.archive";
3534
+ SpaceFeature["RoomsHistoryRotation"] = "space.rooms.history_rotation";
3535
+ SpaceFeature["EmoticonsLimit"] = "space.emoticons.limit";
3536
+ SpaceFeature["MessageLength"] = "space.message.length";
3537
+ SpaceFeature["StorageLimit"] = "space.storage.limit";
3538
+ SpaceFeature["StorageSingleFileLimit"] = "space.storage.single_file_limit";
3539
+ SpaceFeature["AccessWhitelist"] = "space.access.whitelist";
3540
+ SpaceFeature["SearchRange"] = "space.search.range";
3541
+ SpaceFeature["ContentExport"] = "space.content.export";
3542
+ SpaceFeature["ContentAuditLog"] = "space.content.auditlog";
3543
+ SpaceFeature["AvMemberLimit"] = "space.av.member_limit";
3544
+ SpaceFeature["AvBroadcasterLimit"] = "space.av.broadcaster_limit";
3545
+ SpaceFeature["AvQuality"] = "space.av.quality";
3546
+ SpaceFeature["UiPurpose"] = "app.ui.purpose";
3547
+ SpaceFeature["ApiAccess"] = "app.api.access";
3548
+ SpaceFeature["DataSovereignty"] = "app.data.sovereignty";
3549
+ SpaceFeature["Support"] = "app.support";
3550
+ return SpaceFeature;
3551
+ }({});
3552
+
3553
+ /**
3554
+ * Entitlement keys of user packages.
3555
+ */
3556
+ let UserFeature = /*#__PURE__*/function (UserFeature) {
3557
+ UserFeature["MessageLength"] = "user.message.length";
3558
+ UserFeature["StorageLimit"] = "user.storage.limit";
3559
+ UserFeature["StorageSingleFileLimit"] = "user.storage.single_file_limit";
3560
+ return UserFeature;
3561
+ }({});
3562
+
3563
+ /**
3564
+ * How far back a room of the space may be told to keep its history.
3565
+ */
3566
+ let HistoryRotation = /*#__PURE__*/function (HistoryRotation) {
3567
+ HistoryRotation["Low"] = "low";
3568
+ HistoryRotation["High"] = "high";
3569
+ return HistoryRotation;
3570
+ }({});
3571
+
3572
+ /**
3573
+ * What the space is for; a space for work gets the simplified interface.
3574
+ */
3575
+ let UiPurpose = /*#__PURE__*/function (UiPurpose) {
3576
+ UiPurpose["Work"] = "work";
3577
+ UiPurpose["Fun"] = "fun";
3578
+ return UiPurpose;
3579
+ }({});
3580
+
3581
+ /**
3582
+ * How much of the space search reaches.
3583
+ */
3584
+ let SearchRange = /*#__PURE__*/function (SearchRange) {
3585
+ SearchRange["JoinedRooms"] = "joined_rooms";
3586
+ SearchRange["AvailableRooms"] = "available_rooms";
3587
+ return SearchRange;
3588
+ }({});
3589
+
3590
+ /**
3591
+ * Every storage entitlement is stated in megabytes.
3592
+ */
3593
+ const STORAGE_UNIT_BYTES = 1024 * 1024;
3594
+ ;// ./src/protocol/schemes/Space.ts
3595
+ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
3596
+ SpaceIntent["Community"] = "Community";
3597
+ SpaceIntent["Friends"] = "Friends";
3598
+ SpaceIntent["Team"] = "Team";
3599
+ return SpaceIntent;
3600
+ }({});
3601
+ ;// ./src/index.ts
3602
+
3603
+
3604
+
3605
+
3606
+
3607
+
3608
+
3609
+
3610
+
3611
+ export { AbstractRestClient, ErrorCode, FilesClient, HistoryRotation, IndexedCollection, IndexedObjectCollection, Layer, NO_LIMIT, ObservableIndexedCollection, ObservableIndexedObjectCollection, PermissionDefinition, Permissions, RoleFlag, STORAGE_UNIT_BYTES, SearchRange, SpaceFeature, SpaceIntent, UiPurpose, UserFeature, UserStatus, WebApiChatClient, WebSocketChatClient, extractUserFromMember };
3612
+
3613
+ //# sourceMappingURL=index.mjs.map