@devanachat/sdk 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,50 @@ All notable changes to this project are documented in this file.
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project follows
5
5
  [semver](https://semver.org) (`0.x` minor releases may break the API).
6
6
 
7
+ ## [0.7.0] - Unreleased
8
+
9
+ ### Added
10
+
11
+ - `SearchMessages` command (answered with `FoundMessages` or an `Error`), typed end to end:
12
+ `client.send('SearchMessages', {query, spaceId, privateMessages, from, in, before, after, during, hasFile, timezone, cursor})`.
13
+ `query` is plain text (words and `"phrases"`, the last word is a prefix); the server recognises no modifiers, so
14
+ the filters (`from`, `in`, `before`, `after`, `during`, `hasFile`) are fields of the command, and parsing a search
15
+ syntax such as `from:ania` is up to the application.
16
+ Results come newest first in pages of 25; pass the returned `cursor` to get the next page (`null` means the end).
17
+ Each result carries the `message`, its `spaceId` and `ranges` of the matches (`{start, end}` in UTF-16 units,
18
+ `end` exclusive, so `content.slice(start, end)` works). Whether the user is in the room of a result is not part of
19
+ it - check your rooms: `(await client.state.rooms.get()).has(roomId)`.
20
+ - Type exports `SearchMessages`, `SearchDate`, `FoundMessages`, `FoundMessage` and `TextRange`.
21
+ - **Room preview** - the history of a room you have not joined (the `PreviewRooms` permission):
22
+ `client.state.rooms.messages.getRoomHistory(roomId)` of a room you have not joined returns a `RoomMessagesHistory` with
23
+ `isPreview` set, whose
24
+ `getMessagesWindow(topicId)` gives the usual `TopicHistoryWindow` (`resetToLatest`, `fetchPrevious`, `fetchNext`,
25
+ `jumpTo`, mirrors, `change`). No events reach such windows; at the latest messages `fetchNext()` fetches the newer
26
+ ones (and loads the latest in a window not fetched yet). It sends only reads - no `Ack`, no change of the unread counters, the room is not added to your rooms. Release it
27
+ with `forgetRoomPreview(roomId)`; joining the room replaces it with the regular history. The default topic is
28
+ `RoomSummary.defaultTopicId`.
29
+ - `PreviewRooms` (`1 << 24`) and `SearchMessages` (`1 << 25`) permissions in `Permissions.list`, definable on a space or
30
+ a room.
31
+ - `RoomSummary.defaultTopicId`: the default topic of the room, given to everyone who may read it (`null` otherwise).
32
+ - `ErrorCode` enum with the codes worth telling apart (`InvalidSearchQueryException`,
33
+ `MessageSearchUnavailableException`, `RoomNotFoundException`, `UserNotFoundException`, ...).
34
+
35
+ ### Changed
36
+
37
+ - `rooms.messages.getRoomHistory(roomId)` never resolves to `undefined`: for a room you have not joined (also one you
38
+ have left, or an unknown id) it gives the preview history, whose fetch methods throw an `Error`
39
+ without access. Tell a joined room by `history.isPreview` or by your rooms.
40
+ - `permissions.check()` and `calculatePermissions()` work for a room or a space you have not joined: they ask the server
41
+ (`GetComputedPermissions`) instead of throwing.
42
+ - Server `feature/search` semantics: `GetRoomMembers`, `GetMessages` (also `around`),
43
+ `GetTopics` and `GetReactionDetails` accept a non-member with `PreviewRooms`; `GetPermissionOverwriteTargets`
44
+ always returns the former members of a room (their overwrites still apply); `GetComputedPermissions`,
45
+ `GetPermissionOverwrites` and `GetOwners` can be read in a room by a user with `ManagePermissions` who is not a
46
+ member. Commands of participation (`CreateMessage`, `React`, `Ack`, ...) still need the membership
47
+ (`UserNotFoundException`).
48
+
49
+ Migrating from `polfan-server-js-client` 0.5.0: see [docs/migration-0.5-to-0.7.md](docs/migration-0.5-to-0.7.md).
50
+
7
51
  ## [0.6.0] - Unreleased
8
52
 
9
53
  The first release under the new name. Earlier versions were published as `polfan-server-js-client`.
package/README.md CHANGED
@@ -251,6 +251,30 @@ await topicWindow!.jumpTo('message-id');
251
251
  `topicWindow.state` tells which part of the history is loaded (`LIVE`, `LATEST`, `PAST`, `OLDEST`). Set `topicWindow.limit` to cap
252
252
  how many messages a window keeps in memory - the oldest are dropped when it grows over it.
253
253
 
254
+ ### Preview a room you have not joined
255
+
256
+ With the `PreviewRooms` permission you can read a room without joining it. `getRoomHistory()` of a room you have not
257
+ joined gives its preview (`history.isPreview`); the windows are the same as above, except that no events reach them -
258
+ at the latest messages `fetchNext()` asks the server for the newer ones. Nothing is marked as read and the room does
259
+ not join your rooms.
260
+
261
+ ```ts
262
+ const {hasAll} = await client.state!.permissions.check(['PreviewRooms'], {roomId: 'room-id'});
263
+ const {data} = await client.send('GetRoomSummary', {location: {roomId: 'room-id'}});
264
+
265
+ if (hasAll && data?.summary.defaultTopicId) {
266
+ const history = await client.state!.rooms.messages.getRoomHistory('room-id');
267
+ const topicWindow = await history.getMessagesWindow(data.summary.defaultTopicId); // Or the id of a thread
268
+
269
+ await topicWindow!.jumpTo('message-id'); // Or resetToLatest()
270
+ await topicWindow!.fetchNext(); // At the latest messages: fetch those written since
271
+
272
+ client.state!.rooms.messages.forgetRoomPreview('room-id'); // When the preview is closed
273
+ }
274
+ ```
275
+
276
+ Once you join the room, `getRoomHistory()` returns its regular history and the preview is dropped.
277
+
254
278
  ### Unread messages and mentions
255
279
 
256
280
  ```ts
@@ -287,6 +311,9 @@ client.state!.permissions.on('change', () => {
287
311
  });
288
312
  ```
289
313
 
314
+ For a room or a space you have not joined (e.g. `PreviewRooms` of a room to preview), `check()` asks the server, every
315
+ time - the `change` event does not cover such locations.
316
+
290
317
  The full list of permissions is in `Permissions.list`.
291
318
 
292
319
  ### Users and relationships
@@ -40,6 +40,7 @@ __webpack_require__.r(__webpack_exports__);
40
40
  // EXPORTS
41
41
  __webpack_require__.d(__webpack_exports__, {
42
42
  AbstractRestClient: () => (/* reexport */ AbstractRestClient),
43
+ ErrorCode: () => (/* reexport */ ErrorCode),
43
44
  FilesClient: () => (/* reexport */ FilesClient),
44
45
  HistoryRotation: () => (/* reexport */ HistoryRotation),
45
46
  IndexedCollection: () => (/* reexport */ IndexedCollection),
@@ -589,7 +590,17 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
589
590
  this.emitChangeWithDiff(true, originalState);
590
591
  }
591
592
  async fetchNext() {
592
- if (this.internalState.ongoing || this.hasLatest) {
593
+ if (this.hasLatest) {
594
+ return;
595
+ }
596
+ return this.fetchAfterLast();
597
+ }
598
+
599
+ /**
600
+ * Append the items that follow the last one in the window; an empty window gets the latest items.
601
+ */
602
+ async fetchAfterLast() {
603
+ if (this.internalState.ongoing) {
593
604
  return;
594
605
  }
595
606
  let result;
@@ -602,7 +613,7 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
602
613
  this.internalState.ongoing = undefined;
603
614
  }
604
615
  if (!result) {
605
- await this.resetToLatest();
616
+ await this.resetToLatest(true);
606
617
  return;
607
618
  }
608
619
  if (result.length) {
@@ -712,23 +723,31 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
712
723
  /**
713
724
  * The window does not subscribe to the client itself - the messages manager routes the events of its topic to it.
714
725
  */
715
- constructor(roomId, topicId, tracker) {
726
+ constructor(roomId, topicId, tracker, preview = false) {
716
727
  super('id');
717
728
  this.roomId = roomId;
718
729
  this.topicId = topicId;
719
730
  this.tracker = tracker;
731
+ this.preview = preview;
720
732
  this.internalState.traverseLock = false;
721
- this.internalState.includeMyReactions = true;
733
+ this.internalState.includeMyReactions = !preview;
722
734
  this.internalState.myReactions = {};
723
735
  this.internalState.liveLimit = 50;
724
736
  }
725
737
  createMirror() {
726
- const copy = new TopicHistoryWindow(this.roomId, this.topicId, this.tracker);
738
+ const copy = new TopicHistoryWindow(this.roomId, this.topicId, this.tracker, this.preview);
727
739
  copy.eventTarget = this.eventTarget;
728
740
  copy._items = this._items;
729
741
  copy.internalState = this.internalState;
730
742
  return copy;
731
743
  }
744
+
745
+ /**
746
+ * Window of a room you have not joined. It gets no live messages - at the latest ones fetchNext() fetches the newer.
747
+ */
748
+ get isPreview() {
749
+ return this.preview;
750
+ }
732
751
  get isTraverseLocked() {
733
752
  return this.internalState.traverseLock;
734
753
  }
@@ -779,6 +798,9 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
779
798
  if (this.internalState.traverseLock) {
780
799
  return;
781
800
  }
801
+ if (this.preview && this.hasLatest) {
802
+ return this.fetchAfterLast(); // No events reach a preview
803
+ }
782
804
  return super.fetchNext();
783
805
  }
784
806
  async fetchPrevious() {
@@ -871,6 +893,17 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
871
893
  this.internalState.myReactions = next;
872
894
  }
873
895
  async getTopic() {
896
+ if (this.preview) {
897
+ // The tracker holds the topics of the joined rooms only
898
+ const result = await this.tracker.client.send('GetTopics', {
899
+ roomId: this.roomId,
900
+ topicIds: [this.topicId]
901
+ });
902
+ if (result.error) {
903
+ throw new Error(`Cannot fetch topic: ${result.error.message}`);
904
+ }
905
+ return result.data.topics.find(topic => topic.id === this.topicId);
906
+ }
874
907
  return (await this.tracker.rooms.getTopics(this.roomId, [this.topicId])).get(this.topicId);
875
908
  }
876
909
  async getLatestMessageId() {
@@ -985,13 +1018,20 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
985
1018
  * dropped together with its room stops receiving them.
986
1019
  */
987
1020
  class RoomMessagesHistory {
1021
+ isPreview;
1022
+ roomId;
988
1023
  historyWindows = new IndexedCollection();
989
1024
  traverseLock = false;
1025
+ room;
990
1026
  constructor(room, tracker) {
991
- this.room = room;
992
1027
  this.tracker = tracker;
993
- this.updateTraverseLock(this.room);
994
- if (this.room.defaultTopic) {
1028
+ this.roomId = typeof room === 'string' ? room : room.id;
1029
+ this.room = typeof room === 'string' ? null : room;
1030
+ this.isPreview = this.room === null;
1031
+ if (this.room) {
1032
+ this.updateTraverseLock(this.room);
1033
+ }
1034
+ if (this.room?.defaultTopic) {
995
1035
  this.createHistoryWindowForTopic(this.room.defaultTopic);
996
1036
  }
997
1037
  }
@@ -1003,9 +1043,13 @@ class RoomMessagesHistory {
1003
1043
  */
1004
1044
  async getMessagesWindow(topicId, peek = false) {
1005
1045
  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);
1046
+ if (this.isPreview) {
1047
+ this.createHistoryWindow(topicId);
1048
+ } else {
1049
+ const topic = (await this.tracker.rooms.getTopics(this.roomId, [topicId])).get(topicId);
1050
+ if (topic) {
1051
+ this.createHistoryWindowForTopic(topic);
1052
+ }
1009
1053
  }
1010
1054
  }
1011
1055
  return this.historyWindows.get(topicId);
@@ -1118,9 +1162,18 @@ class RoomMessagesHistory {
1118
1162
  if (this.historyWindows.has(topic.id)) {
1119
1163
  return;
1120
1164
  }
1121
- const historyWindow = new TopicHistoryWindow(this.room.id, topic.id, this.tracker);
1165
+ this.createHistoryWindow(topic.id);
1166
+
1167
+ // If new topic refers to some message from this room, update other structures
1168
+ if (topic.refMessage) {
1169
+ const refHistoryWindow = this.historyWindows.get(topic.refMessage.location.topicId);
1170
+ refHistoryWindow?._updateMessageReference(topic);
1171
+ }
1172
+ }
1173
+ createHistoryWindow(topicId) {
1174
+ const historyWindow = new TopicHistoryWindow(this.roomId, topicId, this.tracker, this.isPreview);
1122
1175
  void historyWindow.setTraverseLock(this.traverseLock);
1123
- this.historyWindows.set([topic.id, historyWindow]);
1176
+ this.historyWindows.set([topicId, historyWindow]);
1124
1177
 
1125
1178
  // Current behavior of deletion a message with referenced topic is to delete the whole side topic
1126
1179
  // So we need to listen for topic deletions here
@@ -1128,14 +1181,8 @@ class RoomMessagesHistory {
1128
1181
  for (const topicId of deletedTopicIds) {
1129
1182
  this.historyWindows.delete(topicId);
1130
1183
  }
1131
- this.tracker.rooms._deleteTopicsFromRoom(this.room.id, ...deletedTopicIds);
1184
+ this.tracker.rooms._deleteTopicsFromRoom(this.roomId, ...deletedTopicIds);
1132
1185
  });
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
1186
  }
1140
1187
  updateTraverseLock(room) {
1141
1188
  this.traverseLock = room.history.mode === 'Ephemeral';
@@ -1147,6 +1194,7 @@ class RoomMessagesHistory {
1147
1194
 
1148
1195
  class MessagesManager {
1149
1196
  roomHistories = new IndexedCollection();
1197
+ previewHistories = new IndexedCollection();
1150
1198
  deferredSession = new DeferredTask();
1151
1199
  constructor(tracker) {
1152
1200
  this.tracker = tracker;
@@ -1167,11 +1215,21 @@ class MessagesManager {
1167
1215
  }
1168
1216
 
1169
1217
  /**
1170
- * Get history manager for given room ID.
1218
+ * Get history manager for given room ID. For a room you have not joined it is a preview (requires `PreviewRooms`),
1219
+ * kept until {@link forgetRoomPreview} or until you join the room.
1171
1220
  */
1172
1221
  async getRoomHistory(roomId) {
1173
1222
  await this.deferredSession.promise;
1174
- return this.roomHistories.get(roomId);
1223
+ if (this.roomHistories.has(roomId)) {
1224
+ return this.roomHistories.get(roomId);
1225
+ }
1226
+ if (!this.previewHistories.has(roomId)) {
1227
+ this.previewHistories.set([roomId, new RoomMessagesHistory(roomId, this.tracker)]);
1228
+ }
1229
+ return this.previewHistories.get(roomId);
1230
+ }
1231
+ forgetRoomPreview(roomId) {
1232
+ this.previewHistories.delete(roomId);
1175
1233
  }
1176
1234
 
1177
1235
  /**
@@ -1179,8 +1237,10 @@ class MessagesManager {
1179
1237
  * @internal
1180
1238
  */
1181
1239
  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));
1240
+ // Try to get last message from history window (if cached); not getRoomHistory(), it would create a preview
1241
+ await this.deferredSession.promise;
1242
+ const historyWindow = await this.roomHistories.get(location.roomId)?.getMessagesWindow(location.topicId, true);
1243
+ let message = historyWindow?.hasLatest && historyWindow.getAt(historyWindow.length - 1);
1184
1244
  if (!message) {
1185
1245
  const result = await this.tracker.client.send('GetMessages', {
1186
1246
  location,
@@ -1196,6 +1256,7 @@ class MessagesManager {
1196
1256
  }
1197
1257
  }
1198
1258
  createHistoryForNewRoom(room) {
1259
+ this.previewHistories.delete(room.id);
1199
1260
  this.roomHistories.set([room.id, new RoomMessagesHistory(room, this.tracker)]);
1200
1261
  }
1201
1262
  handleRoomDeleted(ev) {
@@ -2415,6 +2476,14 @@ class Permissions {
2415
2476
  MentionAllRoles: {
2416
2477
  value: 1 << 23,
2417
2478
  maxLayer: Layer.Topic
2479
+ },
2480
+ PreviewRooms: {
2481
+ value: 1 << 24,
2482
+ maxLayer: Layer.Room
2483
+ },
2484
+ SearchMessages: {
2485
+ value: 1 << 25,
2486
+ maxLayer: Layer.Room
2418
2487
  }
2419
2488
  };
2420
2489
  static getNames() {
@@ -2492,6 +2561,10 @@ class PermissionsManager extends EventTarget {
2492
2561
  missing
2493
2562
  };
2494
2563
  }
2564
+
2565
+ /**
2566
+ * For a room or a space you have not joined the permissions are fetched from the server, on every call.
2567
+ */
2495
2568
  async calculatePermissions(location) {
2496
2569
  const room = location.roomId ? (await this.tracker.rooms.get()).get(location.roomId) : null;
2497
2570
  location = {
@@ -2500,6 +2573,9 @@ class PermissionsManager extends EventTarget {
2500
2573
  topicId: location.topicId
2501
2574
  };
2502
2575
  this.validateLocation(location);
2576
+ if (location.roomId && !room || location.spaceId && !(await this.tracker.spaces.get())?.has(location.spaceId)) {
2577
+ return this.fetchComputedPermissions(location);
2578
+ }
2503
2579
  const userId = (await this.tracker.getMe()).id;
2504
2580
  const [spaceMember, roomMember] = await this.fetchMembersOrFail(location);
2505
2581
  const userRoles = [...(spaceMember?.roles ?? []), ...(roomMember?.roles ?? [])];
@@ -2665,6 +2741,15 @@ class PermissionsManager extends EventTarget {
2665
2741
  }
2666
2742
  return result;
2667
2743
  }
2744
+ async fetchComputedPermissions(location) {
2745
+ const result = await this.tracker.client.send('GetComputedPermissions', {
2746
+ location
2747
+ });
2748
+ if (result.error) {
2749
+ throw result.error;
2750
+ }
2751
+ return result.data.permissions;
2752
+ }
2668
2753
  async fetchMembersOrFail(location) {
2669
2754
  const results = await Promise.all([location.spaceId ? this.tracker.spaces.getMe(location.spaceId) : null, location.roomId ? this.tracker.rooms.getMe(location.roomId) : null]);
2670
2755
  const spaceFail = location.spaceId && !results[0];
@@ -3407,6 +3492,18 @@ class FilesClient extends AbstractRestClient {
3407
3492
  return this.send('GET', 'files?' + searchParams);
3408
3493
  }
3409
3494
  }
3495
+ ;// ./src/protocol/schemes/events/Error.ts
3496
+ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
3497
+ ErrorCode["Authentication"] = "AuthenticationException";
3498
+ ErrorCode["CommandRateLimitExceeded"] = "CommandRateLimitExceededException";
3499
+ ErrorCode["InvalidSearchQuery"] = "InvalidSearchQueryException";
3500
+ ErrorCode["MessageSearchUnavailable"] = "MessageSearchUnavailableException";
3501
+ ErrorCode["MessageNotFound"] = "MessageNotFoundException";
3502
+ ErrorCode["RoomNotFound"] = "RoomNotFoundException";
3503
+ ErrorCode["TopicNotFound"] = "TopicNotFoundException";
3504
+ ErrorCode["UserNotFound"] = "UserNotFoundException";
3505
+ return ErrorCode;
3506
+ }({});
3410
3507
  ;// ./src/protocol/schemes/User.ts
3411
3508
  /**
3412
3509
  * Availability of a user, aggregated over all of their sessions.