@eleven-am/pondsocket 0.1.169 → 0.1.171

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 (41) hide show
  1. package/abstracts/middleware.js +40 -17
  2. package/abstracts/redisClient.js +278 -0
  3. package/engines/channelEngine.js +163 -0
  4. package/engines/endpointEngine.js +163 -0
  5. package/engines/lobbyEngine.js +79 -0
  6. package/errors/httpError.js +11 -0
  7. package/index.js +2 -2
  8. package/managers/distributedManager.js +115 -0
  9. package/managers/localManager.js +41 -0
  10. package/managers/manager.js +219 -0
  11. package/managers/managerFactory.js +31 -0
  12. package/package.json +24 -14
  13. package/requests/eventRequest.js +51 -0
  14. package/requests/joinRequest.js +56 -0
  15. package/responses/connectionResponse.js +89 -0
  16. package/{channel → responses}/eventResponse.js +8 -79
  17. package/{lobby → responses}/joinResponse.js +25 -84
  18. package/server/{pondSocket.js → server.js} +55 -55
  19. package/types.d.ts +34 -103
  20. package/wrappers/channel.js +70 -0
  21. package/wrappers/endpoint.js +32 -0
  22. package/wrappers/pondChannel.js +48 -0
  23. package/abstracts/abstractRequest.js +0 -57
  24. package/abstracts/abstractRequest.test.js +0 -48
  25. package/abstracts/middleware.test.js +0 -70
  26. package/channel/channel.js +0 -351
  27. package/channel/channel.test.js +0 -435
  28. package/channel/eventRequest.js +0 -25
  29. package/channel/eventRequest.test.js +0 -30
  30. package/channel/eventResponse.test.js +0 -175
  31. package/endpoint/endpoint.js +0 -299
  32. package/endpoint/endpoint.test.js +0 -299
  33. package/endpoint/response.js +0 -129
  34. package/errors/pondError.js +0 -28
  35. package/lobby/JoinRequest.test.js +0 -50
  36. package/lobby/JoinResponse.test.js +0 -142
  37. package/lobby/joinRequest.js +0 -43
  38. package/lobby/lobby.js +0 -186
  39. package/matcher/matcher.test.js +0 -90
  40. package/presence/presence.js +0 -112
  41. package/presence/presenceEngine.test.js +0 -129
