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