@ermis-network/ermis-chat-sdk 1.0.5 → 1.0.7

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.
@@ -938,10 +938,9 @@ var Channel = class {
938
938
  };
939
939
  this.state.addMessageSorted(optimisticMessage);
940
940
  try {
941
- return await this.getClient().post(
942
- this._channelURL() + "/message",
943
- { message: { ...message } }
944
- );
941
+ return await this.getClient().post(this._channelURL() + "/message", {
942
+ message: { ...message }
943
+ });
945
944
  } catch (error) {
946
945
  const isOfflineError = !error.response || error.code === "ERR_NETWORK" || error.isWSFailure || !this.getClient().wsConnection?.isHealthy;
947
946
  const statusToSet = isOfflineError ? "failed_offline" : "error";
@@ -966,10 +965,9 @@ var Channel = class {
966
965
  messagePayload.show_in_channel = stateMsg.show_in_channel;
967
966
  }
968
967
  try {
969
- return await this.getClient().post(
970
- this._channelURL() + "/message",
971
- { message: messagePayload }
972
- );
968
+ return await this.getClient().post(this._channelURL() + "/message", {
969
+ message: messagePayload
970
+ });
973
971
  } catch (error) {
974
972
  const isOfflineError = !error.response || error.code === "ERR_NETWORK" || error.isWSFailure || !this.getClient().wsConnection?.isHealthy;
975
973
  this.state.updateMessageStatus(messageId, isOfflineError ? "failed_offline" : "error");
@@ -1010,6 +1008,44 @@ var Channel = class {
1010
1008
  this.getClient().baseURL + `/messages/${this.type}/${this.id}/${messageID}/unpin`
1011
1009
  );
1012
1010
  }
1011
+ async pin() {
1012
+ if (this.data) this.data.is_pinned = true;
1013
+ this.getClient().dispatchEvent({
1014
+ type: "channel.pinned",
1015
+ cid: this.cid,
1016
+ channel: this.data
1017
+ });
1018
+ try {
1019
+ return await this.getClient().pinChannel(this.type, this.id);
1020
+ } catch (e) {
1021
+ if (this.data) this.data.is_pinned = false;
1022
+ this.getClient().dispatchEvent({
1023
+ type: "channel.unpinned",
1024
+ cid: this.cid,
1025
+ channel: this.data
1026
+ });
1027
+ throw e;
1028
+ }
1029
+ }
1030
+ async unpin() {
1031
+ if (this.data) this.data.is_pinned = false;
1032
+ this.getClient().dispatchEvent({
1033
+ type: "channel.unpinned",
1034
+ cid: this.cid,
1035
+ channel: this.data
1036
+ });
1037
+ try {
1038
+ return await this.getClient().unpinChannel(this.type, this.id);
1039
+ } catch (e) {
1040
+ if (this.data) this.data.is_pinned = true;
1041
+ this.getClient().dispatchEvent({
1042
+ type: "channel.pinned",
1043
+ cid: this.cid,
1044
+ channel: this.data
1045
+ });
1046
+ throw e;
1047
+ }
1048
+ }
1013
1049
  async editMessage(oldMessageID, message) {
1014
1050
  return await this.getClient().post(this.getClient().baseURL + `/messages/${this.type}/${this.id}/${oldMessageID}`, {
1015
1051
  message
@@ -1036,9 +1072,7 @@ var Channel = class {
1036
1072
  return file;
1037
1073
  });
1038
1074
  const uploadResults = await Promise.allSettled(
1039
- processedFiles.map(
1040
- (file) => this.sendFile(file, file.name, file.type)
1041
- )
1075
+ processedFiles.map((file) => this.sendFile(file, file.name, file.type))
1042
1076
  );
1043
1077
  const thumbUrls = /* @__PURE__ */ new Map();
1044
1078
  const thumbPromises = [];
@@ -1050,11 +1084,7 @@ var Channel = class {
1050
1084
  try {
1051
1085
  const thumbBlob = await this.getThumbBlobVideo(files[i]);
1052
1086
  if (thumbBlob) {
1053
- const thumbFile = new File(
1054
- [thumbBlob],
1055
- `thumb_${processedFiles[i].name}.jpg`,
1056
- { type: "image/jpeg" }
1057
- );
1087
+ const thumbFile = new File([thumbBlob], `thumb_${processedFiles[i].name}.jpg`, { type: "image/jpeg" });
1058
1088
  const thumbResp = await this.sendFile(thumbFile, thumbFile.name, "image/jpeg");
1059
1089
  thumbUrls.set(i, thumbResp.file);
1060
1090
  }
@@ -1072,9 +1102,7 @@ var Channel = class {
1072
1102
  const uploadedUrl = result.value.file;
1073
1103
  const thumbUrl = thumbUrls.get(i);
1074
1104
  const voiceMeta = options?.voiceMetadata?.get(i);
1075
- attachments.push(
1076
- buildAttachmentPayload(processedFiles[i], uploadedUrl, thumbUrl, voiceMeta)
1077
- );
1105
+ attachments.push(buildAttachmentPayload(processedFiles[i], uploadedUrl, thumbUrl, voiceMeta));
1078
1106
  } else {
1079
1107
  failedFiles.push({
1080
1108
  file: files[i],
@@ -1422,7 +1450,7 @@ var Channel = class {
1422
1450
  if (this.id) {
1423
1451
  queryURL += `/${this.id}`;
1424
1452
  } else {
1425
- if (this.type === "team") {
1453
+ if (this.type === "team" || this.type === "meeting") {
1426
1454
  const uuid = randomId();
1427
1455
  this.id = `${project_id}:${uuid}`;
1428
1456
  queryURL += `/${this.id}`;
@@ -1923,6 +1951,18 @@ var Channel = class {
1923
1951
  delete channelState.members[event.user.id];
1924
1952
  }
1925
1953
  break;
1954
+ case "channel.topic.enabled":
1955
+ if (channel.data) {
1956
+ channel.data.topics_enabled = true;
1957
+ }
1958
+ channelState.topics = channelState.topics || [];
1959
+ break;
1960
+ case "channel.topic.disabled":
1961
+ if (channel.data) {
1962
+ channel.data.topics_enabled = false;
1963
+ }
1964
+ channelState.topics = [];
1965
+ break;
1926
1966
  case "channel.updated":
1927
1967
  if (event.channel) {
1928
1968
  channel.data = {
@@ -2061,7 +2101,12 @@ var Channel = class {
2061
2101
  const topic = this.getClient().channel(event.channel_type || "", event.channel_id || "");
2062
2102
  topic.data = event.channel;
2063
2103
  topic._initializeState(topicState, "latest");
2064
- channelState.topics?.unshift(topic);
2104
+ if (!channelState.topics) {
2105
+ channelState.topics = [];
2106
+ }
2107
+ if (!channelState.topics.some((t) => t.cid === topic.cid)) {
2108
+ channelState.topics.push(topic);
2109
+ }
2065
2110
  break;
2066
2111
  case "channel.topic.closed":
2067
2112
  if (channel.data) {
@@ -2880,7 +2925,6 @@ var ErmisChat = class _ErmisChat {
2880
2925
  params.avatar = user.avatar;
2881
2926
  }
2882
2927
  const url = this.userBaseURL + "/get_token/external_auth";
2883
- const query = new URLSearchParams(params).toString();
2884
2928
  const headers = {
2885
2929
  "Content-Type": "application/json"
2886
2930
  };
@@ -2888,21 +2932,21 @@ var ErmisChat = class _ErmisChat {
2888
2932
  const tokenStr = typeof token === "string" && token.startsWith("Bearer ") ? token : `Bearer ${token}`;
2889
2933
  headers["Authorization"] = tokenStr;
2890
2934
  }
2891
- const response = await fetch(`${url}?${query}`, {
2892
- method: "GET",
2893
- headers
2894
- });
2895
- if (!response.ok) {
2896
- let errorMsg = "";
2897
- try {
2898
- const errorData = await response.json();
2899
- errorMsg = errorData.message || JSON.stringify(errorData);
2900
- } catch {
2901
- errorMsg = await response.text();
2935
+ try {
2936
+ const response = await this.axiosInstance.get(url, {
2937
+ params,
2938
+ headers
2939
+ });
2940
+ return response.data;
2941
+ } catch (error) {
2942
+ let errorMsg = "Failed to fetch external auth token";
2943
+ if (error.response && error.response.data) {
2944
+ errorMsg = error.response.data.message || JSON.stringify(error.response.data);
2945
+ } else if (error.message) {
2946
+ errorMsg = error.message;
2902
2947
  }
2903
2948
  throw new Error(errorMsg);
2904
2949
  }
2905
- return await response.json();
2906
2950
  }
2907
2951
  /**
2908
2952
  * Connects a user to the Ermis network and establishes the WebSocket connection.
@@ -2913,19 +2957,24 @@ var ErmisChat = class _ErmisChat {
2913
2957
  * @param extenal_auth - Set to `true` to use your custom backend external authentication flow.
2914
2958
  * @returns A promise resolving to the API connection response once authenticated.
2915
2959
  */
2916
- connectUser = async (user, userTokenOrProvider, extenal_auth) => {
2960
+ connectUser = async (user, userTokenOrProvider, external_auth) => {
2917
2961
  this.logger("info", "client:connectUser() - started", {
2918
2962
  tags: ["connection", "client"]
2919
2963
  });
2920
2964
  if (!user.id) {
2921
2965
  throw new Error('The "id" field on the user is missing');
2922
2966
  }
2923
- if (extenal_auth) {
2967
+ let connectionUser = user;
2968
+ let connectionToken = userTokenOrProvider;
2969
+ if (external_auth) {
2924
2970
  const external_auth_token = await this.getExternalAuthToken(user, userTokenOrProvider);
2925
- userTokenOrProvider = external_auth_token.token;
2926
- user.id = external_auth_token.user_id;
2971
+ connectionToken = external_auth_token.token;
2972
+ connectionUser = {
2973
+ ...user,
2974
+ id: external_auth_token.user_id
2975
+ };
2927
2976
  }
2928
- if (this.userID === user.id && this.setUserPromise) {
2977
+ if (this.userID === connectionUser.id && this.setUserPromise) {
2929
2978
  console.warn(
2930
2979
  "Consecutive calls to connectUser is detected, ideally you should only call this function once in your app."
2931
2980
  );
@@ -2941,10 +2990,10 @@ var ErmisChat = class _ErmisChat {
2941
2990
  'Please do not use connectUser server side. connectUser impacts MAU and concurrent connection usage and thus your bill. If you have a valid use-case, add "allowServerSideConnect: true" to the client options to disable this warning.'
2942
2991
  );
2943
2992
  }
2944
- this.userID = user.id;
2945
- const setTokenPromise = this._setToken(user, userTokenOrProvider);
2946
- this._setUser(user);
2947
- this.state.updateUser({ id: user.id, name: user?.name || user.id, avatar: user?.avatar || "" });
2993
+ this.userID = connectionUser.id;
2994
+ const setTokenPromise = this._setToken(connectionUser, connectionToken);
2995
+ this._setUser(connectionUser);
2996
+ this.state.updateUser({ id: connectionUser.id, name: connectionUser?.name || connectionUser.id, avatar: connectionUser?.avatar || "" });
2948
2997
  const wsPromise = this.openConnection();
2949
2998
  this.setUserPromise = Promise.all([setTokenPromise, wsPromise]).then(
2950
2999
  (result) => result[1]
@@ -3170,7 +3219,7 @@ var ErmisChat = class _ErmisChat {
3170
3219
  }
3171
3220
  dispatchEvent = (event) => {
3172
3221
  if (!event.received_at) event.received_at = /* @__PURE__ */ new Date();
3173
- if (event.type === "channel.created") {
3222
+ if (event.type === "channel.created" || event.type === "channel.topic.created") {
3174
3223
  this._handleChannelCreatedEvent(event).then(() => {
3175
3224
  this._afterDispatchEvent(event);
3176
3225
  });
@@ -3304,6 +3353,79 @@ var ErmisChat = class _ErmisChat {
3304
3353
  });
3305
3354
  }
3306
3355
  }
3356
+ if (event.type === "message.new" && event.channel_type === "topic") {
3357
+ postListenerCallbacks.push(() => {
3358
+ const parentCid = event.parent_cid || event.channel?.parent_cid;
3359
+ if (parentCid && this.activeChannels[parentCid]) {
3360
+ const parentChannel = this.activeChannels[parentCid];
3361
+ if (parentChannel.state.topics) {
3362
+ parentChannel.state.topics.sort((a, b) => {
3363
+ const aLatest = a.state?.latestMessages?.[a.state.latestMessages.length - 1]?.created_at;
3364
+ const bLatest = b.state?.latestMessages?.[b.state.latestMessages.length - 1]?.created_at;
3365
+ const aTime = aLatest ? new Date(aLatest).getTime() : 0;
3366
+ const bTime = bLatest ? new Date(bLatest).getTime() : 0;
3367
+ return bTime - aTime;
3368
+ });
3369
+ parentChannel._callChannelListeners({ ...event, type: "channel.updated", channel: parentChannel.data });
3370
+ }
3371
+ }
3372
+ });
3373
+ }
3374
+ if (event.type === "channel.topic.updated") {
3375
+ postListenerCallbacks.push(() => {
3376
+ const parentCid = event.parent_cid || event.channel?.parent_cid;
3377
+ if (parentCid && this.activeChannels[parentCid]) {
3378
+ const parentChannel = this.activeChannels[parentCid];
3379
+ if (parentChannel.state?.topics && event.channel) {
3380
+ const topicIndex = parentChannel.state.topics.findIndex((t) => t.cid === event.cid || t.channel?.cid === event.cid);
3381
+ if (topicIndex !== -1) {
3382
+ const t = parentChannel.state.topics[topicIndex];
3383
+ if (t.data) {
3384
+ t.data = { ...t.data, ...event.channel };
3385
+ } else if (t.channel) {
3386
+ t.channel = { ...t.channel, ...event.channel };
3387
+ } else {
3388
+ Object.assign(t, event.channel);
3389
+ }
3390
+ }
3391
+ parentChannel._callChannelListeners({ ...event, type: "channel.updated", channel: parentChannel.data });
3392
+ }
3393
+ }
3394
+ if (event.cid && this.activeChannels[event.cid]) {
3395
+ const topicChannel = this.activeChannels[event.cid];
3396
+ if (event.channel) {
3397
+ topicChannel.data = { ...topicChannel.data, ...event.channel };
3398
+ topicChannel._callChannelListeners({ ...event, type: "channel.updated", channel: topicChannel.data });
3399
+ }
3400
+ }
3401
+ });
3402
+ }
3403
+ if (event.type === "channel.topic.closed" || event.type === "channel.topic.reopen") {
3404
+ postListenerCallbacks.push(() => {
3405
+ const isClosed = event.type === "channel.topic.closed";
3406
+ const parentCid = event.parent_cid;
3407
+ if (parentCid && this.activeChannels[parentCid]) {
3408
+ const parentChannel = this.activeChannels[parentCid];
3409
+ if (parentChannel.state?.topics) {
3410
+ const topicIndex = parentChannel.state.topics.findIndex((t) => t.cid === event.cid || t.channel?.cid === event.cid);
3411
+ if (topicIndex !== -1) {
3412
+ const t = parentChannel.state.topics[topicIndex];
3413
+ if (t.data) t.data.is_closed_topic = isClosed;
3414
+ else if (t.channel) t.channel.is_closed_topic = isClosed;
3415
+ else t.is_closed_topic = isClosed;
3416
+ }
3417
+ parentChannel._callChannelListeners({ ...event, type: "channel.updated", channel: parentChannel.data });
3418
+ }
3419
+ }
3420
+ if (event.cid && this.activeChannels[event.cid]) {
3421
+ const topicChannel = this.activeChannels[event.cid];
3422
+ if (topicChannel.data) {
3423
+ topicChannel.data.is_closed_topic = isClosed;
3424
+ }
3425
+ topicChannel._callChannelListeners({ ...event, type: "channel.updated", channel: topicChannel.data });
3426
+ }
3427
+ });
3428
+ }
3307
3429
  if (event.type === "connection.recovered") {
3308
3430
  postListenerCallbacks.push(() => {
3309
3431
  Object.values(this.activeChannels).forEach((channel) => {
@@ -3541,7 +3663,14 @@ var ErmisChat = class _ErmisChat {
3541
3663
  _updateProjectID(project_id) {
3542
3664
  this.projectId = project_id;
3543
3665
  }
3544
- async uploadFile(file) {
3666
+ /**
3667
+ * Uploads a new avatar image for the current user.
3668
+ * The user's avatar URL is automatically updated in both the client and the local state.
3669
+ *
3670
+ * @param file - The image file to upload.
3671
+ * @returns The response containing the new avatar URL.
3672
+ */
3673
+ async uploadAvatar(file) {
3545
3674
  const formData = new FormData();
3546
3675
  formData.append("avatar", file);
3547
3676
  let response = await this.post(this.userBaseURL + "/users/upload", formData, {
@@ -3556,12 +3685,8 @@ var ErmisChat = class _ErmisChat {
3556
3685
  }
3557
3686
  return response;
3558
3687
  }
3559
- async updateProfile(name, about_me) {
3560
- let body = {
3561
- name,
3562
- about_me
3563
- };
3564
- let response = await this.patch(this.userBaseURL + "/users/update", body);
3688
+ async updateProfile(updates) {
3689
+ let response = await this.patch(this.userBaseURL + "/users/update", updates);
3565
3690
  this.user = response;
3566
3691
  this.state.updateUser(response);
3567
3692
  return response;
@@ -3713,6 +3838,57 @@ var ErmisChat = class _ErmisChat {
3713
3838
  this.activeChannels[channel.cid] = channel;
3714
3839
  return channel;
3715
3840
  };
3841
+ /**
3842
+ * Creates a quick channel and immediately registers it on the server.
3843
+ * Quick channels are public group channels that anyone can join without an invitation.
3844
+ * The creator is added as the first member automatically.
3845
+ *
3846
+ * @param name - An optional display name for the channel.
3847
+ * @returns A promise that resolves to the created `Channel` object.
3848
+ */
3849
+ async createQuickChannel(name) {
3850
+ if (!this.userID) {
3851
+ throw Error("Call connectUser before creating a channel");
3852
+ }
3853
+ const now = /* @__PURE__ */ new Date();
3854
+ const formattedDate = new Intl.DateTimeFormat("en-US", {
3855
+ month: "short",
3856
+ day: "2-digit",
3857
+ year: "numeric",
3858
+ hour: "2-digit",
3859
+ minute: "2-digit",
3860
+ hour12: false
3861
+ }).format(now);
3862
+ const payload = {
3863
+ name: name || `Quick Channel - ${formattedDate}`,
3864
+ members: [this.userID],
3865
+ public: true
3866
+ };
3867
+ const quickChannel = this.channel("meeting", payload);
3868
+ await quickChannel.create();
3869
+ return quickChannel;
3870
+ }
3871
+ /**
3872
+ * Joins a quick channel by its ID.
3873
+ * Automatically checks whether the caller is already a member.
3874
+ * If not, it joins the channel and synchronizes state.
3875
+ *
3876
+ * @param channelId - The ID of the quick channel to join.
3877
+ * @returns A promise that resolves to the joined `Channel` object.
3878
+ */
3879
+ async joinQuickChannel(channelId) {
3880
+ if (!this.userID) {
3881
+ throw Error("Call connectUser before joining a channel");
3882
+ }
3883
+ const quickChannel = this.channel("meeting", channelId);
3884
+ await quickChannel.watch();
3885
+ const isMember = quickChannel.state.members && quickChannel.state.members[this.userID];
3886
+ if (!isMember) {
3887
+ await quickChannel.acceptInvite("join");
3888
+ await quickChannel.watch();
3889
+ }
3890
+ return quickChannel;
3891
+ }
3716
3892
  _normalizeExpiration(timeoutOrExpirationDate) {
3717
3893
  let pinExpires = null;
3718
3894
  if (typeof timeoutOrExpirationDate === "number") {
@@ -3727,7 +3903,7 @@ var ErmisChat = class _ErmisChat {
3727
3903
  return pinExpires;
3728
3904
  }
3729
3905
  getUserAgent() {
3730
- return this.userAgent || `ermis-chat-sdk-javascript-client-${this.node ? "node" : "browser"}-${"1.0.5"}`;
3906
+ return this.userAgent || `ermis-chat-sdk-javascript-client-${this.node ? "node" : "browser"}-${"1.0.7"}`;
3731
3907
  }
3732
3908
  setUserAgent(userAgent) {
3733
3909
  this.userAgent = userAgent;
@@ -7085,7 +7261,7 @@ var ErmisAuthProvider = class {
7085
7261
  return data;
7086
7262
  }
7087
7263
  getUserAgent() {
7088
- return this.userAgent || `ermis-chat-sdk-javascript-client-${this.node ? "node" : "browser"}-${"1.0.5"}`;
7264
+ return this.userAgent || `ermis-chat-sdk-javascript-client-${this.node ? "node" : "browser"}-${"1.0.7"}`;
7089
7265
  }
7090
7266
  setUserAgent(userAgent) {
7091
7267
  this.userAgent = userAgent;