polfan-server-js-client 0.0.96 → 0.1.1

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 (158) hide show
  1. package/build/index.js +1 -1
  2. package/build/index.js.map +1 -1
  3. package/build/types/AbstractChatClient.d.ts +78 -0
  4. package/build/types/AbstractRestClient.d.ts +19 -0
  5. package/build/types/AuthClient.d.ts +16 -0
  6. package/build/types/ChatStateTracker.d.ts +54 -0
  7. package/build/types/EventTarget.d.ts +16 -0
  8. package/build/types/IndexedObjectCollection.d.ts +53 -0
  9. package/build/types/WebApiChatClient.d.ts +30 -0
  10. package/build/types/WebSocketChatClient.d.ts +36 -0
  11. package/build/types/index.d.ts +5 -68
  12. package/package.json +65 -64
  13. package/src/AbstractChatClient.ts +174 -0
  14. package/src/AbstractRestClient.ts +66 -0
  15. package/src/AuthClient.ts +46 -0
  16. package/src/ChatStateTracker.ts +326 -0
  17. package/src/EventTarget.ts +39 -0
  18. package/src/IndexedObjectCollection.ts +209 -0
  19. package/src/{connections/WebApiConnection.ts → WebApiChatClient.ts} +94 -81
  20. package/src/WebSocketChatClient.ts +125 -0
  21. package/src/index.ts +15 -123
  22. package/build/types/Client.d.ts +0 -107
  23. package/build/types/ObservableInterface.d.ts +0 -16
  24. package/build/types/connections/ConnectionAssets.d.ts +0 -17
  25. package/build/types/connections/RestApiConnection.d.ts +0 -14
  26. package/build/types/connections/WebApiConnection.d.ts +0 -21
  27. package/build/types/connections/WebSocketConnection.d.ts +0 -22
  28. package/build/types/dtos/Dto.d.ts +0 -16
  29. package/build/types/dtos/Message.d.ts +0 -9
  30. package/build/types/dtos/Permission.d.ts +0 -7
  31. package/build/types/dtos/Role.d.ts +0 -7
  32. package/build/types/dtos/Room.d.ts +0 -10
  33. package/build/types/dtos/RoomMember.d.ts +0 -6
  34. package/build/types/dtos/RoomSummary.d.ts +0 -7
  35. package/build/types/dtos/Space.d.ts +0 -8
  36. package/build/types/dtos/SpaceMember.d.ts +0 -7
  37. package/build/types/dtos/Topic.d.ts +0 -7
  38. package/build/types/dtos/User.d.ts +0 -9
  39. package/build/types/dtos/UserState.d.ts +0 -8
  40. package/build/types/dtos/protocol/Envelope.d.ts +0 -7
  41. package/build/types/dtos/protocol/commands/AssignRole.d.ts +0 -7
  42. package/build/types/dtos/protocol/commands/CreateMessage.d.ts +0 -7
  43. package/build/types/dtos/protocol/commands/CreateRole.d.ts +0 -7
  44. package/build/types/dtos/protocol/commands/CreateRoom.d.ts +0 -7
  45. package/build/types/dtos/protocol/commands/CreateSpace.d.ts +0 -5
  46. package/build/types/dtos/protocol/commands/CreateTopic.d.ts +0 -7
  47. package/build/types/dtos/protocol/commands/DeassignRole.d.ts +0 -7
  48. package/build/types/dtos/protocol/commands/DeleteRole.d.ts +0 -6
  49. package/build/types/dtos/protocol/commands/DeleteRoom.d.ts +0 -5
  50. package/build/types/dtos/protocol/commands/DeleteSpace.d.ts +0 -5
  51. package/build/types/dtos/protocol/commands/DeleteTopic.d.ts +0 -5
  52. package/build/types/dtos/protocol/commands/GetComputedPermissions.d.ts +0 -8
  53. package/build/types/dtos/protocol/commands/GetRolePermissions.d.ts +0 -8
  54. package/build/types/dtos/protocol/commands/GetRoomMembers.d.ts +0 -5
  55. package/build/types/dtos/protocol/commands/GetSession.d.ts +0 -4
  56. package/build/types/dtos/protocol/commands/GetSpaceMembers.d.ts +0 -5
  57. package/build/types/dtos/protocol/commands/GetSpaceRooms.d.ts +0 -5
  58. package/build/types/dtos/protocol/commands/GetUserPermissions.d.ts +0 -8
  59. package/build/types/dtos/protocol/commands/JoinRoom.d.ts +0 -5
  60. package/build/types/dtos/protocol/commands/JoinSpace.d.ts +0 -5
  61. package/build/types/dtos/protocol/commands/LeaveRoom.d.ts +0 -5
  62. package/build/types/dtos/protocol/commands/LeaveSpace.d.ts +0 -5
  63. package/build/types/dtos/protocol/commands/SetRolePermissions.d.ts +0 -9
  64. package/build/types/dtos/protocol/commands/SetUserPermissions.d.ts +0 -9
  65. package/build/types/dtos/protocol/events/Bye.d.ts +0 -5
  66. package/build/types/dtos/protocol/events/Error.d.ts +0 -6
  67. package/build/types/dtos/protocol/events/NewMessage.d.ts +0 -6
  68. package/build/types/dtos/protocol/events/NewRole.d.ts +0 -7
  69. package/build/types/dtos/protocol/events/NewRoom.d.ts +0 -7
  70. package/build/types/dtos/protocol/events/NewTopic.d.ts +0 -7
  71. package/build/types/dtos/protocol/events/Ok.d.ts +0 -4
  72. package/build/types/dtos/protocol/events/Permissions.d.ts +0 -6
  73. package/build/types/dtos/protocol/events/RoleDeleted.d.ts +0 -6
  74. package/build/types/dtos/protocol/events/RoomDeleted.d.ts +0 -5
  75. package/build/types/dtos/protocol/events/RoomJoined.d.ts +0 -6
  76. package/build/types/dtos/protocol/events/RoomLeft.d.ts +0 -5
  77. package/build/types/dtos/protocol/events/RoomMemberJoined.d.ts +0 -6
  78. package/build/types/dtos/protocol/events/RoomMemberLeft.d.ts +0 -5
  79. package/build/types/dtos/protocol/events/RoomMembers.d.ts +0 -6
  80. package/build/types/dtos/protocol/events/Session.d.ts +0 -9
  81. package/build/types/dtos/protocol/events/SpaceDeleted.d.ts +0 -5
  82. package/build/types/dtos/protocol/events/SpaceJoined.d.ts +0 -6
  83. package/build/types/dtos/protocol/events/SpaceLeft.d.ts +0 -5
  84. package/build/types/dtos/protocol/events/SpaceMemberJoined.d.ts +0 -6
  85. package/build/types/dtos/protocol/events/SpaceMemberLeft.d.ts +0 -5
  86. package/build/types/dtos/protocol/events/SpaceMemberUpdate.d.ts +0 -6
  87. package/build/types/dtos/protocol/events/SpaceMembers.d.ts +0 -6
  88. package/build/types/dtos/protocol/events/SpaceRooms.d.ts +0 -6
  89. package/build/types/dtos/protocol/events/TopicDeleted.d.ts +0 -5
  90. package/build/types/protocol.d.ts +0 -102
  91. package/src/Client.ts +0 -267
  92. package/src/ObservableInterface.ts +0 -39
  93. package/src/connections/ConnectionAssets.ts +0 -20
  94. package/src/connections/RestApiConnection.ts +0 -47
  95. package/src/connections/WebSocketConnection.ts +0 -103
  96. package/src/dtos/Dto.ts +0 -45
  97. package/src/dtos/Message.ts +0 -16
  98. package/src/dtos/Permission.ts +0 -12
  99. package/src/dtos/Role.ts +0 -12
  100. package/src/dtos/Room.ts +0 -17
  101. package/src/dtos/RoomMember.ts +0 -13
  102. package/src/dtos/RoomSummary.ts +0 -12
  103. package/src/dtos/Space.ts +0 -15
  104. package/src/dtos/SpaceMember.ts +0 -14
  105. package/src/dtos/Topic.ts +0 -12
  106. package/src/dtos/User.ts +0 -15
  107. package/src/dtos/UserState.ts +0 -16
  108. package/src/dtos/protocol/Envelope.ts +0 -12
  109. package/src/dtos/protocol/commands/AssignRole.ts +0 -12
  110. package/src/dtos/protocol/commands/CreateMessage.ts +0 -12
  111. package/src/dtos/protocol/commands/CreateRole.ts +0 -12
  112. package/src/dtos/protocol/commands/CreateRoom.ts +0 -12
  113. package/src/dtos/protocol/commands/CreateSpace.ts +0 -10
  114. package/src/dtos/protocol/commands/CreateTopic.ts +0 -12
  115. package/src/dtos/protocol/commands/DeassignRole.ts +0 -12
  116. package/src/dtos/protocol/commands/DeleteRole.ts +0 -11
  117. package/src/dtos/protocol/commands/DeleteRoom.ts +0 -10
  118. package/src/dtos/protocol/commands/DeleteSpace.ts +0 -10
  119. package/src/dtos/protocol/commands/DeleteTopic.ts +0 -10
  120. package/src/dtos/protocol/commands/GetComputedPermissions.ts +0 -13
  121. package/src/dtos/protocol/commands/GetRolePermissions.ts +0 -13
  122. package/src/dtos/protocol/commands/GetRoomMembers.ts +0 -10
  123. package/src/dtos/protocol/commands/GetSession.ts +0 -8
  124. package/src/dtos/protocol/commands/GetSpaceMembers.ts +0 -10
  125. package/src/dtos/protocol/commands/GetSpaceRooms.ts +0 -10
  126. package/src/dtos/protocol/commands/GetUserPermissions.ts +0 -13
  127. package/src/dtos/protocol/commands/JoinRoom.ts +0 -10
  128. package/src/dtos/protocol/commands/JoinSpace.ts +0 -10
  129. package/src/dtos/protocol/commands/LeaveRoom.ts +0 -10
  130. package/src/dtos/protocol/commands/LeaveSpace.ts +0 -10
  131. package/src/dtos/protocol/commands/SetRolePermissions.ts +0 -16
  132. package/src/dtos/protocol/commands/SetUserPermissions.ts +0 -16
  133. package/src/dtos/protocol/events/Bye.ts +0 -10
  134. package/src/dtos/protocol/events/Error.ts +0 -11
  135. package/src/dtos/protocol/events/NewMessage.ts +0 -13
  136. package/src/dtos/protocol/events/NewRole.ts +0 -14
  137. package/src/dtos/protocol/events/NewRoom.ts +0 -14
  138. package/src/dtos/protocol/events/NewTopic.ts +0 -14
  139. package/src/dtos/protocol/events/Ok.ts +0 -8
  140. package/src/dtos/protocol/events/Permissions.ts +0 -13
  141. package/src/dtos/protocol/events/RoleDeleted.ts +0 -11
  142. package/src/dtos/protocol/events/RoomDeleted.ts +0 -10
  143. package/src/dtos/protocol/events/RoomJoined.ts +0 -13
  144. package/src/dtos/protocol/events/RoomLeft.ts +0 -10
  145. package/src/dtos/protocol/events/RoomMemberJoined.ts +0 -13
  146. package/src/dtos/protocol/events/RoomMemberLeft.ts +0 -10
  147. package/src/dtos/protocol/events/RoomMembers.ts +0 -13
  148. package/src/dtos/protocol/events/Session.ts +0 -17
  149. package/src/dtos/protocol/events/SpaceDeleted.ts +0 -10
  150. package/src/dtos/protocol/events/SpaceJoined.ts +0 -13
  151. package/src/dtos/protocol/events/SpaceLeft.ts +0 -10
  152. package/src/dtos/protocol/events/SpaceMemberJoined.ts +0 -13
  153. package/src/dtos/protocol/events/SpaceMemberLeft.ts +0 -10
  154. package/src/dtos/protocol/events/SpaceMemberUpdate.ts +0 -13
  155. package/src/dtos/protocol/events/SpaceMembers.ts +0 -13
  156. package/src/dtos/protocol/events/SpaceRooms.ts +0 -13
  157. package/src/dtos/protocol/events/TopicDeleted.ts +0 -10
  158. package/src/protocol.ts +0 -113
