@eleven-am/pondsocket 0.1.50 → 0.1.51

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 (54) hide show
  1. package/abstracts/abstractRequest.js +58 -0
  2. package/abstracts/middleware.js +51 -0
  3. package/channel/channel.js +253 -0
  4. package/{server/channel → channel}/eventRequest.js +4 -1
  5. package/channel/eventResponse.js +150 -0
  6. package/client/channel.js +120 -97
  7. package/client.d.ts +2 -3
  8. package/client.js +34 -20
  9. package/endpoint/endpoint.js +233 -0
  10. package/endpoint/response.js +86 -0
  11. package/enums.js +14 -10
  12. package/errors/pondError.js +27 -0
  13. package/express.d.ts +2 -2
  14. package/express.js +3 -3
  15. package/index.d.ts +1 -2
  16. package/index.js +1 -4
  17. package/lobby/joinRequest.js +39 -0
  18. package/lobby/joinResponse.js +125 -0
  19. package/lobby/lobby.js +174 -0
  20. package/matcher/matcher.js +94 -0
  21. package/node.d.ts +2 -3
  22. package/node.js +3 -4
  23. package/package.json +3 -2
  24. package/presence/presence.js +113 -0
  25. package/server/pondSocket.js +123 -0
  26. package/subjects/subject.js +93 -0
  27. package/types.d.ts +274 -323
  28. package/client/channel.test.js +0 -546
  29. package/server/abstracts/abstractRequest.js +0 -40
  30. package/server/abstracts/abstractRequest.test.js +0 -41
  31. package/server/abstracts/middleware.js +0 -38
  32. package/server/abstracts/middleware.test.js +0 -70
  33. package/server/channel/channelEngine.js +0 -280
  34. package/server/channel/channelEngine.test.js +0 -377
  35. package/server/channel/channelRequest.test.js +0 -29
  36. package/server/channel/channelResponse.test.js +0 -164
  37. package/server/channel/eventResponse.js +0 -153
  38. package/server/endpoint/connectionResponse.js +0 -64
  39. package/server/endpoint/endpoint.js +0 -253
  40. package/server/endpoint/endpoint.test.js +0 -428
  41. package/server/endpoint/endpointResponse.test.js +0 -43
  42. package/server/pondChannel/joinRequest.js +0 -29
  43. package/server/pondChannel/joinResponse.js +0 -103
  44. package/server/pondChannel/pondChannel.js +0 -185
  45. package/server/pondChannel/pondChannelResponse.test.js +0 -109
  46. package/server/presence/presenceEngine.js +0 -107
  47. package/server/presence/presenceEngine.test.js +0 -105
  48. package/server/server/pondSocket.js +0 -121
  49. package/server/server/server.test.js +0 -121
  50. package/server/utils/matchPattern.js +0 -108
  51. package/server/utils/matchPattern.test.js +0 -76
  52. package/server/utils/subjectUtils.js +0 -68
  53. package/server/utils/subjectUtils.test.js +0 -128
  54. /package/{server/abstracts → abstracts}/abstractResponse.js +0 -0
package/types.d.ts CHANGED
@@ -1,360 +1,329 @@
1
- import { Server as HTTPServer, IncomingMessage, IncomingHttpHeaders } from 'http';
2
- import internal from 'stream';
3
-
4
- // eslint-disable-next-line import/no-unresolved
5
1
  import { Express } from 'express';
