@amityco/ts-sdk 7.5.4-6dc7299.0 → 7.5.4-91188fd.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 (39) hide show
  1. package/dist/@types/domains/channel.d.ts +0 -1
  2. package/dist/@types/domains/channel.d.ts.map +1 -1
  3. package/dist/@types/domains/group.d.ts +0 -2
  4. package/dist/@types/domains/group.d.ts.map +1 -1
  5. package/dist/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.d.ts.map +1 -1
  6. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberLiveCollectionController.d.ts.map +1 -1
  7. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberQueryStreamController.d.ts +2 -2
  8. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberQueryStreamController.d.ts.map +1 -1
  9. package/dist/client/api/index.d.ts +0 -1
  10. package/dist/client/api/index.d.ts.map +1 -1
  11. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsPaginationController.d.ts.map +1 -1
  12. package/dist/index.cjs.js +15 -216
  13. package/dist/index.esm.js +15 -215
  14. package/dist/index.umd.js +4 -4
  15. package/dist/utils/linkedObject/channelLinkedObject.d.ts.map +1 -1
  16. package/dist/utils/linkedObject/index.d.ts +0 -1
  17. package/dist/utils/linkedObject/index.d.ts.map +1 -1
  18. package/dist/utils/tests/dummy/comment.d.ts +1 -1
  19. package/dist/utils/tests/dummy/community.d.ts +0 -2
  20. package/dist/utils/tests/dummy/community.d.ts.map +1 -1
  21. package/package.json +1 -2
  22. package/src/@types/domains/channel.ts +0 -1
  23. package/src/@types/domains/group.ts +0 -2
  24. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.ts +1 -3
  25. package/src/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberLiveCollectionController.ts +1 -2
  26. package/src/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberQueryStreamController.ts +2 -2
  27. package/src/client/api/index.ts +0 -1
  28. package/src/communityRepository/observers/getJoinRequests/JoinRequestsPaginationController.ts +2 -1
  29. package/src/utils/linkedObject/channelLinkedObject.ts +0 -19
  30. package/src/utils/linkedObject/index.ts +0 -2
  31. package/dist/client/api/resumeSession.d.ts +0 -32
  32. package/dist/client/api/resumeSession.d.ts.map +0 -1
  33. package/dist/client/api/tests/resumeSession.test.d.ts +0 -2
  34. package/dist/client/api/tests/resumeSession.test.d.ts.map +0 -1
  35. package/dist/utils/linkedObject/channelMemberLinkedObject.d.ts +0 -2
  36. package/dist/utils/linkedObject/channelMemberLinkedObject.d.ts.map +0 -1
  37. package/src/client/api/resumeSession.ts +0 -282
  38. package/src/client/api/tests/resumeSession.test.ts +0 -173
  39. package/src/utils/linkedObject/channelMemberLinkedObject.ts +0 -20