@@ -1,299 +0,0 @@
1
- "use strict";
2
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
- if (kind === "m") throw new TypeError("Private method is not writable");
4
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
- };
8
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
- };
13
- var _EndpointEngine_instances, _EndpointEngine_middleware, _EndpointEngine_lobbyEngines, _EndpointEngine_channels, _EndpointEngine_sockets, _EndpointEngine_parentEngine, _EndpointEngine_joinChannel, _EndpointEngine_broadcastMessage, _EndpointEngine_retrieveChannel, _EndpointEngine_handleMessage, _EndpointEngine_readMessage, _EndpointEngine_buildError, _EndpointEngine_leaveChannel, _Endpoint_engine;
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.Endpoint = exports.EndpointEngine = void 0;
16
- const pondsocket_common_1 = require("@eleven-am/pondsocket-common");
17
- const zod_1 = require("zod");
18
- const middleware_1 = require("../abstracts/middleware");
19
- const pondError_1 = require("../errors/pondError");
20
- const joinRequest_1 = require("../lobby/joinRequest");
21
- const joinResponse_1 = require("../lobby/joinResponse");
22
- const lobby_1 = require("../lobby/lobby");
23
- const matcher_1 = require("../matcher/matcher");
24
- class EndpointEngine {
25
- constructor(parent) {
26
- _EndpointEngine_instances.add(this);
27
- _EndpointEngine_middleware.set(this, void 0);
28
- _EndpointEngine_lobbyEngines.set(this, void 0);
29
- _EndpointEngine_channels.set(this, void 0);
30
- _EndpointEngine_sockets.set(this, void 0);
31
- _EndpointEngine_parentEngine.set(this, void 0);
32
- __classPrivateFieldSet(this, _EndpointEngine_sockets, new Map(), "f");
33
- __classPrivateFieldSet(this, _EndpointEngine_middleware, new middleware_1.Middleware(), "f");
34
- __classPrivateFieldSet(this, _EndpointEngine_lobbyEngines, new Map(), "f");
35
- __classPrivateFieldSet(this, _EndpointEngine_parentEngine, parent, "f");
36
- __classPrivateFieldSet(this, _EndpointEngine_channels, new Map(), "f");
37
- }
38
- get parent() {
39
- return __classPrivateFieldGet(this, _EndpointEngine_parentEngine, "f");
40
- }
41
- /**
42
- * @desc Adds a new PondChannel to this path on this endpoint
43
- * @param path - The path to add the channel to
44
- * @param handler - The handler to use to authenticate the client
45
- *
46
- * @example
47
- * const channel = endpoint.createChannel('/chat', (request, response) => {
48
- * if (request.user.assigns.admin)
49
- * response.accept();
50
- *
51
- * else
52
- * response.decline('You are not an admin', 403);
53
- * });
54
- */
55
- createChannel(path, handler) {
56
- const pondChannel = new lobby_1.LobbyEngine(this, path);
57
- __classPrivateFieldGet(this, _EndpointEngine_middleware, "f").use((user, joinParams, next) => {
58
- const event = (0, matcher_1.parseAddress)(path, user.channelName);
59
- if (event) {
60
- const channel = pondChannel.getChannel(user.channelName) || pondChannel.createChannel(user.channelName);
61
- const request = new joinRequest_1.JoinRequest(user, joinParams, channel);
62
- const response = new joinResponse_1.JoinResponse(user, channel);
63
- request._parseQueries(path);
64
- __classPrivateFieldGet(this, _EndpointEngine_channels, "f").set(user.channelName, channel);
65
- return handler(request, response);
66
- }
67
- next();
68
- });
69
- __classPrivateFieldGet(this, _EndpointEngine_lobbyEngines, "f").set(path, pondChannel);
70
- return new lobby_1.PondChannel(pondChannel);
71
- }
72
- /**
73
- * @desc Gets all clients connected to this endpoint
74
- */
75
- getClients() {
76
- return [...__classPrivateFieldGet(this, _EndpointEngine_sockets, "f").values()];
77
- }
78
- /**
79
- * @desc Closes specific clients connected to this endpoint
80
- * @param clientIds - The id for the client / clients to close
81
- */
82
- closeConnection(clientIds) {
83
- const clients = typeof clientIds === 'string' ? [clientIds] : clientIds;
84
- this.getClients()
85
- .forEach(({ clientId, socket }) => {
86
- if (clients.includes(clientId)) {
87
- socket.close();
88
- }
89
- });
90
- }
91
- /**
92
- * @desc Manages a new socket connection
93
- * @param cache - The socket cache
94
- */
95
- manageSocket(cache) {
96
- __classPrivateFieldGet(this, _EndpointEngine_sockets, "f").set(cache.clientId, cache);
97
- const socket = cache.socket;
98
- socket.addEventListener('message', (message) => {
99
- __classPrivateFieldGet(this, _EndpointEngine_instances, "m", _EndpointEngine_readMessage).call(this, cache, message.data);
100
- });
101
- socket.addEventListener('close', () => {
102
- __classPrivateFieldGet(this, _EndpointEngine_sockets, "f").delete(cache.clientId);
103
- cache.subscriptions.forEach((unsubscribe) => unsubscribe());
104
- });
105
- socket.addEventListener('error', () => {
106
- __classPrivateFieldGet(this, _EndpointEngine_sockets, "f").delete(cache.clientId);
107
- cache.subscriptions.forEach((unsubscribe) => unsubscribe());
108
- });
109
- const event = {
110
- event: pondsocket_common_1.Events.CONNECTION,
111
- action: pondsocket_common_1.ServerActions.CONNECT,
112
- channelName: pondsocket_common_1.SystemSender.ENDPOINT,
113
- requestId: (0, pondsocket_common_1.uuid)(),
114
- payload: {},
115
- };
116
- this.sendMessage(socket, event);
117
- }
118
- /**
119
- * @desc Retrieves a user from the endpoint
120
- * @param clientId - The id of the user to retrieve
121
- * @private
122
- */
123
- getUser(clientId) {
124
- const user = __classPrivateFieldGet(this, _EndpointEngine_sockets, "f").get(clientId);
125
- if (!user) {
126
- throw new pondError_1.EndpointError(`GatewayEngine: User ${clientId} does not exist`, 404);
127
- }
128
- return user;
129
- }
130
- /**
131
- * @desc Subscribes a user to a channel, Will join the channel if it exists or add to pending subscriptions
132
- * @param userId - The id of the user to subscribe
133
- * @param channel - The name of the channel to subscribe to
134
- */
135
- subscribeTo(userId, channel) {
136
- const user = this.getUser(userId);
137
- const channelEngine = __classPrivateFieldGet(this, _EndpointEngine_instances, "m", _EndpointEngine_retrieveChannel).call(this, channel);
138
- const onMessage = this.sendMessage.bind(this, user.socket);
139
- const subscription = channelEngine.addUser(userId, user.assigns, onMessage);
140
- user.subscriptions.set(channel, subscription);
141
- }
142
- /**
143
- * @desc Unsubscribes a user from a channel
144
- * @param userId - The id of the user to unsubscribe
145
- * @param channel - The name of the channel to unsubscribe from
146
- */
147
- unsubscribeFrom(userId, channel) {
148
- const user = this.getUser(userId);
149
- const unsubscribe = user.subscriptions.get(channel);
150
- if (unsubscribe) {
151
- unsubscribe();
152
- user.subscriptions.delete(channel);
153
- return;
154
- }
155
- throw new pondError_1.EndpointError(`GatewayEngine: Channel ${channel} does not exist`, 404);
156
- }
157
- /**
158
- * @desc Sends a message to a client
159
- * @param socket - The socket to send the message to
160
- * @param message - The message to send
161
- */
162
- sendMessage(socket, message) {
163
- socket.send(JSON.stringify(message));
164
- }
165
- }
166
- exports.EndpointEngine = EndpointEngine;
167
- _EndpointEngine_middleware = new WeakMap(), _EndpointEngine_lobbyEngines = new WeakMap(), _EndpointEngine_channels = new WeakMap(), _EndpointEngine_sockets = new WeakMap(), _EndpointEngine_parentEngine = new WeakMap(), _EndpointEngine_instances = new WeakSet(), _EndpointEngine_joinChannel = function _EndpointEngine_joinChannel(channel, socket, joinParams, requestId) {
168
- const cache = Object.assign(Object.assign({}, socket), { requestId, channelName: channel });
169
- __classPrivateFieldGet(this, _EndpointEngine_middleware, "f").run(cache, joinParams, () => {
170
- throw new pondError_1.EndpointError(`GatewayEngine: Channel ${channel} does not exist`, 404);
171
- });
172
- }, _EndpointEngine_broadcastMessage = function _EndpointEngine_broadcastMessage(cache, message) {
173
- const engine = __classPrivateFieldGet(this, _EndpointEngine_channels, "f").get(message.channelName);
174
- if (!engine) {
175
- throw new pondError_1.EndpointError(`GatewayEngine: Channel ${message.channelName} does not exist`, 404);
176
- }
177
- engine.broadcastMessage(cache.clientId, message);
178
- }, _EndpointEngine_retrieveChannel = function _EndpointEngine_retrieveChannel(channel) {
179
- let channelEngine;
180
- for (const [path, manager] of __classPrivateFieldGet(this, _EndpointEngine_lobbyEngines, "f")) {
181
- const event = (0, matcher_1.parseAddress)(path, channel);
182
- if (event) {
183
- channelEngine = manager.getChannel(channel) || manager.createChannel(channel);
184
- break;
185
- }
186
- }
187
- if (!channelEngine) {
188
- throw new pondError_1.EndpointError(`GatewayEngine: Channel ${channel} does not exist`, 400);
189
- }
190
- return channelEngine;
191
- }, _EndpointEngine_handleMessage = function _EndpointEngine_handleMessage(cache, message) {
192
- switch (message.action) {
193
- case pondsocket_common_1.ClientActions.JOIN_CHANNEL:
194
- __classPrivateFieldGet(this, _EndpointEngine_instances, "m", _EndpointEngine_joinChannel).call(this, message.channelName, cache, message.payload, message.requestId);
195
- break;
196
- case pondsocket_common_1.ClientActions.LEAVE_CHANNEL:
197
- __classPrivateFieldGet(this, _EndpointEngine_instances, "m", _EndpointEngine_leaveChannel).call(this, message.channelName, cache);
198
- break;
199
- case pondsocket_common_1.ClientActions.BROADCAST:
200
- __classPrivateFieldGet(this, _EndpointEngine_instances, "m", _EndpointEngine_broadcastMessage).call(this, cache, message);
201
- break;
202
- default:
203
- throw new Error(`GatewayEngine: Action ${message.action} does not exist`);
204
- }
205
- }, _EndpointEngine_readMessage = function _EndpointEngine_readMessage(cache, message) {
206
- try {
207
- const data = JSON.parse(message);
208
- const result = pondsocket_common_1.clientMessageSchema.parse(data);
209
- __classPrivateFieldGet(this, _EndpointEngine_instances, "m", _EndpointEngine_handleMessage).call(this, cache, result);
210
- }
211
- catch (e) {
212
- this.sendMessage(cache.socket, __classPrivateFieldGet(this, _EndpointEngine_instances, "m", _EndpointEngine_buildError).call(this, e));
213
- }
214
- }, _EndpointEngine_buildError = function _EndpointEngine_buildError(error) {
215
- const event = {
216
- event: pondsocket_common_1.ErrorTypes.INVALID_MESSAGE,
217
- action: pondsocket_common_1.ServerActions.ERROR,
218
- channelName: pondsocket_common_1.SystemSender.ENDPOINT,
219
- requestId: (0, pondsocket_common_1.uuid)(),
220
- payload: {},
221
- };
222
- if (error instanceof SyntaxError) {
223
- event.payload = {
224
- message: 'Invalid JSON',
225
- };
226
- }
227
- else if (error instanceof Error) {
228
- event.event = pondsocket_common_1.ErrorTypes.INTERNAL_SERVER_ERROR;
229
- event.payload = {
230
- message: error.message,
231
- };
232
- }
233
- else if (error instanceof pondError_1.PresenceError) {
234
- event.event = pondsocket_common_1.ErrorTypes.PRESENCE_ERROR;
235
- event.channelName = error.channel;
236
- event.payload = {
237
- message: error.message,
238
- code: error.code,
239
- action: error.event,
240
- };
241
- }
242
- else if (error instanceof pondError_1.ChannelError) {
243
- event.event = pondsocket_common_1.ErrorTypes.CHANNEL_ERROR;
244
- event.channelName = error.channel;
245
- event.payload = {
246
- message: error.message,
247
- code: error.code,
248
- };
249
- }
250
- else if (error instanceof pondError_1.EndpointError) {
251
- event.event = pondsocket_common_1.ErrorTypes.ENDPOINT_ERROR;
252
- event.payload = {
253
- message: error.message,
254
- code: error.code,
255
- };
256
- }
257
- else if (error instanceof zod_1.ZodError) {
258
- const message = error.errors.map((error) => {
259
- if ('expected' in error && 'received' in error) {
260
- return `Expected ${error.path.join('.')} to be ${error.expected}, but received ${error.received}`;
261
- }
262
- return `${error.path.join('.')} ${error.message}`;
263
- }).join(', ');
264
- event.payload = {
265
- message,
266
- code: 400,
267
- };
268
- }
269
- else {
270
- event.payload = {
271
- message: 'Unknown error',
272
- };
273
- }
274
- return event;
275
- }, _EndpointEngine_leaveChannel = function _EndpointEngine_leaveChannel(channel, socket) {
276
- const unsubscribe = socket.subscriptions.get(channel);
277
- if (!unsubscribe) {
278
- throw new pondError_1.EndpointError(`GatewayEngine: Channel ${channel} does not exist`, 404);
279
- }
280
- unsubscribe();
281
- socket.subscriptions.delete(channel);
282
- };
283
- class Endpoint {
284
- constructor(engine) {
285
- _Endpoint_engine.set(this, void 0);
286
- __classPrivateFieldSet(this, _Endpoint_engine, engine, "f");
287
- }
288
- createChannel(path, handler) {
289
- return __classPrivateFieldGet(this, _Endpoint_engine, "f").createChannel(path, handler);
290
- }
291
- closeConnection(clientIds) {
292
- __classPrivateFieldGet(this, _Endpoint_engine, "f").closeConnection(clientIds);
293
- }
294
- getClients() {
295
- return __classPrivateFieldGet(this, _Endpoint_engine, "f").getClients().map(({ socket }) => socket);
296
- }
297
- }
298
- exports.Endpoint = Endpoint;
299
- _Endpoint_engine = new WeakMap();
@@ -1,299 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.createEndpointEngine = void 0;
16
- const pondsocket_common_1 = require("@eleven-am/pondsocket-common");
17
- const superwstest_1 = __importDefault(require("superwstest"));
18
- const pondSocket_1 = require("../server/pondSocket");
19
- const createEndpointEngine = (socket) => ({
20
- createChannel: jest.fn(),
21
- listConnections: jest.fn(),
22
- getClients: jest.fn(),
23
- broadcast: jest.fn(),
24
- closeConnection: jest.fn(),
25
- manageSocket: jest.fn(),
26
- getUser: () => socket,
27
- subscribeTo: jest.fn(),
28
- unsubscribeFrom: jest.fn(),
29
- sendMessage: (socket, msg) => socket.send(JSON.stringify(msg)),
30
- getPubSubClient: () => ({
31
- publish: jest.fn(),
32
- subscribeToPresence: jest.fn(),
33
- subscribe: jest.fn(),
34
- getPresence: () => new Promise((resolve) => setTimeout(() => resolve([]), 100)),
35
- }),
36
- });
37
- exports.createEndpointEngine = createEndpointEngine;
38
- describe('endpoint', () => {
39
- let socket;
40
- let server;
41
- beforeEach((done) => {
42
- socket = new pondSocket_1.PondSocket();
43
- server = socket.listen(3000, 'localhost', () => {
44
- done();
45
- });
46
- });
47
- afterEach((done) => {
48
- server.close(() => {
49
- done();
50
- });
51
- });
52
- it('should be able to close a single socket', () => __awaiter(void 0, void 0, void 0, function* () {
53
- let count = 0;
54
- const endpoint = socket.createEndpoint('/api/:room', (req, res) => {
55
- if (req.params.room === 'socket') {
56
- res.accept();
57
- count++;
58
- setTimeout(() => {
59
- endpoint.closeConnection(req.id);
60
- }, 1000);
61
- }
62
- else {
63
- res.decline();
64
- }
65
- });
66
- yield (0, superwstest_1.default)(server)
67
- .ws('/api/socket')
68
- .expectUpgrade((res) => expect(res.statusCode).toBe(101))
69
- .wait(200)
70
- .expectClosed();
71
- expect(count).toBe(1);
72
- }));
73
- it('should be able to list connections', () => __awaiter(void 0, void 0, void 0, function* () {
74
- const endpoint = socket.createEndpoint('/api/:room', (req, res) => {
75
- if (req.params.room === 'socket') {
76
- res.accept();
77
- const connections = endpoint.getClients();
78
- expect(connections).toHaveLength(1);
79
- }
80
- else {
81
- res.decline();
82
- }
83
- });
84
- yield (0, superwstest_1.default)(server)
85
- .ws('/api/socket')
86
- .expectUpgrade((res) => expect(res.statusCode).toBe(101));
87
- }));
88
- it('should be able to refuse connections to the endpoint', () => __awaiter(void 0, void 0, void 0, function* () {
89
- let count = 0;
90
- socket.createEndpoint('/api/:path', (req, res) => {
91
- count++;
92
- expect(req.params.path).toBe('socket');
93
- res.decline();
94
- });
95
- yield (0, superwstest_1.default)(server)
96
- .ws('/api/socket')
97
- .expectUpgrade((res) => expect(res.statusCode).toBe(101))
98
- .expectMessage(expect.objectContaining({
99
- action: pondsocket_common_1.ServerActions.ERROR,
100
- event: pondsocket_common_1.ErrorTypes.UNAUTHORIZED_CONNECTION,
101
- channelName: pondsocket_common_1.SystemSender.ENDPOINT,
102
- payload: {
103
- message: 'Unauthorized connection',
104
- code: 401,
105
- },
106
- }))
107
- .expectClosed();
108
- expect(count).toBe(1);
109
- }));
110
- it('should be able to accept connections on this handler', () => __awaiter(void 0, void 0, void 0, function* () {
111
- const message = {
112
- action: pondsocket_common_1.ClientActions.JOIN_CHANNEL,
113
- channelName: '/test/socket',
114
- event: 'TEST',
115
- payload: {},
116
- };
117
- const endpoint = socket.createEndpoint('/api/:room', (req, res) => {
118
- if (req.params.room === 'socket') {
119
- res.accept();
120
- }
121
- else {
122
- res.decline();
123
- }
124
- });
125
- endpoint.createChannel('/test/:room', (req, res) => {
126
- expect(req.event.params.room).toBeDefined();
127
- res.accept().assign({
128
- assigns: {
129
- status: 'online',
130
- },
131
- });
132
- });
133
- yield (0, superwstest_1.default)(server)
134
- .ws('/api/socket')
135
- .expectUpgrade((res) => expect(res.statusCode).toBe(101))
136
- .sendJson(message)
137
- .close()
138
- .expectClosed();
139
- yield (0, superwstest_1.default)(server)
140
- .ws('/api/socket')
141
- .expectUpgrade((res) => expect(res.statusCode).toBe(101))
142
- .sendJson(Object.assign(Object.assign({}, message), { channelName: '/socket/socket' }))
143
- .expectMessage(expect.objectContaining({
144
- action: pondsocket_common_1.ServerActions.SYSTEM,
145
- channelName: '/socket/socket',
146
- event: pondsocket_common_1.Events.ACKNOWLEDGE,
147
- payload: {},
148
- }))
149
- .close()
150
- .expectClosed();
151
- }));
152
- it('should send an error when the channel exists but other things happen', () => __awaiter(void 0, void 0, void 0, function* () {
153
- const message = {
154
- action: pondsocket_common_1.ClientActions.JOIN_CHANNEL,
155
- channelName: '/test/socket',
156
- event: 'TEST',
157
- payload: {},
158
- };
159
- const endpoint = socket.createEndpoint('/api/:room', (_, res) => {
160
- res.accept();
161
- });
162
- endpoint.createChannel('/test/:room', (req, res) => {
163
- expect(req.event.params.room).toBeDefined();
164
- res.decline('Something went wrong');
165
- });
166
- yield (0, superwstest_1.default)(server)
167
- .ws('/api/socket')
168
- .expectUpgrade((res) => expect(res.statusCode).toBe(101))
169
- .sendJson(message)
170
- .expectMessage(expect.objectContaining({
171
- action: pondsocket_common_1.ServerActions.ERROR,
172
- channelName: '/test/socket',
173
- event: pondsocket_common_1.ErrorTypes.UNAUTHORIZED_JOIN_REQUEST,
174
- payload: {
175
- message: 'Request to join channel /test/socket rejected: Something went wrong',
176
- code: 403,
177
- },
178
- }))
179
- .close()
180
- .expectClosed();
181
- }));
182
- it('should be able to track the presence of its users', () => __awaiter(void 0, void 0, void 0, function* () {
183
- const message = {
184
- action: pondsocket_common_1.ClientActions.JOIN_CHANNEL,
185
- channelName: '/test/socket',
186
- event: 'TEST',
187
- payload: {},
188
- };
189
- const endpoint = socket.createEndpoint('/api/:room', (_, res) => {
190
- res.accept();
191
- });
192
- endpoint.createChannel('/test/:room', (req, res) => {
193
- expect(req.event.params.room).toBeDefined();
194
- res
195
- .accept()
196
- .trackPresence({
197
- status: 'online',
198
- });
199
- });
200
- yield (0, superwstest_1.default)(server)
201
- .ws('/api/socket')
202
- .expectUpgrade((res) => expect(res.statusCode).toBe(101))
203
- .sendJson(message)
204
- .expectMessage(expect.objectContaining({
205
- action: pondsocket_common_1.ServerActions.SYSTEM,
206
- channelName: '/test/socket',
207
- event: pondsocket_common_1.Events.ACKNOWLEDGE,
208
- payload: {},
209
- }))
210
- .close();
211
- }));
212
- it('should throw an error if accept, reject is called more than once', () => __awaiter(void 0, void 0, void 0, function* () {
213
- socket.createEndpoint('/api/:room', (_, res) => {
214
- res.reply('hello', {
215
- test: 'test',
216
- });
217
- res.accept();
218
- expect(() => res.decline()).toThrowError('Cannot execute response more than once');
219
- });
220
- yield (0, superwstest_1.default)(server)
221
- .ws('/api/socket')
222
- .expectUpgrade((res) => expect(res.statusCode).toBe(101))
223
- .expectMessage(expect.objectContaining({
224
- action: pondsocket_common_1.ServerActions.BROADCAST,
225
- channelName: pondsocket_common_1.SystemSender.ENDPOINT,
226
- event: 'hello',
227
- payload: {
228
- test: 'test',
229
- },
230
- }));
231
- }));
232
- it('should be able to connect, join a channel and send a message', () => __awaiter(void 0, void 0, void 0, function* () {
233
- const message = {
234
- action: pondsocket_common_1.ClientActions.JOIN_CHANNEL,
235
- channelName: '/test/socket',
236
- event: 'TEST',
237
- payload: {},
238
- };
239
- const endpoint = socket.createEndpoint('/api/:room', (_, res) => {
240
- res.accept();
241
- });
242
- const channel = endpoint.createChannel('/test/:room', (req, res) => {
243
- expect(req.event.params.room).toBeDefined();
244
- res.accept();
245
- });
246
- channel.onEvent('echo', (req, res) => {
247
- res.reply('echo', req.event.payload);
248
- });
249
- channel.onEvent('broadcast', (req) => {
250
- const internal = channel.getChannel('/test/socket');
251
- expect(internal).toBeDefined();
252
- internal.broadcast('broadcast', Object.assign(Object.assign({}, req.event.payload), { broadcast: true }));
253
- });
254
- yield (0, superwstest_1.default)(server)
255
- .ws('/api/socket')
256
- .expectUpgrade((res) => expect(res.statusCode).toBe(101))
257
- .sendJson(message)
258
- .expectMessage(expect.objectContaining({
259
- action: pondsocket_common_1.ServerActions.SYSTEM,
260
- channelName: '/test/socket',
261
- event: pondsocket_common_1.Events.ACKNOWLEDGE,
262
- payload: {},
263
- }))
264
- .sendJson({
265
- addresses: pondsocket_common_1.ChannelReceiver.ALL_EXCEPT_SENDER,
266
- action: pondsocket_common_1.ClientActions.BROADCAST,
267
- channelName: '/test/socket',
268
- event: 'echo',
269
- payload: {
270
- test: 'test',
271
- },
272
- })
273
- .expectMessage(expect.objectContaining({
274
- action: pondsocket_common_1.ServerActions.SYSTEM,
275
- channelName: '/test/socket',
276
- event: 'echo',
277
- payload: {
278
- test: 'test',
279
- },
280
- }))
281
- .sendJson({
282
- action: pondsocket_common_1.ClientActions.BROADCAST,
283
- channelName: '/test/socket',
284
- event: 'broadcast',
285
- payload: {
286
- test: 'test',
287
- },
288
- })
289
- .expectMessage(expect.objectContaining({
290
- action: pondsocket_common_1.ServerActions.SYSTEM,
291
- channelName: '/test/socket',
292
- event: 'broadcast',
293
- payload: {
294
- test: 'test',
295
- broadcast: true,
296
- },
297
- }));
298
- }));
299
- });