6
- import { WebSocketServer, WebSocket } from 'ws';
7
-
8
- import { ClientActions, PresenceEventTypes, ChannelState } from './enums';
9
-
10
- export type PondPath = string | RegExp;
11
- type NextFunction = () => void;
12
- export type JoinParams = Record<string, any>;
13
- type PondAssigns = Record<string, any>;
14
- export type PondMessage = Record<string, any>;
15
- export type PondPresence = Record<string, any>;
16
- export type EndpointHandler = (req: IncomingConnection, res: ConnectionResponse) => void;
17
- type SocketCache = Pick<RequestCache, 'socket' | 'clientId' | 'assigns'>;
18
- type AuthorizeMiddleware = (request: JoinRequest, response: JoinResponse) => void | Promise<void>;
19
- type SocketMiddlewareFunction = (req: IncomingMessage, socket: internal.Duplex, head: Buffer, next: NextFunction) => void;
20
- export type ChannelReceivers = 'all_users' | 'all_except_sender' | string[];
21
- export type ChannelEvent = Event | PresenceEvent;
22
-
23
- interface Event {
24
- action: 'SYSTEM' | 'BROADCAST' | 'ERROR';
25
- event: string;
26
- payload: PondMessage;
27
- channelName: string;
2
+ import { Server as HTTPServer, IncomingHttpHeaders } from 'http';
3
+ import { WebSocketServer } from 'ws';
4
+
5
+ export type Unsubscribe = () => void;
6
+
7
+ type IsParam<Path> = Path extends `:${infer Param}` ? Param : never;
8
+
9
+ type FilteredParams<Path> = Path extends `${infer First}/${infer Second}`
10
+ ? IsParam<First> | FilteredParams<Second>
11
+ : IsParam<Path>
12
+
13
+ export type Params<Path> = {
14
+ [Key in FilteredParams<Path>]: string
28
15
  }
29
- export interface ClientMessage {
30
- action: ClientActions;
31
- channelName: string;
32
- event: string;
33
- payload: Record<string, any>;
34
- addresses?: ChannelReceivers;
16
+
17
+ export type PondPath<Path extends string> = Path | RegExp;
18
+
19
+ export type EventParams<Path> = {
20
+ query: Record<string, string>;
21
+ params: Params<Path>;
35
22
  }
36
- interface PresenceEvent {
37
- action: 'PRESENCE';
38
- event: PresenceEventTypes;
39
- channelName: string;
40
- payload: PresencePayload;
23
+
24
+ type Primitives = number | string | boolean | null | undefined;
25
+
26
+ type PondObject = {
27
+ [key: string]: Primitives | PondObject | PondObject[];
41
28
  }
42
- interface RequestCache {
43
- clientId: string;
44
- socket: WebSocket;
45
- channelName: string;
46
- assigns: PondAssigns;
47
- joinParams: Record<string, any>;
48
- params: Record<string, string>;
49
- query: Record<string, string>;
29
+
30
+ export type PondPresence = PondObject;
31
+ export type PondMessage = PondObject;
32
+ export type PondAssigns = PondObject;
33
+ export type JoinParams = PondObject;
34
+
35
+ export interface PresencePayload {
36
+ changed: PondPresence;
37
+ presence: PondPresence[];
50
38
  }
51
- interface UserAssigns {
52
- [userId: string]: PondAssigns;
39
+
40
+ export interface UserPresences {
41
+ [userId: string]: PondPresence;
53
42
  }
54
- interface UserData {
55
- assigns: PondAssigns;
56
- presence: PondPresence;
57
- id: string;
43
+
44
+ export interface UserAssigns {
45
+ [userId: string]: PondAssigns;
58
46
  }
59
- interface EventObject {
60
- event: string;
61
- params: Record<string, string>;
62
- query: Record<string, string>;
47
+
48
+ export type PondEvent<Path> = EventParams<Path> & {
63
49
  payload: PondMessage;
50
+ event: string;
64
51
  }
65
- interface IncomingConnection {
52
+
53
+ export type IncomingConnection<Path> = EventParams<Path> & {
66
54
  id: string;
67
- params: Record<string, string>;
68
- query: Record<string, string>;
69
55
  headers: IncomingHttpHeaders;
70
56
  address: string;
71
57
  }
72
- interface UserPresences {
73
- [userId: string]: PondPresence;
58
+
59
+ export interface UserData {
60
+ assigns: PondAssigns;
61
+ presence: PondPresence;
62
+ id: string;
74
63
  }
75
64
 
76
- declare global {
77
- // eslint-disable-next-line @typescript-eslint/no-namespace
78
- namespace Express {
79
- export interface Application {
80
- upgrade(path: PondPath, handler: EndpointHandler): Endpoint;
81
- }
82
- }
65
+ export enum ChannelState {
66
+ IDLE = 'IDLE',
67
+ JOINING = 'JOINING',
68
+ JOINED = 'JOINED',
69
+ STALLED = 'STALLED',
70
+ CLOSED = 'CLOSED',
83
71
  }
84
72
 
85
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
86
- // @ts-ignore
87
- interface PondSocketExpressApp extends Express {
73
+ export declare class AbstractRequest<Path extends string> {
74
+ event: PondEvent<Path>;
88
75
 
89
- /**
90
- * @desc Accepts a new socket upgrade request on the provided endpoint using the handler function to authenticate the socket
91
- * @param path - the pattern to accept || can also be a regex
92
- * @param handler - the handler function to authenticate the socket
93
- * @example
94
- * const endpoint = pond.createEndpoint('/api/socket', (req, res) => {
95
- * const token = req.query.token;
96
- * if (!token)
97
- * return res.reject("No token provided");
98
- * res.accept({
99
- * assign: {
100
- * token
101
- * }
102
- * });
103
- * })
104
- */
105
- upgrade(path: PondPath, handler: EndpointHandler): Endpoint;
106
- }
107
- export type PondState = 'CONNECTING' | 'OPEN' | 'CLOSING' | 'CLOSED';
108
- type Unsubscribe = () => void;
76
+ channelNme: string;
109
77
 
110
- export interface PresencePayload {
111
- changed: PondPresence;
112
- presence: PondPresence[];
78
+ assigns: UserAssigns;
79
+
80
+ presence: UserPresences;
113
81
  }
114
82
 
115
- export declare class Channel {
83
+ export declare abstract class PondResponse {
116
84
  /**
117
- * @desc Connects to the channel.
85
+ * @desc Rejects the request with the given error message
86
+ * @param message - the error message
87
+ * @param errorCode - the error code
88
+ * @param assigns - the data to assign to the client
118
89
  */
119
- public join(): void;
90
+ abstract reject (message?: string, errorCode?: number, assigns?: PondAssigns): void;
120
91
 
121
92
  /**
122
- * @desc Disconnects from the channel.
93
+ * @desc Emits a direct message to the client
94
+ * @param event - the event name
95
+ * @param payload - the payload to send
96
+ * @param assigns - the data to assign to the client
123
97
  */
124
- public leave(): void;
98
+ abstract send (event: string, payload: PondMessage, assigns?: PondAssigns): void;
125
99
 
126
100
  /**
127
- * @desc Monitors the channel for messages.
128
- * @param event - The event to monitor.
129
- * @param callback - The callback to call when a message is received.
101
+ * @desc Accepts the request and optionally assigns data to the client
102
+ * @param assigns - the data to assign to the client
130
103
  */
131
- public onMessageEvent(event: string, callback: (message: PondMessage) => void): Unsubscribe;
104
+ abstract accept (assigns?: PondAssigns): void;
105
+ }
132
106
 
133
- /**
134
- * @desc Monitors the channel for messages.
135
- * @param callback - The callback to call when a message is received.
136
- */
137
- public onMessage(callback: (event: string, message: PondMessage) => void): Unsubscribe;
107
+ export declare class EventRequest<Path extends string> extends AbstractRequest<Path> {
108
+ user: UserData;
109
+ }
138
110
 
111
+ export declare class EventResponse extends PondResponse {
139
112
  /**
140
- * @desc Monitors the connection state of the channel.
141
- * @param callback - The callback to call when the connection state changes.
113
+ * @desc Accepts the request and optionally assigns data to the client
114
+ * @param assigns - the data to assign to the client
142
115
  */
143
- public onConnectionChange(callback: (connected: boolean) => void): Unsubscribe;
116
+ accept (assigns?: PondAssigns): EventResponse;
144
117
 
145
118
  /**
146
- * @desc Monitors the channel state of the channel.
147
- * @param callback - The callback to call when the connection state changes.
119
+ * @desc Rejects the request and optionally assigns data to the client
120
+ * @param message - the error message
121
+ * @param errorCode - the error code
122
+ * @param assigns - the data to assign to the client
148
123
  */
149
- public onChannelStateChange (callback: (connected: ChannelState) => void): Unsubscribe;
124
+ reject (message?: string, errorCode?: number, assigns?: PondAssigns): EventResponse;
150
125
 
151
126
  /**
152
- * @desc Detects when clients join the channel.
153
- * @param callback - The callback to call when a client joins the channel.
127
+ * @desc Emits a direct message to the client
128
+ * @param event - the event name
129
+ * @param payload - the payload to send
130
+ * @param assigns - the data to assign to the client
154
131
  */
155
- public onJoin(callback: (presence: PondPresence) => void): Unsubscribe;
132
+ send (event: string, payload: PondMessage, assigns?: PondAssigns): void;
156
133
 
157
134
  /**
158
- * @desc Detects when clients leave the channel.
159
- * @param callback - The callback to call when a client leaves the channel.
135
+ * @desc Sends a message to all clients in the channel
136
+ * @param event - the event to send
137
+ * @param payload - the payload to send
160
138
  */
161
- public onLeave(callback: (presence: PondPresence) => void): Unsubscribe;
139
+ broadcast (event: string, payload: PondMessage): EventResponse;
162
140
 
163
141
  /**
164
- * @desc Detects when clients change their presence in the channel.
165
- * @param callback - The callback to call when a client changes their presence in the channel.
142
+ * @desc Sends a message to all clients in the channel except the client making the request
143
+ * @param event - the event to send
144
+ * @param payload - the payload to send
166
145
  */
167
- public onPresenceChange(callback: (presence: PresencePayload) => void): Unsubscribe;
146
+ broadcastFromUser (event: string, payload: PondMessage): EventResponse;
168
147
 
169
148
  /**
170
- * @desc Sends a message to specific clients in the channel.
171
- * @param event - The event to send.
172
- * @param payload - The message to send.
173
- * @param recipient - The clients to send the message to.
149
+ * @desc Sends a message to a set of clients in the channel
150
+ * @param event - the event to send
151
+ * @param payload - the payload to send
152
+ * @param userIds - the ids of the clients to send the message to
174
153
  */
175
- public sendMessage(event: string, payload: PondMessage, recipient: string[]): void;
154
+ sendToUsers (event: string, payload: PondMessage, userIds: string[]): EventResponse;
176
155
 
177
156
  /**
178
- * @desc Broadcasts a message to every other client in the channel except yourself.
179
- * @param event - The event to send.
180
- * @param payload - The message to send.
157
+ * @desc Tracks a user's presence in the channel
158
+ * @param presence - the initial presence data
159
+ * @param userId - the id of the user to track
181
160
  */
182
- public broadcastFrom(event: string, payload: PondMessage): void;
161
+ trackPresence (presence: PondPresence, userId?: string): EventResponse;
183
162
 
184
163
  /**
185
- * @desc Broadcasts a message to the channel, including yourself.
186
- * @param event - The event to send.
187
- * @param payload - The message to send.
164
+ * @desc Updates a user's presence in the channel
165
+ * @param presence - the updated presence data
166
+ * @param userId - the id of the user to update
188
167
  */
189
- public broadcast(event: string, payload: PondMessage): void;
168
+ updatePresence (presence: PondPresence, userId?: string): EventResponse;
190
169
 
191
170
  /**
192
- * @desc Gets the current connection state of the channel.
171
+ * @desc Removes a user's presence from the channel
172
+ * @param userId - the id of the user to remove
193
173
  */
194
- public channelState: ChannelState;
174
+ unTrackPresence (userId?: string): EventResponse;
195
175
 
196
176
  /**
197
- * @desc Gets the current presence of the channel.
177
+ * @desc Evicts a user from the channel
178
+ * @param reason - the reason for the eviction
179
+ * @param userId - the id of the user to evict,
198
180
  */
199
- public getPresence(): PondPresence[];
181
+ evictUser (reason: string, userId?: string): void;
200
182
 
201
183
  /**
202
- * @desc Monitors the presence of the channel.
203
- * @param callback - The callback to call when the presence changes.
184
+ * @desc Closes the channel from the server side for all clients
185
+ * @param reason - the reason for closing the channel
204
186
  */
205
- public onUsersChange(callback: (users: PondPresence[]) => void): Unsubscribe;
187
+ closeChannel (reason: string): void;
188
+ }
206
189
 
190
+ export declare class Channel {
207
191
  /**
208
192
  * @desc Gets the current connection state of the channel.
209
193
  */
210
- public isConnected (): boolean;
211
- }
212
-
213
- declare class PondSocketClient {
214
- constructor(endpoint: string, params?: Record<string, any>);
194
+ get channelState (): ChannelState;
215
195
 
216
196
  /**
217
- * @desc Connects to the server and returns the socket.
197
+ * @desc Connects to the channel.
218
198
  */
219
- public connect(backoff?: number): void;
199
+ join (): void;
220
200
 
221
201
  /**
222
- * @desc Returns the current state of the socket.
202
+ * @desc Disconnects from the channel.
223
203
  */
224
- public getState(): PondState;
204
+ leave (): void;
225
205
 
226
206
  /**
227
- * @desc Disconnects the socket.
207
+ * @desc Monitors the channel for messages.
208
+ * @param callback - The callback to call when a message is received.
228
209
  */
229
- public disconnect(): void;
210
+ onMessage (callback: (event: string, message: PondMessage) => void): Unsubscribe;
230
211
 
231
212
  /**
232
- * @desc Creates a channel with the given name and params.
233
- * @param name - The name of the channel.
234
- * @param params - The params to send to the server.
213
+ * @desc Monitors the channel for messages.
214
+ * @param event - The event to monitor.
215
+ * @param callback - The callback to call when a message is received.
235
216
  */
236
- public createChannel(name: string, params?: JoinParams): Channel;
217
+ onMessageEvent (event: string, callback: (message: PondMessage) => void): Unsubscribe;
237
218
 
238
219
  /**
239
- * @desc Subscribes to the connection state.
240
- * @param callback - The callback to call when the state changes.
220
+ * @desc Monitors the channel state of the channel.
221
+ * @param callback - The callback to call when the connection state changes.
241
222
  */
242
- public onConnectionChange (callback: (state: PondState) => void): Unsubscribe;
243
- }
244
-
245
- declare class AbstractRequest {
246
- get event (): EventObject;
247
-
248
- get channelNme (): string;
249
-
250
- get assigns (): UserAssigns;
251
-
252
- get presence (): UserPresences;
253
- }
223
+ onChannelStateChange (callback: (connected: ChannelState) => void): Unsubscribe;
254
224
 
255
- declare class EventRequest extends AbstractRequest {
256
- get user (): UserData;
257
- }
258
-
259
- declare class EventResponse {
260
225
  /**
261
- * @desc Checks if the response has been sent
226
+ * @desc Detects when clients join the channel.
227
+ * @param callback - The callback to call when a client joins the channel.
262
228
  */
263
- get responseSent (): boolean;
229
+ onJoin (callback: (presence: PondPresence) => void): Unsubscribe;
264
230
 
265
231
  /**
266
- * @desc Accepts the request and optionally assigns data to the client
267
- * @param assigns - the data to assign to the client
232
+ * @desc Detects when clients leave the channel.
233
+ * @param callback - The callback to call when a client leaves the channel.
268
234
  */
269
- accept (assigns?: PondAssigns): EventResponse;
235
+ onLeave (callback: (presence: PondPresence) => void): Unsubscribe;
270
236
 
271
237
  /**
272
- * @desc Rejects the request and optionally assigns data to the client
273
- * @param message - the error message
274
- * @param errorCode - the error code
275
- * @param assigns - the data to assign to the client
238
+ * @desc Detects when clients change their presence in the channel.
239
+ * @param callback - The callback to call when a client changes their presence in the channel.
276
240
  */
277
- reject (message?: string, errorCode?: number, assigns?: PondAssigns): EventResponse;
241
+ onPresenceChange (callback: (presence: PresencePayload) => void): Unsubscribe;
278
242
 
279
243
  /**
280
- * @desc Emits a direct message to the client
281
- * @param event - the event name
282
- * @param payload - the payload to send
283
- * @param assigns - the data to assign to the client
244
+ * @desc Sends a message to specific clients in the channel.
245
+ * @param event - The event to send.
246
+ * @param payload - The message to send.
247
+ * @param recipient - The clients to send the message to.
284
248
  */
285
- send (event: string, payload: PondMessage, assigns?: PondAssigns): EventResponse;
249
+ sendMessage (event: string, payload: PondMessage, recipient: string[]): void;
286
250
 
287
251
  /**
288
- * @desc Sends a message to all clients in the channel
289
- * @param event - the event to send
290
- * @param payload - the payload to send
252
+ * @desc Broadcasts a message to every other client in the channel except yourself.
253
+ * @param event - The event to send.
254
+ * @param payload - The message to send.
291
255
  */
292
- broadcast (event: string, payload: PondMessage): EventResponse;
256
+ broadcastFrom (event: string, payload: PondMessage): void;
293
257
 
294
258
  /**
295
- * @desc Sends a message to all clients in the channel except the client making the request
296
- * @param event - the event to send
297
- * @param payload - the payload to send
259
+ * @desc Broadcasts a message to the channel, including yourself.
260
+ * @param event - The event to send.
261
+ * @param payload - The message to send.
298
262
  */
299
- broadcastFromUser (event: string, payload: PondMessage): EventResponse;
263
+ broadcast (event: string, payload: PondMessage): void;
300
264
 
301
265
  /**
302
- * @desc Sends a message to a set of clients in the channel
303
- * @param event - the event to send
304
- * @param payload - the payload to send
305
- * @param userIds - the ids of the clients to send the message to
266
+ * @desc Gets the current presence of the channel.
306
267
  */
307
- sendToUsers (event: string, payload: PondMessage, userIds: string[]): EventResponse;
268
+ getPresence (): PondPresence[];
308
269
 
309
270
  /**
310
- * @desc Tracks a user's presence in the channel
311
- * @param presence - the initial presence data
312
- * @param userId - the id of the user to track
271
+ * @desc Monitors the presence of the channel.
272
+ * @param callback - The callback to call when the presence changes.
313
273
  */
314
- trackPresence (presence: PondPresence, userId?: string): EventResponse;
274
+ onUsersChange (callback: (users: PondPresence[]) => void): Unsubscribe;
315
275
 
316
276
  /**
317
- * @desc Updates a user's presence in the channel
318
- * @param presence - the updated presence data
319
- * @param userId - the id of the user to update
277
+ * @desc Gets the current connection state of the channel.
320
278
  */
321
- updatePresence (presence: PondPresence, userId?: string): EventResponse;
279
+ isConnected (): boolean;
322
280
 
323
281
  /**
324
- * @desc Removes a user's presence from the channel
325
- * @param userId - the id of the user to remove
282
+ * @desc Monitors the connection state of the channel.
283
+ * @param callback - The callback to call when the connection state changes.
326
284
  */
327
- unTrackPresence (userId?: string): EventResponse;
285
+ onConnectionChange (callback: (connected: boolean) => void): Unsubscribe;
286
+ }
328
287
 
288
+ export declare class Endpoint {
329
289
  /**
330
- * @desc Evicts a user from the channel
331
- * @param reason - the reason for the eviction
332
- * @param userId - the id of the user to evict,
290
+ * @desc Adds a new PondChannel to this path on this endpoint
291
+ * @param path - The path to add the channel to
292
+ * @param handler - The handler to use to authenticate the client
293
+ *
294
+ * @example
295
+ * const channel = endpoint.createChannel('/chat', (request, response) => {
296
+ * if (request.user.assigns.admin)
297
+ * response.accept();
298
+ *
299
+ * else
300
+ * response.reject('You are not an admin', 403);
301
+ * });
333
302
  */
334
- evictUser (reason: string, userId?: string): void;
303
+ createChannel<Path extends string> (path: PondPath<Path>, handler: (request: JoinRequest<Path>, response: JoinResponse) => void | Promise<void>): PondChannel;
335
304
 
336
305
  /**
337
- * @desc Closes the channel from the server side for all clients
338
- * @param reason - the reason for closing the channel
306
+ * @desc Broadcasts a message to all clients connected to this endpoint
307
+ * @param event - The event to broadcast
308
+ * @param payload - The payload to broadcast
339
309
  */
340
- closeChannel (reason: string): void;
310
+ broadcast (event: string, payload: PondMessage): void;
341
311
 
342
312
  /**
343
- * @desc Resolves the request as sent with no further action
313
+ * @desc Closes specific clients connected to this endpoint
314
+ * @param clientIds - The id for the client / clients to close
344
315
  */
345
- end (): void;
316
+ closeConnection (clientIds: string | string[]): void;
346
317
  }
347
318
 
348
- declare class JoinRequest extends AbstractRequest {
349
- get joinParams (): JoinParams;
319
+ export declare class JoinRequest<Path extends string> extends AbstractRequest<Path> {
320
+ joinParams: JoinParams;
350
321
 
351
- get user (): UserData;
352
-
353
- get event (): EventObject;
322
+ user: UserData;
354
323
  }
355
324
 
356
- declare class JoinResponse {
357
- get responseSent (): boolean;
325
+ export declare class JoinResponse extends PondResponse {
326
+ #private;
358
327
 
359
328
  /**
360
329
  * @desc Accepts the request and optionally assigns data to the client
@@ -404,28 +373,32 @@ declare class JoinResponse {
404
373
  * @param presence - the presence data to track
405
374
  */
406
375
  trackPresence (presence: PondPresence): JoinResponse;
376
+ }
407
377
 
378
+ export declare class ConnectionResponse extends PondResponse {
408
379
  /**
409
- * @desc Resolves the request as sent with no further action
380
+ * @desc Accepts the request and optionally assigns data to the client
381
+ * @param assigns - the data to assign to the client
410
382
  */
411
- end (): void;
412
- }
383
+ accept (assigns?: PondAssigns): void;
413
384
 
414
- declare class PondChannel {
415
385
  /**
416
- * @desc Authorize a user to join a channel
417
- * @param handler - The handler to authorize the user
418
- * @example
419
- * const pond = new PondChannelEngine();
420
- * pond.onJoinRequest((request, response) => {
421
- * if (request.user.assigns.admin)
422
- * response.accept();
423
- * else
424
- * response.reject('You are not an admin', 403);
425
- * });
386
+ * @desc Rejects the request with the given error message
387
+ * @param message - the error message
388
+ * @param errorCode - the error code
389
+ */
390
+ reject (message?: string, errorCode?: number): void;
391
+
392
+ /**
393
+ * @desc Emits a direct message to the client
394
+ * @param event - the event name
395
+ * @param payload - the payload to send
396
+ * @param assigns - the data to assign to the client
426
397
  */
427
- onJoinRequest (handler: AuthorizeMiddleware): void;
398
+ send (event: string, payload: PondMessage, assigns?: PondAssigns): void;
399
+ }
428
400
 
401
+ export declare class PondChannel {
429
402
  /**
430
403
  * @desc Handles an event request made by a user
431
404
  * @param event - The event to listen for
@@ -437,7 +410,7 @@ declare class PondChannel {
437
410
  * });
438
411
  * });
439
412
  */
440
- onEvent (event: PondPath, handler: (request: EventRequest, response: EventResponse) => void | Promise<void>): void;
413
+ onEvent<Event extends string> (event: PondPath<Event>, handler: (request: EventRequest<Event>, response: EventResponse) => void | Promise<void>): void;
441
414
 
442
415
  /**
443
416
  * @desc Broadcasts a message to all users in a channel
@@ -454,84 +427,41 @@ declare class PondChannel {
454
427
  broadcast (event: string, payload: PondMessage, channelName?: string): void;
455
428
  }
456
429
 
457
- declare class ConnectionResponse {
458
- /**
459
- * @desc Accepts the request and optionally assigns data to the client
460
- * @param assigns - the data to assign to the client
461
- */
462
- accept (assigns?: PondAssigns): void;
463
-
464
- /**
465
- * @desc Rejects the request with the given error message
466
- * @param message - the error message
467
- * @param errorCode - the error code
468
- */
469
- reject (message?: string, errorCode?: number): void;
430
+ export declare class PondSocket {
431
+ constructor (server?: HTTPServer, socketServer?: WebSocketServer);
470
432
 
471
433
  /**
472
- * @desc Emits a direct message to the client
473
- * @param event - the event name
474
- * @param payload - the payload to send
475
- * @param assigns - the data to assign to the client
434
+ * @desc Specifies the port to listen on
435
+ * @param args - the arguments to pass to the server
476
436
  */
477
- send (event: string, payload: PondMessage, assigns?: PondAssigns): void;
437
+ listen (...args: any[]): HTTPServer<typeof import('http').IncomingMessage, typeof import('http').ServerResponse>;
478
438
 
479
439
  /**
480
- * @desc Resolves the request as sent with no further action
440
+ * @desc Closes the server
441
+ * @param callback - the callback to call when the server is closed
481
442
  */
482
- end (): void;
483
- }
443
+ close (callback?: () => void): HTTPServer<typeof import('http').IncomingMessage, typeof import('http').ServerResponse>;
484
444
 
485
- declare class Endpoint {
486
445
  /**
487
- * @desc Adds a new PondChannel to this path on this endpoint
488
- * @param path - The path to add the channel to
489
- * @param channel - The channel to add
490
- *
446
+ * @desc Accepts a new socket upgrade request on the provided endpoint using the handler function to authenticate the socket
447
+ * @param path - the pattern to accept || can also be a regex
448
+ * @param handler - the handler function to authenticate the socket
491
449
  * @example
492
- * endpoint.addChannel('/chat', pondChannelInstance);
493
- */
494
- addChannel (path: PondPath, channel: PondChannel): void;
495
-
496
- /**
497
- * @desc List all clients connected to this endpoint
498
- */
499
- listConnections (): string[];
500
-
501
- /**
502
- * @desc Gets all clients connected to this endpoint
503
- */
504
- getClients (): SocketCache[];
505
-
506
- /**
507
- * @desc Broadcasts a message to all clients connected to this endpoint
508
- * @param event - The event to broadcast
509
- * @param payload - The payload to broadcast
510
- */
511
- broadcast (event: string, payload: PondMessage): void;
512
-
513
- /**
514
- * @desc Closes specific clients connected to this endpoint
515
- * @param clientIds - The id for the client / clients to close
450
+ * const endpoint = pond.createEndpoint('/api/socket', (req, res) => {
451
+ * const token = req.query.token;
452
+ * if (!token)
453
+ * return res.reject('No token provided');
454
+ * res.accept({
455
+ * assign: {
456
+ * token
457
+ * }
458
+ * });
459
+ * })
516
460
  */
517
- closeConnection (clientIds: string | string[]): void;
461
+ createEndpoint<Path extends string> (path: PondPath<Path>, handler: (request: IncomingConnection<Path>, response: ConnectionResponse) => void | Promise<void>): Endpoint;
518
462
  }
519
463
 
520
- declare class PondSocket {
521
- constructor (server?: HTTPServer, socketServer?: WebSocketServer);
522
-
523
- /**
524
- * @desc Specifies the port to listen on
525
- * @param port - the port to listen on
526
- * @param callback - the callback to call when the server is listening
527
- */
528
- listen (port: number, callback: (port?: number) => void): HTTPServer<typeof IncomingMessage, typeof import('http').ServerResponse>;
529
-
530
- /**
531
- * @desc Closes the server
532
- * @param callback - the callback to call when the server is closed
533
- */
534
- close (callback?: () => void): HTTPServer<typeof IncomingMessage, typeof import('http').ServerResponse>;
464
+ interface PondSocketExpressApp extends Express {
535
465
 
536
466
  /**
537
467
  * @desc Accepts a new socket upgrade request on the provided endpoint using the handler function to authenticate the socket
@@ -549,19 +479,40 @@ declare class PondSocket {
549
479
  * });
550
480
  * })
551
481
  */
552
- createEndpoint (path: PondPath, handler: EndpointHandler): Endpoint;
482
+ upgrade<Path extends string> (path: PondPath<Path>, handler: (request: IncomingConnection<Path>, response: ConnectionResponse) => void | Promise<void>): Endpoint;
483
+ }
484
+
485
+ export declare class PondClient {
486
+ constructor (endpoint: string, params?: Record<string, any>);
487
+
488
+ /**
489
+ * @desc Connects to the server and returns the socket.
490
+ */
491
+ connect (backoff?: number): void;
492
+
493
+ /**
494
+ * @desc Returns the current state of the socket.
495
+ */
496
+ getState (): boolean;
553
497
 
554
498
  /**
555
- * @desc Adds a middleware function to the socket server
556
- * @param middleware - the middleware function to add
499
+ * @desc Disconnects the socket.
500
+ */
501
+ disconnect (): void;
502
+
503
+ /**
504
+ * @desc Creates a channel with the given name and params.
505
+ * @param name - The name of the channel.
506
+ * @param params - The params to send to the server.
507
+ */
508
+ createChannel (name: string, params?: JoinParams): Channel;
509
+
510
+ /**
511
+ * @desc Subscribes to the connection state.
512
+ * @param callback - The callback to call when the state changes.
557
513
  */
558
- use (middleware: SocketMiddlewareFunction): void;
514
+ onConnectionChange (callback: (state: boolean) => void): Unsubscribe;
559
515
  }
560
516
 
561
- /**
562
- * @desc Creates a pond socket server
563
- * @param app - The Express app to be used by the server
564
- * @constructor
565
- */
566
- declare const PondSocketFromExpress: (app: Express) => PondSocketExpressApp;
517
+ declare const pondSocket: (app: Express) => PondSocketExpressApp;
567
518