@@ -1 +1 @@
1
- {"version":3,"file":"channelLinkedObject.d.ts","sourceRoot":"","sources":["../../../src/utils/linkedObject/channelLinkedObject.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,mBAAmB,YAAa,MAAM,eAAe,KAAG,MAAM,OAqB1E,CAAC"}
1
+ {"version":3,"file":"channelLinkedObject.d.ts","sourceRoot":"","sources":["../../../src/utils/linkedObject/channelLinkedObject.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,mBAAmB,YAAa,MAAM,eAAe,KAAG,MAAM,OAI1E,CAAC"}
@@ -15,6 +15,5 @@ export declare const LinkedObject: {
15
15
  community: (community: Amity.InternalCommunity) => Amity.Community;
16
16
  invitation: (invitation: Amity.InternalInvitation) => Amity.Invitation;
17
17
  joinRequest: (joinRequest: Amity.InternalJoinRequest) => Amity.JoinRequest;
18
- channelMember: (channelMember: Amity.Membership<"channel">) => Amity.Membership<"channel">;
19
18
  };
20
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/utils/linkedObject/index.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;;;;CAkBxB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/utils/linkedObject/index.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;;;CAiBxB,CAAC"}
@@ -18,7 +18,7 @@ export declare const generateComment: (params?: Partial<Amity.InternalComment>)
18
18
  editedAt: string;
19
19
  attachments?: Amity.Attachment[] | undefined;
20
20
  targetId: string;
21
- targetType: "community" | "user" | "content";
21
+ targetType: "user" | "community" | "content";
22
22
  referenceId: string;
23
23
  referenceType: Amity.CommentReferenceType;
24
24
  dataType?: any;
@@ -55,8 +55,6 @@ export declare const communityUserModel: {
55
55
  muteTimeout: string;
56
56
  lastActivity: string;
57
57
  userId: string;
58
- userInternalId: string;
59
- userPublicId: string;
60
58
  communityId: string;
61
59
  communityMembership: Amity.GroupMembership;
62
60
  createdAt: string;
@@ -1 +1 @@
1
- {"version":3,"file":"community.d.ts","sourceRoot":"","sources":["../../../../src/utils/tests/dummy/community.ts"],"names":[],"mappings":"AAqBA,eAAO,MAAM,aAAa,EAAE,KAAK,CAAC,SAajC,CAAC;AAEF,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,SAoB/B,CAAC;AAEF,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,SAI/B,CAAC;AAEF,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,WAAW,CAa5D,CAAC;AAEF,eAAO,MAAM,uBAAuB,+BAAuD,CAAC;AAE5F,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,WAAW,CAO5D,CAAC;AAEF,eAAO,MAAM,uBAAuB,+BAAuD,CAAC;AAE5F,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,WAAW,CAO5D,CAAC;AAEF,eAAO,MAAM,uBAAuB,+BAAuD,CAAC;AAE5F,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,WAAW,CAM5D,CAAC;AAEF,eAAO,MAAM,qBAAqB,+BAAuD,CAAC;AAE1F,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,WAAW,CAK5D,CAAC;AAEF,eAAO,MAAM,mBAAmB,+BAAuD,CAAC;AAExF,eAAO,MAAM,qBAAqB;;;;;;;CAOjC,CAAC;AAEF,eAAO,MAAM,gBAAgB,EAAE,KAAK,CAAC,gBAOpC,CAAC;AAEF,eAAO,MAAM,0BAA0B;;;;;;;;;;;;;CAUtC,CAAC;AAEF,eAAO,MAAM,+BAA+B;;;;;;;;;;;;;CAU3C,CAAC;AAEF,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;GAG9B,CAAC;AAEF,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;CAuBzB,CAAC;AAEF,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;CAuBzB,CAAC;AAEF,eAAO,MAAM,sBAAsB;;CAqBlC,CAAC;AAEF,eAAO,MAAM,2BAA2B;;CAqBvC,CAAC"}
1
+ {"version":3,"file":"community.d.ts","sourceRoot":"","sources":["../../../../src/utils/tests/dummy/community.ts"],"names":[],"mappings":"AAqBA,eAAO,MAAM,aAAa,EAAE,KAAK,CAAC,SAajC,CAAC;AAEF,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,SAoB/B,CAAC;AAEF,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,SAI/B,CAAC;AAEF,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,WAAW,CAa5D,CAAC;AAEF,eAAO,MAAM,uBAAuB,+BAAuD,CAAC;AAE5F,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,WAAW,CAO5D,CAAC;AAEF,eAAO,MAAM,uBAAuB,+BAAuD,CAAC;AAE5F,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,WAAW,CAO5D,CAAC;AAEF,eAAO,MAAM,uBAAuB,+BAAuD,CAAC;AAE5F,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,WAAW,CAM5D,CAAC;AAEF,eAAO,MAAM,qBAAqB,+BAAuD,CAAC;AAE1F,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,WAAW,CAK5D,CAAC;AAEF,eAAO,MAAM,mBAAmB,+BAAuD,CAAC;AAExF,eAAO,MAAM,qBAAqB;;;;;;;CAOjC,CAAC;AAEF,eAAO,MAAM,gBAAgB,EAAE,KAAK,CAAC,gBAOpC,CAAC;AAEF,eAAO,MAAM,0BAA0B;;;;;;;;;;;;;CAUtC,CAAC;AAEF,eAAO,MAAM,+BAA+B;;;;;;;;;;;;;CAU3C,CAAC;AAEF,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;GAG9B,CAAC;AAEF,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;CAuBzB,CAAC;AAEF,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;CAuBzB,CAAC;AAEF,eAAO,MAAM,sBAAsB;;CAqBlC,CAAC;AAEF,eAAO,MAAM,2BAA2B;;CAqBvC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amityco/ts-sdk",
3
- "version": "7.5.4-6dc7299.0",
3
+ "version": "7.5.4-91188fd.0",
4
4
  "license": "CC-BY-ND-4.0",
5
5
  "author": "amity.co <developers@amity.co> (https://amity.co)",
6
6
  "description": "Amity Social Cloud Typescript SDK",
@@ -63,7 +63,6 @@
63
63
  "debug": "^4.3.4",
64
64
  "hls.js": "^1.4.10",
65
65
  "js-base64": "^3.7.2",
66
- "jwt-decode": "^3.1.2",
67
66
  "mitt": "^3.0.0",
68
67
  "mqtt": "^4.3.7",
69
68
  "object-hash": "^3.0.0",
@@ -93,7 +93,6 @@ declare global {
93
93
  type Channel<T extends ChannelType = any> = InternalChannel<T> & {
94
94
  messagePreview?: Amity.MessagePreview | null;
95
95
  markAsRead: () => Promise<boolean>;
96
- previewMembers: Amity.Membership<'channel'>[];
97
96
  };
98
97
 
99
98
  type QueryChannels = {
@@ -15,8 +15,6 @@ declare global {
15
15
 
16
16
  type Member<T extends Amity.GroupType> = {
17
17
  userId: Amity.InternalUser['userId'];
18
- userInternalId: Amity.InternalUser['userInternalId'];
19
- userPublicId: Amity.InternalUser['userPublicId'];
20
18
  } & (T extends 'channel'
21
19
  ? {
22
20
  channelId: Amity.Channel['channelId'];
@@ -23,7 +23,6 @@ import {
23
23
  } from '~/core/query';
24
24
  import { prepareChannelPayload } from '~/channelRepository/utils';
25
25
  import { onUserDeleted } from '~/channelRepository/events/onUserDeleted';
26
- import { LinkedObject } from '~/utils/linkedObject';
27
26
 
28
27
  export class ChannelMemberLiveCollectionController extends LiveCollectionController<
29
28
  'channelUser',
@@ -101,8 +100,7 @@ export class ChannelMemberLiveCollectionController extends LiveCollectionControl
101
100
  collection.data
102
101
  .map(id => pullFromCache<Amity.Membership<'channel'>>(['channelUsers', 'get', id])!)
103
102
  .filter(Boolean)
104
- .map(({ data }) => data)
105
- .map(LinkedObject.channelMember) ?? [],
103
+ .map(({ data }) => data) ?? [],
106
104
  );
107
105
 
108
106
  if (!this.shouldNotify(data) && origin === 'event') return;
@@ -17,7 +17,6 @@ import {
17
17
  import { filterByPropIntersection, filterBySearchTerm } from '~/core/query';
18
18
  import { prepareChannelPayload } from '~/channelRepository/utils';
19
19
  import { onUserDeleted } from '~/channelRepository/events/onUserDeleted';
20
- import { LinkedObject } from '~/utils/linkedObject';
21
20
 
22
21
  export class SearchChannelMemberLiveCollectionController extends LiveCollectionController<
23
22
  'channelUser',
@@ -95,7 +94,7 @@ export class SearchChannelMemberLiveCollectionController extends LiveCollectionC
95
94
  collection.data
96
95
  .map(id => pullFromCache<Amity.Membership<'channel'>>(['channelUsers', 'get', id])!)
97
96
  .filter(Boolean)
98
- .map(({ data }) => LinkedObject.channelMember(data) ?? []),
97
+ .map(({ data }) => data) ?? [],
99
98
  );
100
99
 
101
100
  if (!this.shouldNotify(data) && origin === 'event') return;
@@ -72,7 +72,7 @@ export class SearchChannelMemberQueryStreamController extends QueryStreamControl
72
72
  }
73
73
 
74
74
  reactor(action: string) {
75
- return (channel: Amity.StaticInternalChannel, channelMember: Amity.Membership<'channel'>) => {
75
+ return (channel: Amity.InternalChannel, channelMember: Amity.Membership<'channel'>) => {
76
76
  if (this.query.channelId !== channelMember.channelId) return;
77
77
 
78
78
  const collection = pullFromCache<Amity.ChannelMembersLiveCollectionCache>(
@@ -100,7 +100,7 @@ export class SearchChannelMemberQueryStreamController extends QueryStreamControl
100
100
  createSubscriber: {
101
101
  fn: (
102
102
  reactor: (
103
- channel: Amity.StaticInternalChannel,
103
+ channel: Amity.InternalChannel,
104
104
  channelMember: Amity.Membership<'channel'>,
105
105
  ) => void,
106
106
  ) => Amity.Unsubscriber;
@@ -6,7 +6,6 @@ export * from './createClient';
6
6
  export * from './login';
7
7
  export * from './logout';
8
8
  export * from './secureLogout';
9
- export * from './resumeSession';
10
9
 
11
10
  export * from './isConnected';
12
11
 
@@ -1,4 +1,5 @@
1
1
  import { PaginationController } from '~/core/liveCollection/PaginationController';
2
+ import { COLLECTION_DEFAULT_PAGINATION_LIMIT } from '~/utils/constants';
2
3
 
3
4
  /**
4
5
  * TODO: handle cache receive cache option, and cache policy
@@ -9,7 +10,7 @@ export class JoinRequestsPaginationController extends PaginationController<
9
10
  Amity.JoinRequestLiveCollection
10
11
  > {
11
12
  async getRequest(queryParams: Amity.JoinRequestLiveCollection, token: string | undefined) {
12
- const { limit = 20, communityId, ...params } = queryParams;
13
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, communityId, ...params } = queryParams;
13
14
  const options = token ? { token } : { limit };
14
15
 
15
16
  const { data: queryResponse } = await this.http.get<
@@ -1,27 +1,8 @@
1
1
  import { markAsRead } from '~/channelRepository/internalApi/markAsRead';
2
2
  import { shallowClone } from '../shallowClone';
3
- import { queryCache } from '~/cache/api';
4
- import { channelMemberLinkedObject } from './channelMemberLinkedObject';
5
3
 
6
4
  export const channelLinkedObject = (channel: Amity.InternalChannel): Amity.Channel => {
7
- let previewMembers: Amity.Membership<'channel'>[] = [];
8
-
9
- if (channel.type === 'conversation') {
10
- const channelUsers = queryCache<Amity.Membership<'channel'>>(['channelUsers', 'get']);
11
- if (channelUsers && channelUsers?.length > 0) {
12
- previewMembers = (
13
- channelUsers?.filter(({ data }) => data.channelId === channel.channelId) ?? []
14
- )
15
- // sort in ascending order by userInternalId
16
- .sort((a, b) => a.data.userInternalId.localeCompare(b.data.userInternalId))
17
- // Select only first 4 members
18
- .slice(0, 4)
19
- .map(({ data }) => channelMemberLinkedObject(data));
20
- }
21
- }
22
-
23
5
  return shallowClone(channel, {
24
6
  markAsRead: () => markAsRead(channel.channelInternalId),
25
- previewMembers,
26
7
  });
27
8
  };
@@ -14,7 +14,6 @@ import { notificationTrayLinkedObject } from './notificationTrayLinkedObject';
14
14
  import { communityLinkedObject } from './communityLinkedObject';
15
15
  import { invitationLinkedObject } from './invitationLinkedObject';
16
16
  import { joinRequestLinkedObject } from './joinRequestLinkedObject';
17
- import { channelMemberLinkedObject } from './channelMemberLinkedObject';
18
17
 
19
18
  export const LinkedObject = {
20
19
  ad: adLinkedObject,
@@ -33,5 +32,4 @@ export const LinkedObject = {
33
32
  community: communityLinkedObject,
34
33
  invitation: invitationLinkedObject,
35
34
  joinRequest: joinRequestLinkedObject,
36
- channelMember: channelMemberLinkedObject,
37
35
  };
@@ -1,32 +0,0 @@
1
- interface Params {
2
- userId: string;
3
- token: {
4
- issuedAt: string;
5
- expiresAt: string;
6
- accessToken: string;
7
- };
8
- }
9
- /**
10
- * ```js
11
- * import { resumeSession } from '@amityco/ts-sdk/client/api'
12
- * const success = await resumeSession({
13
- * userId: 'XYZ123456789',
14
- * token: { accessToken: 'abc123', issuedAt: '2023-01-01T00:00:00Z', expiresAt: '2023-01-02T00:00:00Z' }
15
- * })
16
- * ```
17
- *
18
- * Connects an {@link Amity.Client} instance to ASC servers using an existing access token
19
- *
20
- * @param params the connect parameters
21
- * @param params.userId the user ID for the current session
22
- * @param params.token the existing access token with its metadata
23
- * @param sessionHandler the session handler for token renewal
24
- * @param config optional configuration
25
- * @returns a success boolean if connected
26
- *
27
- * @category Client API
28
- * @async
29
- */
30
- export declare const resumeSession: (params: Params, sessionHandler: Amity.SessionHandler, config?: Amity.ConnectClientConfig) => Promise<boolean>;
31
- export {};
32
- //# sourceMappingURL=resumeSession.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"resumeSession.d.ts","sourceRoot":"","sources":["../../../src/client/api/resumeSession.ts"],"names":[],"mappings":"AA0CA,UAAU,MAAM;IACd,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE;QACL,QAAQ,EAAE,MAAM,CAAC;QACjB,SAAS,EAAE,MAAM,CAAC;QAClB,WAAW,EAAE,MAAM,CAAC;KACrB,CAAC;CACH;AA+DD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,aAAa,WAChB,MAAM,kBACE,MAAM,cAAc,WAC3B,MAAM,mBAAmB,KACjC,QAAQ,OAAO,CA+IjB,CAAC"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=resumeSession.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"resumeSession.test.d.ts","sourceRoot":"","sources":["../../../../src/client/api/tests/resumeSession.test.ts"],"names":[],"mappings":""}
@@ -1,2 +0,0 @@
1
- export declare const channelMemberLinkedObject: (channelMember: Amity.Membership<'channel'>) => Amity.Membership<'channel'>;
2
- //# sourceMappingURL=channelMemberLinkedObject.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"channelMemberLinkedObject.d.ts","sourceRoot":"","sources":["../../../src/utils/linkedObject/channelMemberLinkedObject.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,yBAAyB,kBACrB,MAAM,UAAU,CAAC,SAAS,CAAC,KACzC,MAAM,UAAU,CAAC,SAAS,CAc5B,CAAC"}
@@ -1,282 +0,0 @@
1
- import jwtDecode from 'jwt-decode';
2
- /* eslint-disable no-param-reassign */
3
- import { modifyMqttConnection } from '~/client/utils/modifyMqttConnection';
4
- /* eslint-disable require-atomic-updates */
5
- import { proxyWebsocketEvents } from '~/core/events';
6
- import { onChannelDeleted } from '~/channelRepository/events/onChannelDeleted';
7
- import { onChannelMemberBanned } from '~/channelRepository/events/onChannelMemberBanned';
8
-
9
- import { markReadEngineOnLoginHandler } from '~/subChannelRepository/utils/markReadEngine';
10
- import { onUserDeleted } from '~/userRepository/events/onUserDeleted';
11
-
12
- import analyticsEngineOnLoginHandler from '~/analytic/utils/analyticsEngineOnLoginHandler';
13
- import readReceiptSyncEngineOnLoginHandler from '~/client/utils/ReadReceiptSync/readReceiptSyncEngineOnLoginHandler';
14
- import legacyReadReceiptSyncEngineOnLoginHandler from '~/client/utils/ReadReceiptSync/legacyReadReceiptSyncEngineOnLoginHandler';
15
- import objectResolverEngineOnLoginHandler from '~/client/utils/ObjectResolver/objectResolverEngineOnLoginHandler';
16
- import { logout } from './logout';
17
-
18
- import { getActiveClient } from './activeClient';
19
- import { terminateClient } from './terminateClient';
20
- import { setActiveUser } from './activeUser';
21
- import { setSessionState } from './setSessionState';
22
-
23
- import { onClientBanned } from '../events';
24
- import { onTokenExpired } from '../events/onTokenExpired';
25
- import { onTokenTerminated } from '../events/onTokenTerminated';
26
-
27
- import { removeChannelMarkerCache } from '../utils/removeChannelMarkerCache';
28
- import { initializeMessagePreviewSetting } from '../utils/messagePreviewEngine';
29
- import { ASCError } from '~/core/errors';
30
- import SessionWatcher from '../utils/SessionWatcher';
31
-
32
- /*
33
- * declared earlier to accomodate case when logging in with a different user
34
- * than the one already connected, in which case the existing subscriptions need
35
- * to be cleared
36
- */
37
- let subscriptions: Amity.Unsubscriber[] = [];
38
-
39
- async function runMqtt() {
40
- await modifyMqttConnection();
41
- }
42
-
43
- interface Params {
44
- userId: string;
45
- token: {
46
- issuedAt: string;
47
- expiresAt: string;
48
- accessToken: string;
49
- };
50
- }
51
-
52
- const isSameUserId = (token: Params['token']['accessToken']) => {
53
- const client = getActiveClient();
54
-
55
- const decoded = jwtDecode<{
56
- user: {
57
- userId: string;
58
- publicUserId: string;
59
- deviceInfo: Amity.Device['deviceInfo'];
60
- networkId: string;
61
- displayName: string;
62
- refreshToken: string;
63
- };
64
- }>(token);
65
-
66
- return decoded?.user?.publicUserId === client.userId;
67
- };
68
-
69
- const validateAccessToken = async ({ token, userId }: Params) => {
70
- const client = getActiveClient();
71
- // begin establishing session
72
- setSessionState(Amity.SessionStates.ESTABLISHING);
73
-
74
- const {
75
- data: { users },
76
- } = await client.http.get(`/api/v3/users/${userId}`, {
77
- headers: {
78
- Authorization: `Bearer ${token.accessToken}`,
79
- },
80
- });
81
-
82
- const user = users.find((u: Amity.User) => u.userId === userId);
83
-
84
- client.http.defaults.headers.common.Authorization = `Bearer ${token.accessToken}`;
85
-
86
- client.http.defaults.metadata = {
87
- tokenExpiry: token.expiresAt,
88
- isGlobalBanned: false,
89
- isUserDeleted: false,
90
- };
91
-
92
- client.upload.defaults.headers.common.Authorization = `Bearer ${token.accessToken}`;
93
-
94
- client.upload.defaults.metadata = {
95
- tokenExpiry: token.expiresAt,
96
- isGlobalBanned: false,
97
- isUserDeleted: false,
98
- };
99
-
100
- // manually setup the token for ws transport
101
- if (client.ws) client.ws.io.opts.query = { token: token.accessToken };
102
-
103
- client.token = token;
104
-
105
- setSessionState(Amity.SessionStates.ESTABLISHED);
106
-
107
- return user;
108
- };
109
-
110
- /* begin_public_function
111
- id: client.resumeSession
112
- */
113
- /**
114
- * ```js
115
- * import { resumeSession } from '@amityco/ts-sdk/client/api'
116
- * const success = await resumeSession({
117
- * userId: 'XYZ123456789',
118
- * token: { accessToken: 'abc123', issuedAt: '2023-01-01T00:00:00Z', expiresAt: '2023-01-02T00:00:00Z' }
119
- * })
120
- * ```
121
- *
122
- * Connects an {@link Amity.Client} instance to ASC servers using an existing access token
123
- *
124
- * @param params the connect parameters
125
- * @param params.userId the user ID for the current session
126
- * @param params.token the existing access token with its metadata
127
- * @param sessionHandler the session handler for token renewal
128
- * @param config optional configuration
129
- * @returns a success boolean if connected
130
- *
131
- * @category Client API
132
- * @async
133
- */
134
- export const resumeSession = async (
135
- params: Params,
136
- sessionHandler: Amity.SessionHandler,
137
- config?: Amity.ConnectClientConfig,
138
- ): Promise<boolean> => {
139
- const client = getActiveClient();
140
- let unsubWatcher: Amity.Unsubscriber;
141
-
142
- client.log('client/api/resumeSession', {
143
- apiKey: client.apiKey,
144
- sessionState: client.sessionState,
145
- ...params,
146
- });
147
-
148
- // Handle existing connected user
149
- if (client.userId) {
150
- if (client.userId === params.userId && isSameUserId(params.token.accessToken)) {
151
- // Clear connections and listeners but preserve cache
152
- if (client.mqtt && client.mqtt.connected) {
153
- client.mqtt.disconnect();
154
- }
155
- if (client.ws && client.ws.connected) {
156
- client.ws.disconnect();
157
- }
158
-
159
- // Clear existing subscriptions
160
- subscriptions.forEach(fn => fn());
161
- subscriptions = [];
162
- } else {
163
- // Different user - do full logout
164
- await logout();
165
-
166
- // Remove subscription to ban and delete
167
- subscriptions.forEach(fn => fn());
168
- subscriptions = [];
169
- }
170
- }
171
-
172
- try {
173
- const user = await validateAccessToken(params);
174
-
175
- if (user == null) {
176
- throw new ASCError(
177
- `${params.userId} has not been found`,
178
- Amity.ClientError.UNKNOWN_ERROR,
179
- Amity.ErrorLevel.ERROR,
180
- );
181
- }
182
-
183
- if (user.isDeleted) {
184
- terminateClient(Amity.TokenTerminationReason.USER_DELETED);
185
- return false;
186
- }
187
-
188
- if (user.isGlobalBanned) {
189
- terminateClient(Amity.TokenTerminationReason.GLOBAL_BAN);
190
- return false;
191
- }
192
-
193
- // FIXME: events are duplicated if connectClient is called few times without disconnectClient
194
- // wire websocket events to our event emitter
195
- proxyWebsocketEvents(client.ws, client.emitter);
196
-
197
- client.ws?.open();
198
-
199
- client.userId = user.userId;
200
-
201
- client.sessionHandler = sessionHandler;
202
-
203
- /*
204
- * Cannot push to subscriptions as watcher needs to continue working even if
205
- * token expires
206
- */
207
- unsubWatcher = client.accessTokenExpiryWatcher(sessionHandler);
208
-
209
- setActiveUser(user);
210
- } catch (error) {
211
- /*
212
- * if getting token failed session state reverts to initial state when app
213
- * is first launched
214
- */
215
- SessionWatcher.getInstance().setSessionState(Amity.SessionStates.NOT_LOGGED_IN);
216
-
217
- // pass error down tree so the calling function handle it
218
- throw error;
219
- }
220
-
221
- if (config?.disableRTE !== true) {
222
- runMqtt();
223
- }
224
-
225
- await initializeMessagePreviewSetting();
226
-
227
- if (subscriptions.length === 0) {
228
- subscriptions.push(
229
- // GLOBAL_BAN
230
- onClientBanned((_: Amity.UserPayload) => {
231
- terminateClient(Amity.TokenTerminationReason.GLOBAL_BAN);
232
-
233
- subscriptions.forEach(fn => fn());
234
-
235
- unsubWatcher();
236
- }),
237
-
238
- onTokenTerminated(_ => {
239
- terminateClient();
240
-
241
- subscriptions.forEach(fn => fn());
242
-
243
- unsubWatcher();
244
- }),
245
-
246
- onUserDeleted((user: Amity.InternalUser) => {
247
- if (user.userId === client.userId) {
248
- terminateClient(Amity.TokenTerminationReason.USER_DELETED);
249
-
250
- subscriptions.forEach(fn => fn());
251
-
252
- unsubWatcher();
253
- }
254
- }),
255
-
256
- onTokenExpired(state => {
257
- SessionWatcher.getInstance().setSessionState(state);
258
-
259
- logout();
260
-
261
- subscriptions.forEach(fn => fn());
262
- }),
263
-
264
- // NOTE: This is a temporary solution to handle the channel marker when the user is forced to leave
265
- // the channel because currently backend can't handle this, so every time a user is banned from
266
- // a channel or the channel is deleted the channel's unread count will not be reset to zero
267
- onChannelDeleted(removeChannelMarkerCache),
268
- onChannelMemberBanned(removeChannelMarkerCache),
269
-
270
- markReadEngineOnLoginHandler(),
271
- analyticsEngineOnLoginHandler(),
272
- objectResolverEngineOnLoginHandler(),
273
- );
274
-
275
- if (client.useLegacyUnreadCount) {
276
- subscriptions.push(readReceiptSyncEngineOnLoginHandler());
277
- } else subscriptions.push(legacyReadReceiptSyncEngineOnLoginHandler());
278
- }
279
-
280
- return true;
281
- };
282
- /* end_public_function */