@devanachat/sdk 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/LICENSE +21 -0
  3. package/README.md +391 -2
  4. package/build/index.cjs.js +3559 -0
  5. package/build/index.cjs.js.map +1 -0
  6. package/build/index.mjs +3517 -0
  7. package/build/index.mjs.map +1 -0
  8. package/build/index.umd.js +2 -0
  9. package/build/index.umd.js.map +1 -0
  10. package/build/types/AbstractChatClient.d.ts +182 -0
  11. package/build/types/AbstractRestClient.d.ts +21 -0
  12. package/build/types/EventTarget.d.ts +32 -0
  13. package/build/types/FilesClient.d.ts +16 -0
  14. package/build/types/IndexedObjectCollection.d.ts +66 -0
  15. package/build/types/Permissions.d.ts +109 -0
  16. package/build/types/WebApiChatClient.d.ts +38 -0
  17. package/build/types/WebSocketChatClient.d.ts +110 -0
  18. package/build/types/index.d.ts +19 -0
  19. package/build/types/protocol/index.d.ts +163 -0
  20. package/build/types/protocol/schemes/BanObject.d.ts +14 -0
  21. package/build/types/protocol/schemes/ChatLocation.d.ts +5 -0
  22. package/build/types/protocol/schemes/Emoticon.d.ts +9 -0
  23. package/build/types/protocol/schemes/Entitlements.d.ts +92 -0
  24. package/build/types/protocol/schemes/Envelope.d.ts +5 -0
  25. package/build/types/protocol/schemes/FollowedTopic.d.ts +10 -0
  26. package/build/types/protocol/schemes/LeaveReason.d.ts +9 -0
  27. package/build/types/protocol/schemes/Message.d.ts +32 -0
  28. package/build/types/protocol/schemes/MessagePoll.d.ts +10 -0
  29. package/build/types/protocol/schemes/PermissionOverwritesTarget.d.ts +5 -0
  30. package/build/types/protocol/schemes/PermissionOverwritesValue.d.ts +4 -0
  31. package/build/types/protocol/schemes/Reaction.d.ts +13 -0
  32. package/build/types/protocol/schemes/Role.d.ts +20 -0
  33. package/build/types/protocol/schemes/Room.d.ts +17 -0
  34. package/build/types/protocol/schemes/RoomHistory.d.ts +5 -0
  35. package/build/types/protocol/schemes/RoomMember.d.ts +11 -0
  36. package/build/types/protocol/schemes/RoomStream.d.ts +5 -0
  37. package/build/types/protocol/schemes/RoomSummary.d.ts +14 -0
  38. package/build/types/protocol/schemes/SessionData.d.ts +10 -0
  39. package/build/types/protocol/schemes/Space.d.ts +19 -0
  40. package/build/types/protocol/schemes/SpaceMember.d.ts +7 -0
  41. package/build/types/protocol/schemes/SpaceSummary.d.ts +8 -0
  42. package/build/types/protocol/schemes/Topic.d.ts +8 -0
  43. package/build/types/protocol/schemes/User.d.ts +23 -0
  44. package/build/types/protocol/schemes/UserData.d.ts +10 -0
  45. package/build/types/protocol/schemes/UserInformation.d.ts +11 -0
  46. package/build/types/protocol/schemes/UserRelationship.d.ts +6 -0
  47. package/build/types/protocol/schemes/UserState.d.ts +6 -0
  48. package/build/types/protocol/schemes/commands/Ack.d.ts +5 -0
  49. package/build/types/protocol/schemes/commands/AssignRole.d.ts +6 -0
  50. package/build/types/protocol/schemes/commands/Ban.d.ts +10 -0
  51. package/build/types/protocol/schemes/commands/CreateAccessTicket.d.ts +13 -0
  52. package/build/types/protocol/schemes/commands/CreateEmoticon.d.ts +5 -0
  53. package/build/types/protocol/schemes/commands/CreateMessage.d.ts +11 -0
  54. package/build/types/protocol/schemes/commands/CreateOwner.d.ts +5 -0
  55. package/build/types/protocol/schemes/commands/CreateRelationship.d.ts +5 -0
  56. package/build/types/protocol/schemes/commands/CreateRole.d.ts +6 -0
  57. package/build/types/protocol/schemes/commands/CreateRoom.d.ts +9 -0
  58. package/build/types/protocol/schemes/commands/CreateSpace.d.ts +6 -0
  59. package/build/types/protocol/schemes/commands/CreateTopic.d.ts +11 -0
  60. package/build/types/protocol/schemes/commands/DeassignRole.d.ts +6 -0
  61. package/build/types/protocol/schemes/commands/DeleteEmoticon.d.ts +3 -0
  62. package/build/types/protocol/schemes/commands/DeleteOwner.d.ts +5 -0
  63. package/build/types/protocol/schemes/commands/DeleteRelationship.d.ts +5 -0
  64. package/build/types/protocol/schemes/commands/DeleteRole.d.ts +4 -0
  65. package/build/types/protocol/schemes/commands/DeleteRoom.d.ts +3 -0
  66. package/build/types/protocol/schemes/commands/DeleteSpace.d.ts +3 -0
  67. package/build/types/protocol/schemes/commands/DeleteTopic.d.ts +4 -0
  68. package/build/types/protocol/schemes/commands/FollowTopic.d.ts +4 -0
  69. package/build/types/protocol/schemes/commands/GetBans.d.ts +6 -0
  70. package/build/types/protocol/schemes/commands/GetClientData.d.ts +2 -0
  71. package/build/types/protocol/schemes/commands/GetComputedPermissions.d.ts +10 -0
  72. package/build/types/protocol/schemes/commands/GetDiscoverableSpaces.d.ts +2 -0
  73. package/build/types/protocol/schemes/commands/GetEmoticons.d.ts +3 -0
  74. package/build/types/protocol/schemes/commands/GetEntitlements.d.ts +8 -0
  75. package/build/types/protocol/schemes/commands/GetFollowedTopics.d.ts +4 -0
  76. package/build/types/protocol/schemes/commands/GetInvited.d.ts +3 -0
  77. package/build/types/protocol/schemes/commands/GetMessages.d.ts +13 -0
  78. package/build/types/protocol/schemes/commands/GetOwners.d.ts +4 -0
  79. package/build/types/protocol/schemes/commands/GetPermissionOverwriteTargets.d.ts +4 -0
  80. package/build/types/protocol/schemes/commands/GetPermissionOverwrites.d.ts +6 -0
  81. package/build/types/protocol/schemes/commands/GetReactionDetails.d.ts +8 -0
  82. package/build/types/protocol/schemes/commands/GetRelationships.d.ts +2 -0
  83. package/build/types/protocol/schemes/commands/GetRoomMembers.d.ts +3 -0
  84. package/build/types/protocol/schemes/commands/GetRoomSummary.d.ts +4 -0
  85. package/build/types/protocol/schemes/commands/GetSession.d.ts +2 -0
  86. package/build/types/protocol/schemes/commands/GetSessionData.d.ts +2 -0
  87. package/build/types/protocol/schemes/commands/GetSpaceMembers.d.ts +3 -0
  88. package/build/types/protocol/schemes/commands/GetSpaceRooms.d.ts +3 -0
  89. package/build/types/protocol/schemes/commands/GetSpaceSummary.d.ts +3 -0
  90. package/build/types/protocol/schemes/commands/GetTopics.d.ts +4 -0
  91. package/build/types/protocol/schemes/commands/GetUserData.d.ts +2 -0
  92. package/build/types/protocol/schemes/commands/GetUserInfo.d.ts +3 -0
  93. package/build/types/protocol/schemes/commands/Invite.d.ts +5 -0
  94. package/build/types/protocol/schemes/commands/JoinRoom.d.ts +13 -0
  95. package/build/types/protocol/schemes/commands/JoinSpace.d.ts +3 -0
  96. package/build/types/protocol/schemes/commands/Kick.d.ts +7 -0
  97. package/build/types/protocol/schemes/commands/LeaveRoom.d.ts +3 -0
  98. package/build/types/protocol/schemes/commands/LeaveSpace.d.ts +3 -0
  99. package/build/types/protocol/schemes/commands/Ping.d.ts +2 -0
  100. package/build/types/protocol/schemes/commands/React.d.ts +6 -0
  101. package/build/types/protocol/schemes/commands/RedactMessages.d.ts +3 -0
  102. package/build/types/protocol/schemes/commands/ReportAbuse.d.ts +9 -0
  103. package/build/types/protocol/schemes/commands/SetClientData.d.ts +1 -0
  104. package/build/types/protocol/schemes/commands/SetPermissionOverwrites.d.ts +8 -0
  105. package/build/types/protocol/schemes/commands/SetSessionData.d.ts +17 -0
  106. package/build/types/protocol/schemes/commands/SetUserData.d.ts +6 -0
  107. package/build/types/protocol/schemes/commands/Unban.d.ts +3 -0
  108. package/build/types/protocol/schemes/commands/UnfollowTopic.d.ts +4 -0
  109. package/build/types/protocol/schemes/commands/Uninvite.d.ts +5 -0
  110. package/build/types/protocol/schemes/commands/Unreact.d.ts +6 -0
  111. package/build/types/protocol/schemes/commands/UpdateFollowedTopic.d.ts +6 -0
  112. package/build/types/protocol/schemes/commands/UpdateRole.d.ts +8 -0
  113. package/build/types/protocol/schemes/commands/UpdateRoom.d.ts +10 -0
  114. package/build/types/protocol/schemes/commands/UpdateRoomMember.d.ts +8 -0
  115. package/build/types/protocol/schemes/commands/UpdateSpace.d.ts +12 -0
  116. package/build/types/protocol/schemes/commands/UpdateSpaceMember.d.ts +6 -0
  117. package/build/types/protocol/schemes/commands/UpdateTopic.d.ts +5 -0
  118. package/build/types/protocol/schemes/events/AccessTicket.d.ts +14 -0
  119. package/build/types/protocol/schemes/events/Bans.d.ts +6 -0
  120. package/build/types/protocol/schemes/events/Bye.d.ts +4 -0
  121. package/build/types/protocol/schemes/events/ClientData.d.ts +1 -0
  122. package/build/types/protocol/schemes/events/ComputedPermissions.d.ts +9 -0
  123. package/build/types/protocol/schemes/events/DiscoverableSpaces.d.ts +4 -0
  124. package/build/types/protocol/schemes/events/EmoticonDeleted.d.ts +4 -0
  125. package/build/types/protocol/schemes/events/Emoticons.d.ts +6 -0
  126. package/build/types/protocol/schemes/events/EntitlementUsage.d.ts +11 -0
  127. package/build/types/protocol/schemes/events/Entitlements.d.ts +12 -0
  128. package/build/types/protocol/schemes/events/Error.d.ts +4 -0
  129. package/build/types/protocol/schemes/events/FollowedTopicUpdated.d.ts +4 -0
  130. package/build/types/protocol/schemes/events/FollowedTopics.d.ts +6 -0
  131. package/build/types/protocol/schemes/events/Invited.d.ts +10 -0
  132. package/build/types/protocol/schemes/events/Messages.d.ts +9 -0
  133. package/build/types/protocol/schemes/events/MessagesRedacted.d.ts +5 -0
  134. package/build/types/protocol/schemes/events/NewEmoticon.d.ts +4 -0
  135. package/build/types/protocol/schemes/events/NewMessage.d.ts +4 -0
  136. package/build/types/protocol/schemes/events/NewRelationship.d.ts +4 -0
  137. package/build/types/protocol/schemes/events/NewRole.d.ts +5 -0
  138. package/build/types/protocol/schemes/events/NewRoom.d.ts +5 -0
  139. package/build/types/protocol/schemes/events/NewTopic.d.ts +5 -0
  140. package/build/types/protocol/schemes/events/Ok.d.ts +2 -0
  141. package/build/types/protocol/schemes/events/Owners.d.ts +8 -0
  142. package/build/types/protocol/schemes/events/PermissionOverwriteTargets.d.ts +10 -0
  143. package/build/types/protocol/schemes/events/PermissionOverwrites.d.ts +8 -0
  144. package/build/types/protocol/schemes/events/PermissionOverwritesUpdated.d.ts +8 -0
  145. package/build/types/protocol/schemes/events/Pong.d.ts +2 -0
  146. package/build/types/protocol/schemes/events/Reacted.d.ts +9 -0
  147. package/build/types/protocol/schemes/events/ReactionDetails.d.ts +11 -0
  148. package/build/types/protocol/schemes/events/ReactionUpdated.d.ts +8 -0
  149. package/build/types/protocol/schemes/events/RelationshipDeleted.d.ts +4 -0
  150. package/build/types/protocol/schemes/events/Relationships.d.ts +4 -0
  151. package/build/types/protocol/schemes/events/RoleDeleted.d.ts +4 -0
  152. package/build/types/protocol/schemes/events/RoleUpdated.d.ts +5 -0
  153. package/build/types/protocol/schemes/events/RoomDeleted.d.ts +3 -0
  154. package/build/types/protocol/schemes/events/RoomJoined.d.ts +4 -0
  155. package/build/types/protocol/schemes/events/RoomLeft.d.ts +5 -0
  156. package/build/types/protocol/schemes/events/RoomMemberLeft.d.ts +4 -0
  157. package/build/types/protocol/schemes/events/RoomMemberUpdated.d.ts +6 -0
  158. package/build/types/protocol/schemes/events/RoomMembers.d.ts +5 -0
  159. package/build/types/protocol/schemes/events/RoomMembersJoined.d.ts +9 -0
  160. package/build/types/protocol/schemes/events/RoomSummary.d.ts +4 -0
  161. package/build/types/protocol/schemes/events/RoomSummaryUpdated.d.ts +8 -0
  162. package/build/types/protocol/schemes/events/RoomUpdated.d.ts +4 -0
  163. package/build/types/protocol/schemes/events/Session.d.ts +9 -0
  164. package/build/types/protocol/schemes/events/SpaceDeleted.d.ts +3 -0
  165. package/build/types/protocol/schemes/events/SpaceJoined.d.ts +4 -0
  166. package/build/types/protocol/schemes/events/SpaceLeft.d.ts +5 -0
  167. package/build/types/protocol/schemes/events/SpaceMemberJoined.d.ts +5 -0
  168. package/build/types/protocol/schemes/events/SpaceMemberLeft.d.ts +4 -0
  169. package/build/types/protocol/schemes/events/SpaceMemberUpdated.d.ts +6 -0
  170. package/build/types/protocol/schemes/events/SpaceMembers.d.ts +5 -0
  171. package/build/types/protocol/schemes/events/SpaceRooms.d.ts +5 -0
  172. package/build/types/protocol/schemes/events/SpaceSummary.d.ts +4 -0
  173. package/build/types/protocol/schemes/events/SpaceUpdated.d.ts +4 -0
  174. package/build/types/protocol/schemes/events/TopicDeleted.d.ts +4 -0
  175. package/build/types/protocol/schemes/events/TopicFollowed.d.ts +4 -0
  176. package/build/types/protocol/schemes/events/TopicUnfollowed.d.ts +4 -0
  177. package/build/types/protocol/schemes/events/TopicUpdated.d.ts +6 -0
  178. package/build/types/protocol/schemes/events/Topics.d.ts +6 -0
  179. package/build/types/protocol/schemes/events/UserInfo.d.ts +4 -0
  180. package/build/types/protocol/schemes/events/UserUpdated.d.ts +4 -0
  181. package/build/types/state-tracker/AsyncUtils.d.ts +15 -0
  182. package/build/types/state-tracker/ChatStateTracker.d.ts +41 -0
  183. package/build/types/state-tracker/EmoticonsManager.d.ts +15 -0
  184. package/build/types/state-tracker/FollowedTopicsManager.d.ts +85 -0
  185. package/build/types/state-tracker/MessagesManager.d.ts +24 -0
  186. package/build/types/state-tracker/PermissionsManager.d.ts +47 -0
  187. package/build/types/state-tracker/RelationshipsManager.d.ts +15 -0
  188. package/build/types/state-tracker/RoomMessagesHistory.d.ts +69 -0
  189. package/build/types/state-tracker/RoomsManager.d.ts +72 -0
  190. package/build/types/state-tracker/SpacesManager.d.ts +63 -0
  191. package/build/types/state-tracker/TopicHistoryWindow.d.ts +182 -0
  192. package/build/types/state-tracker/UsersManager.d.ts +23 -0
  193. package/build/types/state-tracker/functions.d.ts +6 -0
  194. package/package.json +67 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project follows