package/src/Client.ts DELETED
@@ -1,267 +0,0 @@
1
- import {ChatConnectionEvent, ChatConnectionInterface} from "./connections/ConnectionAssets";
2
- import {EventTarget} from "./ObservableInterface";
3
- import {Envelope} from "./dtos/protocol/Envelope";
4
- import {JoinRoom} from "./dtos/protocol/commands/JoinRoom";
5
- import {Dto} from "./dtos/Dto";
6
- import {RoomJoined} from "./dtos/protocol/events/RoomJoined";
7
- import {LeaveRoom} from "./dtos/protocol/commands/LeaveRoom";
8
- import {RoomLeft} from "./dtos/protocol/events/RoomLeft";
9
- import {CreateRoom} from "./dtos/protocol/commands/CreateRoom";
10
- import {Error as ErrorEvent} from "./dtos/protocol/events/Error";
11
- import {SpaceRooms} from "./dtos/protocol/events/SpaceRooms";
12
- import {DeleteRoom} from "./dtos/protocol/commands/DeleteRoom";
13
- import {RoomDeleted} from "./dtos/protocol/events/RoomDeleted";
14
- import {GetRoomMembers} from "./dtos/protocol/commands/GetRoomMembers";
15
- import {RoomMembers} from "./dtos/protocol/events/RoomMembers";
16
- import {JoinSpace} from "./dtos/protocol/commands/JoinSpace";
17
- import {SpaceJoined} from "./dtos/protocol/events/SpaceJoined";
18
- import {LeaveSpace} from "./dtos/protocol/commands/LeaveSpace";
19
- import {SpaceLeft} from "./dtos/protocol/events/SpaceLeft";
20
- import {CreateSpace} from "./dtos/protocol/commands/CreateSpace";
21
- import {DeleteSpace} from "./dtos/protocol/commands/DeleteSpace";
22
- import {SpaceDeleted} from "./dtos/protocol/events/SpaceDeleted";
23
- import {GetSpaceMembers} from "./dtos/protocol/commands/GetSpaceMembers";
24
- import {SpaceMembers} from "./dtos/protocol/events/SpaceMembers";
25
- import {GetSpaceRooms} from "./dtos/protocol/commands/GetSpaceRooms";
26
- import {GetSession} from "./dtos/protocol/commands/GetSession";
27
- import {Session} from "./dtos/protocol/events/Session";
28
- import {AssignRole} from "./dtos/protocol/commands/AssignRole";
29
- import {SpaceMemberUpdate} from "./dtos/protocol/events/SpaceMemberUpdate";
30
- import {DeassignRole} from "./dtos/protocol/commands/DeassignRole";
31
- import {CreateRole} from "./dtos/protocol/commands/CreateRole";
32
- import {NewRole} from "./dtos/protocol/events/NewRole";
33
- import {DeleteRole} from "./dtos/protocol/commands/DeleteRole";
34
- import {RoleDeleted} from "./dtos/protocol/events/RoleDeleted";
35
- import {SetRolePermissions} from "./dtos/protocol/commands/SetRolePermissions";
36
- import {Permissions} from "./dtos/protocol/events/Permissions";
37
- import {SetUserPermissions} from "./dtos/protocol/commands/SetUserPermissions";
38
- import {CreateTopic} from "./dtos/protocol/commands/CreateTopic";
39
- import {NewTopic} from "./dtos/protocol/events/NewTopic";
40
- import {DeleteTopic} from "./dtos/protocol/commands/DeleteTopic";
41
- import {TopicDeleted} from "./dtos/protocol/events/TopicDeleted";
42
- import {CreateMessage} from "./dtos/protocol/commands/CreateMessage";
43
- import {NewMessage} from "./dtos/protocol/events/NewMessage";
44
- import {GetComputedPermissions} from "./dtos/protocol/commands/GetComputedPermissions";
45
- import {GetRolePermissions} from "./dtos/protocol/commands/GetRolePermissions";
46
- import {GetUserPermissions} from "./dtos/protocol/commands/GetUserPermissions";
47
- import {commands, events} from "./protocol";
48
- import {WebSocketConnection} from "./connections/WebSocketConnection";
49
- import {RestApiConnection} from "./connections/RestApiConnection";
50
-
51
- type ArrayOfPromiseResolvers = [(value: any) => void, (reason?: any) => void];
52
- type CmdResult<EventDto> = EventDto | ErrorEvent;
53
- type CommandsToEventsType<CommandT> =
54
- // General commands
55
- CommandT extends GetSession ? CmdResult<Session> :
56
- CommandT extends SetUserPermissions ? CmdResult<Permissions> :
57
- CommandT extends GetUserPermissions ? CmdResult<Permissions> :
58
- CommandT extends GetComputedPermissions ? CmdResult<Permissions> :
59
- // Space commands
60
- CommandT extends JoinSpace ? CmdResult<SpaceJoined> :
61
- CommandT extends LeaveSpace ? CmdResult<SpaceLeft> :
62
- CommandT extends CreateSpace ? CmdResult<SpaceJoined> :
63
- CommandT extends DeleteSpace ? CmdResult<SpaceDeleted> :
64
- CommandT extends GetSpaceMembers ? CmdResult<SpaceMembers> :
65
- CommandT extends GetSpaceRooms ? CmdResult<SpaceRooms> :
66
- CommandT extends CreateRole ? CmdResult<NewRole> :
67
- CommandT extends DeleteRole ? CmdResult<RoleDeleted> :
68
- CommandT extends AssignRole ? CmdResult<SpaceMemberUpdate> :
69
- CommandT extends DeassignRole ? CmdResult<SpaceMemberUpdate> :
70
- CommandT extends SetRolePermissions ? CmdResult<Permissions> :
71
- CommandT extends GetRolePermissions ? CmdResult<Permissions> :
72
- // Room commands
73
- CommandT extends JoinRoom ? CmdResult<RoomJoined> :
74
- CommandT extends LeaveRoom ? CmdResult<RoomLeft> :
75
- CommandT extends CreateRoom ? CmdResult<RoomJoined> :
76
- CommandT extends DeleteRoom ? CmdResult<RoomDeleted> :
77
- CommandT extends GetRoomMembers ? CmdResult<RoomMembers> :
78
- // Topic commands
79
- CommandT extends CreateTopic ? CmdResult<NewTopic> :
80
- CommandT extends DeleteTopic ? CmdResult<TopicDeleted> :
81
- CommandT extends CreateMessage ? CmdResult<NewMessage> :
82
- any;
83
-
84
- function guessCommandType(obj: any): string {
85
- for (const type in commands) {
86
- if (obj instanceof commands[type]) {
87
- return type;
88
- }
89
- }
90
- return Object.getPrototypeOf(obj).constructor.name;
91
- }
92
-
93
- export enum ClientEvent {
94
- message = 'message',
95
- ready = 'ready',
96
- renewal = 'renewalStart',
97
- renewalSuccess = 'renewalSuccess',
98
- renewalError = 'renewalError',
99
- }
100
-
101
- export interface TokenInterface {
102
- token: string,
103
- expiration: string
104
- }
105
-
106
- export interface MyAccountInterface {
107
- id: string;
108
- nick: string;
109
- avatar: string;
110
- }
111
-
112
- export class Client extends EventTarget {
113
- public static readonly defaultClientName = 'polfan-server-js-client';
114
- public static readonly defaultWebSocketUrl = 'ws://pserv.shado.p5.tiktalik.io:1600/ws';
115
- public static readonly defaultWebApiUrl = 'http://pserv.shado.p5.tiktalik.io:1600/api';
116
- public static readonly defaultRestApiUrl = 'https://polfan.pl/webservice/api';
117
- public static readonly defaultAvatarUrlPrefix = 'https://polfan.pl/modules/users/avatars/';
118
-
119
- public static async getToken(
120
- login: string,
121
- password: string,
122
- clientName: string = Client.defaultClientName
123
- ): Promise<TokenInterface> {
124
- const connection = new RestApiConnection({url: Client.defaultRestApiUrl});
125
- const response = await connection.send('POST', 'auth/tokens', {
126
- login, password, client_name: clientName
127
- });
128
- if (response.ok) {
129
- return response.data;
130
- }
131
- throw new Error(`Cannot create user token: ${response.data.errors[0]}`);
132
- }
133
-
134
- public static createByToken(token: string): Client {
135
- return new Client(
136
- new WebSocketConnection({token, url: Client.defaultWebSocketUrl}),
137
- new RestApiConnection({token, url: Client.defaultRestApiUrl}),
138
- );
139
- }
140
-
141
- public static createByTemporaryNick(temporaryNick: string): Client {
142
- return new Client(
143
- new WebSocketConnection({temporaryNick, url: Client.defaultWebSocketUrl}),
144
- new RestApiConnection({url: Client.defaultRestApiUrl}),
145
- );
146
- }
147
-
148
- protected commandsCount = 0;
149
- protected awaitingResponse: Map<string, ArrayOfPromiseResolvers> = new Map<string, ArrayOfPromiseResolvers>();
150
- protected eventsMap: {[x: string]: typeof Dto};
151
- protected reconnecting: boolean;
152
-
153
- public constructor(
154
- public readonly chatConnection: ChatConnectionInterface,
155
- public readonly restConnection: RestApiConnection,
156
- ) {
157
- super();
158
- this.setCustomEventMap({}); // Set default event map.
159
- this.chatConnection.on(ChatConnectionEvent.message, (payload: any) => this.onMessage(payload));
160
- this.chatConnection.on(ChatConnectionEvent.destroy, (reconnect: boolean) => this.onDisconnect(reconnect));
161
- this.chatConnection.on(ChatConnectionEvent.ready, () => {
162
- if (this.reconnecting) {
163
- this.reconnecting = false;
164
- this.emit(ClientEvent.renewalSuccess);
165
- return;
166
- }
167
- this.emit(ClientEvent.ready);
168
- });
169
- this.chatConnection.on(ChatConnectionEvent.error, () => {
170
- if (this.reconnecting) {
171
- this.reconnecting = false;
172
- this.emit(ClientEvent.renewalError);
173
- }
174
- });
175
- }
176
-
177
- /**
178
- * Send command to chat server.
179
- * @param commandPayload Command payload object.
180
- * @param commandType Command type; if not specified, it will be guessed from the command payload class name.
181
- * @return Promise which resolves to the event returned by server (including `Error`)
182
- * in response to command and rejects with connection error.
183
- */
184
- public async sendCommand<CommandT extends Dto = any>(
185
- commandPayload: CommandT,
186
- commandType?: string
187
- ): Promise<CommandsToEventsType<CommandT>> {
188
- const message = this.createEnvelope(commandType ?? guessCommandType(commandPayload), commandPayload);
189
- this.chatConnection.send(message.toRaw());
190
- return new Promise(
191
- (...args) => this.awaitingResponse.set(message.ref as string, args)
192
- );
193
- }
194
-
195
- /**
196
- * Set custom DTO classes for events.
197
- */
198
- public setCustomEventMap(customMap: {[x: string]: typeof Dto}): this {
199
- this.eventsMap = {...events, ...customMap};
200
- return this;
201
- }
202
-
203
- public init(): this {
204
- this.chatConnection.init();
205
- return this;
206
- }
207
-
208
- public destroy(): this {
209
- this.chatConnection.destroy();
210
- return this;
211
- }
212
-
213
- public async getMe(): Promise<MyAccountInterface> {
214
- const response = await this.restConnection.send('GET', 'auth/me');
215
- if (response.ok) {
216
- response.data.id = response.data.id.toString();
217
- return response.data;
218
- }
219
- throw new Error(`Cannot get current user account: ${response.data.errors[0]}`);
220
- }
221
-
222
- public async deleteToken(token: string): Promise<void> {
223
- const response = await this.restConnection.send('DELETE', `auth/tokens/${token}`);
224
- if (!response.ok) {
225
- throw new Error(`Cannot delete access token: ${response.data.errors[0]}`);
226
- }
227
- }
228
-
229
- private onMessage(message: any) {
230
- const dto = this.createEvent(message);
231
-
232
- const [resolve] = this.awaitingResponse.get(message.ref ?? '') ?? [];
233
- if (resolve) {
234
- resolve(dto ?? message.data);
235
- this.awaitingResponse.delete(message.ref as string);
236
- }
237
-
238
- this.emit(ClientEvent.message, message);
239
- this.emit(message.type ?? 'unknown', dto, message);
240
- }
241
-
242
- private onDisconnect(reconnect: boolean): void {
243
- this.awaitingResponse.forEach(([resolve, reject], key: string) => {
244
- reject('Disconnected');
245
- this.awaitingResponse.delete(key);
246
- });
247
- if (reconnect) {
248
- this.reconnecting = true;
249
- this.emit(ClientEvent.renewal);
250
- }
251
- }
252
-
253
- private createEnvelope(commandType: string, dto: Dto): Envelope {
254
- return new Envelope({
255
- type: commandType,
256
- ref: (++this.commandsCount).toString(),
257
- data: dto
258
- });
259
- }
260
-
261
- private createEvent(message: Envelope): Dto | null {
262
- if ((message.type ?? false) && this.eventsMap.hasOwnProperty(message.type)) {
263
- return new (this.eventsMap[message.type] as any)(message.data);
264
- }
265
- return null;
266
- }
267
- }
@@ -1,39 +0,0 @@
1
- export type EventHandler<T = any> = (...args: T[]) => void;
2
- type HandlersMap = Map<string, EventHandler[]>;
3
-
4
- export interface ObservableInterface {
5
- on(eventName: string, handler: EventHandler): ObservableInterface;
6
- once(eventName: string, handler: EventHandler): ObservableInterface;
7
- }
8
-
9
- export abstract class EventTarget implements ObservableInterface {
10
- protected events: HandlersMap = new Map<string, EventHandler[]>();
11
- protected onceEvents: HandlersMap = new Map<string, EventHandler[]>();
12
-
13
- public on(eventName: string, handler: EventHandler): EventTarget {
14
- this.addHandler(this.events, eventName, handler);
15
- return this;
16
- }
17
-
18
- public once(eventName: string, handler: EventHandler): EventTarget {
19
- this.addHandler(this.onceEvents, eventName, handler);
20
- return this;
21
- }
22
-
23
- public emit(eventName: string, ...args: any): EventTarget {
24
- this.callHandlers(this.events, eventName, args);
25
- this.callHandlers(this.onceEvents, eventName, args);
26
- this.onceEvents.delete(eventName);
27
- return this;
28
- }
29
-
30
- private addHandler(map: HandlersMap, eventName: string, handler: EventHandler): void {
31
- const handlers = map.get(eventName) ?? [];
32
- handlers.push(handler);
33
- map.set(eventName, handlers);
34
- }
35
-
36
- private callHandlers(map: HandlersMap, eventName: string, args: any[]): void {
37
- map.get(eventName)?.forEach(callback => callback(...args));
38
- }
39
- }
@@ -1,20 +0,0 @@
1
- import {ObservableInterface} from "../ObservableInterface";
2
-
3
- export enum ChatConnectionEvent {
4
- message = 'message',
5
- destroy = 'destroy',
6
- ready = 'ready',
7
- error = 'error',
8
- }
9
-
10
- export interface ConnectionOptionsInterface {
11
- url: string;
12
- token?: string;
13
- temporaryNick?: string;
14
- }
15
-
16
- export interface ChatConnectionInterface extends ObservableInterface {
17
- init(): void;
18
- send(data: any): void;
19
- destroy(): void;
20
- }
@@ -1,47 +0,0 @@
1
- import {ConnectionOptionsInterface} from "./ConnectionAssets";
2
-
3
- export interface RestResponseInterface {
4
- ok: boolean;
5
- status: number;
6
- data: any;
7
- }
8
-
9
- export class RestApiConnection {
10
- public constructor(protected options: ConnectionOptionsInterface) {
11
- if (this.options.temporaryNick) {
12
- throw new Error('Temporary nick is not supported authentication method for REST API');
13
- }
14
- }
15
-
16
- public async send(method: string, uri: string, data: any = undefined): Promise<RestResponseInterface> {
17
- const headers: any = {
18
- 'Content-Type': 'application/json',
19
- Accept: 'application/json'
20
- };
21
-
22
- if (this.options.token) {
23
- headers.Authorization = `Bearer ${this.options.token}`;
24
- }
25
-
26
- const body = data === undefined ? undefined : JSON.stringify(data);
27
- const result = await fetch(this.getUrl(uri), {method, body, headers});
28
-
29
- return {
30
- ok: result.ok,
31
- status: result.status,
32
- data: await result.json(),
33
- };
34
- }
35
-
36
- protected getUrl(uri: string): string {
37
- return this.removeEndingSlash(this.options.url) + '/' + this.removeStartingSlash(uri);
38
- }
39
-
40
- private removeStartingSlash(text: string): string {
41
- return text.replace(/^\/+/, '');
42
- }
43
-
44
- private removeEndingSlash(text: string): string {
45
- return text.replace(/\/+$/, '');
46
- }
47
- }
@@ -1,103 +0,0 @@
1
- import {EventTarget} from "../ObservableInterface";
2
- import {
3
- ChatConnectionEvent,
4
- ChatConnectionInterface,
5
- ConnectionOptionsInterface,
6
- } from "./ConnectionAssets";
7
-
8
- export interface WebSocketConnectionInterface extends ConnectionOptionsInterface {
9
- awaitQueueSendDelayMs?: number;
10
- connectingTimeoutMs?: number;
11
- }
12
-
13
- export class WebSocketConnection extends EventTarget implements ChatConnectionInterface {
14
- protected ws: WebSocket|null = null;
15
- protected sendQueue: any[] = [];
16
- protected connectingTimeoutId: any;
17
- protected authenticated: boolean;
18
-
19
- public constructor(private readonly options: WebSocketConnectionInterface) {
20
- super();
21
- if (!this.options.token && !this.options.temporaryNick) {
22
- throw new Error('Token or temporary nick is required');
23
- }
24
- }
25
-
26
- public init() {
27
- if (this.ws) {
28
- this.destroy();
29
- }
30
- this.connect();
31
- }
32
-
33
- public send(data: any): void {
34
- if (!this.ws || this.ws.readyState === this.ws.CLOSED) {
35
- this.connect();
36
- }
37
- if (this.ws.readyState === this.ws.CONNECTING || !this.authenticated) {
38
- this.sendQueue.push(data);
39
- return;
40
- }
41
- const dataJson = JSON.stringify(data);
42
- if (this.ws.readyState !== this.ws.OPEN) {
43
- this.emit(ChatConnectionEvent.error, new Error(`Cannot send ${dataJson}; invalid connection state`));
44
- return;
45
- }
46
- this.ws.send(dataJson);
47
- }
48
-
49
- public destroy(): void {
50
- this.sendQueue = [];
51
- this.ws?.close();
52
- this.ws = null;
53
- }
54
-
55
- private connect(): void {
56
- this.authenticated = false;
57
- const authString = this.options.token ? `token=${this.options.token}` : `nick=${this.options.temporaryNick}`;
58
- this.ws = new WebSocket(`${this.options.url}?${authString}`);
59
- this.ws.onclose = ev => this.onClose(ev);
60
- this.ws.onmessage = ev => this.onMessage(ev);
61
- this.connectingTimeoutId = setTimeout(
62
- () => this.triggerConnectionTimeout(),
63
- this.options.connectingTimeoutMs ?? 10000
64
- );
65
- }
66
-
67
- private onMessage(event: MessageEvent): void {
68
- const payload = JSON.parse(event.data);
69
- // Login successfully
70
- if (!this.authenticated && payload.type && payload.type !== 'Error') {
71
- this.authenticated = true;
72
- this.emit(ChatConnectionEvent.ready);
73
- this.sendFromQueue();
74
- }
75
- this.emit(ChatConnectionEvent.message, payload);
76
- }
77
-
78
- private onClose(event: CloseEvent): void {
79
- clearTimeout(this.connectingTimeoutId);
80
- const reconnect = event.code !== 1000; // Connection was closed because of error
81
- if (reconnect) {
82
- this.connect();
83
- }
84
- this.emit(ChatConnectionEvent.destroy, reconnect);
85
- }
86
-
87
- private sendFromQueue(): void {
88
- // Send awaiting data to server
89
- let lastDelay = 0;
90
- for (const dataIndex in this.sendQueue) {
91
- const data = this.sendQueue[dataIndex];
92
- setTimeout(() => this.send(data), lastDelay);
93
- lastDelay += this.options.awaitQueueSendDelayMs ?? 500;
94
- }
95
- this.sendQueue = [];
96
- clearTimeout(this.connectingTimeoutId);
97
- }
98
-
99
- private triggerConnectionTimeout(): void {
100
- this.destroy();
101
- this.emit(ChatConnectionEvent.error, new Error('Connection timeout'));
102
- }
103
- }
package/src/dtos/Dto.ts DELETED
@@ -1,45 +0,0 @@
1
- export function cast<T extends typeof Dto>(data: any, dto: T): T|undefined {
2
- if (data instanceof dto) {
3
- return data as any;
4
- }
5
- return new (dto as any)(data);
6
- }
7
-
8
- export function castArray<T extends typeof Dto>(data: any[], dto: T): T[] {
9
- if (!Array.isArray(data)) throw new Error(`Passed data is not an array of ${dto.name}`);
10
- return data.map(item => cast(item, dto));
11
- }
12
-
13
- type ExcludeMethods<T> = Pick<T, { [K in keyof T]: T[K] extends Function ? never : K }[keyof T]>;
14
- export type DtoData<T> = { [K in keyof ExcludeMethods<T>]: any };
15
-
16
- export abstract class Dto {
17
- public constructor(...args: any[]) {
18
- }
19
-
20
- public toJson(overrideBy: any = {}): string {
21
- return JSON.stringify(this.toRaw(overrideBy));
22
- }
23
-
24
- public toRaw(overrideBy: any = {}): DtoData<this> {
25
- const object: {[key: string]: any} = {};
26
- Object.keys(this).forEach(key => {
27
- if (overrideBy.hasOwnProperty(key)) {
28
- object[key] = overrideBy[key];
29
- } else if ((this as any)[key] instanceof Dto) {
30
- object[key] = (this as any)[key].toRaw();
31
- } else {
32
- object[key] = (this as any)[key]
33
- }
34
- });
35
- return object as DtoData<this>;
36
- }
37
-
38
- public clone(overrideBy: any = {}): this {
39
- return new (this.constructor as any)(this.toRaw(overrideBy));
40
- }
41
-
42
- protected fill(data: any, overrideBy: any = {}) {
43
- Object.assign(this, {...data, ...overrideBy});
44
- }
45
- }
@@ -1,16 +0,0 @@
1
- import {cast, Dto, DtoData} from "./Dto";
2
- import {User} from "./User";
3
-
4
- export class Message extends Dto {
5
- public readonly id: string;
6
- public readonly author: User;
7
- public readonly topicId: string;
8
- public readonly content: string;
9
-
10
- public constructor(data: DtoData<Message>) {
11
- super();
12
- this.fill(data, {
13
- author: cast(data.author, User),
14
- });
15
- }
16
- }
@@ -1,12 +0,0 @@
1
- import {Dto, DtoData} from "./Dto";
2
-
3
- export class Permission extends Dto {
4
- public readonly name: string;
5
- public readonly value: boolean;
6
- public readonly skip: boolean;
7
-
8
- public constructor(data: DtoData<Permission>) {
9
- super(data);
10
- this.fill(data);
11
- }
12
- }
package/src/dtos/Role.ts DELETED
@@ -1,12 +0,0 @@
1
- import {Dto, DtoData} from "./Dto";
2
-
3
- export class Role extends Dto {
4
- public readonly id: string;
5
- public readonly name: string;
6
- public readonly color?: string;
7
-
8
- public constructor(data: DtoData<Role>) {
9
- super();
10
- this.fill(data);
11
- }
12
- }
package/src/dtos/Room.ts DELETED
@@ -1,17 +0,0 @@
1
- import {castArray, Dto, DtoData} from "./Dto";
2
- import {Topic} from "./Topic";
3
-
4
- export class Room extends Dto {
5
- public readonly id: string;
6
- public readonly spaceId: string|null;
7
- public readonly name: string;
8
- public readonly description: string;
9
- public readonly topics: Topic[];
10
-
11
- public constructor(data: DtoData<Room>) {
12
- super();
13
- this.fill(data, {
14
- topics: castArray(data.topics, Topic),
15
- });
16
- }
17
- }
@@ -1,13 +0,0 @@
1
- import {cast, Dto, DtoData} from "./Dto";
2
- import {User} from "./User";
3
-
4
- export class RoomMember extends Dto {
5
- public readonly user: User;
6
-
7
- public constructor(data: DtoData<RoomMember>) {
8
- super();
9
- this.fill(data, {
10
- user: cast(data.user, User),
11
- });
12
- }
13
- }
@@ -1,12 +0,0 @@
1
- import {Dto, DtoData} from "./Dto";
2
-
3
- export class RoomSummary extends Dto {
4
- public readonly id: string;
5
- public readonly name: string;
6
- public readonly description: string;
7
-
8
- public constructor(data: DtoData<RoomSummary>) {
9
- super();
10
- this.fill(data);
11
- }
12
- }
package/src/dtos/Space.ts DELETED
@@ -1,15 +0,0 @@
1
- import {castArray, Dto, DtoData} from "./Dto";
2
- import {Role} from "./Role";
3
-
4
- export class Space extends Dto {
5
- public readonly id: string;
6
- public readonly name: string;
7
- public readonly roles: Role[];
8
-
9
- public constructor(data: DtoData<Space>) {
10
- super();
11
- this.fill(data, {
12
- roles: castArray(data.roles, Role)
13
- });
14
- }
15
- }
@@ -1,14 +0,0 @@
1
- import {castArray, Dto, DtoData} from "./Dto";
2
- import {User} from "./User";
3
-
4
- export class SpaceMember extends Dto {
5
- public readonly user: User;
6
- public readonly roles: string[];
7
-
8
- public constructor(data: DtoData<SpaceMember>) {
9
- super();
10
- this.fill(data, {
11
- user: castArray(data.user, User),
12
- });
13
- }
14
- }
package/src/dtos/Topic.ts DELETED
@@ -1,12 +0,0 @@
1
- import {Dto, DtoData} from "./Dto";
2
-
3
- export class Topic extends Dto {
4
- public readonly id: string;
5
- public readonly name: string;
6
- public readonly description: string;
7
-
8
- public constructor(data: DtoData<Topic>) {
9
- super();
10
- this.fill(data);
11
- }
12
- }
package/src/dtos/User.ts DELETED
@@ -1,15 +0,0 @@
1
- import {Dto, DtoData} from "./Dto";
2
-
3
- export type UserFlag = 'bot' | 'temp';
4
-
5
- export class User extends Dto {
6
- public readonly id: string;
7
- public readonly nick: string;
8
- public readonly avatar: string;
9
- public readonly flags: UserFlag[];
10
-
11
- public constructor(data: DtoData<User>) {
12
- super();
13
- this.fill(data);
14
- }
15
- }