From e2d5c675d04da286982183e37e73ec3149638a8a Mon Sep 17 00:00:00 2001 From: Evgeny Date: Tue, 26 Aug 2025 16:38:27 +0100 Subject: [PATCH] bots: generate code for TypeScript types module from Haskell tests (#6220) * bots: generate code for TypeScript types module from Haskell tests * types for API events and command responses * code for chat command types * license, readme * fix array types * fix more types * add response type * add Connect command to docs/ts * update typescript client package to use auto-generated types --- bots/api/COMMANDS.md | 281 +- bots/api/TYPES.md | 12 +- bots/src/API/Docs/Commands.hs | 76 +- bots/src/API/Docs/Generate.hs | 18 +- bots/src/API/Docs/Generate/TypeScript.hs | 189 + bots/src/API/Docs/Responses.hs | 2 +- bots/src/API/Docs/Syntax.hs | 37 +- bots/src/API/Docs/Syntax/Types.hs | 12 + bots/src/API/Docs/Types.hs | 6 +- bots/src/API/TypeInfo.hs | 20 +- .../types/typescript/.gitignore | 4 + .../types/typescript/LICENSE | 661 +++ .../types/typescript/README.md | 11 + .../types/typescript/package.json | 42 + .../types/typescript/src/commands.ts | 662 +++ .../types/typescript/src/events.ts | 430 ++ .../types/typescript/src/index.ts | 4 + .../types/typescript/src/responses.ts | 396 ++ .../types/typescript/src/types.ts | 4509 +++++++++++++++++ .../types/typescript/tsconfig.json | 22 + .../simplex-chat-client/typescript/README.md | 2 + .../typescript/package.json | 15 +- .../typescript/src/client.ts | 237 +- .../typescript/src/command.ts | 822 --- .../typescript/src/response.ts | 1109 ---- .../typescript/src/transport.ts | 12 +- .../typescript/tests/client.test.ts | 35 +- simplex-chat.cabal | 1 + src/Simplex/Chat/Controller.hs | 4 +- tests/APIDocs.hs | 35 +- 30 files changed, 7416 insertions(+), 2250 deletions(-) create mode 100644 bots/src/API/Docs/Generate/TypeScript.hs create mode 100644 packages/simplex-chat-client/types/typescript/.gitignore create mode 100644 packages/simplex-chat-client/types/typescript/LICENSE create mode 100644 packages/simplex-chat-client/types/typescript/README.md create mode 100644 packages/simplex-chat-client/types/typescript/package.json create mode 100644 packages/simplex-chat-client/types/typescript/src/commands.ts create mode 100644 packages/simplex-chat-client/types/typescript/src/events.ts create mode 100644 packages/simplex-chat-client/types/typescript/src/index.ts create mode 100644 packages/simplex-chat-client/types/typescript/src/responses.ts create mode 100644 packages/simplex-chat-client/types/typescript/src/types.ts create mode 100644 packages/simplex-chat-client/types/typescript/tsconfig.json delete mode 100644 packages/simplex-chat-client/typescript/src/command.ts delete mode 100644 packages/simplex-chat-client/typescript/src/response.ts diff --git a/bots/api/COMMANDS.md b/bots/api/COMMANDS.md index 4ea8b7e466..dd1dd256d0 100644 --- a/bots/api/COMMANDS.md +++ b/bots/api/COMMANDS.md @@ -42,6 +42,7 @@ This file is generated automatically. - [APIAddContact](#apiaddcontact) - [APIConnectPlan](#apiconnectplan) - [APIConnect](#apiconnect) +- [Connect](#connect) - [APIAcceptContact](#apiacceptcontact) - [APIRejectContact](#apirejectcontact) @@ -90,13 +91,17 @@ Create bot address. '/_address ' + str(userId) # Python ``` -**Response**: +**Responses**: UserContactLinkCreated: User contact address created. - type: "userContactLinkCreated" - user: [User](./TYPES.md#user) - connLinkContact: [CreatedConnLink](./TYPES.md#createdconnlink) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -123,12 +128,16 @@ Delete bot address. '/_delete_address ' + str(userId) # Python ``` -**Response**: +**Responses**: UserContactLinkDeleted: User contact address deleted. - type: "userContactLinkDeleted" - user: [User](./TYPES.md#user) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -155,13 +164,17 @@ Get bot address and settings. '/_show_address ' + str(userId) # Python ``` -**Response**: +**Responses**: UserContactLink: User contact address. - type: "userContactLink" - user: [User](./TYPES.md#user) - contactLink: [UserContactLink](./TYPES.md#usercontactlink) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -189,7 +202,7 @@ Add address to bot profile. '/_profile_address ' + str(userId) + ' ' + ('on' if enable else 'off') # Python ``` -**Response**: +**Responses**: UserProfileUpdated: User profile updated. - type: "userProfileUpdated" @@ -198,6 +211,10 @@ UserProfileUpdated: User profile updated. - toProfile: [Profile](./TYPES.md#profile) - updateSummary: [UserProfileUpdateSummary](./TYPES.md#userprofileupdatesummary) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -225,13 +242,17 @@ Set bot address settings. '/_address_settings ' + str(userId) + ' ' + json.dumps(settings) # Python ``` -**Response**: +**Responses**: UserContactLinkUpdated: User contact address updated. - type: "userContactLinkUpdated" - user: [User](./TYPES.md#user) - contactLink: [UserContactLink](./TYPES.md#usercontactlink) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -266,13 +287,17 @@ Send messages. '/_send ' + str(sendRef) + (' live=on' if liveMessage else '') + ((' ttl=' + str(ttl)) if ttl is not None else '') + ' json ' + json.dumps(composedMessages) # Python ``` -**Response**: +**Responses**: NewChatItems: New messages. - type: "newChatItems" - user: [User](./TYPES.md#user) - chatItems: [[AChatItem](./TYPES.md#achatitem)] +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -349,7 +374,7 @@ Delete message. '/_delete item ' + str(chatRef) + ' ' + ','.join(map(str, chatItemIds)) + ' ' + str(deleteMode) # Python ``` -**Response**: +**Responses**: ChatItemsDeleted: Messages deleted. - type: "chatItemsDeleted" @@ -358,6 +383,10 @@ ChatItemsDeleted: Messages deleted. - byUser: bool - timed: bool +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -385,7 +414,7 @@ Moderate message. Requires Moderator role (and higher than message author's). '/_delete member item #' + str(groupId) + ' ' + ','.join(map(str, chatItemIds)) # Python ``` -**Response**: +**Responses**: ChatItemsDeleted: Messages deleted. - type: "chatItemsDeleted" @@ -394,6 +423,10 @@ ChatItemsDeleted: Messages deleted. - byUser: bool - timed: bool +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -423,7 +456,7 @@ Add/remove message reaction. '/_reaction ' + str(chatRef) + ' ' + str(chatItemId) + ' ' + ('on' if add else 'off') + ' ' + json.dumps(reaction) # Python ``` -**Response**: +**Responses**: ChatItemReaction: Message reaction. - type: "chatItemReaction" @@ -431,6 +464,10 @@ ChatItemReaction: Message reaction. - added: bool - reaction: [ACIReaction](./TYPES.md#acireaction) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -478,6 +515,10 @@ RcvFileAcceptedSndCancelled: File accepted, but no longer sent. - user: [User](./TYPES.md#user) - rcvFileTransfer: [RcvFileTransfer](./TYPES.md#rcvfiletransfer) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -559,7 +600,7 @@ Add contact to group. Requires bot to have Admin role. '/_add #' + str(groupId) + ' ' + str(contactId) + ' ' + str(memberRole) # Python ``` -**Response**: +**Responses**: SentGroupInvitation: Group invitation sent. - type: "sentGroupInvitation" @@ -568,6 +609,10 @@ SentGroupInvitation: Group invitation sent. - contact: [Contact](./TYPES.md#contact) - member: [GroupMember](./TYPES.md#groupmember) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -594,7 +639,7 @@ Join group. '/_join #' + str(groupId) # Python ``` -**Response**: +**Responses**: UserAcceptedGroupSent: User accepted group invitation. - type: "userAcceptedGroupSent" @@ -602,6 +647,10 @@ UserAcceptedGroupSent: User accepted group invitation. - groupInfo: [GroupInfo](./TYPES.md#groupinfo) - hostContact: [Contact](./TYPES.md#contact)? +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -673,7 +722,7 @@ Set members role. Requires Admin role. '/_member role #' + str(groupId) + ' ' + ','.join(map(str, groupMemberIds)) + ' ' + str(memberRole) # Python ``` -**Response**: +**Responses**: MembersRoleUser: Members role changed by user. - type: "membersRoleUser" @@ -682,6 +731,10 @@ MembersRoleUser: Members role changed by user. - members: [[GroupMember](./TYPES.md#groupmember)] - toRole: [GroupMemberRole](./TYPES.md#groupmemberrole) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -710,7 +763,7 @@ Block members. Requires Moderator role. '/_block #' + str(groupId) + ' ' + ','.join(map(str, groupMemberIds)) + ' blocked=' + ('on' if blocked else 'off') # Python ``` -**Response**: +**Responses**: MembersBlockedForAllUser: Members blocked for all by admin. - type: "membersBlockedForAllUser" @@ -719,6 +772,10 @@ MembersBlockedForAllUser: Members blocked for all by admin. - members: [[GroupMember](./TYPES.md#groupmember)] - blocked: bool +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -789,13 +846,17 @@ Leave group. '/_leave #' + str(groupId) # Python ``` -**Response**: +**Responses**: LeftMemberUser: User left group. - type: "leftMemberUser" - user: [User](./TYPES.md#user) - groupInfo: [GroupInfo](./TYPES.md#groupinfo) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -822,13 +883,17 @@ Get group members. '/_members #' + str(groupId) # Python ``` -**Response**: +**Responses**: GroupMembers: Group members. - type: "groupMembers" - user: [User](./TYPES.md#user) - group: [Group](./TYPES.md#group) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -857,13 +922,17 @@ Create group. '/_group ' + str(userId) + (' incognito=on' if incognito else '') + ' ' + json.dumps(groupProfile) # Python ``` -**Response**: +**Responses**: GroupCreated: Group created. - type: "groupCreated" - user: [User](./TYPES.md#user) - groupInfo: [GroupInfo](./TYPES.md#groupinfo) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -891,7 +960,7 @@ Update group profile. '/_group_profile #' + str(groupId) + ' ' + json.dumps(groupProfile) # Python ``` -**Response**: +**Responses**: GroupUpdated: Group updated. - type: "groupUpdated" @@ -900,6 +969,10 @@ GroupUpdated: Group updated. - toGroup: [GroupInfo](./TYPES.md#groupinfo) - member_: [GroupMember](./TYPES.md#groupmember)? +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -932,7 +1005,7 @@ Create group link. '/_create link #' + str(groupId) + ' ' + str(memberRole) # Python ``` -**Response**: +**Responses**: GroupLinkCreated: Group link created. - type: "groupLinkCreated" @@ -940,6 +1013,10 @@ GroupLinkCreated: Group link created. - groupInfo: [GroupInfo](./TYPES.md#groupinfo) - groupLink: [GroupLink](./TYPES.md#grouplink) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -967,7 +1044,7 @@ Set member role for group link. '/_set link role #' + str(groupId) + ' ' + str(memberRole) # Python ``` -**Response**: +**Responses**: GroupLink: Group link. - type: "groupLink" @@ -975,6 +1052,10 @@ GroupLink: Group link. - groupInfo: [GroupInfo](./TYPES.md#groupinfo) - groupLink: [GroupLink](./TYPES.md#grouplink) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1001,13 +1082,17 @@ Delete group link. '/_delete link #' + str(groupId) # Python ``` -**Response**: +**Responses**: GroupLinkDeleted: Group link deleted. - type: "groupLinkDeleted" - user: [User](./TYPES.md#user) - groupInfo: [GroupInfo](./TYPES.md#groupinfo) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1034,7 +1119,7 @@ Get group link. '/_get link #' + str(groupId) # Python ``` -**Response**: +**Responses**: GroupLink: Group link. - type: "groupLink" @@ -1042,6 +1127,10 @@ GroupLink: Group link. - groupInfo: [GroupInfo](./TYPES.md#groupinfo) - groupLink: [GroupLink](./TYPES.md#grouplink) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1074,7 +1163,7 @@ Create 1-time invitation link. '/_connect ' + str(userId) + (' incognito=on' if incognito else '') # Python ``` -**Response**: +**Responses**: Invitation: One-time invitation. - type: "invitation" @@ -1082,6 +1171,10 @@ Invitation: One-time invitation. - connLinkInvitation: [CreatedConnLink](./TYPES.md#createdconnlink) - connection: [PendingContactConnection](./TYPES.md#pendingcontactconnection) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1109,7 +1202,7 @@ Determine SimpleX link type and if the bot is already connected via this link. '/_connect plan ' + str(userId) + ' ' + connectionLink # Python ``` -**Response**: +**Responses**: ConnectionPlan: Connection link information. - type: "connectionPlan" @@ -1117,32 +1210,36 @@ ConnectionPlan: Connection link information. - connLink: [CreatedConnLink](./TYPES.md#createdconnlink) - connectionPlan: [ConnectionPlan](./TYPES.md#connectionplan) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- ### APIConnect -Connect via SimpleX link. The link can be 1-time invitation link, contact address or group link +Connect via prepared SimpleX link. The link can be 1-time invitation link, contact address or group link *Network usage*: interactive. **Parameters**: - userId: int64 - incognito: bool -- connLink_: [CreatedConnLink](./TYPES.md#createdconnlink)? +- preparedLink_: [CreatedConnLink](./TYPES.md#createdconnlink)? **Syntax**: ``` -/_connect +/_connect [ ] ``` ```javascript -'/_connect ' + userId + ' ' + connLink_.toString() // JavaScript +'/_connect ' + userId + (preparedLink_ ? ' ' + preparedLink_.toString() : '') // JavaScript ``` ```python -'/_connect ' + str(userId) + ' ' + str(connLink_) # Python +'/_connect ' + str(userId) + ((' ' + str(preparedLink_)) if preparedLink_ is not None else '') # Python ``` **Responses**: @@ -1164,6 +1261,60 @@ SentInvitation: Invitation sent to contact address. - connection: [PendingContactConnection](./TYPES.md#pendingcontactconnection) - customUserProfile: [Profile](./TYPES.md#profile)? +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + +--- + + +### Connect + +Connect via SimpleX link as string in the active user profile. + +*Network usage*: interactive. + +**Parameters**: +- incognito: bool +- connLink_: string? + +**Syntax**: + +``` +/connect[ ] +``` + +```javascript +'/connect' + (connLink_ ? ' ' + connLink_ : '') // JavaScript +``` + +```python +'/connect' + ((' ' + connLink_) if connLink_ is not None else '') # Python +``` + +**Responses**: + +SentConfirmation: Confirmation sent to one-time invitation. +- type: "sentConfirmation" +- user: [User](./TYPES.md#user) +- connection: [PendingContactConnection](./TYPES.md#pendingcontactconnection) +- customUserProfile: [Profile](./TYPES.md#profile)? + +ContactAlreadyExists: Contact already exists. +- type: "contactAlreadyExists" +- user: [User](./TYPES.md#user) +- contact: [Contact](./TYPES.md#contact) + +SentInvitation: Invitation sent to contact address. +- type: "sentInvitation" +- user: [User](./TYPES.md#user) +- connection: [PendingContactConnection](./TYPES.md#pendingcontactconnection) +- customUserProfile: [Profile](./TYPES.md#profile)? + +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1190,13 +1341,17 @@ Accept contact request. '/_accept ' + str(contactReqId) # Python ``` -**Response**: +**Responses**: AcceptingContactRequest: Contact request accepted. - type: "acceptingContactRequest" - user: [User](./TYPES.md#user) - contact: [Contact](./TYPES.md#contact) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1223,7 +1378,7 @@ Reject contact request. The user who sent the request is **not notified**. '/_reject ' + str(contactReqId) # Python ``` -**Response**: +**Responses**: ContactRequestRejected: Contact request rejected. - type: "contactRequestRejected" @@ -1231,6 +1386,10 @@ ContactRequestRejected: Contact request rejected. - contactRequest: [UserContactRequest](./TYPES.md#usercontactrequest) - contact_: [Contact](./TYPES.md#contact)? +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1262,13 +1421,17 @@ Get contacts. '/_contacts ' + str(userId) # Python ``` -**Response**: +**Responses**: ContactsList: Contacts. - type: "contactsList" - user: [User](./TYPES.md#user) - contacts: [[Contact](./TYPES.md#contact)] +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1297,13 +1460,17 @@ Get groups. '/_groups ' + str(userId) + ((' @' + str(contactId_)) if contactId_ is not None else '') + ((' ' + search) if search is not None else '') # Python ``` -**Response**: +**Responses**: GroupsList: Groups. - type: "groupsList" - user: [User](./TYPES.md#user) - groups: [[GroupInfoSummary](./TYPES.md#groupinfosummary)] +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1348,6 +1515,10 @@ GroupDeletedUser: User deleted group. - user: [User](./TYPES.md#user) - groupInfo: [GroupInfo](./TYPES.md#groupinfo) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1368,12 +1539,16 @@ Get active user profile /user ``` -**Response**: +**Responses**: ActiveUser: Active user profile. - type: "activeUser" - user: [User](./TYPES.md#user) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1400,12 +1575,16 @@ Create new user profile '/_create user ' + json.dumps(newUser) # Python ``` -**Response**: +**Responses**: ActiveUser: Active user profile. - type: "activeUser" - user: [User](./TYPES.md#user) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + **Errors**: - UserExists: User or contact with this name already exists. - InvalidDisplayName: Invalid user display name. @@ -1425,12 +1604,16 @@ Get all user profiles /users ``` -**Response**: +**Responses**: UsersList: Users. - type: "usersList" - users: [[UserInfo](./TYPES.md#userinfo)] +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1458,12 +1641,16 @@ Set active user profile '/_user ' + str(userId) + ((' ' + json.dumps(viewPwd)) if viewPwd is not None else '') # Python ``` -**Response**: +**Responses**: ActiveUser: Active user profile. - type: "activeUser" - user: [User](./TYPES.md#user) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + **Errors**: - ChatNotStarted: Chat not started. @@ -1495,12 +1682,16 @@ Delete user profile. '/_delete user ' + str(userId) + ' del_smp=' + ('on' if delSMPQueues else 'off') + ((' ' + json.dumps(viewPwd)) if viewPwd is not None else '') # Python ``` -**Response**: +**Responses**: CmdOk: Ok. - type: "cmdOk" - user_: [User](./TYPES.md#user)? +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1528,7 +1719,7 @@ Update user profile. '/_profile ' + str(userId) + ' ' + json.dumps(profile) # Python ``` -**Response**: +**Responses**: UserProfileUpdated: User profile updated. - type: "userProfileUpdated" @@ -1537,6 +1728,14 @@ UserProfileUpdated: User profile updated. - toProfile: [Profile](./TYPES.md#profile) - updateSummary: [UserProfileUpdateSummary](./TYPES.md#userprofileupdatesummary) +UserProfileNoChange: User profile was not changed. +- type: "userProfileNoChange" +- user: [User](./TYPES.md#user) + +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- @@ -1564,7 +1763,7 @@ Configure chat preference overrides for the contact. '/_set prefs @' + str(contactId) + ' ' + json.dumps(preferences) # Python ``` -**Response**: +**Responses**: ContactPrefsUpdated: Contact preferences updated. - type: "contactPrefsUpdated" @@ -1572,4 +1771,8 @@ ContactPrefsUpdated: Contact preferences updated. - fromContact: [Contact](./TYPES.md#contact) - toContact: [Contact](./TYPES.md#contact) +ChatCmdError: Command error. +- type: "chatCmdError" +- chatError: [ChatError](./TYPES.md#chaterror) + --- diff --git a/bots/api/TYPES.md b/bots/api/TYPES.md index 449d6a9294..4743ccb881 100644 --- a/bots/api/TYPES.md +++ b/bots/api/TYPES.md @@ -228,14 +228,6 @@ DECRYPT_CB: RATCHET_HEADER: - type: "RATCHET_HEADER" -RATCHET_EARLIER: -- type: "RATCHET_EARLIER" -- : word32 - -RATCHET_SKIPPED: -- type: "RATCHET_SKIPPED" -- : word32 - RATCHET_SYNC: - type: "RATCHET_SYNC" @@ -1359,11 +1351,11 @@ str(chatType) + str(chatId) + ((str(chatScope)) if chatScope is not None else '' ``` ```javascript -self == 'contact' ? '@' : self == 'group' ? '#' : self == 'local' ? '*' : '' // JavaScript +self == 'direct' ? '@' : self == 'group' ? '#' : self == 'local' ? '*' : '' // JavaScript ``` ```python -'@' if str(self) == 'contact' else '#' if str(self) == 'group' else '*' if str(self) == 'local' else '' # Python +'@' if str(self) == 'direct' else '#' if str(self) == 'group' else '*' if str(self) == 'local' else '' # Python ``` diff --git a/bots/src/API/Docs/Commands.hs b/bots/src/API/Docs/Commands.hs index 3804a23f31..279a74480b 100644 --- a/bots/src/API/Docs/Commands.hs +++ b/bots/src/API/Docs/Commands.hs @@ -77,16 +77,16 @@ chatCommandsDocsData :: [(String, String, [(ConsName, [String], Text, [ConsName] chatCommandsDocsData = [ ( "Address commands", "Bots can use these commands to automatically check and create address when initialized", - [ ("APICreateMyAddress", [], "Create bot address.", ["CRUserContactLinkCreated"], [], Just UNInteractive, "/_address " <> Param "userId"), - ("APIDeleteMyAddress", [], "Delete bot address.", ["CRUserContactLinkDeleted"], [], Just UNBackground, "/_delete_address " <> Param "userId"), - ("APIShowMyAddress", [], "Get bot address and settings.", ["CRUserContactLink"], [], Nothing, "/_show_address " <> Param "userId"), - ("APISetProfileAddress", [], "Add address to bot profile.", ["CRUserProfileUpdated"], [], Just UNInteractive, "/_profile_address " <> Param "userId" <> " " <> OnOff "enable"), - ("APISetAddressSettings", [], "Set bot address settings.", ["CRUserContactLinkUpdated"], [], Just UNInteractive, "/_address_settings " <> Param "userId" <> " " <> Json "settings") + [ ("APICreateMyAddress", [], "Create bot address.", ["CRUserContactLinkCreated", "CRChatCmdError"], [], Just UNInteractive, "/_address " <> Param "userId"), + ("APIDeleteMyAddress", [], "Delete bot address.", ["CRUserContactLinkDeleted", "CRChatCmdError"], [], Just UNBackground, "/_delete_address " <> Param "userId"), + ("APIShowMyAddress", [], "Get bot address and settings.", ["CRUserContactLink", "CRChatCmdError"], [], Nothing, "/_show_address " <> Param "userId"), + ("APISetProfileAddress", [], "Add address to bot profile.", ["CRUserProfileUpdated", "CRChatCmdError"], [], Just UNInteractive, "/_profile_address " <> Param "userId" <> " " <> OnOff "enable"), + ("APISetAddressSettings", [], "Set bot address settings.", ["CRUserContactLinkUpdated", "CRChatCmdError"], [], Just UNInteractive, "/_address_settings " <> Param "userId" <> " " <> Json "settings") ] ), ( "Message commands", "Commands to send, update, delete, moderate messages and set message reactions", - [ ("APISendMessages", [], "Send messages.", ["CRNewChatItems"], [], Just UNBackground, "/_send " <> Param "sendRef" <> OnOffParam "live" "liveMessage" (Just False) <> Optional "" (" ttl=" <> Param "$0") "ttl" <> " json " <> Json "composedMessages"), + [ ("APISendMessages", [], "Send messages.", ["CRNewChatItems", "CRChatCmdError"], [], Just UNBackground, "/_send " <> Param "sendRef" <> OnOffParam "live" "liveMessage" (Just False) <> Optional "" (" ttl=" <> Param "$0") "ttl" <> " json " <> Json "composedMessages"), ( "APIUpdateChatItem", [], "Update message.", @@ -95,53 +95,54 @@ chatCommandsDocsData = Just UNBackground, "/_update item " <> Param "chatRef" <> " " <> Param "chatItemId" <> OnOffParam "live" "liveMessage" (Just False) <> " json " <> Json "updatedMessage" ), - ("APIDeleteChatItem", [], "Delete message.", ["CRChatItemsDeleted"], [], Just UNBackground, "/_delete item " <> Param "chatRef" <> " " <> Join ',' "chatItemIds" <> " " <> Param "deleteMode"), - ("APIDeleteMemberChatItem", [], "Moderate message. Requires Moderator role (and higher than message author's).", ["CRChatItemsDeleted"], [], Just UNBackground, "/_delete member item #" <> Param "groupId" <> " " <> Join ',' "chatItemIds"), - ("APIChatItemReaction", [], "Add/remove message reaction.", ["CRChatItemReaction"], [], Just UNBackground, "/_reaction " <> Param "chatRef" <> " " <> Param "chatItemId" <> " " <> OnOff "add" <> " " <> Json "reaction") + ("APIDeleteChatItem", [], "Delete message.", ["CRChatItemsDeleted", "CRChatCmdError"], [], Just UNBackground, "/_delete item " <> Param "chatRef" <> " " <> Join ',' "chatItemIds" <> " " <> Param "deleteMode"), + ("APIDeleteMemberChatItem", [], "Moderate message. Requires Moderator role (and higher than message author's).", ["CRChatItemsDeleted", "CRChatCmdError"], [], Just UNBackground, "/_delete member item #" <> Param "groupId" <> " " <> Join ',' "chatItemIds"), + ("APIChatItemReaction", [], "Add/remove message reaction.", ["CRChatItemReaction", "CRChatCmdError"], [], Just UNBackground, "/_reaction " <> Param "chatRef" <> " " <> Param "chatItemId" <> " " <> OnOff "add" <> " " <> Json "reaction") ] ), ( "File commands", "Commands to receive and to cancel files. Files are sent as part of the message, there are no separate commands to send files.", - [ ("ReceiveFile", [], "Receive file.", ["CRRcvFileAccepted", "CRRcvFileAcceptedSndCancelled"], [], Nothing, "/freceive " <> Param "fileId" <> OnOffParam "approved_relays" "userApprovedRelays" (Just False) <> OnOffParam "encrypt" "storeEncrypted" Nothing <> OnOffParam "inline" "fileInline" Nothing <> Optional "" (" " <> Param "$0") "filePath"), + [ ("ReceiveFile", [], "Receive file.", ["CRRcvFileAccepted", "CRRcvFileAcceptedSndCancelled", "CRChatCmdError"], [], Nothing, "/freceive " <> Param "fileId" <> OnOffParam "approved_relays" "userApprovedRelays" (Just False) <> OnOffParam "encrypt" "storeEncrypted" Nothing <> OnOffParam "inline" "fileInline" Nothing <> Optional "" (" " <> Param "$0") "filePath"), ("CancelFile", [], "Cancel file.", ["CRSndFileCancelled", "CRRcvFileCancelled", "CRChatCmdError"], [TD "CEFileCancel" "Cannot cancel file"], Just UNBackground, "/fcancel " <> Param "fileId") ] ), ( "Group commands", "Commands to manage and moderate groups. These commands can be used with business chats as well - they are groups. E.g., a common scenario would be to add human agents to business chat with the customer who connected via business address.", - [ ("APIAddMember", [], "Add contact to group. Requires bot to have Admin role.", ["CRSentGroupInvitation"], [], Just UNInteractive, "/_add #" <> Param "groupId" <> " " <> Param "contactId" <> " " <> Param "memberRole"), - ("APIJoinGroup", ["enableNtfs"], "Join group.", ["CRUserAcceptedGroupSent"], [], Just UNInteractive, "/_join #" <> Param "groupId"), + [ ("APIAddMember", [], "Add contact to group. Requires bot to have Admin role.", ["CRSentGroupInvitation", "CRChatCmdError"], [], Just UNInteractive, "/_add #" <> Param "groupId" <> " " <> Param "contactId" <> " " <> Param "memberRole"), + ("APIJoinGroup", ["enableNtfs"], "Join group.", ["CRUserAcceptedGroupSent", "CRChatCmdError"], [], Just UNInteractive, "/_join #" <> Param "groupId"), ("APIAcceptMember", [], "Accept group member. Requires Admin role.", ["CRMemberAccepted", "CRChatCmdError"], [TD "CEGroupMemberNotActive" "Member is not connected yet"], Just UNBackground, "/_accept member #" <> Param "groupId" <> " " <> Param "groupMemberId" <> " " <> Param "memberRole"), - ("APIMembersRole", [], "Set members role. Requires Admin role.", ["CRMembersRoleUser"], [], Just UNBackground, "/_member role #" <> Param "groupId" <> " " <> Join ',' "groupMemberIds" <> " " <> Param "memberRole"), - ("APIBlockMembersForAll", [], "Block members. Requires Moderator role.", ["CRMembersBlockedForAllUser"], [], Just UNBackground, "/_block #" <> Param "groupId" <> " " <> Join ',' "groupMemberIds" <> OnOffParam "blocked" "blocked" Nothing), + ("APIMembersRole", [], "Set members role. Requires Admin role.", ["CRMembersRoleUser", "CRChatCmdError"], [], Just UNBackground, "/_member role #" <> Param "groupId" <> " " <> Join ',' "groupMemberIds" <> " " <> Param "memberRole"), + ("APIBlockMembersForAll", [], "Block members. Requires Moderator role.", ["CRMembersBlockedForAllUser", "CRChatCmdError"], [], Just UNBackground, "/_block #" <> Param "groupId" <> " " <> Join ',' "groupMemberIds" <> OnOffParam "blocked" "blocked" Nothing), ("APIRemoveMembers", [], "Remove members. Requires Admin role.", ["CRUserDeletedMembers", "CRChatCmdError"], ["CEGroupMemberNotFound"], Just UNBackground, "/_remove #" <> Param "groupId" <> " " <> Join ',' "groupMemberIds" <> OnOffParam "messages" "withMessages" (Just False)), - ("APILeaveGroup", [], "Leave group.", ["CRLeftMemberUser"], [], Just UNBackground, "/_leave #" <> Param "groupId"), - ("APIListMembers", [], "Get group members.", ["CRGroupMembers"], [], Nothing, "/_members #" <> Param "groupId"), - ("APINewGroup", [], "Create group.", ["CRGroupCreated"], [], Nothing, "/_group " <> Param "userId" <> OnOffParam "incognito" "incognito" (Just False) <> " " <> Json "groupProfile"), - ("APIUpdateGroupProfile", [], "Update group profile.", ["CRGroupUpdated"], [], Just UNBackground, "/_group_profile #" <> Param "groupId" <> " " <> Json "groupProfile") + ("APILeaveGroup", [], "Leave group.", ["CRLeftMemberUser", "CRChatCmdError"], [], Just UNBackground, "/_leave #" <> Param "groupId"), + ("APIListMembers", [], "Get group members.", ["CRGroupMembers", "CRChatCmdError"], [], Nothing, "/_members #" <> Param "groupId"), + ("APINewGroup", [], "Create group.", ["CRGroupCreated", "CRChatCmdError"], [], Nothing, "/_group " <> Param "userId" <> OnOffParam "incognito" "incognito" (Just False) <> " " <> Json "groupProfile"), + ("APIUpdateGroupProfile", [], "Update group profile.", ["CRGroupUpdated", "CRChatCmdError"], [], Just UNBackground, "/_group_profile #" <> Param "groupId" <> " " <> Json "groupProfile") ] ), ( "Group link commands", "These commands can be used by bots that manage multiple public groups", - [ ("APICreateGroupLink", [], "Create group link.", ["CRGroupLinkCreated"], [], Just UNInteractive, "/_create link #" <> Param "groupId" <> " " <> Param "memberRole"), - ("APIGroupLinkMemberRole", [], "Set member role for group link.", ["CRGroupLink"], [], Nothing, "/_set link role #" <> Param "groupId" <> " " <> Param "memberRole"), - ("APIDeleteGroupLink", [], "Delete group link.", ["CRGroupLinkDeleted"], [], Just UNBackground, "/_delete link #" <> Param "groupId"), - ("APIGetGroupLink", [], "Get group link.", ["CRGroupLink"], [], Nothing, "/_get link #" <> Param "groupId") + [ ("APICreateGroupLink", [], "Create group link.", ["CRGroupLinkCreated", "CRChatCmdError"], [], Just UNInteractive, "/_create link #" <> Param "groupId" <> " " <> Param "memberRole"), + ("APIGroupLinkMemberRole", [], "Set member role for group link.", ["CRGroupLink", "CRChatCmdError"], [], Nothing, "/_set link role #" <> Param "groupId" <> " " <> Param "memberRole"), + ("APIDeleteGroupLink", [], "Delete group link.", ["CRGroupLinkDeleted", "CRChatCmdError"], [], Just UNBackground, "/_delete link #" <> Param "groupId"), + ("APIGetGroupLink", [], "Get group link.", ["CRGroupLink", "CRChatCmdError"], [], Nothing, "/_get link #" <> Param "groupId") ] ), ( "Connection commands", "These commands may be used to create connections. Most bots do not need to use them - bot users will connect via bot address with auto-accept enabled.", - [ ("APIAddContact", [], "Create 1-time invitation link.", ["CRInvitation"], [], Just UNInteractive, "/_connect " <> Param "userId" <> OnOffParam "incognito" "incognito" (Just False)), - ("APIConnectPlan", [], "Determine SimpleX link type and if the bot is already connected via this link.", ["CRConnectionPlan"], [], Just UNInteractive, "/_connect plan " <> Param "userId" <> " " <> Param "connectionLink"), - ("APIConnect", [], "Connect via SimpleX link. The link can be 1-time invitation link, contact address or group link", ["CRSentConfirmation", "CRContactAlreadyExists", "CRSentInvitation"], [], Just UNInteractive, "/_connect " <> Param "userId" <> " " <> Param "connLink_"), - ("APIAcceptContact", ["incognito"], "Accept contact request.", ["CRAcceptingContactRequest"], [], Just UNInteractive, "/_accept " <> Param "contactReqId"), - ("APIRejectContact", [], "Reject contact request. The user who sent the request is **not notified**.", ["CRContactRequestRejected"], [], Nothing, "/_reject " <> Param "contactReqId") + [ ("APIAddContact", [], "Create 1-time invitation link.", ["CRInvitation", "CRChatCmdError"], [], Just UNInteractive, "/_connect " <> Param "userId" <> OnOffParam "incognito" "incognito" (Just False)), + ("APIConnectPlan", [], "Determine SimpleX link type and if the bot is already connected via this link.", ["CRConnectionPlan", "CRChatCmdError"], [], Just UNInteractive, "/_connect plan " <> Param "userId" <> " " <> Param "connectionLink"), + ("APIConnect", [], "Connect via prepared SimpleX link. The link can be 1-time invitation link, contact address or group link", ["CRSentConfirmation", "CRContactAlreadyExists", "CRSentInvitation", "CRChatCmdError"], [], Just UNInteractive, "/_connect " <> Param "userId" <> Optional "" (" " <> Param "$0") "preparedLink_"), + ("Connect", [], "Connect via SimpleX link as string in the active user profile.", ["CRSentConfirmation", "CRContactAlreadyExists", "CRSentInvitation", "CRChatCmdError"], [], Just UNInteractive, "/connect" <> Optional "" (" " <> Param "$0") "connLink_"), + ("APIAcceptContact", ["incognito"], "Accept contact request.", ["CRAcceptingContactRequest", "CRChatCmdError"], [], Just UNInteractive, "/_accept " <> Param "contactReqId"), + ("APIRejectContact", [], "Reject contact request. The user who sent the request is **not notified**.", ["CRContactRequestRejected", "CRChatCmdError"], [], Nothing, "/_reject " <> Param "contactReqId") ] ), ( "Chat commands", "Commands to list and delete conversations.", - [ ("APIListContacts", [], "Get contacts.", ["CRContactsList"], [], Nothing, "/_contacts " <> Param "userId"), - ("APIListGroups", [], "Get groups.", ["CRGroupsList"], [], Nothing, "/_groups " <> Param "userId" <> Optional "" (" @" <> Param "$0") "contactId_" <> Optional "" (" " <> Param "$0") "search"), - ("APIDeleteChat", [], "Delete chat.", ["CRContactDeleted", "CRContactConnectionDeleted", "CRGroupDeletedUser"], [], Just UNBackground, "/_delete " <> Param "chatRef" <> " " <> Param "chatDeleteMode") + [ ("APIListContacts", [], "Get contacts.", ["CRContactsList", "CRChatCmdError"], [], Nothing, "/_contacts " <> Param "userId"), + ("APIListGroups", [], "Get groups.", ["CRGroupsList", "CRChatCmdError"], [], Nothing, "/_groups " <> Param "userId" <> Optional "" (" @" <> Param "$0") "contactId_" <> Optional "" (" " <> Param "$0") "search"), + ("APIDeleteChat", [], "Delete chat.", ["CRContactDeleted", "CRContactConnectionDeleted", "CRGroupDeletedUser", "CRChatCmdError"], [], Just UNBackground, "/_delete " <> Param "chatRef" <> " " <> Param "chatDeleteMode") -- ("APIChatItemsRead", [], "Mark items as read.", ["CRItemsReadForChat"], [], Nothing, ""), -- ("APIChatRead", [], "Mark chat as read.", ["CRCmdOk"], [], Nothing, ""), -- ("APIChatUnread", [], "Mark chat as unread.", ["CRCmdOk"], [], Nothing, ""), @@ -162,20 +163,20 @@ chatCommandsDocsData = ), ( "User profile commands", "Most bots don't need to use these commands, as bot profile can be configured manually via CLI or desktop client. These commands can be used by bots that need to manage multiple user profiles (e.g., the profiles of support agents).", - [ ("ShowActiveUser", [], "Get active user profile", ["CRActiveUser"], [], Nothing, "/user"), + [ ("ShowActiveUser", [], "Get active user profile", ["CRActiveUser", "CRChatCmdError"], [], Nothing, "/user"), ( "CreateActiveUser", [], "Create new user profile", - ["CRActiveUser"], + ["CRActiveUser", "CRChatCmdError"], [TD "CEUserExists" "User or contact with this name already exists", TD "CEInvalidDisplayName" "Invalid user display name"], Nothing, "/_create user " <> Json "newUser" ), - ("ListUsers", [], "Get all user profiles", ["CRUsersList"], [], Nothing, "/users"), - ("APISetActiveUser", [], "Set active user profile", ["CRActiveUser"], ["CEChatNotStarted"], Nothing, "/_user " <> Param "userId" <> Optional "" (" " <> Json "$0") "viewPwd"), - ("APIDeleteUser", [], "Delete user profile.", ["CRCmdOk"], [], Just UNBackground, "/_delete user " <> Param "userId" <> OnOffParam "del_smp" "delSMPQueues" Nothing <> Optional "" (" " <> Json "$0") "viewPwd"), - ("APIUpdateProfile", [], "Update user profile.", ["CRUserProfileUpdated"], [], Just UNBackground, "/_profile " <> Param "userId" <> " " <> Json "profile"), - ("APISetContactPrefs", [], "Configure chat preference overrides for the contact.", ["CRContactPrefsUpdated"], [], Just UNBackground, "/_set prefs @" <> Param "contactId" <> " " <> Json "preferences") + ("ListUsers", [], "Get all user profiles", ["CRUsersList", "CRChatCmdError"], [], Nothing, "/users"), + ("APISetActiveUser", [], "Set active user profile", ["CRActiveUser", "CRChatCmdError"], ["CEChatNotStarted"], Nothing, "/_user " <> Param "userId" <> Optional "" (" " <> Json "$0") "viewPwd"), + ("APIDeleteUser", [], "Delete user profile.", ["CRCmdOk", "CRChatCmdError"], [], Just UNBackground, "/_delete user " <> Param "userId" <> OnOffParam "del_smp" "delSMPQueues" Nothing <> Optional "" (" " <> Json "$0") "viewPwd"), + ("APIUpdateProfile", [], "Update user profile.", ["CRUserProfileUpdated", "CRUserProfileNoChange", "CRChatCmdError"], [], Just UNBackground, "/_profile " <> Param "userId" <> " " <> Json "profile"), + ("APISetContactPrefs", [], "Configure chat preference overrides for the contact.", ["CRContactPrefsUpdated", "CRChatCmdError"], [], Just UNBackground, "/_set prefs @" <> Param "contactId" <> " " <> Json "preferences") ] ) ] @@ -193,7 +194,6 @@ cliCommands = "ClearContact", "ClearGroup", "ClearNoteFolder", - "Connect", "ConnectSimplex", "ContactInfo", "ContactQueueInfo", diff --git a/bots/src/API/Docs/Generate.hs b/bots/src/API/Docs/Generate.hs index ad8f68bd36..334ad93bad 100644 --- a/bots/src/API/Docs/Generate.hs +++ b/bots/src/API/Docs/Generate.hs @@ -43,7 +43,7 @@ commandsDocText = <> foldMap commandDocText commands where commandDocText CCDoc {commandType = ATUnionMember tag params, commandDescr, network, syntax, responses, errors} = - ("\n\n### " <> T.pack (fstToUpper tag) <> "\n\n" <> commandDescr <> "\n\n*Network usage*: " <> networkUsage <> ".\n") + ("\n\n### " <> T.pack (fstToUpper tag) <> "\n\n" <> commandDescr <> "\n\n*Network usage*: " <> networkUsage network <> ".\n") <> (if null params then "" else paramsText) <> (if syntax == "" then "" else syntaxText (tag, params) syntax) <> (if length responses > 1 then "\n**Responses**:\n" else "\n**Response**:\n") @@ -52,10 +52,6 @@ commandsDocText = <> foldMap errorText errors <> "\n---\n" where - networkUsage = case network of - Nothing -> "no" - Just UNInteractive -> "interactive" - Just UNBackground -> "background" paramsText = "\n**Parameters**:\n" <> fieldsText "./TYPES.md" params responseText CRDoc {responseType = ATUnionMember tag fields, responseDescr} = (T.pack $ "\n" <> fstToUpper tag <> ": " <> respDescr <> ".\n") @@ -67,11 +63,17 @@ commandsDocText = let descr' = if null descr then camelToSpace err else descr in T.pack $ "- " <> fstToUpper err <> ": " <> descr' <> ".\n" +networkUsage :: Maybe UsesNetwork -> Text +networkUsage = \case + Nothing -> "no" + Just UNInteractive -> "interactive" + Just UNBackground -> "background" + syntaxText :: TypeAndFields -> Expr -> Text syntaxText r syntax = "\n**Syntax**:\n" <> "\n```\n" <> docSyntaxText r syntax <> "\n```\n" - <> (if isConst syntax then "" else "\n```javascript\n" <> jsSyntaxText r syntax <> " // JavaScript\n```\n") + <> (if isConst syntax then "" else "\n```javascript\n" <> jsSyntaxText False r syntax <> " // JavaScript\n```\n") <> (if isConst syntax then "" else "\n```python\n" <> pySyntaxText r syntax <> " # Python\n```\n") camelToSpace :: String -> String @@ -127,14 +129,14 @@ typesDocText = where self = APIRecordField "self" (ATDef td) typeFields = case typeDef of - ATDRecord fs -> L.toList fs + ATDRecord fs -> fs ATDUnion ms -> APIRecordField "type" tagType : concatMap (\(ATUnionMember _ fs) -> fs) ms where tagType = ATDef $ APITypeDef (name <> ".type") $ ATDEnum tags tags = L.map (\(ATUnionMember tag _) -> tag) ms ATDEnum _ -> [] typeDefText = \case - ATDRecord fields -> "\n**Record type**:\n" <> fieldsText "" (L.toList fields) + ATDRecord fields -> "\n**Record type**:\n" <> fieldsText "" fields ATDEnum cs -> "\n**Enum type**:\n" <> foldMap (\m -> "- \"" <> T.pack m <> "\"\n") cs ATDUnion cs -> "\n**Discriminated union type**:\n" <> foldMap constrText cs where diff --git a/bots/src/API/Docs/Generate/TypeScript.hs b/bots/src/API/Docs/Generate/TypeScript.hs new file mode 100644 index 0000000000..b69635086e --- /dev/null +++ b/bots/src/API/Docs/Generate/TypeScript.hs @@ -0,0 +1,189 @@ +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} + +module API.Docs.Generate.TypeScript where + +import API.Docs.Commands +import API.Docs.Events +import API.Docs.Generate +import API.Docs.Responses +import API.Docs.Syntax +import API.Docs.Syntax.Types +import API.Docs.Types +import API.TypeInfo +import Data.Char (toUpper) +import qualified Data.List.NonEmpty as L +import Data.Text (Text) +import qualified Data.Text as T + +commandsCodeFile :: FilePath +commandsCodeFile = "./packages/simplex-chat-client/types/typescript/src/commands.ts" + +responsesCodeFile :: FilePath +responsesCodeFile = "./packages/simplex-chat-client/types/typescript/src/responses.ts" + +eventsCodeFile :: FilePath +eventsCodeFile = "./packages/simplex-chat-client/types/typescript/src/events.ts" + +typesCodeFile :: FilePath +typesCodeFile = "./packages/simplex-chat-client/types/typescript/src/types.ts" + +commandsCodeText :: Text +commandsCodeText = + ("// API Commands\n// " <> autoGenerated <> "\n") + <> "\nimport * as T from \"./types\"\n" + <> "\nimport {CR} from \"./responses\"\n" + <> foldMap commandCatCode chatCommandsDocs + where + commandCatCode CCCategory {categoryName, categoryDescr, commands} = + (T.pack $ "\n// " <> categoryName <> "\n// " <> categoryDescr <> "\n") + <> foldMap commandCode commands + where + commandCode CCDoc {commandType = ATUnionMember tag params, commandDescr, syntax, responses, network} = + ("\n// " <> commandDescr <> "\n") + <> ("// Network usage: " <> networkUsage network <> ".\n") + <> ("export interface " <> T.pack constrName <> " {\n") + <> fieldsCode "" "T." params + <> "}\n\n" + <> ("export namespace " <> T.pack constrName <> " {\n") + <> (" export type Response = " <> constrsCode " " "CR" (("CR." <> ) . T.pack . fstToUpper . memberTag) (map responseType responses)) + <> (if syntax == "" then "" else funcCode APITypeDef {typeName' = constrName, typeDef = ATDRecord params} syntax) + <> "}\n" + where + constrName = fstToUpper tag + +responsesCodeText :: Text +responsesCodeText = + ("// API Responses\n// " <> autoGenerated <> "\n") + <> "\nimport * as T from \"./types\"\n" + <> unionTypeCode "CR" "T." chatRespTypeDef chatRespConstrs "" + where + chatRespTypeDef = APITypeDef {typeName' = "ChatResponse", typeDef = ATDUnion chatRespConstrs} + chatRespConstrs = L.fromList $ map responseType chatResponsesDocs + +eventsCodeText :: Text +eventsCodeText = + ("// API Events\n// " <> autoGenerated <> "\n") + <> "\nimport * as T from \"./types\"\n" + <> unionTypeCode "CEvt" "T." chatEventTypeDef chatEventConstrs "" + where + chatEventTypeDef = APITypeDef {typeName' = "ChatEvent", typeDef = ATDUnion chatEventConstrs} + chatEventConstrs = L.fromList $ concatMap catEvents chatEventsDocs + catEvents CECategory {mainEvents, otherEvents} = map eventType $ mainEvents ++ otherEvents + +typesCodeText :: Text +typesCodeText = ("// API Types\n// " <> autoGenerated <> "\n") <> foldMap typeCode chatTypesDocs + where + typeCode CTDoc {typeDef = td@APITypeDef {typeName' = name, typeDef}, typeDescr, typeSyntax} = + (if T.null typeDescr then "" else "// " <> typeDescr <> "\n") + <> typeDefCode + -- <> (if typeSyntax == "" then "" else syntaxText (name, self : typeFields) typeSyntax) + where + name' = T.pack name + constrName tag = case name of + "ConnectionMode" -> T.pack $ map toUpper tag + "FileProtocol" -> T.pack $ map toUpper tag + _ -> T.replace "-" "_" $ T.pack $ fstToUpper tag + namespaceFuncCode = "\nexport namespace " <> name' <> " {" <> funcCode td typeSyntax <> "}\n" + typeDefCode = case typeDef of + ATDRecord fields -> + ("\nexport interface " <> name' <> " {\n") + <> fieldsCode "" "" fields + <> "}\n" + <> (if typeSyntax == "" then "" else namespaceFuncCode) + ATDEnum cs -> + ("\nexport enum " <> name' <> " {\n") + <> foldMap (\m -> " " <> constrName m <> " = \"" <> T.pack m <> "\",\n") cs + <> "}\n" + <> (if typeSyntax == "" then "" else namespaceFuncCode) + ATDUnion cs -> unionTypeCode name' "" td cs typeSyntax + +unionTypeCode :: Text -> String -> APITypeDef -> L.NonEmpty ATUnionMember -> Expr -> Text +unionTypeCode unionNamespace typesNamespace td@APITypeDef {typeName' = name} cs cmdSyntax = + ("\nexport type " <> name' <> " = " <> constrsCode "" name' constrTypeRef (L.toList cs) <> "\n") + <> ("export namespace " <> unionNamespace <> " {\n") + <> (" export type Tag = " <> constrsCode " " name' constrTag (L.toList cs) <> "\n") + <> (" interface Interface {\n type: Tag\n }\n") + <> foldMap constrType cs + <> (if cmdSyntax == "" then "" else funcCode td cmdSyntax) + <> "}\n" + where + name' = T.pack name + constrTypeRef (ATUnionMember tag _) = unionNamespace <> "." <> constrName tag + constrTag (ATUnionMember tag _) = T.pack $ "\"" <> tag <> "\"" + constrType c@(ATUnionMember tag fields) = + ("\n export interface " <> constrName tag <> " extends Interface {\n") + <> " type: " <> constrTag c <> "\n" + <> fieldsCode " " typesNamespace fields + <> " }\n" + constrName tag = T.replace "-" "_" (T.pack $ fstToUpper tag) + +constrsCode :: Text -> Text -> (ATUnionMember -> Text) -> [ATUnionMember] -> Text +constrsCode indent name' constr cs + | T.length (name' <> " = " <> line) <= 100 = line <> "\n" + | otherwise = "\n" <> foldMap (\c -> indent <> " | " <> c <> "\n") cs' + where + line = T.intercalate " | " cs' + cs' = map constr cs + +funcCode :: APITypeDef -> Expr -> Text +funcCode td@APITypeDef {typeName' = name, typeDef} cmdSyntax = + "\n export function cmdString(" <> param <> ": " <> T.pack name <> "): string {\n return " <> jsSyntaxText True (name, self : typeFields) cmdSyntax <> "\n }\n" + where + param = if hasParams cmdSyntax then "self" else "_self" + self = APIRecordField "self" (ATDef td) + typeFields = case typeDef of + ATDRecord fs -> fs + ATDUnion ms -> APIRecordField "type" tagType : concatMap (\(ATUnionMember _ fs) -> fs) ms + where + tagType = ATDef $ APITypeDef (name <> ".type") $ ATDEnum tags + tags = L.map (\(ATUnionMember tag _) -> tag) ms + ATDEnum _ -> [] + +fieldsCode :: Text -> String -> [APIRecordField] -> Text +fieldsCode indent namespace = foldMap $ (indent <>) . T.pack . fieldText + where + fieldText (APIRecordField name t) = " " <> name <> optional t <> ": " <> typeText t <> typeComment t <> "\n" + optional = \case + ATOptional _ -> "?" + _ -> "" + typeText = \case + ATPrim (PT t) -> typeName t + ATDef (APITypeDef t _) -> namespace <> t + ATRef t -> namespace <> t + ATOptional t -> typeText t + ATArray {elemType} -> typeText elemType <> "[]" + ATMap (PT t) valueType -> "{[key: " <> typeName t <> "]: " <> typeText valueType <> "}" + typeName = \case + TBool -> "boolean" + TInt -> "number" + TInt64 -> "number" + TWord32 -> "number" + TDouble -> "number" + TJSONObject -> "object" + TUTCTime -> "string" + t -> t + typeComment t = let c = typeComment' t in if null c then "" else " // " <> c + typeComment' = \case + ATPrim (PT t) -> typeComment_ t + ATOptional (ATPrim (PT t)) -> typeComment_ t + ATArray {elemType, nonEmpty} + | nonEmpty -> (if null c then "" else c <> ", ") <> "non-empty" + | otherwise -> c + where + c = typeComment' elemType + ATMap (PT k) v -> + let kc = typeComment_ k + vc = typeComment' v + tc t c = if null c then t else c + in if null kc && null vc then "" else tc (typeName k) kc <> " : " <> tc (typeText v) vc + _ -> "" + typeComment_ = \case + TInt -> "int" + TInt64 -> "int64" + TWord32 -> "word32" + TDouble -> "double" + TUTCTime -> "ISO-8601 timestamp" + _ -> "" diff --git a/bots/src/API/Docs/Responses.hs b/bots/src/API/Docs/Responses.hs index 96f461e696..1c2e4baec3 100644 --- a/bots/src/API/Docs/Responses.hs +++ b/bots/src/API/Docs/Responses.hs @@ -88,6 +88,7 @@ chatResponsesDocsData = ("CRUserContactLinkUpdated", "User contact address updated"), ("CRUserDeletedMembers", "Members deleted"), ("CRUserProfileUpdated", "User profile updated"), + ("CRUserProfileNoChange", "User profile was not changed"), ("CRUsersList", "Users") -- ("CRApiChat", "Chat and messages"), -- ("CRApiChats", "Chats with the most recent messages"), @@ -195,7 +196,6 @@ undocumentedResponses = "CRUserPrivacy", "CRUserProfile", "CRUserProfileImage", - "CRUserProfileNoChange", "CRUserServers", "CRUserServersValidation", "CRVersionInfo", diff --git a/bots/src/API/Docs/Syntax.hs b/bots/src/API/Docs/Syntax.hs index df6e126ca4..83fa2bf6a2 100644 --- a/bots/src/API/Docs/Syntax.hs +++ b/bots/src/API/Docs/Syntax.hs @@ -99,8 +99,8 @@ withOptBoolParam r param p f = (ATOptional (ATPrim (PT TBool))) -> f True _ -> paramError r param p "is not [optional] boolean" -jsSyntaxText :: TypeAndFields -> Expr -> Text -jsSyntaxText r = T.replace "' + '" "" . T.pack . go Nothing True +jsSyntaxText :: Bool -> TypeAndFields -> Expr -> Text +jsSyntaxText useSelf r = T.replace "' + '" "" . T.pack . go Nothing True where go param top = \case Concat exs -> intercalate " + " $ map (go param False) $ L.toList exs @@ -109,14 +109,14 @@ jsSyntaxText r = T.replace "' + '" "" . T.pack . go Nothing True withParamType r param p $ \case ATDef td -> toStringSyntax td ATOptional (ATDef td) -> toStringSyntax td - _ -> paramName param p + _ -> paramName' useSelf param p where toStringSyntax (APITypeDef typeName _) - | typeHasSyntax typeName = paramName param p <> ".toString()" - | otherwise = paramName param p + | typeHasSyntax typeName = paramName' useSelf param p <> ".toString()" + | otherwise = paramName' useSelf param p Optional exN exJ p -> open <> n <> " ? " <> go (Just p) False exJ <> " : " <> nothing <> close where - n = paramName param p + n = paramName' useSelf param p nothing = if exN == "" then "''" else go param False exN Choice p opts else' -> withParamType r param p $ \case @@ -125,15 +125,15 @@ jsSyntaxText r = T.replace "' + '" "" . T.pack . go Nothing True _ -> paramError r param p "is not union type" where choiceSyntax = \case - APITypeDef _ (ATDUnion _) -> choices "type" + APITypeDef _ (ATDUnion _) -> choices $ (if useSelf then "self." else "") <> "type" APITypeDef _ (ATDEnum _) -> choices "self" _ -> paramError r param p "is not union type" choices var = open <> optsSyntax <> " : " <> go param top else' <> close where optsSyntax = intercalate " : " $ map (\(tag, ex) -> var <> " == '" <> tag <> "' ? " <> go param top ex) $ L.toList opts - Join c p -> paramName param p <> ".join('" <> [c] <> "')" - Json p -> "JSON.stringify(" <> paramName param p <> ")" - OnOff p -> open <> paramName param p <> " ? 'on' : 'off'" <> close + Join c p -> paramName' useSelf param p <> ".join('" <> [c] <> "')" + Json p -> "JSON.stringify(" <> paramName' useSelf param p <> ")" + OnOff p -> open <> paramName' useSelf param p <> " ? 'on' : 'off'" <> close OnOffParam name p def_ -> case def_ of Nothing -> withOptBoolParam r param p $ \optional -> @@ -141,13 +141,13 @@ jsSyntaxText r = T.replace "' + '" "" . T.pack . go Nothing True then "(typeof " <> n <> " == 'boolean' ? " <> res <> " : '')" else res where - n = paramName param p + n = paramName' useSelf param p res = "' " <> name <> "=' + (" <> n <> " ? 'on' : 'off')" Just def | def -> open <> "!" <> n <> " ? ' " <> name <> "=off' : ''" <> close | otherwise -> open <> n <> " ? ' " <> name <> "=on' : ''" <> close where - n = paramName param p + n = paramName' useSelf param p where open = if top then "" else "(" close = if top then "" else ")" @@ -215,6 +215,13 @@ pySyntaxText r = T.pack . go Nothing True close = if top then "" else ")" paramName :: Maybe ExprParam -> ExprParam -> String -paramName param_ p = case param_ of - Just param | p == "$0" -> param - _ -> p +paramName = paramName' False + +paramName' :: Bool -> Maybe ExprParam -> ExprParam -> String +paramName' useSelf param_ p + | useSelf && p' /= "self" = "self." <> p' + | otherwise = p' + where + p' = case param_ of + Just param | p == "$0" -> param + _ -> p diff --git a/bots/src/API/Docs/Syntax/Types.hs b/bots/src/API/Docs/Syntax/Types.hs index 211348d5a9..385c5e02c2 100644 --- a/bots/src/API/Docs/Syntax/Types.hs +++ b/bots/src/API/Docs/Syntax/Types.hs @@ -26,6 +26,18 @@ isConst = \case Const _ -> True _ -> False +hasParams :: Expr -> Bool +hasParams = \case + Concat es -> any (hasParams) es + Const _ -> False + Param _ -> True + Optional {} -> True + Choice {} -> True + Join {} -> True + Json _ -> True + OnOff _ -> True + OnOffParam {} -> True + instance IsString Expr where fromString = Const instance Semigroup Expr where diff --git a/bots/src/API/Docs/Types.hs b/bots/src/API/Docs/Types.hs index c0cf2867c2..758fc62d53 100644 --- a/bots/src/API/Docs/Types.hs +++ b/bots/src/API/Docs/Types.hs @@ -83,7 +83,7 @@ toTypeDef acc@(!visited, !typeDefs) (STI typeName allConstrs, jsonEncoding, cons [RecordTypeInfo {fieldInfos}] -> let fields = fromMaybe (error $ "Record type without fields: " <> typeName) $ L.nonEmpty fieldInfos ((visited', typeDefs'), fields') = mapAccumL (toAPIField_ typeName) (S.insert typeName visited, typeDefs) fields - td = APITypeDef typeName $ ATDRecord fields' + td = APITypeDef typeName $ ATDRecord $ L.toList fields' in ((S.insert typeName visited', M.insert typeName td typeDefs'), Just td) _ -> error $ "Record type with " <> show (length constrs) <> " constructors: " <> typeName STUnion -> if length constrs > 1 then toUnionType constrs else unionError constrs @@ -199,7 +199,7 @@ chatTypesDocsData = (sti @(ContactUserPreference SimplePreference), STRecord, "", [], "", ""), (sti @(CreatedConnLink 'CMContact), STRecord, "", [], Param "connFullLink" <> Optional "" (" " <> Param "$0") "connShortLink", ""), (sti @AddressSettings, STRecord, "", [], "", ""), - (sti @AgentCryptoError, STUnion, "", [], "", ""), + (sti @AgentCryptoError, STUnion, "", ["RATCHET_EARLIER", "RATCHET_SKIPPED"], "", ""), -- TODO add fields to types (sti @AgentErrorType, STUnion, "", [], "", ""), (sti @AutoAccept, STRecord, "", [], "", ""), (sti @BlockingInfo, STRecord, "", [], "", ""), @@ -217,7 +217,7 @@ chatTypesDocsData = (sti @ChatRef, STRecord, "", [], Param "chatType" <> Param "chatId" <> Optional "" (Param "$0") "chatScope", "Used in API commands. Chat scope can only be passed with groups."), (sti @ChatSettings, STRecord, "", [], "", ""), (sti @ChatStats, STRecord, "", [], "", ""), - (sti @ChatType, STEnum, "CT", ["CTContactRequest", "CTContactConnection"], Choice "self" [("contact", "@"), ("group", "#"), ("local", "*")] "", ""), + (sti @ChatType, STEnum, "CT", ["CTContactRequest", "CTContactConnection"], Choice "self" [("direct", "@"), ("group", "#"), ("local", "*")] "", ""), (sti @ChatWallpaper, STRecord, "", [], "", ""), (sti @ChatWallpaperScale, STEnum, "CWS", [], "", ""), (sti @CICallStatus, STEnum, "CISCall", [], "", ""), diff --git a/bots/src/API/TypeInfo.hs b/bots/src/API/TypeInfo.hs index 3d7269e766..df43374ffa 100644 --- a/bots/src/API/TypeInfo.hs +++ b/bots/src/API/TypeInfo.hs @@ -33,7 +33,7 @@ data APIType data APITypeDef = APITypeDef {typeName' :: String, typeDef :: APITypeDefinition} data APITypeDefinition - = ATDRecord (NonEmpty APIRecordField) + = ATDRecord [APIRecordField] | ATDUnion (NonEmpty ATUnionMember) | ATDEnum (NonEmpty String) @@ -45,10 +45,6 @@ data ATUnionMember = ATUnionMember {memberTag :: String, memberFields :: [APIRec newtype PrimitiveType = PT String --- data PrimitiveType = PTBool | PTString StringFormat | PTInt | PTInt64 | PTWord32 | PTDouble - -data StringFormat = SFTimestamp | SFBase64 | SFSimpleXLink | SFServerAddr | SFHexColor - pattern TBool :: String pattern TBool = "bool" @@ -61,8 +57,20 @@ pattern TInt = "int" pattern TInt64 :: String pattern TInt64 = "int64" +pattern TWord32 :: String +pattern TWord32 = "word32" + +pattern TDouble :: String +pattern TDouble = "double" + +pattern TJSONObject :: String +pattern TJSONObject = "JSONObject" + +pattern TUTCTime :: String +pattern TUTCTime = "UTCTime" + primitiveTypes :: [ConsName] -primitiveTypes = [TBool, TString, TInt, TInt64, "word32", "double", "JSONObject", "UTCTime"] +primitiveTypes = [TBool, TString, TInt, TInt64, TWord32, TDouble, TJSONObject, TUTCTime] data SumTypeInfo = STI {typeName :: String, recordTypes :: [RecordTypeInfo]} deriving (Show) diff --git a/packages/simplex-chat-client/types/typescript/.gitignore b/packages/simplex-chat-client/types/typescript/.gitignore new file mode 100644 index 0000000000..7481e30d5a --- /dev/null +++ b/packages/simplex-chat-client/types/typescript/.gitignore @@ -0,0 +1,4 @@ +node_modules +package-lock.json +dist +coverage diff --git a/packages/simplex-chat-client/types/typescript/LICENSE b/packages/simplex-chat-client/types/typescript/LICENSE new file mode 100644 index 0000000000..0ad25db4bd --- /dev/null +++ b/packages/simplex-chat-client/types/typescript/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/simplex-chat-client/types/typescript/README.md b/packages/simplex-chat-client/types/typescript/README.md new file mode 100644 index 0000000000..ad13a5d76e --- /dev/null +++ b/packages/simplex-chat-client/types/typescript/README.md @@ -0,0 +1,11 @@ +# SimpleX Chat bots API: typeScript types + +This TypeScript library provides auto-generated types for bots API: commands and responses, events and all types they use. + +It is used in [simplex-chat](https://www.npmjs.com/package/simplex-chat) library that uses WebSockets interface of SimpleX Chat CLI. + +[API reference](https://github.com/simplex-chat/simplex-chat/tree/stable/bots). + +## License + +[AGPL v3](./LICENSE) diff --git a/packages/simplex-chat-client/types/typescript/package.json b/packages/simplex-chat-client/types/typescript/package.json new file mode 100644 index 0000000000..1bf593b483 --- /dev/null +++ b/packages/simplex-chat-client/types/typescript/package.json @@ -0,0 +1,42 @@ +{ + "name": "@simplex-chat/types", + "version": "0.1.0", + "description": "TypeScript types for SimpleX Chat bot libraries", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "dist" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "build": "tsc", + "prepublishOnly": "tsc" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/simplex-chat/simplex-chat.git", + "directory": "/packages/simplex-chat-client/types/typescript" + }, + "keywords": [ + "simplex", + "messenger", + "chat", + "privacy", + "security", + "bots", + "types" + ], + "author": "SimpleX Chat", + "license": "AGPL-3.0", + "bugs": { + "url": "https://github.com/simplex-chat/simplex-chat/issues" + }, + "homepage": "https://github.com/simplex-chat/simplex-chat#readme", + "dependencies": { + "typescript": "^5.9.2" + } +} diff --git a/packages/simplex-chat-client/types/typescript/src/commands.ts b/packages/simplex-chat-client/types/typescript/src/commands.ts new file mode 100644 index 0000000000..de6a7a7ce1 --- /dev/null +++ b/packages/simplex-chat-client/types/typescript/src/commands.ts @@ -0,0 +1,662 @@ +// API Commands +// This file is generated automatically. + +import * as T from "./types" + +import {CR} from "./responses" + +// Address commands +// Bots can use these commands to automatically check and create address when initialized + +// Create bot address. +// Network usage: interactive. +export interface APICreateMyAddress { + userId: number // int64 +} + +export namespace APICreateMyAddress { + export type Response = CR.UserContactLinkCreated | CR.ChatCmdError + + export function cmdString(self: APICreateMyAddress): string { + return '/_address ' + self.userId + } +} + +// Delete bot address. +// Network usage: background. +export interface APIDeleteMyAddress { + userId: number // int64 +} + +export namespace APIDeleteMyAddress { + export type Response = CR.UserContactLinkDeleted | CR.ChatCmdError + + export function cmdString(self: APIDeleteMyAddress): string { + return '/_delete_address ' + self.userId + } +} + +// Get bot address and settings. +// Network usage: no. +export interface APIShowMyAddress { + userId: number // int64 +} + +export namespace APIShowMyAddress { + export type Response = CR.UserContactLink | CR.ChatCmdError + + export function cmdString(self: APIShowMyAddress): string { + return '/_show_address ' + self.userId + } +} + +// Add address to bot profile. +// Network usage: interactive. +export interface APISetProfileAddress { + userId: number // int64 + enable: boolean +} + +export namespace APISetProfileAddress { + export type Response = CR.UserProfileUpdated | CR.ChatCmdError + + export function cmdString(self: APISetProfileAddress): string { + return '/_profile_address ' + self.userId + ' ' + (self.enable ? 'on' : 'off') + } +} + +// Set bot address settings. +// Network usage: interactive. +export interface APISetAddressSettings { + userId: number // int64 + settings: T.AddressSettings +} + +export namespace APISetAddressSettings { + export type Response = CR.UserContactLinkUpdated | CR.ChatCmdError + + export function cmdString(self: APISetAddressSettings): string { + return '/_address_settings ' + self.userId + ' ' + JSON.stringify(self.settings) + } +} + +// Message commands +// Commands to send, update, delete, moderate messages and set message reactions + +// Send messages. +// Network usage: background. +export interface APISendMessages { + sendRef: T.ChatRef + liveMessage: boolean + ttl?: number // int + composedMessages: T.ComposedMessage[] // non-empty +} + +export namespace APISendMessages { + export type Response = CR.NewChatItems | CR.ChatCmdError + + export function cmdString(self: APISendMessages): string { + return '/_send ' + self.sendRef.toString() + (self.liveMessage ? ' live=on' : '') + (self.ttl ? ' ttl=' + self.ttl : '') + ' json ' + JSON.stringify(self.composedMessages) + } +} + +// Update message. +// Network usage: background. +export interface APIUpdateChatItem { + chatRef: T.ChatRef + chatItemId: number // int64 + liveMessage: boolean + updatedMessage: T.UpdatedMessage +} + +export namespace APIUpdateChatItem { + export type Response = CR.ChatItemUpdated | CR.ChatItemNotChanged | CR.ChatCmdError + + export function cmdString(self: APIUpdateChatItem): string { + return '/_update item ' + self.chatRef.toString() + ' ' + self.chatItemId + (self.liveMessage ? ' live=on' : '') + ' json ' + JSON.stringify(self.updatedMessage) + } +} + +// Delete message. +// Network usage: background. +export interface APIDeleteChatItem { + chatRef: T.ChatRef + chatItemIds: number[] // int64, non-empty + deleteMode: T.CIDeleteMode +} + +export namespace APIDeleteChatItem { + export type Response = CR.ChatItemsDeleted | CR.ChatCmdError + + export function cmdString(self: APIDeleteChatItem): string { + return '/_delete item ' + self.chatRef.toString() + ' ' + self.chatItemIds.join(',') + ' ' + self.deleteMode + } +} + +// Moderate message. Requires Moderator role (and higher than message author's). +// Network usage: background. +export interface APIDeleteMemberChatItem { + groupId: number // int64 + chatItemIds: number[] // int64, non-empty +} + +export namespace APIDeleteMemberChatItem { + export type Response = CR.ChatItemsDeleted | CR.ChatCmdError + + export function cmdString(self: APIDeleteMemberChatItem): string { + return '/_delete member item #' + self.groupId + ' ' + self.chatItemIds.join(',') + } +} + +// Add/remove message reaction. +// Network usage: background. +export interface APIChatItemReaction { + chatRef: T.ChatRef + chatItemId: number // int64 + add: boolean + reaction: T.MsgReaction +} + +export namespace APIChatItemReaction { + export type Response = CR.ChatItemReaction | CR.ChatCmdError + + export function cmdString(self: APIChatItemReaction): string { + return '/_reaction ' + self.chatRef.toString() + ' ' + self.chatItemId + ' ' + (self.add ? 'on' : 'off') + ' ' + JSON.stringify(self.reaction) + } +} + +// File commands +// Commands to receive and to cancel files. Files are sent as part of the message, there are no separate commands to send files. + +// Receive file. +// Network usage: no. +export interface ReceiveFile { + fileId: number // int64 + userApprovedRelays: boolean + storeEncrypted?: boolean + fileInline?: boolean + filePath?: string +} + +export namespace ReceiveFile { + export type Response = CR.RcvFileAccepted | CR.RcvFileAcceptedSndCancelled | CR.ChatCmdError + + export function cmdString(self: ReceiveFile): string { + return '/freceive ' + self.fileId + (self.userApprovedRelays ? ' approved_relays=on' : '') + (typeof self.storeEncrypted == 'boolean' ? ' encrypt=' + (self.storeEncrypted ? 'on' : 'off') : '') + (typeof self.fileInline == 'boolean' ? ' inline=' + (self.fileInline ? 'on' : 'off') : '') + (self.filePath ? ' ' + self.filePath : '') + } +} + +// Cancel file. +// Network usage: background. +export interface CancelFile { + fileId: number // int64 +} + +export namespace CancelFile { + export type Response = CR.SndFileCancelled | CR.RcvFileCancelled | CR.ChatCmdError + + export function cmdString(self: CancelFile): string { + return '/fcancel ' + self.fileId + } +} + +// Group commands +// Commands to manage and moderate groups. These commands can be used with business chats as well - they are groups. E.g., a common scenario would be to add human agents to business chat with the customer who connected via business address. + +// Add contact to group. Requires bot to have Admin role. +// Network usage: interactive. +export interface APIAddMember { + groupId: number // int64 + contactId: number // int64 + memberRole: T.GroupMemberRole +} + +export namespace APIAddMember { + export type Response = CR.SentGroupInvitation | CR.ChatCmdError + + export function cmdString(self: APIAddMember): string { + return '/_add #' + self.groupId + ' ' + self.contactId + ' ' + self.memberRole + } +} + +// Join group. +// Network usage: interactive. +export interface APIJoinGroup { + groupId: number // int64 +} + +export namespace APIJoinGroup { + export type Response = CR.UserAcceptedGroupSent | CR.ChatCmdError + + export function cmdString(self: APIJoinGroup): string { + return '/_join #' + self.groupId + } +} + +// Accept group member. Requires Admin role. +// Network usage: background. +export interface APIAcceptMember { + groupId: number // int64 + groupMemberId: number // int64 + memberRole: T.GroupMemberRole +} + +export namespace APIAcceptMember { + export type Response = CR.MemberAccepted | CR.ChatCmdError + + export function cmdString(self: APIAcceptMember): string { + return '/_accept member #' + self.groupId + ' ' + self.groupMemberId + ' ' + self.memberRole + } +} + +// Set members role. Requires Admin role. +// Network usage: background. +export interface APIMembersRole { + groupId: number // int64 + groupMemberIds: number[] // int64, non-empty + memberRole: T.GroupMemberRole +} + +export namespace APIMembersRole { + export type Response = CR.MembersRoleUser | CR.ChatCmdError + + export function cmdString(self: APIMembersRole): string { + return '/_member role #' + self.groupId + ' ' + self.groupMemberIds.join(',') + ' ' + self.memberRole + } +} + +// Block members. Requires Moderator role. +// Network usage: background. +export interface APIBlockMembersForAll { + groupId: number // int64 + groupMemberIds: number[] // int64, non-empty + blocked: boolean +} + +export namespace APIBlockMembersForAll { + export type Response = CR.MembersBlockedForAllUser | CR.ChatCmdError + + export function cmdString(self: APIBlockMembersForAll): string { + return '/_block #' + self.groupId + ' ' + self.groupMemberIds.join(',') + ' blocked=' + (self.blocked ? 'on' : 'off') + } +} + +// Remove members. Requires Admin role. +// Network usage: background. +export interface APIRemoveMembers { + groupId: number // int64 + groupMemberIds: number[] // int64, non-empty + withMessages: boolean +} + +export namespace APIRemoveMembers { + export type Response = CR.UserDeletedMembers | CR.ChatCmdError + + export function cmdString(self: APIRemoveMembers): string { + return '/_remove #' + self.groupId + ' ' + self.groupMemberIds.join(',') + (self.withMessages ? ' messages=on' : '') + } +} + +// Leave group. +// Network usage: background. +export interface APILeaveGroup { + groupId: number // int64 +} + +export namespace APILeaveGroup { + export type Response = CR.LeftMemberUser | CR.ChatCmdError + + export function cmdString(self: APILeaveGroup): string { + return '/_leave #' + self.groupId + } +} + +// Get group members. +// Network usage: no. +export interface APIListMembers { + groupId: number // int64 +} + +export namespace APIListMembers { + export type Response = CR.GroupMembers | CR.ChatCmdError + + export function cmdString(self: APIListMembers): string { + return '/_members #' + self.groupId + } +} + +// Create group. +// Network usage: no. +export interface APINewGroup { + userId: number // int64 + incognito: boolean + groupProfile: T.GroupProfile +} + +export namespace APINewGroup { + export type Response = CR.GroupCreated | CR.ChatCmdError + + export function cmdString(self: APINewGroup): string { + return '/_group ' + self.userId + (self.incognito ? ' incognito=on' : '') + ' ' + JSON.stringify(self.groupProfile) + } +} + +// Update group profile. +// Network usage: background. +export interface APIUpdateGroupProfile { + groupId: number // int64 + groupProfile: T.GroupProfile +} + +export namespace APIUpdateGroupProfile { + export type Response = CR.GroupUpdated | CR.ChatCmdError + + export function cmdString(self: APIUpdateGroupProfile): string { + return '/_group_profile #' + self.groupId + ' ' + JSON.stringify(self.groupProfile) + } +} + +// Group link commands +// These commands can be used by bots that manage multiple public groups + +// Create group link. +// Network usage: interactive. +export interface APICreateGroupLink { + groupId: number // int64 + memberRole: T.GroupMemberRole +} + +export namespace APICreateGroupLink { + export type Response = CR.GroupLinkCreated | CR.ChatCmdError + + export function cmdString(self: APICreateGroupLink): string { + return '/_create link #' + self.groupId + ' ' + self.memberRole + } +} + +// Set member role for group link. +// Network usage: no. +export interface APIGroupLinkMemberRole { + groupId: number // int64 + memberRole: T.GroupMemberRole +} + +export namespace APIGroupLinkMemberRole { + export type Response = CR.GroupLink | CR.ChatCmdError + + export function cmdString(self: APIGroupLinkMemberRole): string { + return '/_set link role #' + self.groupId + ' ' + self.memberRole + } +} + +// Delete group link. +// Network usage: background. +export interface APIDeleteGroupLink { + groupId: number // int64 +} + +export namespace APIDeleteGroupLink { + export type Response = CR.GroupLinkDeleted | CR.ChatCmdError + + export function cmdString(self: APIDeleteGroupLink): string { + return '/_delete link #' + self.groupId + } +} + +// Get group link. +// Network usage: no. +export interface APIGetGroupLink { + groupId: number // int64 +} + +export namespace APIGetGroupLink { + export type Response = CR.GroupLink | CR.ChatCmdError + + export function cmdString(self: APIGetGroupLink): string { + return '/_get link #' + self.groupId + } +} + +// Connection commands +// These commands may be used to create connections. Most bots do not need to use them - bot users will connect via bot address with auto-accept enabled. + +// Create 1-time invitation link. +// Network usage: interactive. +export interface APIAddContact { + userId: number // int64 + incognito: boolean +} + +export namespace APIAddContact { + export type Response = CR.Invitation | CR.ChatCmdError + + export function cmdString(self: APIAddContact): string { + return '/_connect ' + self.userId + (self.incognito ? ' incognito=on' : '') + } +} + +// Determine SimpleX link type and if the bot is already connected via this link. +// Network usage: interactive. +export interface APIConnectPlan { + userId: number // int64 + connectionLink?: string +} + +export namespace APIConnectPlan { + export type Response = CR.ConnectionPlan | CR.ChatCmdError + + export function cmdString(self: APIConnectPlan): string { + return '/_connect plan ' + self.userId + ' ' + self.connectionLink + } +} + +// Connect via prepared SimpleX link. The link can be 1-time invitation link, contact address or group link +// Network usage: interactive. +export interface APIConnect { + userId: number // int64 + incognito: boolean + preparedLink_?: T.CreatedConnLink +} + +export namespace APIConnect { + export type Response = CR.SentConfirmation | CR.ContactAlreadyExists | CR.SentInvitation | CR.ChatCmdError + + export function cmdString(self: APIConnect): string { + return '/_connect ' + self.userId + (self.preparedLink_ ? ' ' + self.preparedLink_.toString() : '') + } +} + +// Connect via SimpleX link as string in the active user profile. +// Network usage: interactive. +export interface Connect { + incognito: boolean + connLink_?: string +} + +export namespace Connect { + export type Response = CR.SentConfirmation | CR.ContactAlreadyExists | CR.SentInvitation | CR.ChatCmdError + + export function cmdString(self: Connect): string { + return '/connect' + (self.connLink_ ? ' ' + self.connLink_ : '') + } +} + +// Accept contact request. +// Network usage: interactive. +export interface APIAcceptContact { + contactReqId: number // int64 +} + +export namespace APIAcceptContact { + export type Response = CR.AcceptingContactRequest | CR.ChatCmdError + + export function cmdString(self: APIAcceptContact): string { + return '/_accept ' + self.contactReqId + } +} + +// Reject contact request. The user who sent the request is **not notified**. +// Network usage: no. +export interface APIRejectContact { + contactReqId: number // int64 +} + +export namespace APIRejectContact { + export type Response = CR.ContactRequestRejected | CR.ChatCmdError + + export function cmdString(self: APIRejectContact): string { + return '/_reject ' + self.contactReqId + } +} + +// Chat commands +// Commands to list and delete conversations. + +// Get contacts. +// Network usage: no. +export interface APIListContacts { + userId: number // int64 +} + +export namespace APIListContacts { + export type Response = CR.ContactsList | CR.ChatCmdError + + export function cmdString(self: APIListContacts): string { + return '/_contacts ' + self.userId + } +} + +// Get groups. +// Network usage: no. +export interface APIListGroups { + userId: number // int64 + contactId_?: number // int64 + search?: string +} + +export namespace APIListGroups { + export type Response = CR.GroupsList | CR.ChatCmdError + + export function cmdString(self: APIListGroups): string { + return '/_groups ' + self.userId + (self.contactId_ ? ' @' + self.contactId_ : '') + (self.search ? ' ' + self.search : '') + } +} + +// Delete chat. +// Network usage: background. +export interface APIDeleteChat { + chatRef: T.ChatRef + chatDeleteMode: T.ChatDeleteMode +} + +export namespace APIDeleteChat { + export type Response = CR.ContactDeleted | CR.ContactConnectionDeleted | CR.GroupDeletedUser | CR.ChatCmdError + + export function cmdString(self: APIDeleteChat): string { + return '/_delete ' + self.chatRef.toString() + ' ' + self.chatDeleteMode.toString() + } +} + +// User profile commands +// Most bots don't need to use these commands, as bot profile can be configured manually via CLI or desktop client. These commands can be used by bots that need to manage multiple user profiles (e.g., the profiles of support agents). + +// Get active user profile +// Network usage: no. +export interface ShowActiveUser { +} + +export namespace ShowActiveUser { + export type Response = CR.ActiveUser | CR.ChatCmdError + + export function cmdString(_self: ShowActiveUser): string { + return '/user' + } +} + +// Create new user profile +// Network usage: no. +export interface CreateActiveUser { + newUser: T.NewUser +} + +export namespace CreateActiveUser { + export type Response = CR.ActiveUser | CR.ChatCmdError + + export function cmdString(self: CreateActiveUser): string { + return '/_create user ' + JSON.stringify(self.newUser) + } +} + +// Get all user profiles +// Network usage: no. +export interface ListUsers { +} + +export namespace ListUsers { + export type Response = CR.UsersList | CR.ChatCmdError + + export function cmdString(_self: ListUsers): string { + return '/users' + } +} + +// Set active user profile +// Network usage: no. +export interface APISetActiveUser { + userId: number // int64 + viewPwd?: string +} + +export namespace APISetActiveUser { + export type Response = CR.ActiveUser | CR.ChatCmdError + + export function cmdString(self: APISetActiveUser): string { + return '/_user ' + self.userId + (self.viewPwd ? ' ' + JSON.stringify(self.viewPwd) : '') + } +} + +// Delete user profile. +// Network usage: background. +export interface APIDeleteUser { + userId: number // int64 + delSMPQueues: boolean + viewPwd?: string +} + +export namespace APIDeleteUser { + export type Response = CR.CmdOk | CR.ChatCmdError + + export function cmdString(self: APIDeleteUser): string { + return '/_delete user ' + self.userId + ' del_smp=' + (self.delSMPQueues ? 'on' : 'off') + (self.viewPwd ? ' ' + JSON.stringify(self.viewPwd) : '') + } +} + +// Update user profile. +// Network usage: background. +export interface APIUpdateProfile { + userId: number // int64 + profile: T.Profile +} + +export namespace APIUpdateProfile { + export type Response = CR.UserProfileUpdated | CR.UserProfileNoChange | CR.ChatCmdError + + export function cmdString(self: APIUpdateProfile): string { + return '/_profile ' + self.userId + ' ' + JSON.stringify(self.profile) + } +} + +// Configure chat preference overrides for the contact. +// Network usage: background. +export interface APISetContactPrefs { + contactId: number // int64 + preferences: T.Preferences +} + +export namespace APISetContactPrefs { + export type Response = CR.ContactPrefsUpdated | CR.ChatCmdError + + export function cmdString(self: APISetContactPrefs): string { + return '/_set prefs @' + self.contactId + ' ' + JSON.stringify(self.preferences) + } +} diff --git a/packages/simplex-chat-client/types/typescript/src/events.ts b/packages/simplex-chat-client/types/typescript/src/events.ts new file mode 100644 index 0000000000..d7a0419bbe --- /dev/null +++ b/packages/simplex-chat-client/types/typescript/src/events.ts @@ -0,0 +1,430 @@ +// API Events +// This file is generated automatically. + +import * as T from "./types" + +export type ChatEvent = + | CEvt.ContactConnected + | CEvt.ContactUpdated + | CEvt.ContactDeletedByContact + | CEvt.ReceivedContactRequest + | CEvt.NewMemberContactReceivedInv + | CEvt.ContactSndReady + | CEvt.NewChatItems + | CEvt.ChatItemReaction + | CEvt.ChatItemsDeleted + | CEvt.ChatItemUpdated + | CEvt.GroupChatItemsDeleted + | CEvt.ChatItemsStatusesUpdated + | CEvt.ReceivedGroupInvitation + | CEvt.UserJoinedGroup + | CEvt.GroupUpdated + | CEvt.JoinedGroupMember + | CEvt.MemberRole + | CEvt.DeletedMember + | CEvt.LeftMember + | CEvt.DeletedMemberUser + | CEvt.GroupDeleted + | CEvt.ConnectedToGroupMember + | CEvt.MemberAcceptedByOther + | CEvt.MemberBlockedForAll + | CEvt.GroupMemberUpdated + | CEvt.RcvFileDescrReady + | CEvt.RcvFileComplete + | CEvt.SndFileCompleteXFTP + | CEvt.RcvFileStart + | CEvt.RcvFileSndCancelled + | CEvt.RcvFileAccepted + | CEvt.RcvFileError + | CEvt.RcvFileWarning + | CEvt.SndFileError + | CEvt.SndFileWarning + | CEvt.AcceptingContactRequest + | CEvt.AcceptingBusinessRequest + | CEvt.ContactConnecting + | CEvt.BusinessLinkConnecting + | CEvt.JoinedGroupMemberConnecting + | CEvt.SentGroupInvitation + | CEvt.GroupLinkConnecting + | CEvt.MessageError + | CEvt.ChatError + | CEvt.ChatErrors + +export namespace CEvt { + export type Tag = + | "contactConnected" + | "contactUpdated" + | "contactDeletedByContact" + | "receivedContactRequest" + | "newMemberContactReceivedInv" + | "contactSndReady" + | "newChatItems" + | "chatItemReaction" + | "chatItemsDeleted" + | "chatItemUpdated" + | "groupChatItemsDeleted" + | "chatItemsStatusesUpdated" + | "receivedGroupInvitation" + | "userJoinedGroup" + | "groupUpdated" + | "joinedGroupMember" + | "memberRole" + | "deletedMember" + | "leftMember" + | "deletedMemberUser" + | "groupDeleted" + | "connectedToGroupMember" + | "memberAcceptedByOther" + | "memberBlockedForAll" + | "groupMemberUpdated" + | "rcvFileDescrReady" + | "rcvFileComplete" + | "sndFileCompleteXFTP" + | "rcvFileStart" + | "rcvFileSndCancelled" + | "rcvFileAccepted" + | "rcvFileError" + | "rcvFileWarning" + | "sndFileError" + | "sndFileWarning" + | "acceptingContactRequest" + | "acceptingBusinessRequest" + | "contactConnecting" + | "businessLinkConnecting" + | "joinedGroupMemberConnecting" + | "sentGroupInvitation" + | "groupLinkConnecting" + | "messageError" + | "chatError" + | "chatErrors" + + interface Interface { + type: Tag + } + + export interface ContactConnected extends Interface { + type: "contactConnected" + user: T.User + contact: T.Contact + userCustomProfile?: T.Profile + } + + export interface ContactUpdated extends Interface { + type: "contactUpdated" + user: T.User + fromContact: T.Contact + toContact: T.Contact + } + + export interface ContactDeletedByContact extends Interface { + type: "contactDeletedByContact" + user: T.User + contact: T.Contact + } + + export interface ReceivedContactRequest extends Interface { + type: "receivedContactRequest" + user: T.User + contactRequest: T.UserContactRequest + chat_?: T.AChat + } + + export interface NewMemberContactReceivedInv extends Interface { + type: "newMemberContactReceivedInv" + user: T.User + contact: T.Contact + groupInfo: T.GroupInfo + member: T.GroupMember + } + + export interface ContactSndReady extends Interface { + type: "contactSndReady" + user: T.User + contact: T.Contact + } + + export interface NewChatItems extends Interface { + type: "newChatItems" + user: T.User + chatItems: T.AChatItem[] + } + + export interface ChatItemReaction extends Interface { + type: "chatItemReaction" + user: T.User + added: boolean + reaction: T.ACIReaction + } + + export interface ChatItemsDeleted extends Interface { + type: "chatItemsDeleted" + user: T.User + chatItemDeletions: T.ChatItemDeletion[] + byUser: boolean + timed: boolean + } + + export interface ChatItemUpdated extends Interface { + type: "chatItemUpdated" + user: T.User + chatItem: T.AChatItem + } + + export interface GroupChatItemsDeleted extends Interface { + type: "groupChatItemsDeleted" + user: T.User + groupInfo: T.GroupInfo + chatItemIDs: number[] // int64 + byUser: boolean + member_?: T.GroupMember + } + + export interface ChatItemsStatusesUpdated extends Interface { + type: "chatItemsStatusesUpdated" + user: T.User + chatItems: T.AChatItem[] + } + + export interface ReceivedGroupInvitation extends Interface { + type: "receivedGroupInvitation" + user: T.User + groupInfo: T.GroupInfo + contact: T.Contact + fromMemberRole: T.GroupMemberRole + memberRole: T.GroupMemberRole + } + + export interface UserJoinedGroup extends Interface { + type: "userJoinedGroup" + user: T.User + groupInfo: T.GroupInfo + hostMember: T.GroupMember + } + + export interface GroupUpdated extends Interface { + type: "groupUpdated" + user: T.User + fromGroup: T.GroupInfo + toGroup: T.GroupInfo + member_?: T.GroupMember + } + + export interface JoinedGroupMember extends Interface { + type: "joinedGroupMember" + user: T.User + groupInfo: T.GroupInfo + member: T.GroupMember + } + + export interface MemberRole extends Interface { + type: "memberRole" + user: T.User + groupInfo: T.GroupInfo + byMember: T.GroupMember + member: T.GroupMember + fromRole: T.GroupMemberRole + toRole: T.GroupMemberRole + } + + export interface DeletedMember extends Interface { + type: "deletedMember" + user: T.User + groupInfo: T.GroupInfo + byMember: T.GroupMember + deletedMember: T.GroupMember + withMessages: boolean + } + + export interface LeftMember extends Interface { + type: "leftMember" + user: T.User + groupInfo: T.GroupInfo + member: T.GroupMember + } + + export interface DeletedMemberUser extends Interface { + type: "deletedMemberUser" + user: T.User + groupInfo: T.GroupInfo + member: T.GroupMember + withMessages: boolean + } + + export interface GroupDeleted extends Interface { + type: "groupDeleted" + user: T.User + groupInfo: T.GroupInfo + member: T.GroupMember + } + + export interface ConnectedToGroupMember extends Interface { + type: "connectedToGroupMember" + user: T.User + groupInfo: T.GroupInfo + member: T.GroupMember + memberContact?: T.Contact + } + + export interface MemberAcceptedByOther extends Interface { + type: "memberAcceptedByOther" + user: T.User + groupInfo: T.GroupInfo + acceptingMember: T.GroupMember + member: T.GroupMember + } + + export interface MemberBlockedForAll extends Interface { + type: "memberBlockedForAll" + user: T.User + groupInfo: T.GroupInfo + byMember: T.GroupMember + member: T.GroupMember + blocked: boolean + } + + export interface GroupMemberUpdated extends Interface { + type: "groupMemberUpdated" + user: T.User + groupInfo: T.GroupInfo + fromMember: T.GroupMember + toMember: T.GroupMember + } + + export interface RcvFileDescrReady extends Interface { + type: "rcvFileDescrReady" + user: T.User + chatItem: T.AChatItem + rcvFileTransfer: T.RcvFileTransfer + rcvFileDescr: T.RcvFileDescr + } + + export interface RcvFileComplete extends Interface { + type: "rcvFileComplete" + user: T.User + chatItem: T.AChatItem + } + + export interface SndFileCompleteXFTP extends Interface { + type: "sndFileCompleteXFTP" + user: T.User + chatItem: T.AChatItem + fileTransferMeta: T.FileTransferMeta + } + + export interface RcvFileStart extends Interface { + type: "rcvFileStart" + user: T.User + chatItem: T.AChatItem + } + + export interface RcvFileSndCancelled extends Interface { + type: "rcvFileSndCancelled" + user: T.User + chatItem: T.AChatItem + rcvFileTransfer: T.RcvFileTransfer + } + + export interface RcvFileAccepted extends Interface { + type: "rcvFileAccepted" + user: T.User + chatItem: T.AChatItem + } + + export interface RcvFileError extends Interface { + type: "rcvFileError" + user: T.User + chatItem_?: T.AChatItem + agentError: T.AgentErrorType + rcvFileTransfer: T.RcvFileTransfer + } + + export interface RcvFileWarning extends Interface { + type: "rcvFileWarning" + user: T.User + chatItem_?: T.AChatItem + agentError: T.AgentErrorType + rcvFileTransfer: T.RcvFileTransfer + } + + export interface SndFileError extends Interface { + type: "sndFileError" + user: T.User + chatItem_?: T.AChatItem + fileTransferMeta: T.FileTransferMeta + errorMessage: string + } + + export interface SndFileWarning extends Interface { + type: "sndFileWarning" + user: T.User + chatItem_?: T.AChatItem + fileTransferMeta: T.FileTransferMeta + errorMessage: string + } + + export interface AcceptingContactRequest extends Interface { + type: "acceptingContactRequest" + user: T.User + contact: T.Contact + } + + export interface AcceptingBusinessRequest extends Interface { + type: "acceptingBusinessRequest" + user: T.User + groupInfo: T.GroupInfo + } + + export interface ContactConnecting extends Interface { + type: "contactConnecting" + user: T.User + contact: T.Contact + } + + export interface BusinessLinkConnecting extends Interface { + type: "businessLinkConnecting" + user: T.User + groupInfo: T.GroupInfo + hostMember: T.GroupMember + fromContact: T.Contact + } + + export interface JoinedGroupMemberConnecting extends Interface { + type: "joinedGroupMemberConnecting" + user: T.User + groupInfo: T.GroupInfo + hostMember: T.GroupMember + member: T.GroupMember + } + + export interface SentGroupInvitation extends Interface { + type: "sentGroupInvitation" + user: T.User + groupInfo: T.GroupInfo + contact: T.Contact + member: T.GroupMember + } + + export interface GroupLinkConnecting extends Interface { + type: "groupLinkConnecting" + user: T.User + groupInfo: T.GroupInfo + hostMember: T.GroupMember + } + + export interface MessageError extends Interface { + type: "messageError" + user: T.User + severity: string + errorMessage: string + } + + export interface ChatError extends Interface { + type: "chatError" + chatError: T.ChatError + } + + export interface ChatErrors extends Interface { + type: "chatErrors" + chatErrors: T.ChatError[] + } +} diff --git a/packages/simplex-chat-client/types/typescript/src/index.ts b/packages/simplex-chat-client/types/typescript/src/index.ts new file mode 100644 index 0000000000..9a92af29a0 --- /dev/null +++ b/packages/simplex-chat-client/types/typescript/src/index.ts @@ -0,0 +1,4 @@ +export * as CC from "./commands" +export {ChatResponse, CR} from "./responses" +export {ChatEvent, CEvt} from "./events" +export * as T from "./types" diff --git a/packages/simplex-chat-client/types/typescript/src/responses.ts b/packages/simplex-chat-client/types/typescript/src/responses.ts new file mode 100644 index 0000000000..2ea67432f5 --- /dev/null +++ b/packages/simplex-chat-client/types/typescript/src/responses.ts @@ -0,0 +1,396 @@ +// API Responses +// This file is generated automatically. + +import * as T from "./types" + +export type ChatResponse = + | CR.AcceptingContactRequest + | CR.ActiveUser + | CR.ChatItemNotChanged + | CR.ChatItemReaction + | CR.ChatItemUpdated + | CR.ChatItemsDeleted + | CR.CmdOk + | CR.ChatCmdError + | CR.ConnectionPlan + | CR.ContactAlreadyExists + | CR.ContactConnectionDeleted + | CR.ContactDeleted + | CR.ContactPrefsUpdated + | CR.ContactRequestRejected + | CR.ContactsList + | CR.GroupDeletedUser + | CR.GroupLink + | CR.GroupLinkCreated + | CR.GroupLinkDeleted + | CR.GroupCreated + | CR.GroupMembers + | CR.GroupUpdated + | CR.GroupsList + | CR.Invitation + | CR.LeftMemberUser + | CR.MemberAccepted + | CR.MembersBlockedForAllUser + | CR.MembersRoleUser + | CR.NewChatItems + | CR.RcvFileAccepted + | CR.RcvFileAcceptedSndCancelled + | CR.RcvFileCancelled + | CR.SentConfirmation + | CR.SentGroupInvitation + | CR.SentInvitation + | CR.SndFileCancelled + | CR.UserAcceptedGroupSent + | CR.UserContactLink + | CR.UserContactLinkCreated + | CR.UserContactLinkDeleted + | CR.UserContactLinkUpdated + | CR.UserDeletedMembers + | CR.UserProfileUpdated + | CR.UserProfileNoChange + | CR.UsersList + +export namespace CR { + export type Tag = + | "acceptingContactRequest" + | "activeUser" + | "chatItemNotChanged" + | "chatItemReaction" + | "chatItemUpdated" + | "chatItemsDeleted" + | "cmdOk" + | "chatCmdError" + | "connectionPlan" + | "contactAlreadyExists" + | "contactConnectionDeleted" + | "contactDeleted" + | "contactPrefsUpdated" + | "contactRequestRejected" + | "contactsList" + | "groupDeletedUser" + | "groupLink" + | "groupLinkCreated" + | "groupLinkDeleted" + | "groupCreated" + | "groupMembers" + | "groupUpdated" + | "groupsList" + | "invitation" + | "leftMemberUser" + | "memberAccepted" + | "membersBlockedForAllUser" + | "membersRoleUser" + | "newChatItems" + | "rcvFileAccepted" + | "rcvFileAcceptedSndCancelled" + | "rcvFileCancelled" + | "sentConfirmation" + | "sentGroupInvitation" + | "sentInvitation" + | "sndFileCancelled" + | "userAcceptedGroupSent" + | "userContactLink" + | "userContactLinkCreated" + | "userContactLinkDeleted" + | "userContactLinkUpdated" + | "userDeletedMembers" + | "userProfileUpdated" + | "userProfileNoChange" + | "usersList" + + interface Interface { + type: Tag + } + + export interface AcceptingContactRequest extends Interface { + type: "acceptingContactRequest" + user: T.User + contact: T.Contact + } + + export interface ActiveUser extends Interface { + type: "activeUser" + user: T.User + } + + export interface ChatItemNotChanged extends Interface { + type: "chatItemNotChanged" + user: T.User + chatItem: T.AChatItem + } + + export interface ChatItemReaction extends Interface { + type: "chatItemReaction" + user: T.User + added: boolean + reaction: T.ACIReaction + } + + export interface ChatItemUpdated extends Interface { + type: "chatItemUpdated" + user: T.User + chatItem: T.AChatItem + } + + export interface ChatItemsDeleted extends Interface { + type: "chatItemsDeleted" + user: T.User + chatItemDeletions: T.ChatItemDeletion[] + byUser: boolean + timed: boolean + } + + export interface CmdOk extends Interface { + type: "cmdOk" + user_?: T.User + } + + export interface ChatCmdError extends Interface { + type: "chatCmdError" + chatError: T.ChatError + } + + export interface ConnectionPlan extends Interface { + type: "connectionPlan" + user: T.User + connLink: T.CreatedConnLink + connectionPlan: T.ConnectionPlan + } + + export interface ContactAlreadyExists extends Interface { + type: "contactAlreadyExists" + user: T.User + contact: T.Contact + } + + export interface ContactConnectionDeleted extends Interface { + type: "contactConnectionDeleted" + user: T.User + connection: T.PendingContactConnection + } + + export interface ContactDeleted extends Interface { + type: "contactDeleted" + user: T.User + contact: T.Contact + } + + export interface ContactPrefsUpdated extends Interface { + type: "contactPrefsUpdated" + user: T.User + fromContact: T.Contact + toContact: T.Contact + } + + export interface ContactRequestRejected extends Interface { + type: "contactRequestRejected" + user: T.User + contactRequest: T.UserContactRequest + contact_?: T.Contact + } + + export interface ContactsList extends Interface { + type: "contactsList" + user: T.User + contacts: T.Contact[] + } + + export interface GroupDeletedUser extends Interface { + type: "groupDeletedUser" + user: T.User + groupInfo: T.GroupInfo + } + + export interface GroupLink extends Interface { + type: "groupLink" + user: T.User + groupInfo: T.GroupInfo + groupLink: T.GroupLink + } + + export interface GroupLinkCreated extends Interface { + type: "groupLinkCreated" + user: T.User + groupInfo: T.GroupInfo + groupLink: T.GroupLink + } + + export interface GroupLinkDeleted extends Interface { + type: "groupLinkDeleted" + user: T.User + groupInfo: T.GroupInfo + } + + export interface GroupCreated extends Interface { + type: "groupCreated" + user: T.User + groupInfo: T.GroupInfo + } + + export interface GroupMembers extends Interface { + type: "groupMembers" + user: T.User + group: T.Group + } + + export interface GroupUpdated extends Interface { + type: "groupUpdated" + user: T.User + fromGroup: T.GroupInfo + toGroup: T.GroupInfo + member_?: T.GroupMember + } + + export interface GroupsList extends Interface { + type: "groupsList" + user: T.User + groups: T.GroupInfoSummary[] + } + + export interface Invitation extends Interface { + type: "invitation" + user: T.User + connLinkInvitation: T.CreatedConnLink + connection: T.PendingContactConnection + } + + export interface LeftMemberUser extends Interface { + type: "leftMemberUser" + user: T.User + groupInfo: T.GroupInfo + } + + export interface MemberAccepted extends Interface { + type: "memberAccepted" + user: T.User + groupInfo: T.GroupInfo + member: T.GroupMember + } + + export interface MembersBlockedForAllUser extends Interface { + type: "membersBlockedForAllUser" + user: T.User + groupInfo: T.GroupInfo + members: T.GroupMember[] + blocked: boolean + } + + export interface MembersRoleUser extends Interface { + type: "membersRoleUser" + user: T.User + groupInfo: T.GroupInfo + members: T.GroupMember[] + toRole: T.GroupMemberRole + } + + export interface NewChatItems extends Interface { + type: "newChatItems" + user: T.User + chatItems: T.AChatItem[] + } + + export interface RcvFileAccepted extends Interface { + type: "rcvFileAccepted" + user: T.User + chatItem: T.AChatItem + } + + export interface RcvFileAcceptedSndCancelled extends Interface { + type: "rcvFileAcceptedSndCancelled" + user: T.User + rcvFileTransfer: T.RcvFileTransfer + } + + export interface RcvFileCancelled extends Interface { + type: "rcvFileCancelled" + user: T.User + chatItem_?: T.AChatItem + rcvFileTransfer: T.RcvFileTransfer + } + + export interface SentConfirmation extends Interface { + type: "sentConfirmation" + user: T.User + connection: T.PendingContactConnection + customUserProfile?: T.Profile + } + + export interface SentGroupInvitation extends Interface { + type: "sentGroupInvitation" + user: T.User + groupInfo: T.GroupInfo + contact: T.Contact + member: T.GroupMember + } + + export interface SentInvitation extends Interface { + type: "sentInvitation" + user: T.User + connection: T.PendingContactConnection + customUserProfile?: T.Profile + } + + export interface SndFileCancelled extends Interface { + type: "sndFileCancelled" + user: T.User + chatItem_?: T.AChatItem + fileTransferMeta: T.FileTransferMeta + sndFileTransfers: T.SndFileTransfer[] + } + + export interface UserAcceptedGroupSent extends Interface { + type: "userAcceptedGroupSent" + user: T.User + groupInfo: T.GroupInfo + hostContact?: T.Contact + } + + export interface UserContactLink extends Interface { + type: "userContactLink" + user: T.User + contactLink: T.UserContactLink + } + + export interface UserContactLinkCreated extends Interface { + type: "userContactLinkCreated" + user: T.User + connLinkContact: T.CreatedConnLink + } + + export interface UserContactLinkDeleted extends Interface { + type: "userContactLinkDeleted" + user: T.User + } + + export interface UserContactLinkUpdated extends Interface { + type: "userContactLinkUpdated" + user: T.User + contactLink: T.UserContactLink + } + + export interface UserDeletedMembers extends Interface { + type: "userDeletedMembers" + user: T.User + groupInfo: T.GroupInfo + members: T.GroupMember[] + withMessages: boolean + } + + export interface UserProfileUpdated extends Interface { + type: "userProfileUpdated" + user: T.User + fromProfile: T.Profile + toProfile: T.Profile + updateSummary: T.UserProfileUpdateSummary + } + + export interface UserProfileNoChange extends Interface { + type: "userProfileNoChange" + user: T.User + } + + export interface UsersList extends Interface { + type: "usersList" + users: T.UserInfo[] + } +} diff --git a/packages/simplex-chat-client/types/typescript/src/types.ts b/packages/simplex-chat-client/types/typescript/src/types.ts new file mode 100644 index 0000000000..1511c3851f --- /dev/null +++ b/packages/simplex-chat-client/types/typescript/src/types.ts @@ -0,0 +1,4509 @@ +// API Types +// This file is generated automatically. + +export interface ACIReaction { + chatInfo: ChatInfo + chatReaction: CIReaction +} + +export interface AChat { + chatInfo: ChatInfo + chatItems: ChatItem[] + chatStats: ChatStats +} + +export interface AChatItem { + chatInfo: ChatInfo + chatItem: ChatItem +} + +export interface AddressSettings { + businessAddress: boolean + autoAccept?: AutoAccept + autoReply?: MsgContent +} + +export type AgentCryptoError = + | AgentCryptoError.DECRYPT_AES + | AgentCryptoError.DECRYPT_CB + | AgentCryptoError.RATCHET_HEADER + | AgentCryptoError.RATCHET_SYNC + +export namespace AgentCryptoError { + export type Tag = "DECRYPT_AES" | "DECRYPT_CB" | "RATCHET_HEADER" | "RATCHET_SYNC" + + interface Interface { + type: Tag + } + + export interface DECRYPT_AES extends Interface { + type: "DECRYPT_AES" + } + + export interface DECRYPT_CB extends Interface { + type: "DECRYPT_CB" + } + + export interface RATCHET_HEADER extends Interface { + type: "RATCHET_HEADER" + } + + export interface RATCHET_SYNC extends Interface { + type: "RATCHET_SYNC" + } +} + +export type AgentErrorType = + | AgentErrorType.CMD + | AgentErrorType.CONN + | AgentErrorType.NO_USER + | AgentErrorType.SMP + | AgentErrorType.NTF + | AgentErrorType.XFTP + | AgentErrorType.FILE + | AgentErrorType.PROXY + | AgentErrorType.RCP + | AgentErrorType.BROKER + | AgentErrorType.AGENT + | AgentErrorType.INTERNAL + | AgentErrorType.CRITICAL + | AgentErrorType.INACTIVE + +export namespace AgentErrorType { + export type Tag = + | "CMD" + | "CONN" + | "NO_USER" + | "SMP" + | "NTF" + | "XFTP" + | "FILE" + | "PROXY" + | "RCP" + | "BROKER" + | "AGENT" + | "INTERNAL" + | "CRITICAL" + | "INACTIVE" + + interface Interface { + type: Tag + } + + export interface CMD extends Interface { + type: "CMD" + cmdErr: CommandErrorType + errContext: string + } + + export interface CONN extends Interface { + type: "CONN" + connErr: ConnectionErrorType + errContext: string + } + + export interface NO_USER extends Interface { + type: "NO_USER" + } + + export interface SMP extends Interface { + type: "SMP" + serverAddress: string + smpErr: ErrorType + } + + export interface NTF extends Interface { + type: "NTF" + serverAddress: string + ntfErr: ErrorType + } + + export interface XFTP extends Interface { + type: "XFTP" + serverAddress: string + xftpErr: XFTPErrorType + } + + export interface FILE extends Interface { + type: "FILE" + fileErr: FileErrorType + } + + export interface PROXY extends Interface { + type: "PROXY" + proxyServer: string + relayServer: string + proxyErr: ProxyClientError + } + + export interface RCP extends Interface { + type: "RCP" + rcpErr: RCErrorType + } + + export interface BROKER extends Interface { + type: "BROKER" + brokerAddress: string + brokerErr: BrokerErrorType + } + + export interface AGENT extends Interface { + type: "AGENT" + agentErr: SMPAgentError + } + + export interface INTERNAL extends Interface { + type: "INTERNAL" + internalErr: string + } + + export interface CRITICAL extends Interface { + type: "CRITICAL" + offerRestart: boolean + criticalErr: string + } + + export interface INACTIVE extends Interface { + type: "INACTIVE" + } +} + +export interface AutoAccept { + acceptIncognito: boolean +} + +export interface BlockingInfo { + reason: BlockingReason +} + +export enum BlockingReason { + Spam = "spam", + Content = "content", +} + +export type BrokerErrorType = + | BrokerErrorType.RESPONSE + | BrokerErrorType.UNEXPECTED + | BrokerErrorType.NETWORK + | BrokerErrorType.HOST + | BrokerErrorType.NO_SERVICE + | BrokerErrorType.TRANSPORT + | BrokerErrorType.TIMEOUT + +export namespace BrokerErrorType { + export type Tag = + | "RESPONSE" + | "UNEXPECTED" + | "NETWORK" + | "HOST" + | "NO_SERVICE" + | "TRANSPORT" + | "TIMEOUT" + + interface Interface { + type: Tag + } + + export interface RESPONSE extends Interface { + type: "RESPONSE" + respErr: string + } + + export interface UNEXPECTED extends Interface { + type: "UNEXPECTED" + respErr: string + } + + export interface NETWORK extends Interface { + type: "NETWORK" + } + + export interface HOST extends Interface { + type: "HOST" + } + + export interface NO_SERVICE extends Interface { + type: "NO_SERVICE" + } + + export interface TRANSPORT extends Interface { + type: "TRANSPORT" + transportErr: TransportError + } + + export interface TIMEOUT extends Interface { + type: "TIMEOUT" + } +} + +export interface BusinessChatInfo { + chatType: BusinessChatType + businessId: string + customerId: string +} + +export enum BusinessChatType { + Business = "business", + Customer = "customer", +} + +export enum CICallStatus { + Pending = "pending", + Missed = "missed", + Rejected = "rejected", + Accepted = "accepted", + Negotiated = "negotiated", + Progress = "progress", + Ended = "ended", + Error = "error", +} + +export type CIContent = + | CIContent.SndMsgContent + | CIContent.RcvMsgContent + | CIContent.SndDeleted + | CIContent.RcvDeleted + | CIContent.SndCall + | CIContent.RcvCall + | CIContent.RcvIntegrityError + | CIContent.RcvDecryptionError + | CIContent.RcvGroupInvitation + | CIContent.SndGroupInvitation + | CIContent.RcvDirectEvent + | CIContent.RcvGroupEvent + | CIContent.SndGroupEvent + | CIContent.RcvConnEvent + | CIContent.SndConnEvent + | CIContent.RcvChatFeature + | CIContent.SndChatFeature + | CIContent.RcvChatPreference + | CIContent.SndChatPreference + | CIContent.RcvGroupFeature + | CIContent.SndGroupFeature + | CIContent.RcvChatFeatureRejected + | CIContent.RcvGroupFeatureRejected + | CIContent.SndModerated + | CIContent.RcvModerated + | CIContent.RcvBlocked + | CIContent.SndDirectE2EEInfo + | CIContent.RcvDirectE2EEInfo + | CIContent.SndGroupE2EEInfo + | CIContent.RcvGroupE2EEInfo + | CIContent.ChatBanner + +export namespace CIContent { + export type Tag = + | "sndMsgContent" + | "rcvMsgContent" + | "sndDeleted" + | "rcvDeleted" + | "sndCall" + | "rcvCall" + | "rcvIntegrityError" + | "rcvDecryptionError" + | "rcvGroupInvitation" + | "sndGroupInvitation" + | "rcvDirectEvent" + | "rcvGroupEvent" + | "sndGroupEvent" + | "rcvConnEvent" + | "sndConnEvent" + | "rcvChatFeature" + | "sndChatFeature" + | "rcvChatPreference" + | "sndChatPreference" + | "rcvGroupFeature" + | "sndGroupFeature" + | "rcvChatFeatureRejected" + | "rcvGroupFeatureRejected" + | "sndModerated" + | "rcvModerated" + | "rcvBlocked" + | "sndDirectE2EEInfo" + | "rcvDirectE2EEInfo" + | "sndGroupE2EEInfo" + | "rcvGroupE2EEInfo" + | "chatBanner" + + interface Interface { + type: Tag + } + + export interface SndMsgContent extends Interface { + type: "sndMsgContent" + msgContent: MsgContent + } + + export interface RcvMsgContent extends Interface { + type: "rcvMsgContent" + msgContent: MsgContent + } + + export interface SndDeleted extends Interface { + type: "sndDeleted" + deleteMode: CIDeleteMode + } + + export interface RcvDeleted extends Interface { + type: "rcvDeleted" + deleteMode: CIDeleteMode + } + + export interface SndCall extends Interface { + type: "sndCall" + status: CICallStatus + duration: number // int + } + + export interface RcvCall extends Interface { + type: "rcvCall" + status: CICallStatus + duration: number // int + } + + export interface RcvIntegrityError extends Interface { + type: "rcvIntegrityError" + msgError: MsgErrorType + } + + export interface RcvDecryptionError extends Interface { + type: "rcvDecryptionError" + msgDecryptError: MsgDecryptError + msgCount: number // word32 + } + + export interface RcvGroupInvitation extends Interface { + type: "rcvGroupInvitation" + groupInvitation: CIGroupInvitation + memberRole: GroupMemberRole + } + + export interface SndGroupInvitation extends Interface { + type: "sndGroupInvitation" + groupInvitation: CIGroupInvitation + memberRole: GroupMemberRole + } + + export interface RcvDirectEvent extends Interface { + type: "rcvDirectEvent" + rcvDirectEvent: RcvDirectEvent + } + + export interface RcvGroupEvent extends Interface { + type: "rcvGroupEvent" + rcvGroupEvent: RcvGroupEvent + } + + export interface SndGroupEvent extends Interface { + type: "sndGroupEvent" + sndGroupEvent: SndGroupEvent + } + + export interface RcvConnEvent extends Interface { + type: "rcvConnEvent" + rcvConnEvent: RcvConnEvent + } + + export interface SndConnEvent extends Interface { + type: "sndConnEvent" + sndConnEvent: SndConnEvent + } + + export interface RcvChatFeature extends Interface { + type: "rcvChatFeature" + feature: ChatFeature + enabled: PrefEnabled + param?: number // int + } + + export interface SndChatFeature extends Interface { + type: "sndChatFeature" + feature: ChatFeature + enabled: PrefEnabled + param?: number // int + } + + export interface RcvChatPreference extends Interface { + type: "rcvChatPreference" + feature: ChatFeature + allowed: FeatureAllowed + param?: number // int + } + + export interface SndChatPreference extends Interface { + type: "sndChatPreference" + feature: ChatFeature + allowed: FeatureAllowed + param?: number // int + } + + export interface RcvGroupFeature extends Interface { + type: "rcvGroupFeature" + groupFeature: GroupFeature + preference: GroupPreference + param?: number // int + memberRole_?: GroupMemberRole + } + + export interface SndGroupFeature extends Interface { + type: "sndGroupFeature" + groupFeature: GroupFeature + preference: GroupPreference + param?: number // int + memberRole_?: GroupMemberRole + } + + export interface RcvChatFeatureRejected extends Interface { + type: "rcvChatFeatureRejected" + feature: ChatFeature + } + + export interface RcvGroupFeatureRejected extends Interface { + type: "rcvGroupFeatureRejected" + groupFeature: GroupFeature + } + + export interface SndModerated extends Interface { + type: "sndModerated" + } + + export interface RcvModerated extends Interface { + type: "rcvModerated" + } + + export interface RcvBlocked extends Interface { + type: "rcvBlocked" + } + + export interface SndDirectE2EEInfo extends Interface { + type: "sndDirectE2EEInfo" + e2eeInfo: E2EInfo + } + + export interface RcvDirectE2EEInfo extends Interface { + type: "rcvDirectE2EEInfo" + e2eeInfo: E2EInfo + } + + export interface SndGroupE2EEInfo extends Interface { + type: "sndGroupE2EEInfo" + e2eeInfo: E2EInfo + } + + export interface RcvGroupE2EEInfo extends Interface { + type: "rcvGroupE2EEInfo" + e2eeInfo: E2EInfo + } + + export interface ChatBanner extends Interface { + type: "chatBanner" + } +} + +export enum CIDeleteMode { + Broadcast = "broadcast", + Internal = "internal", + InternalMark = "internalMark", +} + +export type CIDeleted = CIDeleted.Deleted | CIDeleted.Blocked | CIDeleted.BlockedByAdmin | CIDeleted.Moderated + +export namespace CIDeleted { + export type Tag = "deleted" | "blocked" | "blockedByAdmin" | "moderated" + + interface Interface { + type: Tag + } + + export interface Deleted extends Interface { + type: "deleted" + deletedTs?: string // ISO-8601 timestamp + chatType: ChatType + } + + export interface Blocked extends Interface { + type: "blocked" + deletedTs?: string // ISO-8601 timestamp + } + + export interface BlockedByAdmin extends Interface { + type: "blockedByAdmin" + deletedTs?: string // ISO-8601 timestamp + } + + export interface Moderated extends Interface { + type: "moderated" + deletedTs?: string // ISO-8601 timestamp + byGroupMember: GroupMember + } +} + +export type CIDirection = + | CIDirection.DirectSnd + | CIDirection.DirectRcv + | CIDirection.GroupSnd + | CIDirection.GroupRcv + | CIDirection.LocalSnd + | CIDirection.LocalRcv + +export namespace CIDirection { + export type Tag = "directSnd" | "directRcv" | "groupSnd" | "groupRcv" | "localSnd" | "localRcv" + + interface Interface { + type: Tag + } + + export interface DirectSnd extends Interface { + type: "directSnd" + } + + export interface DirectRcv extends Interface { + type: "directRcv" + } + + export interface GroupSnd extends Interface { + type: "groupSnd" + } + + export interface GroupRcv extends Interface { + type: "groupRcv" + groupMember: GroupMember + } + + export interface LocalSnd extends Interface { + type: "localSnd" + } + + export interface LocalRcv extends Interface { + type: "localRcv" + } +} + +export interface CIFile { + fileId: number // int64 + fileName: string + fileSize: number // int64 + fileSource?: CryptoFile + fileStatus: CIFileStatus + fileProtocol: FileProtocol +} + +export type CIFileStatus = + | CIFileStatus.SndStored + | CIFileStatus.SndTransfer + | CIFileStatus.SndCancelled + | CIFileStatus.SndComplete + | CIFileStatus.SndError + | CIFileStatus.SndWarning + | CIFileStatus.RcvInvitation + | CIFileStatus.RcvAccepted + | CIFileStatus.RcvTransfer + | CIFileStatus.RcvAborted + | CIFileStatus.RcvComplete + | CIFileStatus.RcvCancelled + | CIFileStatus.RcvError + | CIFileStatus.RcvWarning + | CIFileStatus.Invalid + +export namespace CIFileStatus { + export type Tag = + | "sndStored" + | "sndTransfer" + | "sndCancelled" + | "sndComplete" + | "sndError" + | "sndWarning" + | "rcvInvitation" + | "rcvAccepted" + | "rcvTransfer" + | "rcvAborted" + | "rcvComplete" + | "rcvCancelled" + | "rcvError" + | "rcvWarning" + | "invalid" + + interface Interface { + type: Tag + } + + export interface SndStored extends Interface { + type: "sndStored" + } + + export interface SndTransfer extends Interface { + type: "sndTransfer" + sndProgress: number // int64 + sndTotal: number // int64 + } + + export interface SndCancelled extends Interface { + type: "sndCancelled" + } + + export interface SndComplete extends Interface { + type: "sndComplete" + } + + export interface SndError extends Interface { + type: "sndError" + sndFileError: FileError + } + + export interface SndWarning extends Interface { + type: "sndWarning" + sndFileError: FileError + } + + export interface RcvInvitation extends Interface { + type: "rcvInvitation" + } + + export interface RcvAccepted extends Interface { + type: "rcvAccepted" + } + + export interface RcvTransfer extends Interface { + type: "rcvTransfer" + rcvProgress: number // int64 + rcvTotal: number // int64 + } + + export interface RcvAborted extends Interface { + type: "rcvAborted" + } + + export interface RcvComplete extends Interface { + type: "rcvComplete" + } + + export interface RcvCancelled extends Interface { + type: "rcvCancelled" + } + + export interface RcvError extends Interface { + type: "rcvError" + rcvFileError: FileError + } + + export interface RcvWarning extends Interface { + type: "rcvWarning" + rcvFileError: FileError + } + + export interface Invalid extends Interface { + type: "invalid" + text: string + } +} + +export type CIForwardedFrom = CIForwardedFrom.Unknown | CIForwardedFrom.Contact | CIForwardedFrom.Group + +export namespace CIForwardedFrom { + export type Tag = "unknown" | "contact" | "group" + + interface Interface { + type: Tag + } + + export interface Unknown extends Interface { + type: "unknown" + } + + export interface Contact extends Interface { + type: "contact" + chatName: string + msgDir: MsgDirection + contactId?: number // int64 + chatItemId?: number // int64 + } + + export interface Group extends Interface { + type: "group" + chatName: string + msgDir: MsgDirection + groupId?: number // int64 + chatItemId?: number // int64 + } +} + +export interface CIGroupInvitation { + groupId: number // int64 + groupMemberId: number // int64 + localDisplayName: string + groupProfile: GroupProfile + status: CIGroupInvitationStatus +} + +export enum CIGroupInvitationStatus { + Pending = "pending", + Accepted = "accepted", + Rejected = "rejected", + Expired = "expired", +} + +export interface CIMention { + memberId: string + memberRef?: CIMentionMember +} + +export interface CIMentionMember { + groupMemberId: number // int64 + displayName: string + localAlias?: string + memberRole: GroupMemberRole +} + +export interface CIMeta { + itemId: number // int64 + itemTs: string // ISO-8601 timestamp + itemText: string + itemStatus: CIStatus + sentViaProxy?: boolean + itemSharedMsgId?: string + itemForwarded?: CIForwardedFrom + itemDeleted?: CIDeleted + itemEdited: boolean + itemTimed?: CITimed + itemLive?: boolean + userMention: boolean + deletable: boolean + editable: boolean + forwardedByMember?: number // int64 + showGroupAsSender: boolean + createdAt: string // ISO-8601 timestamp + updatedAt: string // ISO-8601 timestamp +} + +export interface CIQuote { + chatDir?: CIDirection + itemId?: number // int64 + sharedMsgId?: string + sentAt: string // ISO-8601 timestamp + content: MsgContent + formattedText?: FormattedText[] +} + +export interface CIReaction { + chatDir: CIDirection + chatItem: ChatItem + sentAt: string // ISO-8601 timestamp + reaction: MsgReaction +} + +export interface CIReactionCount { + reaction: MsgReaction + userReacted: boolean + totalReacted: number // int +} + +export type CIStatus = + | CIStatus.SndNew + | CIStatus.SndSent + | CIStatus.SndRcvd + | CIStatus.SndErrorAuth + | CIStatus.SndError + | CIStatus.SndWarning + | CIStatus.RcvNew + | CIStatus.RcvRead + | CIStatus.Invalid + +export namespace CIStatus { + export type Tag = + | "sndNew" + | "sndSent" + | "sndRcvd" + | "sndErrorAuth" + | "sndError" + | "sndWarning" + | "rcvNew" + | "rcvRead" + | "invalid" + + interface Interface { + type: Tag + } + + export interface SndNew extends Interface { + type: "sndNew" + } + + export interface SndSent extends Interface { + type: "sndSent" + sndProgress: SndCIStatusProgress + } + + export interface SndRcvd extends Interface { + type: "sndRcvd" + msgRcptStatus: MsgReceiptStatus + sndProgress: SndCIStatusProgress + } + + export interface SndErrorAuth extends Interface { + type: "sndErrorAuth" + } + + export interface SndError extends Interface { + type: "sndError" + agentError: SndError + } + + export interface SndWarning extends Interface { + type: "sndWarning" + agentError: SndError + } + + export interface RcvNew extends Interface { + type: "rcvNew" + } + + export interface RcvRead extends Interface { + type: "rcvRead" + } + + export interface Invalid extends Interface { + type: "invalid" + text: string + } +} + +export interface CITimed { + ttl: number // int + deleteAt?: string // ISO-8601 timestamp +} + +export type ChatBotCommand = ChatBotCommand.Command | ChatBotCommand.Menu + +export namespace ChatBotCommand { + export type Tag = "command" | "menu" + + interface Interface { + type: Tag + } + + export interface Command extends Interface { + type: "command" + keyword: string + label: string + params?: string + } + + export interface Menu extends Interface { + type: "menu" + label: string + commands: ChatBotCommand[] + } +} + +export type ChatDeleteMode = ChatDeleteMode.Full | ChatDeleteMode.Entity | ChatDeleteMode.Messages + +export namespace ChatDeleteMode { + export type Tag = "full" | "entity" | "messages" + + interface Interface { + type: Tag + } + + export interface Full extends Interface { + type: "full" + notify: boolean + } + + export interface Entity extends Interface { + type: "entity" + notify: boolean + } + + export interface Messages extends Interface { + type: "messages" + } + + export function cmdString(self: ChatDeleteMode): string { + return self.type + (self.type == 'messages' ? '' : (!self.notify ? ' notify=off' : '')) + } +} + +export type ChatError = ChatError.Error | ChatError.ErrorAgent | ChatError.ErrorStore + +export namespace ChatError { + export type Tag = "error" | "errorAgent" | "errorStore" + + interface Interface { + type: Tag + } + + export interface Error extends Interface { + type: "error" + errorType: ChatErrorType + } + + export interface ErrorAgent extends Interface { + type: "errorAgent" + agentError: AgentErrorType + connectionEntity_?: ConnectionEntity + } + + export interface ErrorStore extends Interface { + type: "errorStore" + storeError: StoreError + } +} + +export type ChatErrorType = + | ChatErrorType.NoActiveUser + | ChatErrorType.NoConnectionUser + | ChatErrorType.NoSndFileUser + | ChatErrorType.NoRcvFileUser + | ChatErrorType.UserUnknown + | ChatErrorType.ActiveUserExists + | ChatErrorType.UserExists + | ChatErrorType.DifferentActiveUser + | ChatErrorType.CantDeleteActiveUser + | ChatErrorType.CantDeleteLastUser + | ChatErrorType.CantHideLastUser + | ChatErrorType.HiddenUserAlwaysMuted + | ChatErrorType.EmptyUserPassword + | ChatErrorType.UserAlreadyHidden + | ChatErrorType.UserNotHidden + | ChatErrorType.InvalidDisplayName + | ChatErrorType.ChatNotStarted + | ChatErrorType.ChatNotStopped + | ChatErrorType.ChatStoreChanged + | ChatErrorType.InvalidConnReq + | ChatErrorType.UnsupportedConnReq + | ChatErrorType.ConnReqMessageProhibited + | ChatErrorType.ContactNotReady + | ChatErrorType.ContactNotActive + | ChatErrorType.ContactDisabled + | ChatErrorType.ConnectionDisabled + | ChatErrorType.GroupUserRole + | ChatErrorType.GroupMemberInitialRole + | ChatErrorType.ContactIncognitoCantInvite + | ChatErrorType.GroupIncognitoCantInvite + | ChatErrorType.GroupContactRole + | ChatErrorType.GroupDuplicateMember + | ChatErrorType.GroupDuplicateMemberId + | ChatErrorType.GroupNotJoined + | ChatErrorType.GroupMemberNotActive + | ChatErrorType.CantBlockMemberForSelf + | ChatErrorType.GroupMemberUserRemoved + | ChatErrorType.GroupMemberNotFound + | ChatErrorType.GroupCantResendInvitation + | ChatErrorType.GroupInternal + | ChatErrorType.FileNotFound + | ChatErrorType.FileSize + | ChatErrorType.FileAlreadyReceiving + | ChatErrorType.FileCancelled + | ChatErrorType.FileCancel + | ChatErrorType.FileAlreadyExists + | ChatErrorType.FileRead + | ChatErrorType.FileWrite + | ChatErrorType.FileSend + | ChatErrorType.FileRcvChunk + | ChatErrorType.FileInternal + | ChatErrorType.FileImageType + | ChatErrorType.FileImageSize + | ChatErrorType.FileNotReceived + | ChatErrorType.FileNotApproved + | ChatErrorType.FallbackToSMPProhibited + | ChatErrorType.InlineFileProhibited + | ChatErrorType.InvalidForward + | ChatErrorType.InvalidChatItemUpdate + | ChatErrorType.InvalidChatItemDelete + | ChatErrorType.HasCurrentCall + | ChatErrorType.NoCurrentCall + | ChatErrorType.CallContact + | ChatErrorType.DirectMessagesProhibited + | ChatErrorType.AgentVersion + | ChatErrorType.AgentNoSubResult + | ChatErrorType.CommandError + | ChatErrorType.AgentCommandError + | ChatErrorType.InvalidFileDescription + | ChatErrorType.ConnectionIncognitoChangeProhibited + | ChatErrorType.ConnectionUserChangeProhibited + | ChatErrorType.PeerChatVRangeIncompatible + | ChatErrorType.InternalError + | ChatErrorType.Exception + +export namespace ChatErrorType { + export type Tag = + | "noActiveUser" + | "noConnectionUser" + | "noSndFileUser" + | "noRcvFileUser" + | "userUnknown" + | "activeUserExists" + | "userExists" + | "differentActiveUser" + | "cantDeleteActiveUser" + | "cantDeleteLastUser" + | "cantHideLastUser" + | "hiddenUserAlwaysMuted" + | "emptyUserPassword" + | "userAlreadyHidden" + | "userNotHidden" + | "invalidDisplayName" + | "chatNotStarted" + | "chatNotStopped" + | "chatStoreChanged" + | "invalidConnReq" + | "unsupportedConnReq" + | "connReqMessageProhibited" + | "contactNotReady" + | "contactNotActive" + | "contactDisabled" + | "connectionDisabled" + | "groupUserRole" + | "groupMemberInitialRole" + | "contactIncognitoCantInvite" + | "groupIncognitoCantInvite" + | "groupContactRole" + | "groupDuplicateMember" + | "groupDuplicateMemberId" + | "groupNotJoined" + | "groupMemberNotActive" + | "cantBlockMemberForSelf" + | "groupMemberUserRemoved" + | "groupMemberNotFound" + | "groupCantResendInvitation" + | "groupInternal" + | "fileNotFound" + | "fileSize" + | "fileAlreadyReceiving" + | "fileCancelled" + | "fileCancel" + | "fileAlreadyExists" + | "fileRead" + | "fileWrite" + | "fileSend" + | "fileRcvChunk" + | "fileInternal" + | "fileImageType" + | "fileImageSize" + | "fileNotReceived" + | "fileNotApproved" + | "fallbackToSMPProhibited" + | "inlineFileProhibited" + | "invalidForward" + | "invalidChatItemUpdate" + | "invalidChatItemDelete" + | "hasCurrentCall" + | "noCurrentCall" + | "callContact" + | "directMessagesProhibited" + | "agentVersion" + | "agentNoSubResult" + | "commandError" + | "agentCommandError" + | "invalidFileDescription" + | "connectionIncognitoChangeProhibited" + | "connectionUserChangeProhibited" + | "peerChatVRangeIncompatible" + | "internalError" + | "exception" + + interface Interface { + type: Tag + } + + export interface NoActiveUser extends Interface { + type: "noActiveUser" + } + + export interface NoConnectionUser extends Interface { + type: "noConnectionUser" + agentConnId: string + } + + export interface NoSndFileUser extends Interface { + type: "noSndFileUser" + agentSndFileId: string + } + + export interface NoRcvFileUser extends Interface { + type: "noRcvFileUser" + agentRcvFileId: string + } + + export interface UserUnknown extends Interface { + type: "userUnknown" + } + + export interface ActiveUserExists extends Interface { + type: "activeUserExists" + } + + export interface UserExists extends Interface { + type: "userExists" + contactName: string + } + + export interface DifferentActiveUser extends Interface { + type: "differentActiveUser" + commandUserId: number // int64 + activeUserId: number // int64 + } + + export interface CantDeleteActiveUser extends Interface { + type: "cantDeleteActiveUser" + userId: number // int64 + } + + export interface CantDeleteLastUser extends Interface { + type: "cantDeleteLastUser" + userId: number // int64 + } + + export interface CantHideLastUser extends Interface { + type: "cantHideLastUser" + userId: number // int64 + } + + export interface HiddenUserAlwaysMuted extends Interface { + type: "hiddenUserAlwaysMuted" + userId: number // int64 + } + + export interface EmptyUserPassword extends Interface { + type: "emptyUserPassword" + userId: number // int64 + } + + export interface UserAlreadyHidden extends Interface { + type: "userAlreadyHidden" + userId: number // int64 + } + + export interface UserNotHidden extends Interface { + type: "userNotHidden" + userId: number // int64 + } + + export interface InvalidDisplayName extends Interface { + type: "invalidDisplayName" + displayName: string + validName: string + } + + export interface ChatNotStarted extends Interface { + type: "chatNotStarted" + } + + export interface ChatNotStopped extends Interface { + type: "chatNotStopped" + } + + export interface ChatStoreChanged extends Interface { + type: "chatStoreChanged" + } + + export interface InvalidConnReq extends Interface { + type: "invalidConnReq" + } + + export interface UnsupportedConnReq extends Interface { + type: "unsupportedConnReq" + } + + export interface ConnReqMessageProhibited extends Interface { + type: "connReqMessageProhibited" + } + + export interface ContactNotReady extends Interface { + type: "contactNotReady" + contact: Contact + } + + export interface ContactNotActive extends Interface { + type: "contactNotActive" + contact: Contact + } + + export interface ContactDisabled extends Interface { + type: "contactDisabled" + contact: Contact + } + + export interface ConnectionDisabled extends Interface { + type: "connectionDisabled" + connection: Connection + } + + export interface GroupUserRole extends Interface { + type: "groupUserRole" + groupInfo: GroupInfo + requiredRole: GroupMemberRole + } + + export interface GroupMemberInitialRole extends Interface { + type: "groupMemberInitialRole" + groupInfo: GroupInfo + initialRole: GroupMemberRole + } + + export interface ContactIncognitoCantInvite extends Interface { + type: "contactIncognitoCantInvite" + } + + export interface GroupIncognitoCantInvite extends Interface { + type: "groupIncognitoCantInvite" + } + + export interface GroupContactRole extends Interface { + type: "groupContactRole" + contactName: string + } + + export interface GroupDuplicateMember extends Interface { + type: "groupDuplicateMember" + contactName: string + } + + export interface GroupDuplicateMemberId extends Interface { + type: "groupDuplicateMemberId" + } + + export interface GroupNotJoined extends Interface { + type: "groupNotJoined" + groupInfo: GroupInfo + } + + export interface GroupMemberNotActive extends Interface { + type: "groupMemberNotActive" + } + + export interface CantBlockMemberForSelf extends Interface { + type: "cantBlockMemberForSelf" + groupInfo: GroupInfo + member: GroupMember + setShowMessages: boolean + } + + export interface GroupMemberUserRemoved extends Interface { + type: "groupMemberUserRemoved" + } + + export interface GroupMemberNotFound extends Interface { + type: "groupMemberNotFound" + } + + export interface GroupCantResendInvitation extends Interface { + type: "groupCantResendInvitation" + groupInfo: GroupInfo + contactName: string + } + + export interface GroupInternal extends Interface { + type: "groupInternal" + message: string + } + + export interface FileNotFound extends Interface { + type: "fileNotFound" + message: string + } + + export interface FileSize extends Interface { + type: "fileSize" + filePath: string + } + + export interface FileAlreadyReceiving extends Interface { + type: "fileAlreadyReceiving" + message: string + } + + export interface FileCancelled extends Interface { + type: "fileCancelled" + message: string + } + + export interface FileCancel extends Interface { + type: "fileCancel" + fileId: number // int64 + message: string + } + + export interface FileAlreadyExists extends Interface { + type: "fileAlreadyExists" + filePath: string + } + + export interface FileRead extends Interface { + type: "fileRead" + filePath: string + message: string + } + + export interface FileWrite extends Interface { + type: "fileWrite" + filePath: string + message: string + } + + export interface FileSend extends Interface { + type: "fileSend" + fileId: number // int64 + agentError: AgentErrorType + } + + export interface FileRcvChunk extends Interface { + type: "fileRcvChunk" + message: string + } + + export interface FileInternal extends Interface { + type: "fileInternal" + message: string + } + + export interface FileImageType extends Interface { + type: "fileImageType" + filePath: string + } + + export interface FileImageSize extends Interface { + type: "fileImageSize" + filePath: string + } + + export interface FileNotReceived extends Interface { + type: "fileNotReceived" + fileId: number // int64 + } + + export interface FileNotApproved extends Interface { + type: "fileNotApproved" + fileId: number // int64 + unknownServers: string[] + } + + export interface FallbackToSMPProhibited extends Interface { + type: "fallbackToSMPProhibited" + fileId: number // int64 + } + + export interface InlineFileProhibited extends Interface { + type: "inlineFileProhibited" + fileId: number // int64 + } + + export interface InvalidForward extends Interface { + type: "invalidForward" + } + + export interface InvalidChatItemUpdate extends Interface { + type: "invalidChatItemUpdate" + } + + export interface InvalidChatItemDelete extends Interface { + type: "invalidChatItemDelete" + } + + export interface HasCurrentCall extends Interface { + type: "hasCurrentCall" + } + + export interface NoCurrentCall extends Interface { + type: "noCurrentCall" + } + + export interface CallContact extends Interface { + type: "callContact" + contactId: number // int64 + } + + export interface DirectMessagesProhibited extends Interface { + type: "directMessagesProhibited" + direction: MsgDirection + contact: Contact + } + + export interface AgentVersion extends Interface { + type: "agentVersion" + } + + export interface AgentNoSubResult extends Interface { + type: "agentNoSubResult" + agentConnId: string + } + + export interface CommandError extends Interface { + type: "commandError" + message: string + } + + export interface AgentCommandError extends Interface { + type: "agentCommandError" + message: string + } + + export interface InvalidFileDescription extends Interface { + type: "invalidFileDescription" + message: string + } + + export interface ConnectionIncognitoChangeProhibited extends Interface { + type: "connectionIncognitoChangeProhibited" + } + + export interface ConnectionUserChangeProhibited extends Interface { + type: "connectionUserChangeProhibited" + } + + export interface PeerChatVRangeIncompatible extends Interface { + type: "peerChatVRangeIncompatible" + } + + export interface InternalError extends Interface { + type: "internalError" + message: string + } + + export interface Exception extends Interface { + type: "exception" + message: string + } +} + +export enum ChatFeature { + TimedMessages = "timedMessages", + FullDelete = "fullDelete", + Reactions = "reactions", + Voice = "voice", + Files = "files", + Calls = "calls", + Sessions = "sessions", +} + +export type ChatInfo = + | ChatInfo.Direct + | ChatInfo.Group + | ChatInfo.Local + | ChatInfo.ContactRequest + | ChatInfo.ContactConnection + +export namespace ChatInfo { + export type Tag = "direct" | "group" | "local" | "contactRequest" | "contactConnection" + + interface Interface { + type: Tag + } + + export interface Direct extends Interface { + type: "direct" + contact: Contact + } + + export interface Group extends Interface { + type: "group" + groupInfo: GroupInfo + groupChatScope?: GroupChatScopeInfo + } + + export interface Local extends Interface { + type: "local" + noteFolder: NoteFolder + } + + export interface ContactRequest extends Interface { + type: "contactRequest" + contactRequest: UserContactRequest + } + + export interface ContactConnection extends Interface { + type: "contactConnection" + contactConnection: PendingContactConnection + } +} + +export interface ChatItem { + chatDir: CIDirection + meta: CIMeta + content: CIContent + mentions: {[key: string]: CIMention} + formattedText?: FormattedText[] + quotedItem?: CIQuote + reactions: CIReactionCount[] + file?: CIFile +} +// Message deletion result. + +export interface ChatItemDeletion { + deletedChatItem: AChatItem + toChatItem?: AChatItem +} + +export enum ChatPeerType { + Human = "human", + Bot = "bot", +} +// Used in API commands. Chat scope can only be passed with groups. + +export interface ChatRef { + chatType: ChatType + chatId: number // int64 + chatScope?: GroupChatScope +} + +export namespace ChatRef { + export function cmdString(self: ChatRef): string { + return self.chatType.toString() + self.chatId + (self.chatScope ? self.chatScope.toString() : '') + } +} + +export interface ChatSettings { + enableNtfs: MsgFilter + sendRcpts?: boolean + favorite: boolean +} + +export interface ChatStats { + unreadCount: number // int + unreadMentions: number // int + reportsCount: number // int + minUnreadItemId: number // int64 + unreadChat: boolean +} + +export enum ChatType { + Direct = "direct", + Group = "group", + Local = "local", +} + +export namespace ChatType { + export function cmdString(self: ChatType): string { + return self == 'direct' ? '@' : self == 'group' ? '#' : self == 'local' ? '*' : '' + } +} + +export interface ChatWallpaper { + preset?: string + imageFile?: string + background?: string + tint?: string + scaleType?: ChatWallpaperScale + scale?: number // double +} + +export enum ChatWallpaperScale { + Fill = "fill", + Fit = "fit", + Repeat = "repeat", +} + +export enum Color { + Black = "black", + Red = "red", + Green = "green", + Yellow = "yellow", + Blue = "blue", + Magenta = "magenta", + Cyan = "cyan", + White = "white", +} + +export type CommandError = + | CommandError.UNKNOWN + | CommandError.SYNTAX + | CommandError.PROHIBITED + | CommandError.NO_AUTH + | CommandError.HAS_AUTH + | CommandError.NO_ENTITY + +export namespace CommandError { + export type Tag = "UNKNOWN" | "SYNTAX" | "PROHIBITED" | "NO_AUTH" | "HAS_AUTH" | "NO_ENTITY" + + interface Interface { + type: Tag + } + + export interface UNKNOWN extends Interface { + type: "UNKNOWN" + } + + export interface SYNTAX extends Interface { + type: "SYNTAX" + } + + export interface PROHIBITED extends Interface { + type: "PROHIBITED" + } + + export interface NO_AUTH extends Interface { + type: "NO_AUTH" + } + + export interface HAS_AUTH extends Interface { + type: "HAS_AUTH" + } + + export interface NO_ENTITY extends Interface { + type: "NO_ENTITY" + } +} + +export type CommandErrorType = + | CommandErrorType.PROHIBITED + | CommandErrorType.SYNTAX + | CommandErrorType.NO_CONN + | CommandErrorType.SIZE + | CommandErrorType.LARGE + +export namespace CommandErrorType { + export type Tag = "PROHIBITED" | "SYNTAX" | "NO_CONN" | "SIZE" | "LARGE" + + interface Interface { + type: Tag + } + + export interface PROHIBITED extends Interface { + type: "PROHIBITED" + } + + export interface SYNTAX extends Interface { + type: "SYNTAX" + } + + export interface NO_CONN extends Interface { + type: "NO_CONN" + } + + export interface SIZE extends Interface { + type: "SIZE" + } + + export interface LARGE extends Interface { + type: "LARGE" + } +} + +export interface ComposedMessage { + fileSource?: CryptoFile + quotedItemId?: number // int64 + msgContent: MsgContent + mentions: {[key: string]: number} // string : int64 +} + +export enum ConnStatus { + New = "new", + Prepared = "prepared", + Joined = "joined", + Requested = "requested", + Accepted = "accepted", + Snd_ready = "snd-ready", + Ready = "ready", + Deleted = "deleted", +} + +export enum ConnType { + Contact = "contact", + Member = "member", + User_contact = "user_contact", +} + +export interface Connection { + connId: number // int64 + agentConnId: string + connChatVersion: number // int + peerChatVRange: VersionRange + connLevel: number // int + viaContact?: number // int64 + viaUserContactLink?: number // int64 + viaGroupLink: boolean + groupLinkId?: string + xContactId?: string + customUserProfileId?: number // int64 + connType: ConnType + connStatus: ConnStatus + contactConnInitiated: boolean + localAlias: string + entityId?: number // int64 + connectionCode?: SecurityCode + pqSupport: boolean + pqEncryption: boolean + pqSndEnabled?: boolean + pqRcvEnabled?: boolean + authErrCounter: number // int + quotaErrCounter: number // int + createdAt: string // ISO-8601 timestamp +} + +export type ConnectionEntity = + | ConnectionEntity.RcvDirectMsgConnection + | ConnectionEntity.RcvGroupMsgConnection + | ConnectionEntity.SndFileConnection + | ConnectionEntity.RcvFileConnection + | ConnectionEntity.UserContactConnection + +export namespace ConnectionEntity { + export type Tag = + | "rcvDirectMsgConnection" + | "rcvGroupMsgConnection" + | "sndFileConnection" + | "rcvFileConnection" + | "userContactConnection" + + interface Interface { + type: Tag + } + + export interface RcvDirectMsgConnection extends Interface { + type: "rcvDirectMsgConnection" + entityConnection: Connection + contact?: Contact + } + + export interface RcvGroupMsgConnection extends Interface { + type: "rcvGroupMsgConnection" + entityConnection: Connection + groupInfo: GroupInfo + groupMember: GroupMember + } + + export interface SndFileConnection extends Interface { + type: "sndFileConnection" + entityConnection: Connection + sndFileTransfer: SndFileTransfer + } + + export interface RcvFileConnection extends Interface { + type: "rcvFileConnection" + entityConnection: Connection + rcvFileTransfer: RcvFileTransfer + } + + export interface UserContactConnection extends Interface { + type: "userContactConnection" + entityConnection: Connection + userContact: UserContact + } +} + +export type ConnectionErrorType = + | ConnectionErrorType.NOT_FOUND + | ConnectionErrorType.DUPLICATE + | ConnectionErrorType.SIMPLEX + | ConnectionErrorType.NOT_ACCEPTED + | ConnectionErrorType.NOT_AVAILABLE + +export namespace ConnectionErrorType { + export type Tag = "NOT_FOUND" | "DUPLICATE" | "SIMPLEX" | "NOT_ACCEPTED" | "NOT_AVAILABLE" + + interface Interface { + type: Tag + } + + export interface NOT_FOUND extends Interface { + type: "NOT_FOUND" + } + + export interface DUPLICATE extends Interface { + type: "DUPLICATE" + } + + export interface SIMPLEX extends Interface { + type: "SIMPLEX" + } + + export interface NOT_ACCEPTED extends Interface { + type: "NOT_ACCEPTED" + } + + export interface NOT_AVAILABLE extends Interface { + type: "NOT_AVAILABLE" + } +} + +export enum ConnectionMode { + INV = "inv", + CON = "con", +} + +export type ConnectionPlan = + | ConnectionPlan.InvitationLink + | ConnectionPlan.ContactAddress + | ConnectionPlan.GroupLink + | ConnectionPlan.Error + +export namespace ConnectionPlan { + export type Tag = "invitationLink" | "contactAddress" | "groupLink" | "error" + + interface Interface { + type: Tag + } + + export interface InvitationLink extends Interface { + type: "invitationLink" + invitationLinkPlan: InvitationLinkPlan + } + + export interface ContactAddress extends Interface { + type: "contactAddress" + contactAddressPlan: ContactAddressPlan + } + + export interface GroupLink extends Interface { + type: "groupLink" + groupLinkPlan: GroupLinkPlan + } + + export interface Error extends Interface { + type: "error" + chatError: ChatError + } +} + +export interface Contact { + contactId: number // int64 + localDisplayName: string + profile: LocalProfile + activeConn?: Connection + viaGroup?: number // int64 + contactUsed: boolean + contactStatus: ContactStatus + chatSettings: ChatSettings + userPreferences: Preferences + mergedPreferences: ContactUserPreferences + createdAt: string // ISO-8601 timestamp + updatedAt: string // ISO-8601 timestamp + chatTs?: string // ISO-8601 timestamp + preparedContact?: PreparedContact + contactRequestId?: number // int64 + contactGroupMemberId?: number // int64 + contactGrpInvSent: boolean + groupDirectInv?: GroupDirectInvitation + chatTags: number[] // int64 + chatItemTTL?: number // int64 + uiThemes?: UIThemeEntityOverrides + chatDeleted: boolean + customData?: object +} + +export type ContactAddressPlan = + | ContactAddressPlan.Ok + | ContactAddressPlan.OwnLink + | ContactAddressPlan.ConnectingConfirmReconnect + | ContactAddressPlan.ConnectingProhibit + | ContactAddressPlan.Known + | ContactAddressPlan.ContactViaAddress + +export namespace ContactAddressPlan { + export type Tag = + | "ok" + | "ownLink" + | "connectingConfirmReconnect" + | "connectingProhibit" + | "known" + | "contactViaAddress" + + interface Interface { + type: Tag + } + + export interface Ok extends Interface { + type: "ok" + contactSLinkData_?: ContactShortLinkData + } + + export interface OwnLink extends Interface { + type: "ownLink" + } + + export interface ConnectingConfirmReconnect extends Interface { + type: "connectingConfirmReconnect" + } + + export interface ConnectingProhibit extends Interface { + type: "connectingProhibit" + contact: Contact + } + + export interface Known extends Interface { + type: "known" + contact: Contact + } + + export interface ContactViaAddress extends Interface { + type: "contactViaAddress" + contact: Contact + } +} + +export interface ContactShortLinkData { + profile: Profile + message?: MsgContent + business: boolean +} + +export enum ContactStatus { + Active = "active", + Deleted = "deleted", + DeletedByUser = "deletedByUser", +} + +export type ContactUserPref = ContactUserPref.Contact | ContactUserPref.User + +export namespace ContactUserPref { + export type Tag = "contact" | "user" + + interface Interface { + type: Tag + } + + export interface Contact extends Interface { + type: "contact" + preference: SimplePreference + } + + export interface User extends Interface { + type: "user" + preference: SimplePreference + } +} + +export interface ContactUserPreference { + enabled: PrefEnabled + userPreference: ContactUserPref + contactPreference: SimplePreference +} + +export interface ContactUserPreferences { + timedMessages: ContactUserPreference + fullDelete: ContactUserPreference + reactions: ContactUserPreference + voice: ContactUserPreference + files: ContactUserPreference + calls: ContactUserPreference + sessions: ContactUserPreference + commands?: ChatBotCommand[] +} + +export interface CreatedConnLink { + connFullLink: string + connShortLink?: string +} + +export namespace CreatedConnLink { + export function cmdString(self: CreatedConnLink): string { + return self.connFullLink + (self.connShortLink ? ' ' + self.connShortLink : '') + } +} + +export interface CryptoFile { + filePath: string + cryptoArgs?: CryptoFileArgs +} + +export interface CryptoFileArgs { + fileKey: string + fileNonce: string +} + +export interface E2EInfo { + pqEnabled?: boolean +} + +export type ErrorType = + | ErrorType.BLOCK + | ErrorType.SESSION + | ErrorType.CMD + | ErrorType.PROXY + | ErrorType.AUTH + | ErrorType.BLOCKED + | ErrorType.SERVICE + | ErrorType.CRYPTO + | ErrorType.QUOTA + | ErrorType.STORE + | ErrorType.NO_MSG + | ErrorType.LARGE_MSG + | ErrorType.EXPIRED + | ErrorType.INTERNAL + | ErrorType.DUPLICATE_ + +export namespace ErrorType { + export type Tag = + | "BLOCK" + | "SESSION" + | "CMD" + | "PROXY" + | "AUTH" + | "BLOCKED" + | "SERVICE" + | "CRYPTO" + | "QUOTA" + | "STORE" + | "NO_MSG" + | "LARGE_MSG" + | "EXPIRED" + | "INTERNAL" + | "DUPLICATE_" + + interface Interface { + type: Tag + } + + export interface BLOCK extends Interface { + type: "BLOCK" + } + + export interface SESSION extends Interface { + type: "SESSION" + } + + export interface CMD extends Interface { + type: "CMD" + cmdErr: CommandError + } + + export interface PROXY extends Interface { + type: "PROXY" + proxyErr: ProxyError + } + + export interface AUTH extends Interface { + type: "AUTH" + } + + export interface BLOCKED extends Interface { + type: "BLOCKED" + blockInfo: BlockingInfo + } + + export interface SERVICE extends Interface { + type: "SERVICE" + } + + export interface CRYPTO extends Interface { + type: "CRYPTO" + } + + export interface QUOTA extends Interface { + type: "QUOTA" + } + + export interface STORE extends Interface { + type: "STORE" + storeErr: string + } + + export interface NO_MSG extends Interface { + type: "NO_MSG" + } + + export interface LARGE_MSG extends Interface { + type: "LARGE_MSG" + } + + export interface EXPIRED extends Interface { + type: "EXPIRED" + } + + export interface INTERNAL extends Interface { + type: "INTERNAL" + } + + export interface DUPLICATE_ extends Interface { + type: "DUPLICATE_" + } +} + +export enum FeatureAllowed { + Always = "always", + Yes = "yes", + No = "no", +} + +export interface FileDescr { + fileDescrText: string + fileDescrPartNo: number // int + fileDescrComplete: boolean +} + +export type FileError = + | FileError.Auth + | FileError.Blocked + | FileError.NoFile + | FileError.Relay + | FileError.Other + +export namespace FileError { + export type Tag = "auth" | "blocked" | "noFile" | "relay" | "other" + + interface Interface { + type: Tag + } + + export interface Auth extends Interface { + type: "auth" + } + + export interface Blocked extends Interface { + type: "blocked" + server: string + blockInfo: BlockingInfo + } + + export interface NoFile extends Interface { + type: "noFile" + } + + export interface Relay extends Interface { + type: "relay" + srvError: SrvError + } + + export interface Other extends Interface { + type: "other" + fileError: string + } +} + +export type FileErrorType = + | FileErrorType.NOT_APPROVED + | FileErrorType.SIZE + | FileErrorType.REDIRECT + | FileErrorType.FILE_IO + | FileErrorType.NO_FILE + +export namespace FileErrorType { + export type Tag = "NOT_APPROVED" | "SIZE" | "REDIRECT" | "FILE_IO" | "NO_FILE" + + interface Interface { + type: Tag + } + + export interface NOT_APPROVED extends Interface { + type: "NOT_APPROVED" + } + + export interface SIZE extends Interface { + type: "SIZE" + } + + export interface REDIRECT extends Interface { + type: "REDIRECT" + redirectError: string + } + + export interface FILE_IO extends Interface { + type: "FILE_IO" + fileIOError: string + } + + export interface NO_FILE extends Interface { + type: "NO_FILE" + } +} + +export interface FileInvitation { + fileName: string + fileSize: number // int64 + fileDigest?: string + fileConnReq?: string + fileInline?: InlineFileMode + fileDescr?: FileDescr +} + +export enum FileProtocol { + SMP = "smp", + XFTP = "xftp", + LOCAL = "local", +} + +export enum FileStatus { + New = "new", + Accepted = "accepted", + Connected = "connected", + Complete = "complete", + Cancelled = "cancelled", +} + +export interface FileTransferMeta { + fileId: number // int64 + xftpSndFile?: XFTPSndFile + xftpRedirectFor?: number // int64 + fileName: string + filePath: string + fileSize: number // int64 + fileInline?: InlineFileMode + chunkSize: number // int64 + cancelled: boolean +} + +export type Format = + | Format.Bold + | Format.Italic + | Format.StrikeThrough + | Format.Snippet + | Format.Secret + | Format.Colored + | Format.Uri + | Format.HyperLink + | Format.SimplexLink + | Format.Command + | Format.Mention + | Format.Email + | Format.Phone + +export namespace Format { + export type Tag = + | "bold" + | "italic" + | "strikeThrough" + | "snippet" + | "secret" + | "colored" + | "uri" + | "hyperLink" + | "simplexLink" + | "command" + | "mention" + | "email" + | "phone" + + interface Interface { + type: Tag + } + + export interface Bold extends Interface { + type: "bold" + } + + export interface Italic extends Interface { + type: "italic" + } + + export interface StrikeThrough extends Interface { + type: "strikeThrough" + } + + export interface Snippet extends Interface { + type: "snippet" + } + + export interface Secret extends Interface { + type: "secret" + } + + export interface Colored extends Interface { + type: "colored" + color: Color + } + + export interface Uri extends Interface { + type: "uri" + } + + export interface HyperLink extends Interface { + type: "hyperLink" + showText?: string + linkUri: string + } + + export interface SimplexLink extends Interface { + type: "simplexLink" + showText?: string + linkType: SimplexLinkType + simplexUri: string + smpHosts: string[] // non-empty + } + + export interface Command extends Interface { + type: "command" + commandStr: string + } + + export interface Mention extends Interface { + type: "mention" + memberName: string + } + + export interface Email extends Interface { + type: "email" + } + + export interface Phone extends Interface { + type: "phone" + } +} + +export interface FormattedText { + format?: Format + text: string +} + +export interface FullGroupPreferences { + timedMessages: TimedMessagesGroupPreference + directMessages: RoleGroupPreference + fullDelete: GroupPreference + reactions: GroupPreference + voice: RoleGroupPreference + files: RoleGroupPreference + simplexLinks: RoleGroupPreference + reports: GroupPreference + history: GroupPreference + sessions: RoleGroupPreference + commands: ChatBotCommand[] +} + +export interface FullPreferences { + timedMessages: TimedMessagesPreference + fullDelete: SimplePreference + reactions: SimplePreference + voice: SimplePreference + files: SimplePreference + calls: SimplePreference + sessions: SimplePreference + commands: ChatBotCommand[] +} + +export interface Group { + groupInfo: GroupInfo + members: GroupMember[] +} + +export type GroupChatScope = GroupChatScope.MemberSupport + +export namespace GroupChatScope { + export type Tag = "memberSupport" + + interface Interface { + type: Tag + } + + export interface MemberSupport extends Interface { + type: "memberSupport" + groupMemberId_?: number // int64 + } + + export function cmdString(self: GroupChatScope): string { + return '(_support' + (self.groupMemberId_ ? ':' + self.groupMemberId_ : '') + ')' + } +} + +export type GroupChatScopeInfo = GroupChatScopeInfo.MemberSupport + +export namespace GroupChatScopeInfo { + export type Tag = "memberSupport" + + interface Interface { + type: Tag + } + + export interface MemberSupport extends Interface { + type: "memberSupport" + groupMember_?: GroupMember + } +} + +export interface GroupDirectInvitation { + groupDirectInvLink: string + fromGroupId_?: number // int64 + fromGroupMemberId_?: number // int64 + fromGroupMemberConnId_?: number // int64 + groupDirectInvStartedConnection: boolean +} + +export enum GroupFeature { + TimedMessages = "timedMessages", + DirectMessages = "directMessages", + FullDelete = "fullDelete", + Reactions = "reactions", + Voice = "voice", + Files = "files", + SimplexLinks = "simplexLinks", + Reports = "reports", + History = "history", + Sessions = "sessions", +} + +export enum GroupFeatureEnabled { + On = "on", + Off = "off", +} + +export interface GroupInfo { + groupId: number // int64 + localDisplayName: string + groupProfile: GroupProfile + localAlias: string + businessChat?: BusinessChatInfo + fullGroupPreferences: FullGroupPreferences + membership: GroupMember + chatSettings: ChatSettings + createdAt: string // ISO-8601 timestamp + updatedAt: string // ISO-8601 timestamp + chatTs?: string // ISO-8601 timestamp + userMemberProfileSentAt?: string // ISO-8601 timestamp + preparedGroup?: PreparedGroup + chatTags: number[] // int64 + chatItemTTL?: number // int64 + uiThemes?: UIThemeEntityOverrides + customData?: object + membersRequireAttention: number // int + viaGroupLinkUri?: string +} + +export interface GroupInfoSummary { + groupInfo: GroupInfo + groupSummary: GroupSummary +} + +export interface GroupLink { + userContactLinkId: number // int64 + connLinkContact: CreatedConnLink + shortLinkDataSet: boolean + shortLinkLargeDataSet: boolean + groupLinkId: string + acceptMemberRole: GroupMemberRole +} + +export type GroupLinkPlan = + | GroupLinkPlan.Ok + | GroupLinkPlan.OwnLink + | GroupLinkPlan.ConnectingConfirmReconnect + | GroupLinkPlan.ConnectingProhibit + | GroupLinkPlan.Known + +export namespace GroupLinkPlan { + export type Tag = "ok" | "ownLink" | "connectingConfirmReconnect" | "connectingProhibit" | "known" + + interface Interface { + type: Tag + } + + export interface Ok extends Interface { + type: "ok" + groupSLinkData_?: GroupShortLinkData + } + + export interface OwnLink extends Interface { + type: "ownLink" + groupInfo: GroupInfo + } + + export interface ConnectingConfirmReconnect extends Interface { + type: "connectingConfirmReconnect" + } + + export interface ConnectingProhibit extends Interface { + type: "connectingProhibit" + groupInfo_?: GroupInfo + } + + export interface Known extends Interface { + type: "known" + groupInfo: GroupInfo + } +} + +export interface GroupMember { + groupMemberId: number // int64 + groupId: number // int64 + memberId: string + memberRole: GroupMemberRole + memberCategory: GroupMemberCategory + memberStatus: GroupMemberStatus + memberSettings: GroupMemberSettings + blockedByAdmin: boolean + invitedBy: InvitedBy + invitedByGroupMemberId?: number // int64 + localDisplayName: string + memberProfile: LocalProfile + memberContactId?: number // int64 + memberContactProfileId: number // int64 + activeConn?: Connection + memberChatVRange: VersionRange + createdAt: string // ISO-8601 timestamp + updatedAt: string // ISO-8601 timestamp + supportChat?: GroupSupportChat +} + +export interface GroupMemberAdmission { + review?: MemberCriteria +} + +export enum GroupMemberCategory { + User = "user", + Invitee = "invitee", + Host = "host", + Pre = "pre", + Post = "post", +} + +export interface GroupMemberRef { + groupMemberId: number // int64 + profile: Profile +} + +export enum GroupMemberRole { + Observer = "observer", + Author = "author", + Member = "member", + Moderator = "moderator", + Admin = "admin", + Owner = "owner", +} + +export interface GroupMemberSettings { + showMessages: boolean +} + +export enum GroupMemberStatus { + Rejected = "rejected", + Removed = "removed", + Left = "left", + Deleted = "deleted", + Unknown = "unknown", + Invited = "invited", + Pending_approval = "pending_approval", + Pending_review = "pending_review", + Introduced = "introduced", + Intro_inv = "intro-inv", + Accepted = "accepted", + Announced = "announced", + Connected = "connected", + Complete = "complete", + Creator = "creator", +} + +export interface GroupPreference { + enable: GroupFeatureEnabled +} + +export interface GroupPreferences { + timedMessages?: TimedMessagesGroupPreference + directMessages?: RoleGroupPreference + fullDelete?: GroupPreference + reactions?: GroupPreference + voice?: RoleGroupPreference + files?: RoleGroupPreference + simplexLinks?: RoleGroupPreference + reports?: GroupPreference + history?: GroupPreference + sessions?: RoleGroupPreference + commands?: ChatBotCommand[] +} + +export interface GroupProfile { + displayName: string + fullName: string + shortDescr?: string + description?: string + image?: string + groupPreferences?: GroupPreferences + memberAdmission?: GroupMemberAdmission +} + +export interface GroupShortLinkData { + groupProfile: GroupProfile +} + +export interface GroupSummary { + currentMembers: number // int +} + +export interface GroupSupportChat { + chatTs: string // ISO-8601 timestamp + unread: number // int64 + memberAttention: number // int64 + mentions: number // int64 + lastMsgFromMemberTs?: string // ISO-8601 timestamp +} + +export enum HandshakeError { + PARSE = "PARSE", + IDENTITY = "IDENTITY", + BAD_AUTH = "BAD_AUTH", + BAD_SERVICE = "BAD_SERVICE", +} + +export enum InlineFileMode { + Offer = "offer", + Sent = "sent", +} + +export type InvitationLinkPlan = + | InvitationLinkPlan.Ok + | InvitationLinkPlan.OwnLink + | InvitationLinkPlan.Connecting + | InvitationLinkPlan.Known + +export namespace InvitationLinkPlan { + export type Tag = "ok" | "ownLink" | "connecting" | "known" + + interface Interface { + type: Tag + } + + export interface Ok extends Interface { + type: "ok" + contactSLinkData_?: ContactShortLinkData + } + + export interface OwnLink extends Interface { + type: "ownLink" + } + + export interface Connecting extends Interface { + type: "connecting" + contact_?: Contact + } + + export interface Known extends Interface { + type: "known" + contact: Contact + } +} + +export type InvitedBy = InvitedBy.Contact | InvitedBy.User | InvitedBy.Unknown + +export namespace InvitedBy { + export type Tag = "contact" | "user" | "unknown" + + interface Interface { + type: Tag + } + + export interface Contact extends Interface { + type: "contact" + byContactId: number // int64 + } + + export interface User extends Interface { + type: "user" + } + + export interface Unknown extends Interface { + type: "unknown" + } +} + +export type LinkContent = LinkContent.Page | LinkContent.Image | LinkContent.Video | LinkContent.Unknown + +export namespace LinkContent { + export type Tag = "page" | "image" | "video" | "unknown" + + interface Interface { + type: Tag + } + + export interface Page extends Interface { + type: "page" + } + + export interface Image extends Interface { + type: "image" + } + + export interface Video extends Interface { + type: "video" + duration?: number // int + } + + export interface Unknown extends Interface { + type: "unknown" + tag: string + json: object + } +} + +export interface LinkPreview { + uri: string + title: string + description: string + image: string + content?: LinkContent +} + +export interface LocalProfile { + profileId: number // int64 + displayName: string + fullName: string + shortDescr?: string + image?: string + contactLink?: string + preferences?: Preferences + peerType?: ChatPeerType + localAlias: string +} + +export enum MemberCriteria { + All = "all", +} +// Connection link sent in a message - only short links are allowed. + +export type MsgChatLink = MsgChatLink.Contact | MsgChatLink.Invitation | MsgChatLink.Group + +export namespace MsgChatLink { + export type Tag = "contact" | "invitation" | "group" + + interface Interface { + type: Tag + } + + export interface Contact extends Interface { + type: "contact" + connLink: string + profile: Profile + business: boolean + } + + export interface Invitation extends Interface { + type: "invitation" + invLink: string + profile: Profile + } + + export interface Group extends Interface { + type: "group" + connLink: string + groupProfile: GroupProfile + } +} + +export type MsgContent = + | MsgContent.Text + | MsgContent.Link + | MsgContent.Image + | MsgContent.Video + | MsgContent.Voice + | MsgContent.File + | MsgContent.Report + | MsgContent.Chat + | MsgContent.Unknown + +export namespace MsgContent { + export type Tag = "text" | "link" | "image" | "video" | "voice" | "file" | "report" | "chat" | "unknown" + + interface Interface { + type: Tag + } + + export interface Text extends Interface { + type: "text" + text: string + } + + export interface Link extends Interface { + type: "link" + text: string + preview: LinkPreview + } + + export interface Image extends Interface { + type: "image" + text: string + image: string + } + + export interface Video extends Interface { + type: "video" + text: string + image: string + duration: number // int + } + + export interface Voice extends Interface { + type: "voice" + text: string + duration: number // int + } + + export interface File extends Interface { + type: "file" + text: string + } + + export interface Report extends Interface { + type: "report" + text: string + reason: ReportReason + } + + export interface Chat extends Interface { + type: "chat" + text: string + chatLink: MsgChatLink + } + + export interface Unknown extends Interface { + type: "unknown" + tag: string + text: string + json: object + } +} + +export enum MsgDecryptError { + RatchetHeader = "ratchetHeader", + TooManySkipped = "tooManySkipped", + RatchetEarlier = "ratchetEarlier", + Other = "other", + RatchetSync = "ratchetSync", +} + +export enum MsgDirection { + Rcv = "rcv", + Snd = "snd", +} + +export type MsgErrorType = + | MsgErrorType.MsgSkipped + | MsgErrorType.MsgBadId + | MsgErrorType.MsgBadHash + | MsgErrorType.MsgDuplicate + +export namespace MsgErrorType { + export type Tag = "msgSkipped" | "msgBadId" | "msgBadHash" | "msgDuplicate" + + interface Interface { + type: Tag + } + + export interface MsgSkipped extends Interface { + type: "msgSkipped" + fromMsgId: number // int64 + toMsgId: number // int64 + } + + export interface MsgBadId extends Interface { + type: "msgBadId" + msgId: number // int64 + } + + export interface MsgBadHash extends Interface { + type: "msgBadHash" + } + + export interface MsgDuplicate extends Interface { + type: "msgDuplicate" + } +} + +export enum MsgFilter { + None = "none", + All = "all", + Mentions = "mentions", +} + +export type MsgReaction = MsgReaction.Emoji | MsgReaction.Unknown + +export namespace MsgReaction { + export type Tag = "emoji" | "unknown" + + interface Interface { + type: Tag + } + + export interface Emoji extends Interface { + type: "emoji" + emoji: string + } + + export interface Unknown extends Interface { + type: "unknown" + tag: string + json: object + } +} + +export enum MsgReceiptStatus { + Ok = "ok", + BadMsgHash = "badMsgHash", +} + +export interface NewUser { + profile?: Profile + pastTimestamp: boolean +} + +export interface NoteFolder { + noteFolderId: number // int64 + userId: number // int64 + createdAt: string // ISO-8601 timestamp + updatedAt: string // ISO-8601 timestamp + chatTs: string // ISO-8601 timestamp + favorite: boolean + unread: boolean +} + +export interface PendingContactConnection { + pccConnId: number // int64 + pccAgentConnId: string + pccConnStatus: ConnStatus + viaContactUri: boolean + viaUserContactLink?: number // int64 + groupLinkId?: string + customUserProfileId?: number // int64 + connLinkInv?: CreatedConnLink + localAlias: string + createdAt: string // ISO-8601 timestamp + updatedAt: string // ISO-8601 timestamp +} + +export interface PrefEnabled { + forUser: boolean + forContact: boolean +} + +export interface Preferences { + timedMessages?: TimedMessagesPreference + fullDelete?: SimplePreference + reactions?: SimplePreference + voice?: SimplePreference + files?: SimplePreference + calls?: SimplePreference + sessions?: SimplePreference + commands?: ChatBotCommand[] +} + +export interface PreparedContact { + connLinkToConnect: CreatedConnLink + uiConnLinkType: ConnectionMode + welcomeSharedMsgId?: string + requestSharedMsgId?: string +} + +export interface PreparedGroup { + connLinkToConnect: CreatedConnLink + connLinkPreparedConnection: boolean + connLinkStartedConnection: boolean + welcomeSharedMsgId?: string + requestSharedMsgId?: string +} + +export interface Profile { + displayName: string + fullName: string + shortDescr?: string + image?: string + contactLink?: string + preferences?: Preferences + peerType?: ChatPeerType +} + +export type ProxyClientError = + | ProxyClientError.ProtocolError + | ProxyClientError.UnexpectedResponse + | ProxyClientError.ResponseError + +export namespace ProxyClientError { + export type Tag = "protocolError" | "unexpectedResponse" | "responseError" + + interface Interface { + type: Tag + } + + export interface ProtocolError extends Interface { + type: "protocolError" + protocolErr: ErrorType + } + + export interface UnexpectedResponse extends Interface { + type: "unexpectedResponse" + responseStr: string + } + + export interface ResponseError extends Interface { + type: "responseError" + responseErr: ErrorType + } +} + +export type ProxyError = ProxyError.PROTOCOL | ProxyError.BROKER | ProxyError.BASIC_AUTH | ProxyError.NO_SESSION + +export namespace ProxyError { + export type Tag = "PROTOCOL" | "BROKER" | "BASIC_AUTH" | "NO_SESSION" + + interface Interface { + type: Tag + } + + export interface PROTOCOL extends Interface { + type: "PROTOCOL" + protocolErr: ErrorType + } + + export interface BROKER extends Interface { + type: "BROKER" + brokerErr: BrokerErrorType + } + + export interface BASIC_AUTH extends Interface { + type: "BASIC_AUTH" + } + + export interface NO_SESSION extends Interface { + type: "NO_SESSION" + } +} + +export type RCErrorType = + | RCErrorType.Internal + | RCErrorType.Identity + | RCErrorType.NoLocalAddress + | RCErrorType.NewController + | RCErrorType.NotDiscovered + | RCErrorType.TLSStartFailed + | RCErrorType.Exception + | RCErrorType.CtrlAuth + | RCErrorType.CtrlNotFound + | RCErrorType.CtrlError + | RCErrorType.Invitation + | RCErrorType.Version + | RCErrorType.Encrypt + | RCErrorType.Decrypt + | RCErrorType.BlockSize + | RCErrorType.Syntax + +export namespace RCErrorType { + export type Tag = + | "internal" + | "identity" + | "noLocalAddress" + | "newController" + | "notDiscovered" + | "tLSStartFailed" + | "exception" + | "ctrlAuth" + | "ctrlNotFound" + | "ctrlError" + | "invitation" + | "version" + | "encrypt" + | "decrypt" + | "blockSize" + | "syntax" + + interface Interface { + type: Tag + } + + export interface Internal extends Interface { + type: "internal" + internalErr: string + } + + export interface Identity extends Interface { + type: "identity" + } + + export interface NoLocalAddress extends Interface { + type: "noLocalAddress" + } + + export interface NewController extends Interface { + type: "newController" + } + + export interface NotDiscovered extends Interface { + type: "notDiscovered" + } + + export interface TLSStartFailed extends Interface { + type: "tLSStartFailed" + } + + export interface Exception extends Interface { + type: "exception" + exception: string + } + + export interface CtrlAuth extends Interface { + type: "ctrlAuth" + } + + export interface CtrlNotFound extends Interface { + type: "ctrlNotFound" + } + + export interface CtrlError extends Interface { + type: "ctrlError" + ctrlErr: string + } + + export interface Invitation extends Interface { + type: "invitation" + } + + export interface Version extends Interface { + type: "version" + } + + export interface Encrypt extends Interface { + type: "encrypt" + } + + export interface Decrypt extends Interface { + type: "decrypt" + } + + export interface BlockSize extends Interface { + type: "blockSize" + } + + export interface Syntax extends Interface { + type: "syntax" + syntaxErr: string + } +} + +export enum RatchetSyncState { + Ok = "ok", + Allowed = "allowed", + Required = "required", + Started = "started", + Agreed = "agreed", +} + +export type RcvConnEvent = + | RcvConnEvent.SwitchQueue + | RcvConnEvent.RatchetSync + | RcvConnEvent.VerificationCodeReset + | RcvConnEvent.PqEnabled + +export namespace RcvConnEvent { + export type Tag = "switchQueue" | "ratchetSync" | "verificationCodeReset" | "pqEnabled" + + interface Interface { + type: Tag + } + + export interface SwitchQueue extends Interface { + type: "switchQueue" + phase: SwitchPhase + } + + export interface RatchetSync extends Interface { + type: "ratchetSync" + syncStatus: RatchetSyncState + } + + export interface VerificationCodeReset extends Interface { + type: "verificationCodeReset" + } + + export interface PqEnabled extends Interface { + type: "pqEnabled" + enabled: boolean + } +} + +export type RcvDirectEvent = + | RcvDirectEvent.ContactDeleted + | RcvDirectEvent.ProfileUpdated + | RcvDirectEvent.GroupInvLinkReceived + +export namespace RcvDirectEvent { + export type Tag = "contactDeleted" | "profileUpdated" | "groupInvLinkReceived" + + interface Interface { + type: Tag + } + + export interface ContactDeleted extends Interface { + type: "contactDeleted" + } + + export interface ProfileUpdated extends Interface { + type: "profileUpdated" + fromProfile: Profile + toProfile: Profile + } + + export interface GroupInvLinkReceived extends Interface { + type: "groupInvLinkReceived" + groupProfile: GroupProfile + } +} + +export interface RcvFileDescr { + fileDescrId: number // int64 + fileDescrText: string + fileDescrPartNo: number // int + fileDescrComplete: boolean +} + +export interface RcvFileInfo { + filePath: string + connId?: number // int64 + agentConnId?: string +} + +export type RcvFileStatus = + | RcvFileStatus.New + | RcvFileStatus.Accepted + | RcvFileStatus.Connected + | RcvFileStatus.Complete + | RcvFileStatus.Cancelled + +export namespace RcvFileStatus { + export type Tag = "new" | "accepted" | "connected" | "complete" | "cancelled" + + interface Interface { + type: Tag + } + + export interface New extends Interface { + type: "new" + } + + export interface Accepted extends Interface { + type: "accepted" + fileInfo: RcvFileInfo + } + + export interface Connected extends Interface { + type: "connected" + fileInfo: RcvFileInfo + } + + export interface Complete extends Interface { + type: "complete" + fileInfo: RcvFileInfo + } + + export interface Cancelled extends Interface { + type: "cancelled" + fileInfo_?: RcvFileInfo + } +} + +export interface RcvFileTransfer { + fileId: number // int64 + xftpRcvFile?: XFTPRcvFile + fileInvitation: FileInvitation + fileStatus: RcvFileStatus + rcvFileInline?: InlineFileMode + senderDisplayName: string + chunkSize: number // int64 + cancelled: boolean + grpMemberId?: number // int64 + cryptoArgs?: CryptoFileArgs +} + +export type RcvGroupEvent = + | RcvGroupEvent.MemberAdded + | RcvGroupEvent.MemberConnected + | RcvGroupEvent.MemberAccepted + | RcvGroupEvent.UserAccepted + | RcvGroupEvent.MemberLeft + | RcvGroupEvent.MemberRole + | RcvGroupEvent.MemberBlocked + | RcvGroupEvent.UserRole + | RcvGroupEvent.MemberDeleted + | RcvGroupEvent.UserDeleted + | RcvGroupEvent.GroupDeleted + | RcvGroupEvent.GroupUpdated + | RcvGroupEvent.InvitedViaGroupLink + | RcvGroupEvent.MemberCreatedContact + | RcvGroupEvent.MemberProfileUpdated + | RcvGroupEvent.NewMemberPendingReview + +export namespace RcvGroupEvent { + export type Tag = + | "memberAdded" + | "memberConnected" + | "memberAccepted" + | "userAccepted" + | "memberLeft" + | "memberRole" + | "memberBlocked" + | "userRole" + | "memberDeleted" + | "userDeleted" + | "groupDeleted" + | "groupUpdated" + | "invitedViaGroupLink" + | "memberCreatedContact" + | "memberProfileUpdated" + | "newMemberPendingReview" + + interface Interface { + type: Tag + } + + export interface MemberAdded extends Interface { + type: "memberAdded" + groupMemberId: number // int64 + profile: Profile + } + + export interface MemberConnected extends Interface { + type: "memberConnected" + } + + export interface MemberAccepted extends Interface { + type: "memberAccepted" + groupMemberId: number // int64 + profile: Profile + } + + export interface UserAccepted extends Interface { + type: "userAccepted" + } + + export interface MemberLeft extends Interface { + type: "memberLeft" + } + + export interface MemberRole extends Interface { + type: "memberRole" + groupMemberId: number // int64 + profile: Profile + role: GroupMemberRole + } + + export interface MemberBlocked extends Interface { + type: "memberBlocked" + groupMemberId: number // int64 + profile: Profile + blocked: boolean + } + + export interface UserRole extends Interface { + type: "userRole" + role: GroupMemberRole + } + + export interface MemberDeleted extends Interface { + type: "memberDeleted" + groupMemberId: number // int64 + profile: Profile + } + + export interface UserDeleted extends Interface { + type: "userDeleted" + } + + export interface GroupDeleted extends Interface { + type: "groupDeleted" + } + + export interface GroupUpdated extends Interface { + type: "groupUpdated" + groupProfile: GroupProfile + } + + export interface InvitedViaGroupLink extends Interface { + type: "invitedViaGroupLink" + } + + export interface MemberCreatedContact extends Interface { + type: "memberCreatedContact" + } + + export interface MemberProfileUpdated extends Interface { + type: "memberProfileUpdated" + fromProfile: Profile + toProfile: Profile + } + + export interface NewMemberPendingReview extends Interface { + type: "newMemberPendingReview" + } +} + +export enum ReportReason { + Spam = "spam", + Content = "content", + Community = "community", + Profile = "profile", + Other = "other", +} + +export interface RoleGroupPreference { + enable: GroupFeatureEnabled + role?: GroupMemberRole +} + +export type SMPAgentError = + | SMPAgentError.A_MESSAGE + | SMPAgentError.A_PROHIBITED + | SMPAgentError.A_VERSION + | SMPAgentError.A_LINK + | SMPAgentError.A_CRYPTO + | SMPAgentError.A_DUPLICATE + | SMPAgentError.A_QUEUE + +export namespace SMPAgentError { + export type Tag = + | "A_MESSAGE" + | "A_PROHIBITED" + | "A_VERSION" + | "A_LINK" + | "A_CRYPTO" + | "A_DUPLICATE" + | "A_QUEUE" + + interface Interface { + type: Tag + } + + export interface A_MESSAGE extends Interface { + type: "A_MESSAGE" + } + + export interface A_PROHIBITED extends Interface { + type: "A_PROHIBITED" + prohibitedErr: string + } + + export interface A_VERSION extends Interface { + type: "A_VERSION" + } + + export interface A_LINK extends Interface { + type: "A_LINK" + linkErr: string + } + + export interface A_CRYPTO extends Interface { + type: "A_CRYPTO" + cryptoErr: AgentCryptoError + } + + export interface A_DUPLICATE extends Interface { + type: "A_DUPLICATE" + } + + export interface A_QUEUE extends Interface { + type: "A_QUEUE" + queueErr: string + } +} + +export interface SecurityCode { + securityCode: string + verifiedAt: string // ISO-8601 timestamp +} + +export interface SimplePreference { + allow: FeatureAllowed +} + +export enum SimplexLinkType { + Contact = "contact", + Invitation = "invitation", + Group = "group", + Channel = "channel", + Relay = "relay", +} + +export enum SndCIStatusProgress { + Partial = "partial", + Complete = "complete", +} + +export type SndConnEvent = SndConnEvent.SwitchQueue | SndConnEvent.RatchetSync | SndConnEvent.PqEnabled + +export namespace SndConnEvent { + export type Tag = "switchQueue" | "ratchetSync" | "pqEnabled" + + interface Interface { + type: Tag + } + + export interface SwitchQueue extends Interface { + type: "switchQueue" + phase: SwitchPhase + member?: GroupMemberRef + } + + export interface RatchetSync extends Interface { + type: "ratchetSync" + syncStatus: RatchetSyncState + member?: GroupMemberRef + } + + export interface PqEnabled extends Interface { + type: "pqEnabled" + enabled: boolean + } +} + +export type SndError = + | SndError.Auth + | SndError.Quota + | SndError.Expired + | SndError.Relay + | SndError.Proxy + | SndError.ProxyRelay + | SndError.Other + +export namespace SndError { + export type Tag = "auth" | "quota" | "expired" | "relay" | "proxy" | "proxyRelay" | "other" + + interface Interface { + type: Tag + } + + export interface Auth extends Interface { + type: "auth" + } + + export interface Quota extends Interface { + type: "quota" + } + + export interface Expired extends Interface { + type: "expired" + } + + export interface Relay extends Interface { + type: "relay" + srvError: SrvError + } + + export interface Proxy extends Interface { + type: "proxy" + proxyServer: string + srvError: SrvError + } + + export interface ProxyRelay extends Interface { + type: "proxyRelay" + proxyServer: string + srvError: SrvError + } + + export interface Other extends Interface { + type: "other" + sndError: string + } +} + +export interface SndFileTransfer { + fileId: number // int64 + fileName: string + filePath: string + fileSize: number // int64 + chunkSize: number // int64 + recipientDisplayName: string + connId: number // int64 + agentConnId: string + groupMemberId?: number // int64 + fileStatus: FileStatus + fileDescrId?: number // int64 + fileInline?: InlineFileMode +} + +export type SndGroupEvent = + | SndGroupEvent.MemberRole + | SndGroupEvent.MemberBlocked + | SndGroupEvent.UserRole + | SndGroupEvent.MemberDeleted + | SndGroupEvent.UserLeft + | SndGroupEvent.GroupUpdated + | SndGroupEvent.MemberAccepted + | SndGroupEvent.UserPendingReview + +export namespace SndGroupEvent { + export type Tag = + | "memberRole" + | "memberBlocked" + | "userRole" + | "memberDeleted" + | "userLeft" + | "groupUpdated" + | "memberAccepted" + | "userPendingReview" + + interface Interface { + type: Tag + } + + export interface MemberRole extends Interface { + type: "memberRole" + groupMemberId: number // int64 + profile: Profile + role: GroupMemberRole + } + + export interface MemberBlocked extends Interface { + type: "memberBlocked" + groupMemberId: number // int64 + profile: Profile + blocked: boolean + } + + export interface UserRole extends Interface { + type: "userRole" + role: GroupMemberRole + } + + export interface MemberDeleted extends Interface { + type: "memberDeleted" + groupMemberId: number // int64 + profile: Profile + } + + export interface UserLeft extends Interface { + type: "userLeft" + } + + export interface GroupUpdated extends Interface { + type: "groupUpdated" + groupProfile: GroupProfile + } + + export interface MemberAccepted extends Interface { + type: "memberAccepted" + groupMemberId: number // int64 + profile: Profile + } + + export interface UserPendingReview extends Interface { + type: "userPendingReview" + } +} + +export type SrvError = SrvError.Host | SrvError.Version | SrvError.Other + +export namespace SrvError { + export type Tag = "host" | "version" | "other" + + interface Interface { + type: Tag + } + + export interface Host extends Interface { + type: "host" + } + + export interface Version extends Interface { + type: "version" + } + + export interface Other extends Interface { + type: "other" + srvError: string + } +} + +export type StoreError = + | StoreError.DuplicateName + | StoreError.UserNotFound + | StoreError.UserNotFoundByName + | StoreError.UserNotFoundByContactId + | StoreError.UserNotFoundByGroupId + | StoreError.UserNotFoundByFileId + | StoreError.UserNotFoundByContactRequestId + | StoreError.ContactNotFound + | StoreError.ContactNotFoundByName + | StoreError.ContactNotFoundByMemberId + | StoreError.ContactNotReady + | StoreError.DuplicateContactLink + | StoreError.UserContactLinkNotFound + | StoreError.ContactRequestNotFound + | StoreError.ContactRequestNotFoundByName + | StoreError.InvalidContactRequestEntity + | StoreError.InvalidBusinessChatContactRequest + | StoreError.GroupNotFound + | StoreError.GroupNotFoundByName + | StoreError.GroupMemberNameNotFound + | StoreError.GroupMemberNotFound + | StoreError.GroupHostMemberNotFound + | StoreError.GroupMemberNotFoundByMemberId + | StoreError.MemberContactGroupMemberNotFound + | StoreError.GroupWithoutUser + | StoreError.DuplicateGroupMember + | StoreError.GroupAlreadyJoined + | StoreError.GroupInvitationNotFound + | StoreError.NoteFolderAlreadyExists + | StoreError.NoteFolderNotFound + | StoreError.UserNoteFolderNotFound + | StoreError.SndFileNotFound + | StoreError.SndFileInvalid + | StoreError.RcvFileNotFound + | StoreError.RcvFileDescrNotFound + | StoreError.FileNotFound + | StoreError.RcvFileInvalid + | StoreError.RcvFileInvalidDescrPart + | StoreError.LocalFileNoTransfer + | StoreError.SharedMsgIdNotFoundByFileId + | StoreError.FileIdNotFoundBySharedMsgId + | StoreError.SndFileNotFoundXFTP + | StoreError.RcvFileNotFoundXFTP + | StoreError.ConnectionNotFound + | StoreError.ConnectionNotFoundById + | StoreError.ConnectionNotFoundByMemberId + | StoreError.PendingConnectionNotFound + | StoreError.IntroNotFound + | StoreError.UniqueID + | StoreError.LargeMsg + | StoreError.InternalError + | StoreError.DBException + | StoreError.DBBusyError + | StoreError.BadChatItem + | StoreError.ChatItemNotFound + | StoreError.ChatItemNotFoundByText + | StoreError.ChatItemSharedMsgIdNotFound + | StoreError.ChatItemNotFoundByFileId + | StoreError.ChatItemNotFoundByContactId + | StoreError.ChatItemNotFoundByGroupId + | StoreError.ProfileNotFound + | StoreError.DuplicateGroupLink + | StoreError.GroupLinkNotFound + | StoreError.HostMemberIdNotFound + | StoreError.ContactNotFoundByFileId + | StoreError.NoGroupSndStatus + | StoreError.DuplicateGroupMessage + | StoreError.RemoteHostNotFound + | StoreError.RemoteHostUnknown + | StoreError.RemoteHostDuplicateCA + | StoreError.RemoteCtrlNotFound + | StoreError.RemoteCtrlDuplicateCA + | StoreError.ProhibitedDeleteUser + | StoreError.OperatorNotFound + | StoreError.UsageConditionsNotFound + | StoreError.InvalidQuote + | StoreError.InvalidMention + +export namespace StoreError { + export type Tag = + | "duplicateName" + | "userNotFound" + | "userNotFoundByName" + | "userNotFoundByContactId" + | "userNotFoundByGroupId" + | "userNotFoundByFileId" + | "userNotFoundByContactRequestId" + | "contactNotFound" + | "contactNotFoundByName" + | "contactNotFoundByMemberId" + | "contactNotReady" + | "duplicateContactLink" + | "userContactLinkNotFound" + | "contactRequestNotFound" + | "contactRequestNotFoundByName" + | "invalidContactRequestEntity" + | "invalidBusinessChatContactRequest" + | "groupNotFound" + | "groupNotFoundByName" + | "groupMemberNameNotFound" + | "groupMemberNotFound" + | "groupHostMemberNotFound" + | "groupMemberNotFoundByMemberId" + | "memberContactGroupMemberNotFound" + | "groupWithoutUser" + | "duplicateGroupMember" + | "groupAlreadyJoined" + | "groupInvitationNotFound" + | "noteFolderAlreadyExists" + | "noteFolderNotFound" + | "userNoteFolderNotFound" + | "sndFileNotFound" + | "sndFileInvalid" + | "rcvFileNotFound" + | "rcvFileDescrNotFound" + | "fileNotFound" + | "rcvFileInvalid" + | "rcvFileInvalidDescrPart" + | "localFileNoTransfer" + | "sharedMsgIdNotFoundByFileId" + | "fileIdNotFoundBySharedMsgId" + | "sndFileNotFoundXFTP" + | "rcvFileNotFoundXFTP" + | "connectionNotFound" + | "connectionNotFoundById" + | "connectionNotFoundByMemberId" + | "pendingConnectionNotFound" + | "introNotFound" + | "uniqueID" + | "largeMsg" + | "internalError" + | "dBException" + | "dBBusyError" + | "badChatItem" + | "chatItemNotFound" + | "chatItemNotFoundByText" + | "chatItemSharedMsgIdNotFound" + | "chatItemNotFoundByFileId" + | "chatItemNotFoundByContactId" + | "chatItemNotFoundByGroupId" + | "profileNotFound" + | "duplicateGroupLink" + | "groupLinkNotFound" + | "hostMemberIdNotFound" + | "contactNotFoundByFileId" + | "noGroupSndStatus" + | "duplicateGroupMessage" + | "remoteHostNotFound" + | "remoteHostUnknown" + | "remoteHostDuplicateCA" + | "remoteCtrlNotFound" + | "remoteCtrlDuplicateCA" + | "prohibitedDeleteUser" + | "operatorNotFound" + | "usageConditionsNotFound" + | "invalidQuote" + | "invalidMention" + + interface Interface { + type: Tag + } + + export interface DuplicateName extends Interface { + type: "duplicateName" + } + + export interface UserNotFound extends Interface { + type: "userNotFound" + userId: number // int64 + } + + export interface UserNotFoundByName extends Interface { + type: "userNotFoundByName" + contactName: string + } + + export interface UserNotFoundByContactId extends Interface { + type: "userNotFoundByContactId" + contactId: number // int64 + } + + export interface UserNotFoundByGroupId extends Interface { + type: "userNotFoundByGroupId" + groupId: number // int64 + } + + export interface UserNotFoundByFileId extends Interface { + type: "userNotFoundByFileId" + fileId: number // int64 + } + + export interface UserNotFoundByContactRequestId extends Interface { + type: "userNotFoundByContactRequestId" + contactRequestId: number // int64 + } + + export interface ContactNotFound extends Interface { + type: "contactNotFound" + contactId: number // int64 + } + + export interface ContactNotFoundByName extends Interface { + type: "contactNotFoundByName" + contactName: string + } + + export interface ContactNotFoundByMemberId extends Interface { + type: "contactNotFoundByMemberId" + groupMemberId: number // int64 + } + + export interface ContactNotReady extends Interface { + type: "contactNotReady" + contactName: string + } + + export interface DuplicateContactLink extends Interface { + type: "duplicateContactLink" + } + + export interface UserContactLinkNotFound extends Interface { + type: "userContactLinkNotFound" + } + + export interface ContactRequestNotFound extends Interface { + type: "contactRequestNotFound" + contactRequestId: number // int64 + } + + export interface ContactRequestNotFoundByName extends Interface { + type: "contactRequestNotFoundByName" + contactName: string + } + + export interface InvalidContactRequestEntity extends Interface { + type: "invalidContactRequestEntity" + contactRequestId: number // int64 + } + + export interface InvalidBusinessChatContactRequest extends Interface { + type: "invalidBusinessChatContactRequest" + } + + export interface GroupNotFound extends Interface { + type: "groupNotFound" + groupId: number // int64 + } + + export interface GroupNotFoundByName extends Interface { + type: "groupNotFoundByName" + groupName: string + } + + export interface GroupMemberNameNotFound extends Interface { + type: "groupMemberNameNotFound" + groupId: number // int64 + groupMemberName: string + } + + export interface GroupMemberNotFound extends Interface { + type: "groupMemberNotFound" + groupMemberId: number // int64 + } + + export interface GroupHostMemberNotFound extends Interface { + type: "groupHostMemberNotFound" + groupId: number // int64 + } + + export interface GroupMemberNotFoundByMemberId extends Interface { + type: "groupMemberNotFoundByMemberId" + memberId: string + } + + export interface MemberContactGroupMemberNotFound extends Interface { + type: "memberContactGroupMemberNotFound" + contactId: number // int64 + } + + export interface GroupWithoutUser extends Interface { + type: "groupWithoutUser" + } + + export interface DuplicateGroupMember extends Interface { + type: "duplicateGroupMember" + } + + export interface GroupAlreadyJoined extends Interface { + type: "groupAlreadyJoined" + } + + export interface GroupInvitationNotFound extends Interface { + type: "groupInvitationNotFound" + } + + export interface NoteFolderAlreadyExists extends Interface { + type: "noteFolderAlreadyExists" + noteFolderId: number // int64 + } + + export interface NoteFolderNotFound extends Interface { + type: "noteFolderNotFound" + noteFolderId: number // int64 + } + + export interface UserNoteFolderNotFound extends Interface { + type: "userNoteFolderNotFound" + } + + export interface SndFileNotFound extends Interface { + type: "sndFileNotFound" + fileId: number // int64 + } + + export interface SndFileInvalid extends Interface { + type: "sndFileInvalid" + fileId: number // int64 + } + + export interface RcvFileNotFound extends Interface { + type: "rcvFileNotFound" + fileId: number // int64 + } + + export interface RcvFileDescrNotFound extends Interface { + type: "rcvFileDescrNotFound" + fileId: number // int64 + } + + export interface FileNotFound extends Interface { + type: "fileNotFound" + fileId: number // int64 + } + + export interface RcvFileInvalid extends Interface { + type: "rcvFileInvalid" + fileId: number // int64 + } + + export interface RcvFileInvalidDescrPart extends Interface { + type: "rcvFileInvalidDescrPart" + } + + export interface LocalFileNoTransfer extends Interface { + type: "localFileNoTransfer" + fileId: number // int64 + } + + export interface SharedMsgIdNotFoundByFileId extends Interface { + type: "sharedMsgIdNotFoundByFileId" + fileId: number // int64 + } + + export interface FileIdNotFoundBySharedMsgId extends Interface { + type: "fileIdNotFoundBySharedMsgId" + sharedMsgId: string + } + + export interface SndFileNotFoundXFTP extends Interface { + type: "sndFileNotFoundXFTP" + agentSndFileId: string + } + + export interface RcvFileNotFoundXFTP extends Interface { + type: "rcvFileNotFoundXFTP" + agentRcvFileId: string + } + + export interface ConnectionNotFound extends Interface { + type: "connectionNotFound" + agentConnId: string + } + + export interface ConnectionNotFoundById extends Interface { + type: "connectionNotFoundById" + connId: number // int64 + } + + export interface ConnectionNotFoundByMemberId extends Interface { + type: "connectionNotFoundByMemberId" + groupMemberId: number // int64 + } + + export interface PendingConnectionNotFound extends Interface { + type: "pendingConnectionNotFound" + connId: number // int64 + } + + export interface IntroNotFound extends Interface { + type: "introNotFound" + } + + export interface UniqueID extends Interface { + type: "uniqueID" + } + + export interface LargeMsg extends Interface { + type: "largeMsg" + } + + export interface InternalError extends Interface { + type: "internalError" + message: string + } + + export interface DBException extends Interface { + type: "dBException" + message: string + } + + export interface DBBusyError extends Interface { + type: "dBBusyError" + message: string + } + + export interface BadChatItem extends Interface { + type: "badChatItem" + itemId: number // int64 + itemTs?: string // ISO-8601 timestamp + } + + export interface ChatItemNotFound extends Interface { + type: "chatItemNotFound" + itemId: number // int64 + } + + export interface ChatItemNotFoundByText extends Interface { + type: "chatItemNotFoundByText" + text: string + } + + export interface ChatItemSharedMsgIdNotFound extends Interface { + type: "chatItemSharedMsgIdNotFound" + sharedMsgId: string + } + + export interface ChatItemNotFoundByFileId extends Interface { + type: "chatItemNotFoundByFileId" + fileId: number // int64 + } + + export interface ChatItemNotFoundByContactId extends Interface { + type: "chatItemNotFoundByContactId" + contactId: number // int64 + } + + export interface ChatItemNotFoundByGroupId extends Interface { + type: "chatItemNotFoundByGroupId" + groupId: number // int64 + } + + export interface ProfileNotFound extends Interface { + type: "profileNotFound" + profileId: number // int64 + } + + export interface DuplicateGroupLink extends Interface { + type: "duplicateGroupLink" + groupInfo: GroupInfo + } + + export interface GroupLinkNotFound extends Interface { + type: "groupLinkNotFound" + groupInfo: GroupInfo + } + + export interface HostMemberIdNotFound extends Interface { + type: "hostMemberIdNotFound" + groupId: number // int64 + } + + export interface ContactNotFoundByFileId extends Interface { + type: "contactNotFoundByFileId" + fileId: number // int64 + } + + export interface NoGroupSndStatus extends Interface { + type: "noGroupSndStatus" + itemId: number // int64 + groupMemberId: number // int64 + } + + export interface DuplicateGroupMessage extends Interface { + type: "duplicateGroupMessage" + groupId: number // int64 + sharedMsgId: string + authorGroupMemberId?: number // int64 + forwardedByGroupMemberId?: number // int64 + } + + export interface RemoteHostNotFound extends Interface { + type: "remoteHostNotFound" + remoteHostId: number // int64 + } + + export interface RemoteHostUnknown extends Interface { + type: "remoteHostUnknown" + } + + export interface RemoteHostDuplicateCA extends Interface { + type: "remoteHostDuplicateCA" + } + + export interface RemoteCtrlNotFound extends Interface { + type: "remoteCtrlNotFound" + remoteCtrlId: number // int64 + } + + export interface RemoteCtrlDuplicateCA extends Interface { + type: "remoteCtrlDuplicateCA" + } + + export interface ProhibitedDeleteUser extends Interface { + type: "prohibitedDeleteUser" + userId: number // int64 + contactId: number // int64 + } + + export interface OperatorNotFound extends Interface { + type: "operatorNotFound" + serverOperatorId: number // int64 + } + + export interface UsageConditionsNotFound extends Interface { + type: "usageConditionsNotFound" + } + + export interface InvalidQuote extends Interface { + type: "invalidQuote" + } + + export interface InvalidMention extends Interface { + type: "invalidMention" + } +} + +export enum SwitchPhase { + Started = "started", + Confirmed = "confirmed", + Secured = "secured", + Completed = "completed", +} + +export interface TimedMessagesGroupPreference { + enable: GroupFeatureEnabled + ttl?: number // int +} + +export interface TimedMessagesPreference { + allow: FeatureAllowed + ttl?: number // int +} + +export type TransportError = + | TransportError.BadBlock + | TransportError.Version + | TransportError.LargeMsg + | TransportError.BadSession + | TransportError.NoServerAuth + | TransportError.Handshake + +export namespace TransportError { + export type Tag = "badBlock" | "version" | "largeMsg" | "badSession" | "noServerAuth" | "handshake" + + interface Interface { + type: Tag + } + + export interface BadBlock extends Interface { + type: "badBlock" + } + + export interface Version extends Interface { + type: "version" + } + + export interface LargeMsg extends Interface { + type: "largeMsg" + } + + export interface BadSession extends Interface { + type: "badSession" + } + + export interface NoServerAuth extends Interface { + type: "noServerAuth" + } + + export interface Handshake extends Interface { + type: "handshake" + handshakeErr: HandshakeError + } +} + +export enum UIColorMode { + Light = "light", + Dark = "dark", +} + +export interface UIColors { + accent?: string + accentVariant?: string + secondary?: string + secondaryVariant?: string + background?: string + menus?: string + title?: string + accentVariant2?: string + sentMessage?: string + sentReply?: string + receivedMessage?: string + receivedReply?: string +} + +export interface UIThemeEntityOverride { + mode: UIColorMode + wallpaper?: ChatWallpaper + colors: UIColors +} + +export interface UIThemeEntityOverrides { + light?: UIThemeEntityOverride + dark?: UIThemeEntityOverride +} + +export interface UpdatedMessage { + msgContent: MsgContent + mentions: {[key: string]: number} // string : int64 +} + +export interface User { + userId: number // int64 + agentUserId: number // int64 + userContactId: number // int64 + localDisplayName: string + profile: LocalProfile + fullPreferences: FullPreferences + activeUser: boolean + activeOrder: number // int64 + viewPwdHash?: UserPwdHash + showNtfs: boolean + sendRcptsContacts: boolean + sendRcptsSmallGroups: boolean + autoAcceptMemberContacts: boolean + userMemberProfileUpdatedAt?: string // ISO-8601 timestamp + uiThemes?: UIThemeEntityOverrides +} + +export interface UserContact { + userContactLinkId: number // int64 + connReqContact: string + groupId?: number // int64 +} + +export interface UserContactLink { + userContactLinkId: number // int64 + connLinkContact: CreatedConnLink + shortLinkDataSet: boolean + shortLinkLargeDataSet: boolean + addressSettings: AddressSettings +} + +export interface UserContactRequest { + contactRequestId: number // int64 + agentInvitationId: string + contactId_?: number // int64 + businessGroupId_?: number // int64 + userContactLinkId_?: number // int64 + cReqChatVRange: VersionRange + localDisplayName: string + profileId: number // int64 + profile: Profile + createdAt: string // ISO-8601 timestamp + updatedAt: string // ISO-8601 timestamp + xContactId?: string + pqSupport: boolean + welcomeSharedMsgId?: string + requestSharedMsgId?: string +} + +export interface UserInfo { + user: User + unreadCount: number // int +} + +export interface UserProfileUpdateSummary { + updateSuccesses: number // int + updateFailures: number // int + changedContacts: Contact[] +} + +export interface UserPwdHash { + hash: string + salt: string +} + +export interface VersionRange { + minVersion: number // int + maxVersion: number // int +} + +export type XFTPErrorType = + | XFTPErrorType.BLOCK + | XFTPErrorType.SESSION + | XFTPErrorType.HANDSHAKE + | XFTPErrorType.CMD + | XFTPErrorType.AUTH + | XFTPErrorType.BLOCKED + | XFTPErrorType.SIZE + | XFTPErrorType.QUOTA + | XFTPErrorType.DIGEST + | XFTPErrorType.CRYPTO + | XFTPErrorType.NO_FILE + | XFTPErrorType.HAS_FILE + | XFTPErrorType.FILE_IO + | XFTPErrorType.TIMEOUT + | XFTPErrorType.INTERNAL + | XFTPErrorType.DUPLICATE_ + +export namespace XFTPErrorType { + export type Tag = + | "BLOCK" + | "SESSION" + | "HANDSHAKE" + | "CMD" + | "AUTH" + | "BLOCKED" + | "SIZE" + | "QUOTA" + | "DIGEST" + | "CRYPTO" + | "NO_FILE" + | "HAS_FILE" + | "FILE_IO" + | "TIMEOUT" + | "INTERNAL" + | "DUPLICATE_" + + interface Interface { + type: Tag + } + + export interface BLOCK extends Interface { + type: "BLOCK" + } + + export interface SESSION extends Interface { + type: "SESSION" + } + + export interface HANDSHAKE extends Interface { + type: "HANDSHAKE" + } + + export interface CMD extends Interface { + type: "CMD" + cmdErr: CommandError + } + + export interface AUTH extends Interface { + type: "AUTH" + } + + export interface BLOCKED extends Interface { + type: "BLOCKED" + blockInfo: BlockingInfo + } + + export interface SIZE extends Interface { + type: "SIZE" + } + + export interface QUOTA extends Interface { + type: "QUOTA" + } + + export interface DIGEST extends Interface { + type: "DIGEST" + } + + export interface CRYPTO extends Interface { + type: "CRYPTO" + } + + export interface NO_FILE extends Interface { + type: "NO_FILE" + } + + export interface HAS_FILE extends Interface { + type: "HAS_FILE" + } + + export interface FILE_IO extends Interface { + type: "FILE_IO" + } + + export interface TIMEOUT extends Interface { + type: "TIMEOUT" + } + + export interface INTERNAL extends Interface { + type: "INTERNAL" + } + + export interface DUPLICATE_ extends Interface { + type: "DUPLICATE_" + } +} + +export interface XFTPRcvFile { + rcvFileDescription: RcvFileDescr + agentRcvFileId?: string + agentRcvFileDeleted: boolean + userApprovedRelays: boolean +} + +export interface XFTPSndFile { + agentSndFileId: string + privateSndFileDescr?: string + agentSndFileDeleted: boolean + cryptoArgs?: CryptoFileArgs +} diff --git a/packages/simplex-chat-client/types/typescript/tsconfig.json b/packages/simplex-chat-client/types/typescript/tsconfig.json new file mode 100644 index 0000000000..d39db52454 --- /dev/null +++ b/packages/simplex-chat-client/types/typescript/tsconfig.json @@ -0,0 +1,22 @@ +{ + "include": ["src"], + "compilerOptions": { + "declaration": true, + "forceConsistentCasingInFileNames": true, + "lib": ["ES2018", "DOM"], + "module": "CommonJS", + "moduleResolution": "Node", + "noFallthroughCasesInSwitch": true, + "noImplicitAny": true, + "noImplicitReturns": true, + "noImplicitThis": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noEmitOnError": true, + "outDir": "dist", + "sourceMap": true, + "strict": true, + "strictNullChecks": true, + "target": "ES2018" + } + } diff --git a/packages/simplex-chat-client/typescript/README.md b/packages/simplex-chat-client/typescript/README.md index 4940eb0f7c..c1756dc82c 100644 --- a/packages/simplex-chat-client/typescript/README.md +++ b/packages/simplex-chat-client/typescript/README.md @@ -38,6 +38,8 @@ See the example of a simple chat bot in [squaring-bot.js](./examples/squaring-bo Please refer to the available client API in [client.ts](./src/client.ts). +This library uses [@simplex-chat/types](https://www.npmjs.com/package/@simplex-chat/types) package with auto-generated [bot API types](https://github.com/simplex-chat/simplex-chat/tree/stable/bots) + ## License [AGPL v3](./LICENSE) diff --git a/packages/simplex-chat-client/typescript/package.json b/packages/simplex-chat-client/typescript/package.json index bb2fdda702..b721dbcce2 100644 --- a/packages/simplex-chat-client/typescript/package.json +++ b/packages/simplex-chat-client/typescript/package.json @@ -1,12 +1,16 @@ { "name": "simplex-chat", - "version": "0.2.1", + "version": "0.3.0", "description": "SimpleX Chat client", "main": "dist/index.js", "types": "dist/index.d.ts", "files": [ "dist" ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, "scripts": { "test": "npm run prettier:check && npm run eslint && jest --coverage", "build": "npm run prettier:write && npm run eslint && tsc && ./copy && npm run bundle", @@ -17,13 +21,17 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/simplex-chat/simplex-chat.git" + "url": "git+https://github.com/simplex-chat/simplex-chat.git", + "directory": "/packages/simplex-chat-client/typescript" }, "keywords": [ + "simplex", "messenger", "chat", "privacy", - "security" + "security", + "bots", + "websockets" ], "author": "SimpleX Chat", "license": "AGPL-3.0", @@ -35,6 +43,7 @@ "isomorphic-ws": "^4.0.1" }, "devDependencies": { + "@simplex-chat/types": "^0.1.0", "@types/jest": "^27.5.1", "@types/node": "^18.11.18", "@typescript-eslint/eslint-plugin": "^5.23.0", diff --git a/packages/simplex-chat-client/typescript/src/client.ts b/packages/simplex-chat-client/typescript/src/client.ts index f908e6a7e3..12fa150fc4 100644 --- a/packages/simplex-chat-client/typescript/src/client.ts +++ b/packages/simplex-chat-client/typescript/src/client.ts @@ -1,9 +1,6 @@ import {ABQueue} from "./queue" -import {ChatTransport, ChatServer, ChatSrvRequest, ChatSrvResponse, ChatResponseError, localServer, noop} from "./transport" -import {ChatCommand, ChatType, Profile} from "./command" -import {ChatResponse, ChatInfo} from "./response" -import * as CC from "./command" -import * as CR from "./response" +import {ChatTransport, ChatServer, ChatSrvRequest, ChatSrvResponse, ChatResponseError, localServer, noop, ChatSrvEvent} from "./transport" +import {CC, ChatResponse, CR, ChatEvent, T} from "@simplex-chat/types" export interface ChatClientConfig { readonly qSize: number @@ -12,7 +9,7 @@ export interface ChatClientConfig { export interface Request { readonly resolve: (resp: ChatResponse) => void - readonly reject: (err?: ChatResponseError | CR.CRChatCmdError) => void + readonly reject: (err?: ChatResponseError | CR.ChatCmdError) => void } export class ChatCommandError extends Error { @@ -39,44 +36,42 @@ export class ChatClient { private constructor( readonly server: ChatServer | string, readonly config: ChatClientConfig, - readonly msgQ: ABQueue, + readonly msgQ: ABQueue, readonly client: Promise, private readonly transport: ChatTransport ) {} static async create(server: ChatServer | string = localServer, cfg: ChatClientConfig = ChatClient.defaultConfig): Promise { const transport = await ChatTransport.connect(server, cfg.tcpTimeout, cfg.qSize) - const msgQ = new ABQueue(cfg.qSize) + const msgQ = new ABQueue(cfg.qSize) const client = runClient().then(noop, noop) const c = new ChatClient(server, cfg, msgQ, client, transport) return c async function runClient(): Promise { for await (const t of transport) { - const apiResp = (t instanceof Promise ? await t : t) as ChatSrvResponse | ChatResponseError + const apiResp = (t instanceof Promise ? await t : t) as ChatSrvResponse | ChatSrvEvent | ChatResponseError if (apiResp instanceof ChatResponseError) { console.log("chat response error: ", apiResp) - } else { + } else if ("corrId" in apiResp) { const {corrId, resp} = apiResp - if (corrId) { - const req = c.sentCommands.get(corrId) - if (req) { - c.sentCommands.delete(corrId) - req.resolve(resp) - } else { - // TODO send error to errQ? - console.log("no command sent for chat response: ", apiResp) - } + const req = c.sentCommands.get(corrId) + if (req) { + c.sentCommands.delete(corrId) + req.resolve(resp) } else { - await msgQ.enqueue(resp) + // TODO send error to errQ? + console.log("no command sent for chat response: ", apiResp) } + } else { + await msgQ.enqueue(apiResp.resp) } } c._connected = false } } - sendChatCmdStr(cmd: string): Promise { + sendChatCmd(cmd: string): Promise { const corrId = `${++this.clientCorrId}` const t: ChatSrvRequest = {corrId, cmd} const p = new Promise((resolve, reject) => this.sentCommands.set(corrId, {resolve, reject})) @@ -84,17 +79,13 @@ export class ChatClient { return p } - sendChatCommand(command: ChatCommand): Promise { - return this.sendChatCmdStr(CC.cmdString(command)) - } - async disconnect(): Promise { await this.transport.close() await this.client } - async apiGetActiveUser(): Promise { - const r = await this.sendChatCommand({type: "showActiveUser"}) + async apiGetActiveUser(): Promise { + const r = await this.sendChatCmd(CC.ShowActiveUser.cmdString({})) switch (r.type) { case "activeUser": return r.user @@ -106,90 +97,66 @@ export class ChatClient { } } - async apiCreateActiveUser(profile?: Profile, sameServers = true, pastTimestamp = false): Promise { - const r = await this.sendChatCommand({type: "createActiveUser", profile, sameServers, pastTimestamp}) + async apiCreateActiveUser(profile?: T.Profile): Promise { + const r = await this.sendChatCmd(CC.CreateActiveUser.cmdString({newUser: {profile, pastTimestamp: false}})) if (r.type === "activeUser") return r.user throw new ChatCommandError("unexpected response", r) } - async apiStartChat(): Promise { - const r = await this.sendChatCommand({type: "startChat"}) - if (r.type !== "chatStarted" && r.type !== "chatRunning") { - throw new ChatCommandError("error starting chat", r) - } - } - - async apiStopChat(): Promise { - const r = await this.sendChatCommand({type: "apiStopChat"}) - if (r.type !== "chatStopped") { - throw new ChatCommandError("error stopping chat", r) - } - } - - apiSetIncognito(incognito: boolean): Promise { - return this.okChatCommand({type: "setIncognito", incognito}) - } - - async enableAddressAutoAccept(acceptIncognito = false, autoReply?: CC.MsgContent): Promise { - const r = await this.sendChatCommand({type: "addressAutoAccept", autoAccept: {acceptIncognito, autoReply}}) + async enableAddressAutoAccept(userId: number, autoReply?: T.MsgContent, businessAddress = false): Promise { + const r = await this.sendChatCmd( + CC.APISetAddressSettings.cmdString({userId, settings: {businessAddress, autoAccept: {acceptIncognito: false}, autoReply}}) + ) if (r.type !== "userContactLinkUpdated") { throw new ChatCommandError("error changing user contact address mode", r) } } - async disableAddressAutoAccept(): Promise { - const r = await this.sendChatCommand({type: "addressAutoAccept"}) + async disableAddressAutoAccept(userId: number, businessAddress = false): Promise { + const r = await this.sendChatCmd(CC.APISetAddressSettings.cmdString({userId, settings: {businessAddress}})) if (r.type !== "userContactLinkUpdated") { throw new ChatCommandError("error changing user contact address mode", r) } } - async apiGetChats(userId: number): Promise { - const r = await this.sendChatCommand({type: "apiGetChats", userId}) - if (r.type === "apiChats") return r.chats - throw new ChatCommandError("error loading chats", r) - } - - async apiGetChat( - chatType: ChatType, - chatId: number, - pagination: CC.ChatPagination = {count: 100}, - search: string | undefined = undefined - ): Promise { - const r = await this.sendChatCommand({type: "apiGetChat", chatType, chatId, pagination, search}) - if (r.type === "apiChat") return r.chat - throw new ChatCommandError("error loading chat", r) - } - - async apiSendMessages(chatType: ChatType, chatId: number, messages: CC.ComposedMessage[]): Promise { - const r = await this.sendChatCommand({type: "apiSendMessage", chatType, chatId, messages}) + async apiSendMessages(chatType: T.ChatType, chatId: number, messages: T.ComposedMessage[]): Promise { + const r = await this.sendChatCmd( + CC.APISendMessages.cmdString({sendRef: {chatType, chatId}, composedMessages: messages, liveMessage: false}) + ) if (r.type === "newChatItems") return r.chatItems throw new ChatCommandError("unexpected response", r) } - async apiSendTextMessage(chatType: ChatType, chatId: number, text: string): Promise { - return this.apiSendMessages(chatType, chatId, [{msgContent: {type: "text", text}}]) + async apiSendTextMessage(chatType: T.ChatType, chatId: number, text: string): Promise { + return this.apiSendMessages(chatType, chatId, [{msgContent: {type: "text", text}, mentions: {}}]) } - async apiUpdateChatItem(chatType: ChatType, chatId: number, chatItemId: CC.ChatItemId, msgContent: CC.MsgContent): Promise { - const r = await this.sendChatCommand({type: "apiUpdateChatItem", chatType, chatId, chatItemId, msgContent}) + async apiUpdateChatItem(chatType: T.ChatType, chatId: number, chatItemId: number, msgContent: T.MsgContent): Promise { + const r = await this.sendChatCmd( + CC.APIUpdateChatItem.cmdString({ + chatRef: {chatType, chatId}, + chatItemId, + liveMessage: false, + updatedMessage: {msgContent, mentions: {}}, + }) + ) if (r.type === "chatItemUpdated") return r.chatItem.chatItem throw new ChatCommandError("error updating chat item", r) } - async apiDeleteChatItem( - chatType: ChatType, + async apiDeleteChatItems( + chatType: T.ChatType, chatId: number, - chatItemId: number, - deleteMode: CC.DeleteMode - ): Promise { - const r = await this.sendChatCommand({type: "apiDeleteChatItem", chatType, chatId, chatItemId, deleteMode}) - if (r.type === "chatItemDeleted") return r.toChatItem?.chatItem + chatItemIds: number[], + deleteMode: T.CIDeleteMode + ): Promise { + const r = await this.sendChatCmd(CC.APIDeleteChatItem.cmdString({chatRef: {chatType, chatId}, chatItemIds, deleteMode})) + if (r.type === "chatItemsDeleted") return r.chatItemDeletions throw new ChatCommandError("error deleting chat item", r) } - async apiCreateLink(): Promise { - const r = await this.sendChatCommand({type: "addContact"}) + async apiCreateLink(userId: number): Promise { + const r = await this.sendChatCmd(CC.APIAddContact.cmdString({userId, incognito: false})) if (r.type === "invitation") { const link = r.connLinkInvitation return link.connShortLink || link.connFullLink @@ -197,8 +164,8 @@ export class ChatClient { throw new ChatCommandError("error creating link", r) } - async apiConnect(connReq: string): Promise { - const r = await this.sendChatCommand({type: "connect", connReq}) + async apiConnectActiveUser(connLink: string): Promise { + const r = await this.sendChatCmd(CC.Connect.cmdString({incognito: false, connLink_: connLink})) switch (r.type) { case "sentConfirmation": return ConnReqType.Invitation @@ -209,30 +176,21 @@ export class ChatClient { } } - async apiDeleteChat(chatType: ChatType, chatId: number): Promise { - const r = await this.sendChatCommand({type: "apiDeleteChat", chatType, chatId}) + async apiDeleteChat(chatType: T.ChatType, chatId: number, deleteMode: T.ChatDeleteMode = {type: "full", notify: true}): Promise { + const r = await this.sendChatCmd(CC.APIDeleteChat.cmdString({chatRef: {chatType, chatId}, chatDeleteMode: deleteMode})) switch (chatType) { - case ChatType.Direct: + case T.ChatType.Direct: if (r.type === "contactDeleted") return break - case ChatType.Group: + case T.ChatType.Group: if (r.type === "groupDeletedUser") return break - case ChatType.ContactRequest: - if (r.type === "contactConnectionDeleted") return - break } throw new ChatCommandError("error deleting chat", r) } - async apiClearChat(chatType: ChatType, chatId: number): Promise { - const r = await this.sendChatCommand({type: "apiClearChat", chatType, chatId}) - if (r.type === "chatCleared") return r.chatInfo - throw new ChatCommandError("error clearing chat", r) - } - - async apiUpdateProfile(userId: number, profile: CC.Profile): Promise { - const r = await this.sendChatCommand({type: "apiUpdateProfile", userId, profile}) + async apiUpdateProfile(userId: number, profile: T.Profile): Promise { + const r = await this.sendChatCmd(CC.APIUpdateProfile.cmdString({userId, profile})) switch (r.type) { case "userProfileNoChange": return undefined @@ -243,14 +201,8 @@ export class ChatClient { } } - async apiSetContactAlias(contactId: number, localAlias: string): Promise { - const r = await this.sendChatCommand({type: "apiSetContactAlias", contactId, localAlias}) - if (r.type === "contactAliasUpdated") return r.toContact - throw new ChatCommandError("error updating contact alias", r) - } - - async apiCreateUserAddress(): Promise { - const r = await this.sendChatCommand({type: "createMyAddress"}) + async apiCreateUserAddress(userId: number): Promise { + const r = await this.sendChatCmd(CC.APICreateMyAddress.cmdString({userId})) if (r.type === "userContactLinkCreated") { const link = r.connLinkContact return link.connShortLink || link.connFullLink @@ -258,14 +210,14 @@ export class ChatClient { throw new ChatCommandError("error creating user address", r) } - async apiDeleteUserAddress(): Promise { - const r = await this.sendChatCommand({type: "deleteMyAddress"}) + async apiDeleteUserAddress(userId: number): Promise { + const r = await this.sendChatCmd(CC.APIDeleteMyAddress.cmdString({userId})) if (r.type === "userContactLinkDeleted") return throw new ChatCommandError("error deleting user address", r) } - async apiGetUserAddress(): Promise { - const r = await this.sendChatCommand({type: "showMyAddress"}) + async apiGetUserAddress(userId: number): Promise { + const r = await this.sendChatCmd(CC.APIShowMyAddress.cmdString({userId})) switch (r.type) { case "userContactLink": { const link = r.contactLink.connLinkContact @@ -279,87 +231,66 @@ export class ChatClient { } } - async apiAcceptContactRequest(contactReqId: number): Promise { - const r = await this.sendChatCommand({type: "apiAcceptContact", contactReqId}) + async apiAcceptContactRequest(contactReqId: number): Promise { + const r = await this.sendChatCmd(CC.APIAcceptContact.cmdString({contactReqId})) if (r.type === "acceptingContactRequest") return r.contact throw new ChatCommandError("error accepting contact request", r) } async apiRejectContactRequest(contactReqId: number): Promise { - const r = await this.sendChatCommand({type: "apiRejectContact", contactReqId}) + const r = await this.sendChatCmd(CC.APIRejectContact.cmdString({contactReqId})) if (r.type === "contactRequestRejected") return throw new ChatCommandError("error rejecting contact request", r) } - apiChatRead(chatType: ChatType, chatId: number, itemRange?: CC.ItemRange): Promise { - return this.okChatCommand({type: "apiChatRead", chatType, chatId, itemRange}) - } - - async apiContactInfo(contactId: number): Promise<[CR.ConnectionStats?, Profile?]> { - const r = await this.sendChatCommand({type: "apiContactInfo", contactId}) - if (r.type === "contactInfo") return [r.connectionStats, r.customUserProfile] - throw new ChatCommandError("error getting contact info", r) - } - - async apiGroupMemberInfo(groupId: number, memberId: number): Promise { - const r = await this.sendChatCommand({type: "apiGroupMemberInfo", groupId, memberId}) - if (r.type === "groupMemberInfo") return r.connectionStats_ - throw new ChatCommandError("error getting group info", r) - } - - async apiReceiveFile(fileId: number): Promise { - const r = await this.sendChatCommand({type: "receiveFile", fileId}) + async apiReceiveFile(fileId: number): Promise { + const r = await this.sendChatCmd(CC.ReceiveFile.cmdString({fileId, userApprovedRelays: true})) if (r.type === "rcvFileAccepted") return r.chatItem throw new ChatCommandError("error receiving file", r) } - async apiNewGroup(groupProfile: CR.GroupProfile): Promise { - const r = await this.sendChatCommand({type: "newGroup", groupProfile}) + async apiNewGroup(userId: number, groupProfile: T.GroupProfile): Promise { + const r = await this.sendChatCmd(CC.APINewGroup.cmdString({userId, groupProfile, incognito: false})) if (r.type === "groupCreated") return r.groupInfo throw new ChatCommandError("error creating group", r) } - async apiAddMember(groupId: number, contactId: number, memberRole: CC.GroupMemberRole): Promise { - const r = await this.sendChatCommand({type: "apiAddMember", groupId, contactId, memberRole}) + async apiAddMember(groupId: number, contactId: number, memberRole: T.GroupMemberRole): Promise { + const r = await this.sendChatCmd(CC.APIAddMember.cmdString({groupId, contactId, memberRole})) if (r.type === "sentGroupInvitation") return r.member throw new ChatCommandError("error adding member", r) } - async apiJoinGroup(groupId: number): Promise { - const r = await this.sendChatCommand({type: "apiJoinGroup", groupId}) + async apiJoinGroup(groupId: number): Promise { + const r = await this.sendChatCmd(CC.APIJoinGroup.cmdString({groupId})) if (r.type === "userAcceptedGroupSent") return r.groupInfo throw new ChatCommandError("error joining group", r) } - async apiRemoveMember(groupId: number, memberId: number): Promise { - const r = await this.sendChatCommand({type: "apiRemoveMember", groupId, memberId}) - if (r.type === "userDeletedMember") return r.member + async apiRemoveMembers(groupId: number, memberIds: number[], withMessages = false): Promise { + const r = await this.sendChatCmd(CC.APIRemoveMembers.cmdString({groupId, groupMemberIds: memberIds, withMessages})) + if (r.type === "userDeletedMembers") return r.members throw new ChatCommandError("error removing member", r) } - async apiLeaveGroup(groupId: number): Promise { - const r = await this.sendChatCommand({type: "apiLeaveGroup", groupId}) + async apiLeaveGroup(groupId: number): Promise { + const r = await this.sendChatCmd(CC.APILeaveGroup.cmdString({groupId})) if (r.type === "leftMemberUser") return r.groupInfo throw new ChatCommandError("error leaving group", r) } - async apiListMembers(groupId: number): Promise { - const r = await this.sendChatCommand({type: "apiListMembers", groupId}) + async apiListMembers(groupId: number): Promise { + const r = await this.sendChatCmd(CC.APIListMembers.cmdString({groupId})) if (r.type === "groupMembers") return r.group.members throw new ChatCommandError("error getting group members", r) } - async apiUpdateGroup(groupId: number, groupProfile: CR.GroupProfile): Promise { - const r = await this.sendChatCommand({type: "apiUpdateGroupProfile", groupId, groupProfile}) + async apiUpdateGroup(groupId: number, groupProfile: T.GroupProfile): Promise { + const r = await this.sendChatCmd(CC.APIUpdateGroupProfile.cmdString({groupId, groupProfile})) if (r.type === "groupUpdated") return r.toGroup throw new ChatCommandError("error updating group", r) } - private async okChatCommand(command: ChatCommand): Promise { - const r = await this.sendChatCommand(command) - if (r.type !== "cmdOk") throw new ChatCommandError(`${command.type} command error`, r) - } - get connected(): boolean { return this._connected } diff --git a/packages/simplex-chat-client/typescript/src/command.ts b/packages/simplex-chat-client/typescript/src/command.ts deleted file mode 100644 index 135dc41ba7..0000000000 --- a/packages/simplex-chat-client/typescript/src/command.ts +++ /dev/null @@ -1,822 +0,0 @@ -export type ChatCommand = - | ShowActiveUser - | CreateActiveUser - | ListUsers - | APISetActiveUser - | APIHideUser - | APIUnhideUser - | APIMuteUser - | APIUnmuteUser - | APIDeleteUser - | StartChat - | APIStopChat - | SetTempFolder - | SetFilesFolder - | SetIncognito - | APIExportArchive - | APIImportArchive - | APIDeleteStorage - | APIGetChats - | APIGetChat - | APISendMessage - | APIUpdateChatItem - | APIDeleteChatItem - | APIDeleteMemberChatItem - | APIChatRead - | APIDeleteChat - | APIClearChat - | APIAcceptContact - | APIRejectContact - | APIUpdateProfile - | APISetContactAlias - | NewGroup - | APIAddMember - | APIJoinGroup - | APIRemoveMember - | APILeaveGroup - | APIListMembers - | APIUpdateGroupProfile - | APICreateGroupLink - | APIGroupLinkMemberRole - | APIDeleteGroupLink - | APIGetGroupLink - | APIGetUserProtoServers - | APISetUserProtoServers - | APIContactInfo - | APIGroupMemberInfo - | APIGetContactCode - | APIGetGroupMemberCode - | APIVerifyContact - | APIVerifyGroupMember - | AddContact - | Connect - | ConnectSimplex - | CreateMyAddress - | DeleteMyAddress - | ShowMyAddress - | SetProfileAddress - | AddressAutoAccept - | APICreateMyAddress - | APIDeleteMyAddress - | APIShowMyAddress - | APISetProfileAddress - | APIAddressAutoAccept - | ReceiveFile - | CancelFile - | FileStatus - -// not included commands (they are not needed for Websocket clients, and can still be sent as strings): -// APIActivateChat -// APISuspendChat -// ResubscribeAllConnections -// APIGetChatItems - not implemented -// APISendCallInvitation -// APIRejectCall -// APISendCallOffer -// APISendCallAnswer -// APISendCallExtraInfo -// APIEndCall -// APIGetCallInvitations -// APICallStatus -// APIGetNtfToken -// APIRegisterToken -// APIVerifyToken -// APIDeleteToken -// APIGetNtfMessage -// APIMemberRole -- not implemented -// ListContacts -// ListGroups -// APISetChatItemTTL -// APIGetChatItemTTL -// APISetNetworkConfig -// APIGetNetworkConfig -// APISetChatSettings -// ShowMessages -// LastMessages -// SendMessageBroadcast - -type ChatCommandTag = - | "showActiveUser" - | "createActiveUser" - | "listUsers" - | "apiSetActiveUser" - | "setActiveUser" - | "apiHideUser" - | "apiUnhideUser" - | "apiMuteUser" - | "apiUnmuteUser" - | "apiDeleteUser" - | "startChat" - | "apiStopChat" - | "setTempFolder" - | "setFilesFolder" - | "setIncognito" - | "apiExportArchive" - | "apiImportArchive" - | "apiDeleteStorage" - | "apiGetChats" - | "apiGetChat" - | "apiSendMessage" - | "apiUpdateChatItem" - | "apiDeleteChatItem" - | "apiDeleteMemberChatItem" - | "apiChatRead" - | "apiDeleteChat" - | "apiClearChat" - | "apiAcceptContact" - | "apiRejectContact" - | "apiUpdateProfile" - | "apiSetContactAlias" - | "newGroup" - | "apiAddMember" - | "apiJoinGroup" - | "apiRemoveMember" - | "apiLeaveGroup" - | "apiListMembers" - | "apiUpdateGroupProfile" - | "apiCreateGroupLink" - | "apiGroupLinkMemberRole" - | "apiDeleteGroupLink" - | "apiGetGroupLink" - | "apiGetUserProtoServers" - | "apiSetUserProtoServers" - | "apiContactInfo" - | "apiGroupMemberInfo" - | "apiGetContactCode" - | "apiGetGroupMemberCode" - | "apiVerifyContact" - | "apiVerifyGroupMember" - | "addContact" - | "connect" - | "connectSimplex" - | "createMyAddress" - | "deleteMyAddress" - | "showMyAddress" - | "setProfileAddress" - | "addressAutoAccept" - | "apiCreateMyAddress" - | "apiDeleteMyAddress" - | "apiShowMyAddress" - | "apiSetProfileAddress" - | "apiAddressAutoAccept" - | "receiveFile" - | "cancelFile" - | "fileStatus" - -interface IChatCommand { - type: ChatCommandTag -} - -export interface ShowActiveUser extends IChatCommand { - type: "showActiveUser" -} - -export interface CreateActiveUser extends IChatCommand { - type: "createActiveUser" - profile?: Profile - sameServers: boolean - pastTimestamp: boolean -} - -export interface ListUsers extends IChatCommand { - type: "listUsers" -} - -export interface APISetActiveUser extends IChatCommand { - type: "apiSetActiveUser" - userId: number - viewPwd?: string -} - -export interface APIHideUser extends IChatCommand { - type: "apiHideUser" - userId: number - viewPwd: string -} - -export interface APIUnhideUser extends IChatCommand { - type: "apiUnhideUser" - userId: number - viewPwd: string -} - -export interface APIMuteUser extends IChatCommand { - type: "apiMuteUser" - userId: number -} - -export interface APIUnmuteUser extends IChatCommand { - type: "apiUnmuteUser" - userId: number -} - -export interface APIDeleteUser extends IChatCommand { - type: "apiDeleteUser" - userId: number - delSMPQueues: boolean - viewPwd?: string -} - -export interface StartChat extends IChatCommand { - type: "startChat" - subscribeConnections?: boolean - enableExpireChatItems?: boolean - startXFTPWorkers?: boolean -} - -export interface APIStopChat extends IChatCommand { - type: "apiStopChat" -} - -export interface SetTempFolder extends IChatCommand { - type: "setTempFolder" - tempFolder: string -} - -export interface SetFilesFolder extends IChatCommand { - type: "setFilesFolder" - filePath: string -} - -export interface SetIncognito extends IChatCommand { - type: "setIncognito" - incognito: boolean -} - -export interface APIExportArchive extends IChatCommand { - type: "apiExportArchive" - config: ArchiveConfig -} - -export interface APIImportArchive extends IChatCommand { - type: "apiImportArchive" - config: ArchiveConfig -} - -export interface APIDeleteStorage extends IChatCommand { - type: "apiDeleteStorage" -} - -export interface APIGetChats extends IChatCommand { - type: "apiGetChats" - userId: number - pendingConnections?: boolean -} - -export interface APIGetChat extends IChatCommand { - type: "apiGetChat" - chatType: ChatType - chatId: number - pagination: ChatPagination - search?: string -} - -export interface APISendMessage extends IChatCommand { - type: "apiSendMessage" - chatType: ChatType - chatId: number - messages: ComposedMessage[] -} - -export interface ComposedMessage { - filePath?: string - quotedItemId?: ChatItemId - msgContent: MsgContent -} - -export interface APIUpdateChatItem extends IChatCommand { - type: "apiUpdateChatItem" - chatType: ChatType - chatId: number - chatItemId: ChatItemId - msgContent: MsgContent -} - -export interface APIDeleteChatItem extends IChatCommand { - type: "apiDeleteChatItem" - chatType: ChatType - chatId: number - chatItemId: ChatItemId - deleteMode: DeleteMode -} - -export interface APIDeleteMemberChatItem extends IChatCommand { - type: "apiDeleteMemberChatItem" - groupId: number - groupMemberId: number - itemId: number -} - -export interface APIChatRead extends IChatCommand { - type: "apiChatRead" - chatType: ChatType - chatId: number - itemRange?: ItemRange -} - -export interface ItemRange { - fromItem: ChatItemId - toItem: ChatItemId -} - -export interface APIDeleteChat extends IChatCommand { - type: "apiDeleteChat" - chatType: ChatType - chatId: number -} - -export interface APIClearChat extends IChatCommand { - type: "apiClearChat" - chatType: ChatType - chatId: number -} - -export interface APIAcceptContact extends IChatCommand { - type: "apiAcceptContact" - contactReqId: number -} - -export interface APIRejectContact extends IChatCommand { - type: "apiRejectContact" - contactReqId: number -} - -export interface APIUpdateProfile extends IChatCommand { - type: "apiUpdateProfile" - userId: number - profile: Profile -} - -export interface APISetContactAlias extends IChatCommand { - type: "apiSetContactAlias" - contactId: number - localAlias: string -} - -export interface NewGroup extends IChatCommand { - type: "newGroup" - groupProfile: GroupProfile -} - -export interface APIAddMember extends IChatCommand { - type: "apiAddMember" - groupId: number - contactId: number - memberRole: GroupMemberRole -} - -export interface APIJoinGroup extends IChatCommand { - type: "apiJoinGroup" - groupId: number -} - -export interface APIRemoveMember extends IChatCommand { - type: "apiRemoveMember" - groupId: number - memberId: number -} - -export interface APILeaveGroup extends IChatCommand { - type: "apiLeaveGroup" - groupId: number -} - -export interface APIListMembers extends IChatCommand { - type: "apiListMembers" - groupId: number -} - -export interface APIUpdateGroupProfile extends IChatCommand { - type: "apiUpdateGroupProfile" - groupId: number - groupProfile: GroupProfile -} - -export interface APICreateGroupLink extends IChatCommand { - type: "apiCreateGroupLink" - groupId: number - memberRole: GroupMemberRole -} - -export interface APIGroupLinkMemberRole extends IChatCommand { - type: "apiGroupLinkMemberRole" - groupId: number - memberRole: GroupMemberRole -} - -export interface APIDeleteGroupLink extends IChatCommand { - type: "apiDeleteGroupLink" - groupId: number -} - -export interface APIGetGroupLink extends IChatCommand { - type: "apiGetGroupLink" - groupId: number -} - -export interface APIGetUserProtoServers extends IChatCommand { - type: "apiGetUserProtoServers" - userId: number - serverProtocol: ServerProtocol -} - -export interface APISetUserProtoServers extends IChatCommand { - type: "apiSetUserProtoServers" - userId: number - serverProtocol: ServerProtocol - servers: ServerCfg[] -} - -export interface ServerCfg { - server: string - preset: boolean - tested?: boolean - enabled: boolean -} - -export enum ServerProtocol { - SMP = "smp", - XFTP = "xftp", -} - -export interface APIContactInfo extends IChatCommand { - type: "apiContactInfo" - contactId: number -} - -export interface APIGroupMemberInfo extends IChatCommand { - type: "apiGroupMemberInfo" - groupId: number - memberId: number -} - -export interface APIGetContactCode extends IChatCommand { - type: "apiGetContactCode" - contactId: number -} - -export interface APIGetGroupMemberCode extends IChatCommand { - type: "apiGetGroupMemberCode" - groupId: number - groupMemberId: number -} - -export interface APIVerifyContact extends IChatCommand { - type: "apiVerifyContact" - contactId: number - connectionCode: string -} - -export interface APIVerifyGroupMember extends IChatCommand { - type: "apiVerifyGroupMember" - groupId: number - groupMemberId: number - connectionCode: string -} - -export interface AddContact extends IChatCommand { - type: "addContact" -} - -export interface Connect extends IChatCommand { - type: "connect" - connReq: string -} - -export interface ConnectSimplex extends IChatCommand { - type: "connectSimplex" -} - -export interface CreateMyAddress extends IChatCommand { - type: "createMyAddress" -} - -export interface DeleteMyAddress extends IChatCommand { - type: "deleteMyAddress" -} - -export interface ShowMyAddress extends IChatCommand { - type: "showMyAddress" -} - -export interface SetProfileAddress extends IChatCommand { - type: "setProfileAddress" - includeInProfile: boolean -} - -export interface AddressAutoAccept extends IChatCommand { - type: "addressAutoAccept" - autoAccept?: AutoAccept -} - -export interface APICreateMyAddress extends IChatCommand { - type: "apiCreateMyAddress" - userId: number -} - -export interface APIDeleteMyAddress extends IChatCommand { - type: "apiDeleteMyAddress" - userId: number -} - -export interface APIShowMyAddress extends IChatCommand { - type: "apiShowMyAddress" - userId: number -} - -export interface APISetProfileAddress extends IChatCommand { - type: "apiSetProfileAddress" - userId: number - includeInProfile: boolean -} - -export interface APIAddressAutoAccept extends IChatCommand { - type: "apiAddressAutoAccept" - userId: number - autoAccept?: AutoAccept -} - -export interface AutoAccept { - acceptIncognito: boolean - autoReply?: MsgContent -} - -export interface ReceiveFile extends IChatCommand { - type: "receiveFile" - fileId: number - filePath?: string -} - -export interface CancelFile extends IChatCommand { - type: "cancelFile" - fileId: number -} - -export interface FileStatus extends IChatCommand { - type: "fileStatus" - fileId: number -} - -interface NewUser { - profile?: Profile - sameServers: boolean - pastTimestamp: boolean -} - -export interface Profile { - displayName: string - fullName: string // can be empty string - image?: string - contactLink?: string - // preferences?: Preferences -} - -export interface LocalProfile { - profileId: number - displayName: string - fullName: string - image?: string - contactLink?: string - // preferences?: Preferences - localAlias: string -} - -export enum ChatType { - Direct = "@", - Group = "#", - ContactRequest = "<@", -} - -export type ChatPagination = - | {count: number} // count from the last item in case neither after nor before specified - | {count: number; after: ChatItemId} - | {count: number; before: ChatItemId} - -export type ChatItemId = number - -type MsgContentTag = "text" | "link" | "image" | "file" - -export type MsgContent = MCText | MCLink | MCImage | MCFile | MCUnknown - -interface MC { - type: MsgContentTag - text: string -} - -interface MCText extends MC { - type: "text" - text: string -} - -interface MCLink extends MC { - type: "link" - text: string - preview: LinkPreview -} - -interface MCImage extends MC { - type: "image" - image: string // image preview as base64 encoded data string -} - -interface MCFile extends MC { - type: "file" - text: string -} - -interface MCUnknown { - type: string - text: string -} - -interface LinkPreview { - uri: string - title: string - description: string - image: string -} - -export enum DeleteMode { - Broadcast = "broadcast", - Internal = "internal", -} - -interface ArchiveConfig { - archivePath: string - disableCompression?: boolean - parentTempDirectory?: string -} - -export enum GroupMemberRole { - GRMember = "member", - GRAdmin = "admin", - GROwner = "owner", -} - -interface GroupProfile { - displayName: string - fullName: string // can be empty string - image?: string -} - -export function cmdString(cmd: ChatCommand): string { - switch (cmd.type) { - case "showActiveUser": - return "/u" - case "createActiveUser": { - const user: NewUser = {profile: cmd.profile, sameServers: cmd.sameServers, pastTimestamp: cmd.pastTimestamp} - return `/_create user ${JSON.stringify(user)}` - } - case "listUsers": - return `/users` - case "apiSetActiveUser": - return `/_user ${cmd.userId}${maybeJSON(cmd.viewPwd)}` - case "apiHideUser": - return `/_hide user ${cmd.userId} ${JSON.stringify(cmd.viewPwd)}` - case "apiUnhideUser": - return `/_unhide user ${cmd.userId} ${JSON.stringify(cmd.viewPwd)}` - case "apiMuteUser": - return `/_mute user ${cmd.userId}` - case "apiUnmuteUser": - return `/_unmute user ${cmd.userId}` - case "apiDeleteUser": - return `/_delete user ${cmd.userId} del_smp=${onOff(cmd.delSMPQueues)}${maybeJSON(cmd.viewPwd)}` - case "startChat": - return `/_start subscribe=${cmd.subscribeConnections ? "on" : "off"} expire=${cmd.enableExpireChatItems ? "on" : "off"}` - case "apiStopChat": - return "/_stop" - case "setTempFolder": - return `/_temp_folder ${cmd.tempFolder}` - case "setFilesFolder": - return `/_files_folder ${cmd.filePath}` - case "setIncognito": - return `/incognito ${onOff(cmd.incognito)}` - case "apiExportArchive": - return `/_db export ${JSON.stringify(cmd.config)}` - case "apiImportArchive": - return `/_db import ${JSON.stringify(cmd.config)}` - case "apiDeleteStorage": - return "/_db delete" - case "apiGetChats": - return `/_get chats pcc=${onOff(cmd.pendingConnections)}` - case "apiGetChat": - return `/_get chat ${cmd.chatType}${cmd.chatId}${paginationStr(cmd.pagination)}` - case "apiSendMessage": - return `/_send ${cmd.chatType}${cmd.chatId} json ${JSON.stringify(cmd.messages)}` - case "apiUpdateChatItem": - return `/_update item ${cmd.chatType}${cmd.chatId} ${cmd.chatItemId} json ${JSON.stringify(cmd.msgContent)}` - case "apiDeleteChatItem": - return `/_delete item ${cmd.chatType}${cmd.chatId} ${cmd.chatItemId} ${cmd.deleteMode}` - case "apiDeleteMemberChatItem": - return `/_delete member item #${cmd.groupId} ${cmd.groupMemberId} ${cmd.itemId}` - case "apiChatRead": { - const itemRange = cmd.itemRange ? ` from=${cmd.itemRange.fromItem} to=${cmd.itemRange.toItem}` : "" - return `/_read chat ${cmd.chatType}${cmd.chatId}${itemRange}` - } - case "apiDeleteChat": - return `/_delete ${cmd.chatType}${cmd.chatId}` - case "apiClearChat": - return `/_clear chat ${cmd.chatType}${cmd.chatId}` - case "apiAcceptContact": - return `/_accept ${cmd.contactReqId}` - case "apiRejectContact": - return `/_reject ${cmd.contactReqId}` - case "apiUpdateProfile": - return `/_profile ${cmd.userId} ${JSON.stringify(cmd.profile)}` - case "apiSetContactAlias": - return `/_set alias @${cmd.contactId} ${cmd.localAlias.trim()}` - case "newGroup": - return `/_group ${JSON.stringify(cmd.groupProfile)}` - case "apiAddMember": - return `/_add #${cmd.groupId} ${cmd.contactId} ${cmd.memberRole}` - case "apiJoinGroup": - return `/_join #${cmd.groupId}` - case "apiRemoveMember": - return `/_remove #${cmd.groupId} ${cmd.memberId}` - case "apiLeaveGroup": - return `/_leave #${cmd.groupId}` - case "apiListMembers": - return `/_members #${cmd.groupId}` - case "apiUpdateGroupProfile": - return `/_group_profile #${cmd.groupId} ${JSON.stringify(cmd.groupProfile)}` - case "apiCreateGroupLink": - return `/_create link #${cmd.groupId} ${cmd.memberRole}` - case "apiGroupLinkMemberRole": - return `/_set link role #${cmd.groupId} ${cmd.memberRole}` - case "apiDeleteGroupLink": - return `/_delete link #${cmd.groupId}` - case "apiGetGroupLink": - return `/_get link #${cmd.groupId}` - case "apiGetUserProtoServers": - return `/_servers ${cmd.userId} ${cmd.serverProtocol}` - case "apiSetUserProtoServers": - return `/_servers ${cmd.userId} ${cmd.serverProtocol} ${JSON.stringify({servers: cmd.servers})}` - case "apiContactInfo": - return `/_info @${cmd.contactId}` - case "apiGroupMemberInfo": - return `/_info #${cmd.groupId} ${cmd.memberId}` - case "apiGetContactCode": - return `/_get code @${cmd.contactId}` - case "apiGetGroupMemberCode": - return `/_get code #${cmd.groupId} ${cmd.groupMemberId}` - case "apiVerifyContact": - return `/_verify code @${cmd.contactId}${maybe(cmd.connectionCode)}` - case "apiVerifyGroupMember": - return `/_verify code #${cmd.groupId} ${cmd.groupMemberId}${maybe(cmd.connectionCode)}` - case "addContact": - return "/connect" - case "connect": - return `/connect ${cmd.connReq}` - case "connectSimplex": - return "/simplex" - case "createMyAddress": - return "/address" - case "deleteMyAddress": - return "/delete_address" - case "showMyAddress": - return "/show_address" - case "setProfileAddress": - return `/profile_address ${onOff(cmd.includeInProfile)}` - case "addressAutoAccept": - return `/auto_accept ${autoAcceptStr(cmd.autoAccept)}` - case "apiCreateMyAddress": - return `/_address ${cmd.userId}` - case "apiDeleteMyAddress": - return `/_delete_address ${cmd.userId}` - case "apiShowMyAddress": - return `/_show_address ${cmd.userId}` - case "apiSetProfileAddress": - return `/_profile_address ${cmd.userId} ${onOff(cmd.includeInProfile)}` - case "apiAddressAutoAccept": - return `/_auto_accept ${cmd.userId} ${autoAcceptStr(cmd.autoAccept)}` - case "receiveFile": - return `/freceive ${cmd.fileId}${cmd.filePath ? " " + cmd.filePath : ""}` - case "cancelFile": - return `/fcancel ${cmd.fileId}` - case "fileStatus": - return `/fstatus ${cmd.fileId}` - } -} - -function paginationStr(cp: ChatPagination): string { - const base = "after" in cp ? ` after=${cp.after}` : "before" in cp ? ` before=${cp.before}` : "" - return base + ` count=${cp.count}` -} - -function maybe(value: T | undefined): string { - return value ? ` ${value}` : "" -} - -function maybeJSON(value: T | undefined): string { - return value ? ` json ${JSON.stringify(value)}` : "" -} - -function onOff(value: T | undefined): string { - return value ? "on" : "off" -} - -function autoAcceptStr(autoAccept: AutoAccept | undefined): string { - if (!autoAccept) return "off" - const msg = autoAccept.autoReply - return "on" + (autoAccept.acceptIncognito ? " incognito=on" : "") + (msg ? " json " + JSON.stringify(msg) : "") -} diff --git a/packages/simplex-chat-client/typescript/src/response.ts b/packages/simplex-chat-client/typescript/src/response.ts deleted file mode 100644 index 95eac89249..0000000000 --- a/packages/simplex-chat-client/typescript/src/response.ts +++ /dev/null @@ -1,1109 +0,0 @@ -import {ChatItemId, MsgContent, DeleteMode, Profile, GroupMemberRole, LocalProfile, ServerProtocol, ServerCfg} from "./command" - -export type ChatResponse = - | CRActiveUser - | CRUsersList - | CRChatStarted - | CRChatRunning - | CRChatStopped - | CRApiChats - | CRApiChat - | CRApiParsedMarkdown - | CRUserProtoServers - | CRContactInfo - | CRGroupMemberInfo - | CRNewChatItems - | CRChatItemStatusUpdated - | CRChatItemUpdated - | CRChatItemDeleted - | CRMsgIntegrityError - | CRCmdOk - | CRUserContactLink - | CRUserContactLinkUpdated - | CRContactRequestRejected - | CRUserProfile - | CRUserProfileNoChange - | CRUserProfileUpdated - | CRContactAliasUpdated - | CRInvitation - | CRSentConfirmation - | CRSentInvitation - | CRContactUpdated - | CRContactsMerged - | CRContactDeleted - | CRChatCleared - | CRUserContactLinkCreated - | CRUserContactLinkDeleted - | CRReceivedContactRequest - | CRAcceptingContactRequest - | CRContactAlreadyExists - | CRContactRequestAlreadyAccepted - | CRContactConnecting - | CRContactConnected - | CRContactAnotherClient - | CRContactSubError - | CRContactSubSummary - | CRContactsDisconnected - | CRContactsSubscribed - | CRHostConnected - | CRHostDisconnected - | CRGroupEmpty - | CRMemberSubError - | CRMemberSubSummary - | CRGroupSubscribed - | CRRcvFileAccepted - | CRRcvFileAcceptedSndCancelled - | CRRcvFileStart - | CRRcvFileComplete - | CRRcvFileCancelled - | CRRcvFileSndCancelled - | CRSndFileStart - | CRSndFileComplete - | CRSndFileCancelled - | CRSndFileRcvCancelled - | CRSndGroupFileCancelled - | CRSndFileSubError - | CRRcvFileSubError - | CRPendingSubSummary - | CRGroupCreated - | CRGroupMembers - | CRUserAcceptedGroupSent - | CRUserDeletedMember - | CRSentGroupInvitation - | CRLeftMemberUser - | CRGroupDeletedUser - | CRGroupInvitation - | CRReceivedGroupInvitation - | CRUserJoinedGroup - | CRJoinedGroupMember - | CRJoinedGroupMemberConnecting - | CRConnectedToGroupMember - | CRDeletedMember - | CRDeletedMemberUser - | CRLeftMember - | CRGroupRemoved - | CRGroupDeleted - | CRGroupUpdated - | CRUserContactLinkSubError - | CRContactConnectionDeleted - | CRMessageError - | CRChatCmdError - | CRChatError - -// not included -// CRChatItemDeletedNotFound -// CRBroadcastSent -// CRGroupsList -// CRFileTransferStatus - -type ChatResponseTag = - | "activeUser" - | "usersList" - | "chatStarted" - | "chatRunning" - | "chatStopped" - | "apiChats" - | "apiChat" - | "apiParsedMarkdown" - | "userProtoServers" - | "contactInfo" - | "groupMemberInfo" - | "newChatItems" - | "chatItemStatusUpdated" - | "chatItemUpdated" - | "chatItemDeleted" - | "msgIntegrityError" - | "cmdOk" - | "userContactLink" - | "userContactLinkUpdated" - | "userContactLinkCreated" - | "userContactLinkDeleted" - | "contactRequestRejected" - | "userProfile" - | "userProfileNoChange" - | "userProfileUpdated" - | "contactAliasUpdated" - | "invitation" - | "sentConfirmation" - | "sentInvitation" - | "contactUpdated" - | "contactsMerged" - | "contactDeleted" - | "chatCleared" - | "receivedContactRequest" - | "acceptingContactRequest" - | "contactAlreadyExists" - | "contactRequestAlreadyAccepted" - | "contactConnecting" - | "contactConnected" - | "contactAnotherClient" - | "contactSubError" - | "contactSubSummary" - | "contactsDisconnected" - | "contactsSubscribed" - | "hostConnected" - | "hostDisconnected" - | "groupEmpty" - | "memberSubError" - | "memberSubSummary" - | "groupSubscribed" - | "rcvFileAccepted" - | "rcvFileAcceptedSndCancelled" - | "rcvFileStart" - | "rcvFileComplete" - | "rcvFileCancelled" - | "rcvFileSndCancelled" - | "sndFileStart" - | "sndFileComplete" - | "sndFileCancelled" - | "sndFileRcvCancelled" - | "sndGroupFileCancelled" - | "fileTransferStatus" - | "sndFileSubError" - | "rcvFileSubError" - | "pendingSubSummary" - | "groupCreated" - | "groupMembers" - | "userAcceptedGroupSent" - | "userDeletedMember" - | "sentGroupInvitation" - | "leftMemberUser" - | "groupDeletedUser" - | "groupInvitation" - | "receivedGroupInvitation" - | "userJoinedGroup" - | "joinedGroupMember" - | "joinedGroupMemberConnecting" - | "connectedToGroupMember" - | "deletedMember" - | "deletedMemberUser" - | "leftMember" - | "groupRemoved" - | "groupDeleted" - | "groupUpdated" - | "userContactLinkSubError" - | "newContactConnection" - | "contactConnectionDeleted" - | "messageError" - | "chatCmdError" - | "chatError" - -interface CR { - type: ChatResponseTag -} - -export interface CRActiveUser extends CR { - type: "activeUser" - user: User -} - -export interface CRUsersList extends CR { - type: "usersList" - users: UserInfo[] -} - -export interface CRChatStarted extends CR { - type: "chatStarted" -} - -export interface CRChatRunning extends CR { - type: "chatRunning" -} - -export interface CRChatStopped extends CR { - type: "chatStopped" -} - -export interface CRApiChats extends CR { - type: "apiChats" - user: User - chats: Chat[] -} - -export interface CRApiChat extends CR { - type: "apiChat" - user: User - chat: Chat -} - -export interface CRApiParsedMarkdown extends CR { - type: "apiParsedMarkdown" - formattedText?: FormattedText[] -} - -export interface CRUserProtoServers extends CR { - type: "userProtoServers" - user: User - servers: UserProtoServers -} - -export interface CRContactInfo extends CR { - type: "contactInfo" - user: User - contact: Contact - connectionStats: ConnectionStats - customUserProfile?: Profile -} - -export interface CRGroupMemberInfo extends CR { - type: "groupMemberInfo" - user: User - groupInfo: GroupInfo - member: GroupMember - connectionStats_?: ConnectionStats -} - -export interface CRNewChatItems extends CR { - type: "newChatItems" - user: User - chatItems: AChatItem[] -} - -export interface CRChatItemStatusUpdated extends CR { - type: "chatItemStatusUpdated" - user: User - chatItem: AChatItem -} - -export interface CRChatItemUpdated extends CR { - type: "chatItemUpdated" - user: User - chatItem: AChatItem -} - -export interface CRChatItemDeleted extends CR { - type: "chatItemDeleted" - user: User - deletedChatItem: AChatItem - toChatItem?: AChatItem - byUser: boolean -} - -export interface CRMsgIntegrityError extends CR { - type: "msgIntegrityError" - user: User - msgError: MsgErrorType -} - -export interface CRCmdOk extends CR { - type: "cmdOk" - user_?: User -} - -export interface CRUserContactLink extends CR { - type: "userContactLink" - user: User - contactLink: UserContactLink -} - -export interface CRUserContactLinkUpdated extends CR { - type: "userContactLinkUpdated" - user: User - contactLink: UserContactLink -} - -export interface CRContactRequestRejected extends CR { - type: "contactRequestRejected" - user: User - contactRequest: UserContactRequest -} - -export interface CRUserProfile extends CR { - type: "userProfile" - user: User - profile: Profile -} - -export interface CRUserProfileNoChange extends CR { - type: "userProfileNoChange" - user: User -} - -export interface CRUserProfileUpdated extends CR { - type: "userProfileUpdated" - user: User - fromProfile: Profile - toProfile: Profile -} - -export interface CRContactAliasUpdated extends CR { - type: "contactAliasUpdated" - user: User - toContact: Contact -} - -export interface CRInvitation extends CR { - type: "invitation" - user: User - connLinkInvitation: CreatedConnLink -} - -export interface CRSentConfirmation extends CR { - type: "sentConfirmation" - user: User -} - -export interface CRSentInvitation extends CR { - type: "sentInvitation" - user: User -} - -export interface CRContactUpdated extends CR { - type: "contactUpdated" - user: User - fromContact: Contact - toContact: Contact -} - -export interface CRContactsMerged extends CR { - type: "contactsMerged" - user: User - intoContact: Contact - mergedContact: Contact -} - -export interface CRContactDeleted extends CR { - type: "contactDeleted" - user: User - contact: Contact -} - -export interface CRChatCleared extends CR { - type: "chatCleared" - user: User - chatInfo: ChatInfo -} - -export interface CRUserContactLinkCreated extends CR { - type: "userContactLinkCreated" - user: User - connLinkContact: CreatedConnLink -} - -export interface CRUserContactLinkDeleted extends CR { - type: "userContactLinkDeleted" - user: User -} - -export interface CRReceivedContactRequest extends CR { - type: "receivedContactRequest" - user: User - contactRequest: UserContactRequest -} - -export interface CRAcceptingContactRequest extends CR { - type: "acceptingContactRequest" - user: User - contact: Contact -} - -export interface CRContactAlreadyExists extends CR { - type: "contactAlreadyExists" - user: User - contact: Contact -} - -export interface CRContactRequestAlreadyAccepted extends CR { - type: "contactRequestAlreadyAccepted" - user: User - contact: Contact -} - -export interface CRContactConnecting extends CR { - type: "contactConnecting" - user: User - contact: Contact -} - -export interface CRContactConnected extends CR { - type: "contactConnected" - contact: Contact - user: User - userCustomProfile?: Profile -} - -export interface CRContactAnotherClient extends CR { - type: "contactAnotherClient" - user: User - contact: Contact -} - -export interface CRContactSubError extends CR { - type: "contactSubError" - user: User - contact: Contact - chatError: ChatError -} - -export interface CRContactSubSummary extends CR { - type: "contactSubSummary" - user: User - contactSubscriptions: ContactSubStatus[] -} - -export interface CRContactsDisconnected extends CR { - type: "contactsDisconnected" - user: User - server: string - contactRefs: ContactRef[] -} - -export interface CRContactsSubscribed extends CR { - type: "contactsSubscribed" - user: User - server: string - contactRefs: ContactRef[] -} - -export interface CRHostConnected extends CR { - type: "hostConnected" - protocol: string - transportHost: string -} - -export interface CRHostDisconnected extends CR { - type: "hostDisconnected" - protocol: string - transportHost: string -} - -export interface CRGroupEmpty extends CR { - type: "groupEmpty" - user: User - groupInfo: GroupInfo -} - -export interface CRMemberSubError extends CR { - type: "memberSubError" - user: User - groupInfo: GroupInfo - member: GroupMember - chatError: ChatError -} - -export interface CRMemberSubSummary extends CR { - type: "memberSubSummary" - user: User - memberSubscriptions: MemberSubStatus[] -} - -export interface CRGroupSubscribed extends CR { - type: "groupSubscribed" - user: User - groupInfo: GroupInfo -} - -export interface CRRcvFileAccepted extends CR { - type: "rcvFileAccepted" - user: User - chatItem: AChatItem -} - -export interface CRRcvFileAcceptedSndCancelled extends CR { - type: "rcvFileAcceptedSndCancelled" - user: User - rcvFileTransfer: RcvFileTransfer -} - -export interface CRRcvFileStart extends CR { - type: "rcvFileStart" - user: User - chatItem: AChatItem -} - -export interface CRRcvFileComplete extends CR { - type: "rcvFileComplete" - user: User - chatItem: AChatItem -} - -export interface CRRcvFileCancelled extends CR { - type: "rcvFileCancelled" - user: User - rcvFileTransfer: RcvFileTransfer -} - -export interface CRRcvFileSndCancelled extends CR { - type: "rcvFileSndCancelled" - user: User - rcvFileTransfer: RcvFileTransfer -} - -export interface CRSndFileStart extends CR { - type: "sndFileStart" - user: User - chatItem: AChatItem - sndFileTransfer: SndFileTransfer -} - -export interface CRSndFileComplete extends CR { - type: "sndFileComplete" - user: User - chatItem: AChatItem - sndFileTransfer: SndFileTransfer -} - -export interface CRSndFileCancelled extends CR { - type: "sndFileCancelled" - user: User - chatItem: AChatItem - sndFileTransfer: SndFileTransfer -} - -export interface CRSndFileRcvCancelled extends CR { - type: "sndFileRcvCancelled" - user: User - chatItem: AChatItem - sndFileTransfer: SndFileTransfer -} - -export interface CRSndGroupFileCancelled extends CR { - type: "sndGroupFileCancelled" - user: User - chatItem: AChatItem - fileTransferMeta: FileTransferMeta - sndFileTransfers: SndFileTransfer[] -} - -export interface CRSndFileSubError extends CR { - type: "sndFileSubError" - user: User - sndFileTransfer: SndFileTransfer - chatError: ChatError -} - -export interface CRRcvFileSubError extends CR { - type: "rcvFileSubError" - user: User - rcvFileTransfer: RcvFileTransfer - chatError: ChatError -} - -export interface CRPendingSubSummary extends CR { - type: "pendingSubSummary" - user: User - pendingSubStatus: PendingSubStatus[] -} - -export interface CRGroupCreated extends CR { - type: "groupCreated" - user: User - groupInfo: GroupInfo -} - -export interface CRGroupMembers extends CR { - type: "groupMembers" - user: User - group: Group -} - -export interface CRUserAcceptedGroupSent extends CR { - type: "userAcceptedGroupSent" - user: User - groupInfo: GroupInfo - hostContact?: Contact // included when joining group via group link -} - -export interface CRUserDeletedMember extends CR { - type: "userDeletedMember" - user: User - groupInfo: GroupInfo - member: GroupMember -} - -export interface CRSentGroupInvitation extends CR { - type: "sentGroupInvitation" - user: User - groupInfo: GroupInfo - contact: Contact - member: GroupMember -} - -export interface CRLeftMemberUser extends CR { - type: "leftMemberUser" - user: User - groupInfo: GroupInfo -} - -export interface CRGroupDeletedUser extends CR { - type: "groupDeletedUser" - user: User - groupInfo: GroupInfo -} - -export interface CRGroupInvitation extends CR { - type: "groupInvitation" - user: User - groupInfo: GroupInfo -} - -export interface CRReceivedGroupInvitation extends CR { - type: "receivedGroupInvitation" - user: User - groupInfo: GroupInfo - contact: Contact - memberRole: GroupMemberRole -} - -export interface CRUserJoinedGroup extends CR { - type: "userJoinedGroup" - user: User - groupInfo: GroupInfo - hostMember: GroupMember -} - -export interface CRJoinedGroupMember extends CR { - type: "joinedGroupMember" - user: User - groupInfo: GroupInfo - member: GroupMember -} - -export interface CRJoinedGroupMemberConnecting extends CR { - type: "joinedGroupMemberConnecting" - user: User - groupInfo: GroupInfo - hostMember: GroupMember - member: GroupMember -} - -export interface CRConnectedToGroupMember extends CR { - type: "connectedToGroupMember" - user: User - groupInfo: GroupInfo - member: GroupMember -} - -export interface CRDeletedMember extends CR { - type: "deletedMember" - user: User - groupInfo: GroupInfo - byMember: GroupMember - deletedMember: GroupMember -} - -export interface CRDeletedMemberUser extends CR { - type: "deletedMemberUser" - user: User - groupInfo: GroupInfo - member: GroupMember -} - -export interface CRLeftMember extends CR { - type: "leftMember" - user: User - groupInfo: GroupInfo - member: GroupMember -} - -export interface CRGroupRemoved extends CR { - type: "groupRemoved" - user: User - groupInfo: GroupInfo -} - -export interface CRGroupDeleted extends CR { - type: "groupDeleted" - user: User - groupInfo: GroupInfo - member: GroupMember -} - -export interface CRGroupUpdated extends CR { - type: "groupUpdated" - user: User - fromGroup: GroupInfo - toGroup: GroupInfo - member_?: GroupMember -} - -export interface CRUserContactLinkSubError extends CR { - type: "userContactLinkSubError" - chatError: ChatError -} - -export interface CRContactConnectionDeleted extends CR { - type: "contactConnectionDeleted" - user: User - connection: PendingContactConnection -} - -export interface CRMessageError extends CR { - type: "messageError" - user: User - severity: string - errorMessage: string -} - -export interface CRChatCmdError extends CR { - type: "chatCmdError" - user_?: User - chatError: ChatError -} - -export interface CRChatError extends CR { - type: "chatError" - user_?: User - chatError: ChatError -} - -export interface User { - userId: number - agentUserId: string - userContactId: number - localDisplayName: string - profile: LocalProfile - // fullPreferences :: FullPreferences - activeUser: boolean - viewPwdHash: string - showNtfs: boolean -} - -export interface UserProtoServers { - serverProtocol: ServerProtocol - protoServers: ServerCfg[] - presetServers: string -} - -export interface Chat { - chatInfo: ChatInfo - chatItems: [ChatItem] - chatStats: ChatStats -} - -export type ChatInfo = CInfoDirect | CInfoGroup | CInfoContactRequest - -export enum ChatInfoType { - Direct = "direct", - Group = "group", - ContactRequest = "contactRequest", -} - -interface IChatInfo { - type: ChatInfoType -} - -interface CInfoDirect extends IChatInfo { - type: ChatInfoType.Direct - contact: Contact -} - -interface CInfoGroup extends IChatInfo { - type: ChatInfoType.Group - groupInfo: GroupInfo -} - -interface CInfoContactRequest extends IChatInfo { - type: ChatInfoType.ContactRequest - contactRequest: UserContactRequest -} - -export interface UserPwdHash { - hash: string - salt: string -} - -interface UserInfo { - user: User - unreadCount: number -} - -export interface Contact { - contactId: number - localDisplayName: string - profile: Profile - activeConn: Connection - viaGroup?: number - createdAt: Date -} - -export interface ContactRef { - contactId: number - localDisplayName: string -} - -export interface Group { - groupInfo: GroupInfo - members: GroupMember[] -} - -export interface GroupInfo { - groupId: number - localDisplayName: string - groupProfile: GroupProfile - membership: GroupMember - createdAt: Date -} - -export interface GroupProfile { - displayName: string - fullName: string - image?: string // web-compatible data/base64 string for the image -} - -export interface GroupMember { - groupMemberId: number - memberId: string - memberRole: GroupMemberRole - // memberCategory: GroupMemberCategory - // memberStatus: GroupMemberStatus - // invitedBy: InvitedBy - localDisplayName: string - memberProfile: Profile - memberContactId?: number - activeConn?: Connection -} - -export interface UserContactRequest { - contactRequestId: number - localDisplayName: string - profile: Profile - createdAt: Date -} - -interface Connection { - connId: number -} - -export interface AChatItem { - chatInfo: ChatInfo - chatItem: ChatItem -} - -export interface ChatItem { - chatDir: CIDirection - meta: CIMeta - content: CIContent - formattedText?: FormattedText[] - quotedItem?: CIQuote -} - -export type CIDirection = CIDirectSnd | CIDirectRcv | CIGroupSnd | CIGroupRcv - -interface ICIDirection { - type: "directSnd" | "directRcv" | "groupSnd" | "groupRcv" -} - -interface CIDirectSnd extends ICIDirection { - type: "directSnd" -} - -interface CIDirectRcv extends ICIDirection { - type: "directRcv" -} - -interface CIGroupSnd extends ICIDirection { - type: "groupSnd" -} - -interface CIGroupRcv extends ICIDirection { - type: "groupRcv" - groupMember: GroupMember -} - -export interface CIMeta { - itemId: ChatItemId - itemTs: Date - itemText: string - itemStatus: CIStatus - createdAt: Date - itemDeleted: boolean - itemEdited: boolean - editable: boolean -} - -export type CIContent = CISndMsgContent | CIRcvMsgContent | CISndDeleted | CIRcvDeleted | CISndFileInvitation | CIRcvFileInvitation - -interface ICIContent { - type: "sndMsgContent" | "rcvMsgContent" | "sndDeleted" | "rcvDeleted" | "sndFileInvitation" | "rcvFileInvitation" -} - -interface CISndMsgContent extends ICIContent { - type: "sndMsgContent" - msgContent: MsgContent -} - -interface CIRcvMsgContent extends ICIContent { - type: "rcvMsgContent" - msgContent: MsgContent -} - -interface CISndDeleted extends ICIContent { - type: "sndDeleted" - deleteMode: DeleteMode -} - -interface CIRcvDeleted extends ICIContent { - type: "rcvDeleted" - deleteMode: DeleteMode -} - -interface CISndFileInvitation extends ICIContent { - type: "sndFileInvitation" - fileId: number - filePath: string -} - -interface CIRcvFileInvitation extends ICIContent { - type: "rcvFileInvitation" - rcvFileTransfer: RcvFileTransfer -} - -export function ciContentText(content: CIContent): string | undefined { - switch (content.type) { - case "sndMsgContent": - return content.msgContent.text - case "rcvMsgContent": - return content.msgContent.text - default: - return undefined - } -} - -interface RcvFileTransfer { - fileId: number - // fileInvitation: FileInvitation - // fileStatus: RcvFileStatus - senderDisplayName: string - chunkSize: number - cancelled: boolean - grpMemberId?: number -} - -interface SndFileTransfer { - fileId: number - fileName: string - filePath: string - fileSize: number - chunkSize: number - recipientDisplayName: string - connId: number - // agentConnId: string - // fileStatus: FileStatus -} - -interface FileTransferMeta { - fileId: number - fileName: string - filePath: string - fileSize: number - chunkSize: number - cancelled: boolean -} - -interface UserContactLink { - connLinkContact: CreatedConnLink - autoAccept?: AutoAccept -} - -interface CreatedConnLink { - connFullLink: string - connShortLink?: string -} - -interface AutoAccept { - acceptIncognito: boolean - autoReply?: MsgContent -} - -export interface ChatStats { - unreadCount: number - minUnreadItemId: number -} - -export interface CIQuote { - chatDir?: CIDirection - itemId?: number - sharedMsgId?: string - sentAt: Date - content: MsgContent - formattedText?: FormattedText[] -} - -export type CIStatus = CISndNew | CISndSent | CISndErrorAuth | CISndError | CIRcvNew | CIRcvRead - -interface ICIStatus { - type: "sndNew" | "sndSent" | "sndErrorAuth" | "sndError" | "rcvNew" | "rcvRead" -} - -interface CISndNew extends ICIStatus { - type: "sndNew" -} - -interface CISndSent extends ICIStatus { - type: "sndSent" -} - -interface CISndErrorAuth extends ICIStatus { - type: "sndErrorAuth" -} - -interface CISndError extends ICIStatus { - type: "sndError" - agentError: AgentErrorType -} - -interface CIRcvNew extends ICIStatus { - type: "rcvNew" -} - -interface CIRcvRead extends ICIStatus { - type: "rcvRead" -} - -interface FormattedText {} - -interface MsgErrorType {} - -export type ChatError = ChatErrorChat | ChatErrorAgent | ChatErrorStore - -interface ChatErrorChat { - type: "error" - errorType: ChatErrorType -} - -interface ChatErrorAgent { - type: "errorAgent" - agentError: AgentErrorType -} - -interface ChatErrorStore { - type: "errorStore" - storeError: StoreErrorType -} - -type ChatErrorType = CENoActiveUser | CEActiveUserExists - -interface CENoActiveUser { - type: "noActiveUser" -} - -interface CEActiveUserExists { - type: "activeUserExists" -} - -interface ContactSubStatus {} - -interface PendingSubStatus {} - -export interface ConnectionStats { - rcvServers?: string[] - sndServers?: string[] -} - -interface PendingContactConnection {} - -interface MemberSubStatus { - member: GroupMember - memberError?: ChatError -} - -interface AgentErrorType { - type: string - [x: string]: any -} - -interface StoreErrorType { - type: string - [x: string]: any -} diff --git a/packages/simplex-chat-client/typescript/src/transport.ts b/packages/simplex-chat-client/typescript/src/transport.ts index 7ac4673ca1..aad3f39579 100644 --- a/packages/simplex-chat-client/typescript/src/transport.ts +++ b/packages/simplex-chat-client/typescript/src/transport.ts @@ -1,5 +1,5 @@ import {ABQueue, NextIter} from "./queue" -import {ChatResponse} from "./response" +import {ChatResponse, ChatEvent} from "@simplex-chat/types" export class TransportError extends Error {} @@ -90,13 +90,17 @@ export interface ChatSrvRequest { } export interface ChatSrvResponse { - corrId?: string + corrId: string resp: ChatResponse } +export interface ChatSrvEvent { + resp: ChatEvent +} + interface ParsedChatSrvResponse { corrId?: string - resp?: ChatResponse + resp?: ChatResponse | ChatEvent } export class ChatResponseError extends Error { @@ -105,7 +109,7 @@ export class ChatResponseError extends Error { } } -export class ChatTransport extends Transport { +export class ChatTransport extends Transport { private constructor(private readonly ws: WSTransport, readonly timeout: number, qSize: number) { super(qSize) } diff --git a/packages/simplex-chat-client/typescript/tests/client.test.ts b/packages/simplex-chat-client/typescript/tests/client.test.ts index eef57558f2..77dca8fa5a 100644 --- a/packages/simplex-chat-client/typescript/tests/client.test.ts +++ b/packages/simplex-chat-client/typescript/tests/client.test.ts @@ -1,42 +1,43 @@ import * as assert from "assert" import {ChatClient} from "../src/index" import {ConnReqType} from "../src/client" -import * as CC from "../src/command" -import * as CR from "../src/response" +import {ChatEvent, CEvt, T} from "@simplex-chat/types" +// This test is currently failing - it gets as far as starting connection. +// It has to be written differently, with event loop to only process "interesting" events, as some events may arrive in different order. describe.skip("ChatClient (expects SimpleX Chat server with a user, without contacts, on localhost:5225)", () => { test("connect, send message to themselves, delete contact", async () => { const c = await ChatClient.create("ws://localhost:5225") assert.strictEqual((await c.msgQ.dequeue()).type, "contactSubSummary") - assert.strictEqual((await c.msgQ.dequeue()).type, "memberSubErrors") - assert.strictEqual((await c.msgQ.dequeue()).type, "pendingSubSummary") + assert.strictEqual((await c.msgQ.dequeue()).type, "userContactSubSummary") + assert.strictEqual((await c.msgQ.dequeue()).type, "terminalEvent") + assert.strictEqual((await c.msgQ.dequeue()).type, "terminalEvent") const user = await c.apiGetActiveUser() assert.strictEqual(typeof user?.localDisplayName, "string") - const connReq = await c.apiCreateLink() + const connReq = await c.apiCreateLink(user!.userId) + console.log("created link") assert.strictEqual(typeof connReq, "string") - assert.strictEqual((await c.msgQ.dequeue()).type, "newContactConnection") // TODO add to response types - const connReqType = await c.apiConnect(connReq) - assert.strictEqual((await c.msgQ.dequeue()).type, "newContactConnection") // TODO add to response types - assert((await c.msgQ.dequeue()).type === "contactConnecting") - assert((await c.msgQ.dequeue()).type === "contactConnecting") + const connReqType = await c.apiConnectActiveUser(connReq) + assert.strictEqual((await c.msgQ.dequeue()).type, "contactConnecting") + assert.strictEqual((await c.msgQ.dequeue()).type, "contactConnected") assert(connReqType === ConnReqType.Invitation || connReqType === ConnReqType.Contact) const r1 = await c.msgQ.dequeue() const r2 = await c.msgQ.dequeue() - assert(r1.type === "contactConnected") - assert(r2.type === "contactConnected") - const contact1 = (r1 as CR.CRContactConnected).contact + assert.strictEqual(r1.type, "contactConnecting") + assert.strictEqual(r2.type, "contactConnected") + const contact1 = (r1 as CEvt.ContactConnected).contact // const contact2 = (r2 as C.CRContactConnected).contact - const r3 = await c.apiSendTextMessage(CC.ChatType.Direct, contact1.contactId, "hello") + const r3 = await c.apiSendTextMessage(T.ChatType.Direct, contact1.contactId, "hello") assert(r3[0].chatItem.content.type === "sndMsgContent" && r3[0].chatItem.content.msgContent.text === "hello") const r4 = await c.msgQ.dequeue() assert(isItemSent(r4) || isNewRcvItem(r4)) await c.disconnect() - function isItemSent(r: CR.ChatResponse): boolean { - return r.type === "chatItemStatusUpdated" && r.chatItem.chatItem.meta.itemStatus.type === "sndSent" + function isItemSent(r: ChatEvent): boolean { + return r.type === "chatItemsStatusesUpdated" && r.chatItems[0].chatItem.meta.itemStatus.type === "sndSent" } - function isNewRcvItem(r: CR.ChatResponse): boolean { + function isNewRcvItem(r: ChatEvent): boolean { return ( r.type === "newChatItems" && r.chatItems[0].chatItem.content.type === "rcvMsgContent" && diff --git a/simplex-chat.cabal b/simplex-chat.cabal index 9b9c5a9581..b2bc988d79 100644 --- a/simplex-chat.cabal +++ b/simplex-chat.cabal @@ -524,6 +524,7 @@ test-suite simplex-chat-test API.Docs.Commands API.Docs.Events API.Docs.Generate + API.Docs.Generate.TypeScript API.Docs.Responses API.Docs.Syntax API.Docs.Syntax.Types diff --git a/src/Simplex/Chat/Controller.hs b/src/Simplex/Chat/Controller.hs index 998d7542b3..53d3839f42 100644 --- a/src/Simplex/Chat/Controller.hs +++ b/src/Simplex/Chat/Controller.hs @@ -460,8 +460,8 @@ data ChatCommand | APIChangePreparedGroupUser GroupId UserId | APIConnectPreparedContact {contactId :: ContactId, incognito :: IncognitoEnabled, msgContent_ :: Maybe MsgContent} | APIConnectPreparedGroup GroupId IncognitoEnabled (Maybe MsgContent) - | APIConnect {userId :: UserId, incognito :: IncognitoEnabled, connLink_ :: Maybe ACreatedConnLink} -- Maybe is used to report link parsing failure as special error - | Connect IncognitoEnabled (Maybe AConnectionLink) + | APIConnect {userId :: UserId, incognito :: IncognitoEnabled, preparedLink_ :: Maybe ACreatedConnLink} -- Maybe is used to report link parsing failure as special error + | Connect {incognito :: IncognitoEnabled, connLink_ :: Maybe AConnectionLink} | APIConnectContactViaAddress UserId IncognitoEnabled ContactId | ConnectSimplex IncognitoEnabled -- UserId (not used in UI) | DeleteContact ContactName ChatDeleteMode diff --git a/tests/APIDocs.hs b/tests/APIDocs.hs index 51261f6fe5..aa9cc8459f 100644 --- a/tests/APIDocs.hs +++ b/tests/APIDocs.hs @@ -8,6 +8,7 @@ module APIDocs where import API.Docs.Commands import API.Docs.Events import API.Docs.Generate +import qualified API.Docs.Generate.TypeScript as TS import API.Docs.Responses import API.Docs.Types import API.TypeInfo @@ -15,6 +16,7 @@ import Control.Monad import Data.Containers.ListUtils (nubOrd) import Data.List (foldl', intercalate, sort, (\\)) import qualified Data.Set as S +import qualified Data.Text as T import qualified Data.Text.IO as T import Simplex.Messaging.Util (ifM) import System.Directory (doesFileExist) @@ -26,15 +28,20 @@ apiDocsTest = do it "should be documented" testCommandsHaveDocs it "should have field names" testCommandsHaveNamedFields it "should have defined responses" testCommandsHaveResponses - it "generate markdown" testGenerateCommandsMD + it "generate markdown" $ testGenerate commandsDocFile commandsDocText describe "API responses" $ do it "should be documented" testResponsesHaveDocs describe "API events" $ do it "should be documented" testEventsHaveDocs - it "generate markdown" testGenerateEventsMD + it "generate markdown" $ testGenerate eventsDocFile eventsDocText describe "API types" $ do it "should be documented" testTypesHaveDocs - it "generate markdown" testGenerateTypesMD + it "generate markdown" $ testGenerate typesDocFile typesDocText + describe "TypeScript" $ do + it "generate typescript commands code" $ testGenerate TS.commandsCodeFile TS.commandsCodeText + it "generate typescript responses code" $ testGenerate TS.responsesCodeFile TS.responsesCodeText + it "generate typescript events code" $ testGenerate TS.eventsCodeFile TS.eventsCodeText + it "generate typescript types code" $ testGenerate TS.typesCodeFile TS.typesCodeText documentedCmds :: [String] documentedCmds = concatMap (map consName' . commands) chatCommandsDocs @@ -137,20 +144,8 @@ testCommandsHaveResponses = do unless (null undocResps) $ expectationFailure $ "Undocumented command responses: " <> intercalate ", " undocResps unless (null extraResps) $ expectationFailure $ "Unused documented command responses: " <> intercalate ", " extraResps -testGenerateCommandsMD :: IO () -testGenerateCommandsMD = do - cmdsDoc <- ifM (doesFileExist commandsDocFile) (T.readFile commandsDocFile) (pure "") - T.writeFile commandsDocFile commandsDocText - commandsDocText `shouldBe` cmdsDoc - -testGenerateEventsMD :: IO () -testGenerateEventsMD = do - evtsDoc <- ifM (doesFileExist eventsDocFile) (T.readFile eventsDocFile) (pure "") - T.writeFile eventsDocFile eventsDocText - eventsDocText `shouldBe` evtsDoc - -testGenerateTypesMD :: IO () -testGenerateTypesMD = do - typesDoc <- ifM (doesFileExist typesDocFile) (T.readFile typesDocFile) (pure "") - T.writeFile typesDocFile typesDocText - typesDocText `shouldBe` typesDoc +testGenerate :: FilePath -> T.Text -> IO () +testGenerate file text = do + current <- ifM (doesFileExist file) (T.readFile file) (pure "") + T.writeFile file text + text `shouldBe` current