5
+ [semver](https://semver.org) (`0.x` minor releases may break the API).
6
+
7
+ ## [0.6.0] - Unreleased
8
+
9
+ The first release under the new name. Earlier versions were published as `polfan-server-js-client`.
10
+
11
+ ### Changed
12
+
13
+ - **Renamed the package to `@devanachat/sdk`** and moved the repository to
14
+ [devanachat/devana-js-sdk](https://github.com/devanachat/devana-js-sdk).
15
+ To keep existing imports while migrating, install it under an alias:
16
+ `npm install polfan-server-js-client@npm:@devanachat/sdk`.
17
+ - The UMD build exposes the global `Devana` (previously `PservClient`).
18
+ - The protocol types (formerly the `pserv-ts-types` git submodule) are now part of this repository, under
19
+ `src/protocol`.
20
+ - Bundlers resolve the new ES module build instead of the UMD one. The output targets modern browsers and
21
+ Node.js 22+, which makes the bundles about three times smaller.
22
+
23
+ - `send()` resolves to a discriminated union, `{data, error: null} | {data: null, error}`: after checking `error`,
24
+ TypeScript knows that `data` is set.
25
+ - Event handlers receive a non-optional payload (`(ev: T) => void`), so destructuring it compiles in strict mode.
26
+
27
+ ### Added
28
+
29
+ - ES module build (`build/index.mjs`).
30
+ - Type exports from the package root: `CommandResult`, `CommandRequest`, `CommandResponse`, `CommandsMap`,
31
+ `EventsMap`, client option types, `EventHandler` and `ObservableInterface` - no more deep imports from `build/`.
32
+
33
+ ### Fixed
34
+
35
+ - Bundlers no longer report missing re-exports for the protocol types.
36
+ - The npm package contains only the build output (it used to include sources and tests).
37
+ - `terser-webpack-plugin` is no longer installed as a runtime dependency.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022–2026 Jarosław Żak
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,392 @@
1
- # Temporary Holding Version
1
+ # Devana JavaScript SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@devanachat/sdk)](https://www.npmjs.com/package/@devanachat/sdk)
4
+ [![CI](https://github.com/devanachat/devana-js-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/devanachat/devana-js-sdk/actions/workflows/ci.yml)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
7
+ The official TypeScript/JavaScript SDK for [Devana](https://devana.pl), a chat platform for communities and teams.
8
+ It is the same library the Devana apps are built on.
9
+
10
+ - **WebSocket client** with automatic reconnection, ping/pong and a typed command/event API
11
+ - **Web API client** for one-off commands over HTTP
12
+ - **State tracking** - spaces, rooms, members, messages and permissions kept up to date from server events
13
+ - **Files client** for uploads and file metadata
14
+ - **Protocol types** for every command and event, included in the package
15
+
16
+ Works in browsers and in Node.js 22+ (it uses the global `fetch` and `WebSocket`).
17
+
18
+ The commands and events themselves are described in the protocol documentation at
19
+ **[developers.devana.pl](https://developers.devana.pl)** - this README covers the SDK on top of them.
20
+
21
+ ## Installation
22
+
23
+ ```sh
24
+ npm install @devanachat/sdk
25
+ ```
26
+
27
+ The package ships ES module, CommonJS and UMD builds with TypeScript declarations. In the browser without a bundler:
28
+
29
+ ```html
30
+ <script src="https://cdn.jsdelivr.net/npm/@devanachat/sdk/build/index.umd.js"></script>
31
+ <script>
32
+ const client = new Devana.WebSocketChatClient({/* ... */});
33
+ </script>
34
+ ```
35
+
36
+ ## Quick start: a bot
37
+
38
+ Create a bot in the Devana app (Settings → For developers) and copy its token. A bot receives the events of the
39
+ spaces and rooms it is a member of, so add it to them like any other user. Then:
40
+
41
+ ```ts
42
+ import {WebSocketChatClient} from '@devanachat/sdk';
43
+
44
+ const client = new WebSocketChatClient({
45
+ url: 'wss://s1.devana.pl:1600/ws',
46
+ token: process.env.DEVANA_TOKEN!,
47
+ });
48
+
49
+ client.on('NewMessage', async ({message}) => {
50
+ if (message.content === '!ping') {
51
+ await client.send('CreateMessage', {location: message.location, content: 'pong'});
52
+ }
53
+ });
54
+
55
+ await client.connect();
56
+
57
+ const {data: session, error} = await client.send('GetSession', {});
58
+ console.log('Connected as', session?.user.nick, 'to server', session?.serverVersion);
59
+ ```
60
+
61
+ Every command resolves to `{data, error}`: exactly one of them is set. A server error (missing permission, invalid
62
+ input) does not throw - check `error`, after which TypeScript knows `data` is there. The promise rejects only when the
63
+ command could not be delivered (e.g. the connection dropped). Command and event names, with their payloads, are typed:
64
+ your editor will complete them. See [developers.devana.pl](https://developers.devana.pl) for what each of them does.
65
+
66
+ ### Web API client
67
+
68
+ For one-off commands that do not need a persistent connection, use `WebApiChatClient` with the same `send()` API:
69
+
70
+ ```ts
71
+ import {WebApiChatClient} from '@devanachat/sdk';
72
+
73
+ const api = new WebApiChatClient({
74
+ url: 'https://s1.devana.pl:1600/api',
75
+ token: process.env.DEVANA_TOKEN!,
76
+ });
77
+
78
+ const {data} = await api.send('GetSession', {});
79
+ ```
80
+
81
+ ## Common use cases
82
+
83
+ The examples below assume a connected `client` with state tracking enabled (see [State tracking](#state-tracking)).
84
+
85
+ ### Answer when the bot is mentioned
86
+
87
+ The bot also receives its own messages - skip them, or it may end up talking to itself.
88
+
89
+ ```ts
90
+ client.on('NewMessage', async ({message}) => {
91
+ const me = await client.state!.getMe();
92
+
93
+ if (message.author.user.id === me.id || !message.mentions?.userIds.includes(me.id)) {
94
+ return;
95
+ }
96
+
97
+ await client.send('CreateMessage', {
98
+ location: message.location,
99
+ content: `Hi ${message.author.user.nick}, how can I help?`,
100
+ });
101
+ });
102
+ ```
103
+
104
+ ### Welcome new members
105
+
106
+ ```ts
107
+ const WELCOME_ROOM_ID = 'room-id'; // Copy it from the room link in the app
108
+
109
+ client.on('SpaceMemberJoined', async ({spaceId, member}) => {
110
+ await client.send('CreateMessage', {
111
+ location: {spaceId, roomId: WELCOME_ROOM_ID},
112
+ content: `Welcome, ${member.customNick ?? member.user?.nick}! Start with the pinned topic.`,
113
+ });
114
+ });
115
+ ```
116
+
117
+ ### Post notifications from your backend
118
+
119
+ A deployment pipeline, a monitoring alert or a form on your website can post to a room without keeping a connection
120
+ open - send one command with the Web API client:
121
+
122
+ ```ts
123
+ const api = new WebApiChatClient({url: 'https://s1.devana.pl:1600/api', token: process.env.DEVANA_TOKEN!});
124
+
125
+ const {error} = await api.send('CreateMessage', {
126
+ location: {spaceId: 'space-id', roomId: 'room-id'},
127
+ content: '✅ Version 2.4.0 has been deployed to production',
128
+ });
129
+ ```
130
+
131
+ ### Moderate messages
132
+
133
+ Check the bot's permissions before acting, so it fails quietly where it is not a moderator:
134
+
135
+ ```ts
136
+ const BANNED_WORDS = ['spam-link.example'];
137
+
138
+ client.on('NewMessage', async ({message}) => {
139
+ if (!BANNED_WORDS.some(word => message.content?.includes(word))) {
140
+ return;
141
+ }
142
+
143
+ const {hasAll} = await client.state!.permissions.check(['RedactMessages'], message.location);
144
+
145
+ if (hasAll) {
146
+ await client.send('RedactMessages', {messageId: message.id});
147
+ }
148
+ });
149
+ ```
150
+
151
+ ### React to messages
152
+
153
+ ```ts
154
+ client.on('NewMessage', async ({message}) => {
155
+ if (message.content?.toLowerCase().includes('thanks')) {
156
+ await client.send('React', {messageId: message.id, type: 'Emoji', value: '❤️'});
157
+ }
158
+ });
159
+ ```
160
+
161
+ ## Connection maintenance
162
+
163
+ `WebSocketChatClient` keeps the connection alive: after any loss (error, connecting timeout, missing pong, closure with
164
+ a code other than 1000) it reconnects indefinitely, with an exponential backoff between attempts. The `disconnect` event
165
+ tells whether a retry follows. A pending `connect()` promise resolves once an attempt authenticates, and is rejected by
166
+ `disconnect()`, which also stops reconnecting. An invalid token (`Bye` with `AuthenticationException`) rejects `connect()`
167
+ with the `Bye` data, emits an `error` event and stops reconnecting as well.
168
+
169
+ ```ts
170
+ const client = new WebSocketChatClient({
171
+ url: 'wss://s1.devana.pl:1600/ws',
172
+ token: 'your-access-token',
173
+ connectingTimeoutMs: 10000, // Per attempt (default)
174
+ reconnect: {
175
+ minDelayMs: 1000, // Delay before the first retry, doubled on every next one (default)
176
+ maxDelayMs: 30000, // Maximum delay between retries (default)
177
+ },
178
+ ping: {
179
+ noActivityTimeoutMs: 15000, // Send a ping after this much silence (default)
180
+ pongBackTimeoutMs: 5000, // Consider the connection dead without a pong (default)
181
+ },
182
+ });
183
+ ```
184
+
185
+ ## State tracking
186
+
187
+ The WebSocket client can maintain the current state of spaces, rooms, members and messages for you, by handling
188
+ incoming server events. Enable it with the `stateTracking` option and read it from `client.state`:
189
+
190
+ ```ts
191
+ const client = new WebSocketChatClient({
192
+ url: 'wss://s1.devana.pl:1600/ws',
193
+ token: 'your-access-token',
194
+ stateTracking: true,
195
+ });
196
+
197
+ await client.connect();
198
+
199
+ const spaces = await client.state!.spaces.get();
200
+ console.log(spaces.items.map(space => space.name));
201
+
202
+ spaces.on('change', ({setItems, deletedItems}) => {
203
+ // React to spaces being added, updated or removed
204
+ });
205
+ ```
206
+
207
+ State is exposed as `ObservableIndexedObjectCollection` objects: look items up by id with `get(id)`, list them with
208
+ `items`, and subscribe to `change` events, which name the ids that were set or deleted. Data is fetched lazily on the
209
+ first call and kept up to date from server events after that, so calling a getter again is cheap.
210
+
211
+ **Important:** you can keep these objects for the lifetime of a connection, but fetch them again after reconnecting,
212
+ because some structures are rebuilt from scratch on the `Session` event.
213
+
214
+ ### What the state tracker covers
215
+
216
+ | Manager | What it gives you |
217
+ |---|---|
218
+ | `state.spaces` | Your spaces; per space: `getRooms()`, `getMembers()`, `getRoles()`, `getMe()` |
219
+ | `state.rooms` | Rooms you are in; per room: `getMembers()`, `getTopics()`, `getMe()` |
220
+ | `state.rooms.messages` | Message history windows per topic |
221
+ | `state.rooms.followedTopics` | Unread counters and mentions, marking rooms as read |
222
+ | `state.permissions` | Your effective permissions in any location |
223
+ | `state.users` | Known users and their online status |
224
+ | `state.relationships` | Users you ignore |
225
+ | `state.emoticons` | Global and space emoticons |
226
+ | `state.me` / `state.getMe()` | The connected user |
227
+
228
+ ### Message history
229
+
230
+ A history window holds a slice of a topic's messages and moves through the history on demand, so you can render a chat
231
+ view with infinite scroll without managing requests and live updates yourself. New messages arrive in the window
232
+ automatically.
233
+
234
+ ```ts
235
+ const room = (await client.state!.rooms.get()).get('room-id')!;
236
+ const history = await client.state!.rooms.messages.getRoomHistory(room.id);
237
+ const topicWindow = await history!.getMessagesWindow(room.defaultTopic!.id);
238
+
239
+ await topicWindow!.resetToLatest(); // Load the newest messages
240
+ render(topicWindow!.items);
241
+
242
+ topicWindow!.on('change', () => render(topicWindow!.items));
243
+
244
+ // When the user scrolls up
245
+ await topicWindow!.fetchPrevious(); // Does nothing once `topicWindow.hasOldest` is true
246
+
247
+ // Open a linked message with its surroundings
248
+ await topicWindow!.jumpTo('message-id');
249
+ ```
250
+
251
+ `topicWindow.state` tells which part of the history is loaded (`LIVE`, `LATEST`, `PAST`, `OLDEST`). Set `topicWindow.limit` to cap
252
+ how many messages a window keeps in memory - the oldest are dropped when it grows over it.
253
+
254
+ ### Unread messages and mentions
255
+
256
+ ```ts
257
+ const followed = client.state!.rooms.followedTopics;
258
+
259
+ const update = async () => {
260
+ const {isUnread, mentionCount, unreadRoomCount} = await followed.summarize({spaceId: 'space-id'});
261
+ setBadge(mentionCount > 0 ? `@${mentionCount}` : isUnread ? `${unreadRoomCount}` : '');
262
+ };
263
+
264
+ followed.on('change', update); // The summary is cached - recalculate it only when something changed
265
+ await update();
266
+
267
+ await followed.ackRoom('room-id'); // Mark everything in a room as read
268
+ ```
269
+
270
+ ### Permissions
271
+
272
+ Permissions in Devana are layered (global, space, room, topic) with role-based overwrites. The tracker computes the
273
+ effective result for a location and recalculates it when roles or overwrites change:
274
+
275
+ ```ts
276
+ const {hasAll, missing} = await client.state!.permissions.check(
277
+ ['CreateMessages', 'CreatePolls'],
278
+ {spaceId: 'space-id', roomId: 'room-id'},
279
+ );
280
+
281
+ if (!hasAll) {
282
+ console.log('Missing permissions:', missing);
283
+ }
284
+
285
+ client.state!.permissions.on('change', () => {
286
+ // Re-check, e.g. to show or hide moderation buttons
287
+ });
288
+ ```
289
+
290
+ The full list of permissions is in `Permissions.list`.
291
+
292
+ ### Users and relationships
293
+
294
+ ```ts
295
+ import {UserStatus} from '@devanachat/sdk';
296
+
297
+ client.state!.users.onlineStatus.on('change', user => {
298
+ console.log(user.nick, user.status === UserStatus.Online ? 'is online' : 'went away');
299
+ });
300
+
301
+ if (await client.state!.relationships.exists('user-id', 'Ignore')) {
302
+ // Hide this user's messages
303
+ }
304
+ ```
305
+
306
+ ## Package entitlements
307
+
308
+ `GetEntitlements` answers what a space or the current account has. A space package and a user
309
+ package describe disjoint features, so their keys live in separate enums and are never mixed:
310
+
311
+ ```ts
312
+ import {NO_LIMIT, SpaceFeature, UserFeature, STORAGE_UNIT_BYTES} from '@devanachat/sdk';
313
+
314
+ const space = await client.send('GetEntitlements', {spaceId: 'space-id'});
315
+
316
+ if (space.error) {
317
+ throw new Error(space.error.message);
318
+ }
319
+
320
+ const members = space.data.entitlements[SpaceFeature.MembersLimit];
321
+
322
+ if (members !== NO_LIMIT && memberCount >= members) {
323
+ // the space package is full
324
+ }
325
+
326
+ const whitelist = space.data.entitlements[SpaceFeature.AccessWhitelist] === true;
327
+ ```
328
+
329
+ A limit of `NO_LIMIT` (`-1`) means no limit, and a feature the package does not grant is
330
+ absent. A dictionary feature states its numbers as strings (`'250'`), and storage is counted in
331
+ megabytes - use `STORAGE_UNIT_BYTES` rather than a literal. The package tells *whether* a
332
+ feature exists; who may use it is still decided by role permissions.
333
+
334
+ The answer to the command also carries what the server knows about the usage, so a client can
335
+ tell that a file will not fit before it uploads it:
336
+
337
+ ```ts
338
+ const me = await client.send('GetEntitlements', {}); // without spaceId: the current account
339
+ if (me.error) {
340
+ throw new Error(me.error.message);
341
+ }
342
+
343
+ const used = me.data.extras?.storageUsedBytes ?? 0;
344
+ const limit = Number(me.data.entitlements[UserFeature.StorageLimit]) * STORAGE_UNIT_BYTES;
345
+ ```
346
+
347
+ Whenever a package changes, the server pushes the same `Entitlements` event on its own - to every
348
+ member of the space, or to every session of the user (without `extras`, which is asked for with
349
+ the command when it is needed):
350
+
351
+ ```ts
352
+ client.on('Entitlements', entitlements => {
353
+ console.log(entitlements.subject, 'now has', entitlements.planCode);
354
+ });
355
+ ```
356
+
357
+ Owners of a space also hear when one of its limits is running out (80%) or is used up (100%):
358
+
359
+ ```ts
360
+ client.on('EntitlementUsage', usage => {
361
+ console.log(usage.feature, `${usage.usage}/${usage.limit}`);
362
+ });
363
+ ```
364
+
365
+ An operation the package does not allow is refused with a single `EntitlementException` error
366
+ whose message is the key that stopped it, e.g. `space.members.limit`.
367
+
368
+ ## Files
369
+
370
+ ```ts
371
+ import {FilesClient} from '@devanachat/sdk';
372
+
373
+ const files = new FilesClient({token: 'your-access-token'});
374
+ const {ok, data: file} = await files.uploadFile(blob);
375
+
376
+ if (ok) {
377
+ await client.send('CreateMessage', {location, content: 'See attachment', attachments: [file.id]});
378
+ }
379
+ ```
380
+
381
+ ## Versioning
382
+
383
+ The SDK follows the Devana protocol and is versioned with [semver](https://semver.org). While the version is `0.x`,
384
+ a minor release may contain breaking changes - see [CHANGELOG.md](CHANGELOG.md).
385
+
386
+ ## Contributing
387
+
388
+ Bug reports and pull requests are welcome - see [CONTRIBUTING.md](CONTRIBUTING.md).
389
+
390
+ ## License
391
+
392
+ [MIT](LICENSE)