UNPKG

29.3 kBTypeScriptView Raw
1/// <reference types="node" />
2
3import events = require("events");
4import http = require("http");
5import https = require("https");
6import net = require("net");
7import url = require("url");
8
9export interface IStringified {
10 toString: (...args: any[]) => string;
11}
12
13export interface IConfig {
14 /**
15 * The maximum allowed received frame size in bytes.
16 * Single frame messages will also be limited to this maximum.
17 * @default 1MiB
18 */
19 maxReceivedFrameSize?: number | undefined;
20
21 /**
22 * The maximum allowed aggregate message size (for fragmented messages) in bytes
23 * @default 8MiB
24 */
25 maxReceivedMessageSize?: number | undefined;
26
27 /**
28 * Whether or not to fragment outgoing messages. If true, messages will be
29 * automatically fragmented into chunks of up to `fragmentationThreshold` bytes.
30 * @default true
31 */
32 fragmentOutgoingMessages?: boolean | undefined;
33
34 /**
35 * The maximum size of a frame in bytes before it is automatically fragmented.
36 * @default 16KiB
37 */
38 fragmentationThreshold?: number | undefined;
39
40 /**
41 * If true, fragmented messages will be automatically assembled and the full
42 * message will be emitted via a `message` event. If false, each frame will be
43 * emitted on the `connection` object via a `frame` event and the application
44 * will be responsible for aggregating multiple fragmented frames. Single-frame
45 * messages will emit a `message` event in addition to the `frame` event.
46 * @default true
47 */
48 assembleFragments?: boolean | undefined;
49
50 /**
51 * The number of milliseconds to wait after sending a close frame for an
52 * `acknowledgement` to come back before giving up and just closing the socket.
53 * @default 5000
54 */
55 closeTimeout?: number | undefined;
56
57 /**
58 * The Nagle Algorithm makes more efficient use of network resources by introducing a
59 * small delay before sending small packets so that multiple messages can be batched
60 * together before going onto the wire. This however comes at the cost of latency.
61 * @default true
62 */
63 disableNagleAlgorithm?: boolean | undefined;
64}
65
66export interface IServerConfig extends IConfig {
67 /** The http or https server instance(s) to attach to */
68 httpServer: http.Server | https.Server | Array<http.Server | https.Server>;
69
70 /**
71 * The maximum allowed received frame size in bytes.
72 * Single frame messages will also be limited to this maximum.
73 * @default 64KiB
74 */
75 maxReceivedFrameSize?: number | undefined;
76
77 /**
78 * The maximum allowed aggregate message size (for fragmented messages) in bytes.
79 * @default 1MiB
80 */
81 maxReceivedMessageSize?: number | undefined;
82
83 /**
84 * If true, the server will automatically send a ping to all clients every
85 * `keepaliveInterval` milliseconds. Each client has an independent `keepalive`
86 * timer, which is reset when any data is received from that client.
87 * @default true
88 */
89 keepalive?: boolean | undefined;
90
91 /**
92 * The interval in milliseconds to send `keepalive` pings to connected clients.
93 * @default 20000
94 */
95 keepaliveInterval?: number | undefined;
96
97 /**
98 * If true, the server will consider any connection that has not received any
99 * data within the amount of time specified by `keepaliveGracePeriod` after a
100 * `keepalive` ping has been sent. Ignored if `keepalive` is false.
101 * @default true
102 */
103 dropConnectionOnKeepaliveTimeout?: boolean | undefined;
104
105 /**
106 * The amount of time to wait after sending a `keepalive` ping before closing
107 * the connection if the connected peer does not respond. Ignored if `keepalive`
108 * or `dropConnectionOnKeepaliveTimeout` are false. The grace period timer is
109 * reset when any data is received from the client.
110 * @default 10000
111 */
112 keepaliveGracePeriod?: number | undefined;
113
114 /**
115 * Whether to use native TCP keep-alive instead of WebSockets ping
116 * and pong packets. Native TCP keep-alive sends smaller packets
117 * on the wire and so uses bandwidth more efficiently. This may
118 * be more important when talking to mobile devices.
119 * If this value is set to true, then these values will be ignored:
120 * keepaliveGracePeriod
121 * dropConnectionOnKeepaliveTimeout
122 * @default false
123 */
124 useNativeKeepalive?: boolean | undefined;
125
126 /**
127 * If this is true, websocket connections will be accepted regardless of the path
128 * and protocol specified by the client. The protocol accepted will be the first
129 * that was requested by the client.
130 * @default false
131 */
132 autoAcceptConnections?: boolean | undefined;
133
134 /**
135 * Whether or not the X-Forwarded-For header should be respected.
136 * It's important to set this to 'true' when accepting connections
137 * from untrusted clients, as a malicious client could spoof its
138 * IP address by simply setting this header. It's meant to be added
139 * by a trusted proxy or other intermediary within your own
140 * infrastructure.
141 * See: http://en.wikipedia.org/wiki/X-Forwarded-For
142 * @default false
143 */
144 ignoreXForwardedFor?: boolean | undefined;
145}
146
147export class server extends events.EventEmitter {
148 config?: IServerConfig | undefined;
149 connections: connection[];
150 pendingRequests: request[];
151
152 constructor(serverConfig?: IServerConfig);
153
154 /** Send binary or UTF-8 message for each connection */
155 broadcast(data: Buffer | IStringified): void;
156 /** Send binary message for each connection */
157 broadcastBytes(data: Buffer): void;
158 /** Send UTF-8 message for each connection */
159 broadcastUTF(data: IStringified): void;
160 /** Attach the `server` instance to a Node http.Server instance */
161 mount(serverConfig: IServerConfig): void;
162
163 /**
164 * Detach the `server` instance from the Node http.Server instance.
165 * All existing connections are left alone and will not be affected,
166 * but no new WebSocket connections will be accepted.
167 */
168 unmount(): void;
169
170 /** Close all open WebSocket connections */
171 closeAllConnections(): void;
172 /** Close all open WebSocket connections and unmount the server */
173 shutDown(): void;
174
175 handleUpgrade(request: http.IncomingMessage, socket: net.Socket): void;
176 handleRequestAccepted(connection: connection): void;
177 handleConnectionClose(connection: connection, closeReason: number, description: string): void;
178 handleRequestResolved(request: request): void;
179
180 // Events
181 on(event: "request", cb: (request: request) => void): this;
182 on(event: "connect", cb: (connection: connection) => void): this;
183 on(event: "close", cb: (connection: connection, reason: number, desc: string) => void): this;
184 addListener(event: "request", cb: (request: request) => void): this;
185 addListener(event: "connect", cb: (connection: connection) => void): this;
186 addListener(event: "close", cb: (connection: connection, reason: number, desc: string) => void): this;
187}
188
189export interface ICookie {
190 name: string;
191 value: string;
192 path?: string | undefined;
193 domain?: string | undefined;
194 expires?: Date | undefined;
195 maxage?: number | undefined;
196 secure?: boolean | undefined;
197 httponly?: boolean | undefined;
198}
199
200export interface IExtension {
201 name: string;
202 value: string;
203}
204
205export class request extends events.EventEmitter {
206 /** A reference to the original Node HTTP request object */
207 httpRequest: http.IncomingMessage;
208 /** This will include the port number if a non-standard port is used */
209 host: string;
210 /** A string containing the path that was requested by the client */
211 resource: string;
212 /** `Sec-WebSocket-Key` */
213 key: string;
214 /** Parsed resource, including the query string parameters */
215 resourceURL: url.UrlWithParsedQuery;
216
217 /**
218 * Client's IP. If an `X-Forwarded-For` header is present, the value will be taken
219 * from that header to facilitate WebSocket servers that live behind a reverse-proxy
220 */
221 remoteAddress: string;
222 remoteAddresses: string[];
223
224 /**
225 * If the client is a web browser, origin will be a string containing the URL
226 * of the page containing the script that opened the connection.
227 * If the client is not a web browser, origin may be `null` or "*".
228 */
229 origin: string;
230
231 /** The version of the WebSocket protocol requested by the client */
232 webSocketVersion: number;
233 /** An array containing a list of extensions requested by the client */
234 requestedExtensions: any[];
235
236 cookies: ICookie[];
237 socket: net.Socket;
238
239 /**
240 * List of strings that indicate the subprotocols the client would like to speak.
241 * The server should select the best one that it can support from the list and
242 * pass it to the `accept` function when accepting the connection.
243 * Note that all the strings in the `requestedProtocols` array will have been
244 * converted to lower case.
245 */
246 requestedProtocols: string[];
247 protocolFullCaseMap: { [key: string]: string };
248
249 serverConfig: IServerConfig;
250
251 _resolved: boolean;
252 _socketIsClosing: boolean;
253
254 constructor(socket: net.Socket, httpRequest: http.IncomingMessage, config: IServerConfig);
255
256 /**
257 * After inspecting the `request` properties, call this function on the
258 * request object to accept the connection. If you don't have a particular subprotocol
259 * you wish to speak, you may pass `null` for the `acceptedProtocol` parameter.
260 *
261 * @param [acceptedProtocol] case-insensitive value that was requested by the client
262 */
263 accept(acceptedProtocol?: string | null, allowedOrigin?: string, cookies?: ICookie[]): connection;
264
265 /**
266 * Reject connection.
267 * You may optionally pass in an HTTP Status code (such as 404) and a textual
268 * description that will be sent to the client in the form of an
269 * `X-WebSocket-Reject-Reason` header.
270 * Optional extra http headers can be added via Object key/values on extraHeaders.
271 */
272 reject(httpStatus?: number, reason?: string, extraHeaders?: object): void;
273
274 // Events
275 on(event: "requestResolved" | "requestRejected", cb: (request: this) => void): this;
276 on(event: "requestAccepted", cb: (connection: connection) => void): this;
277 addListener(event: "requestResolved" | "requestRejected", cb: (request: this) => void): this;
278 addListener(event: "requestAccepted", cb: (connection: connection) => void): this;
279
280 readHandshake(): void;
281
282 parseExtensions(extensionString: string): string[];
283
284 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
285 parseCookies(str: string): ICookie[] | void;
286
287 _handleSocketCloseBeforeAccept(): void;
288 _removeSocketCloseListeners(): void;
289 _verifyResolution(): void;
290}
291
292export interface IUtf8Message {
293 type: "utf8";
294 utf8Data: string;
295}
296
297export interface IBinaryMessage {
298 type: "binary";
299 binaryData: Buffer;
300}
301
302export type Message = IUtf8Message | IBinaryMessage;
303
304export interface IBufferList extends events.EventEmitter {
305 encoding: string;
306 length: number;
307 write(buf: Buffer): boolean;
308 end(buf: Buffer): void;
309 push(): void;
310
311 /**
312 * For each buffer, perform some action.
313 * If fn's result is a true value, cut out early.
314 */
315 forEach(fn: (buf: Buffer) => boolean): void;
316
317 /** Create a single buffer out of all the chunks */
318 join(start: number, end: number): Buffer;
319
320 /** Join all the chunks to existing buffer */
321 joinInto(buf: Buffer, offset: number, start: number, end: number): Buffer;
322
323 /**
324 * Advance the buffer stream by `n` bytes.
325 * If `n` the aggregate advance offset passes the end of the buffer list,
326 * operations such as `take` will return empty strings until enough data is pushed.
327 */
328 advance(n: number): IBufferList;
329
330 /**
331 * Take `n` bytes from the start of the buffers.
332 * If there are less than `n` bytes in all the buffers or `n` is undefined,
333 * returns the entire concatenated buffer string.
334 */
335 take(n: number, encoding?: string): any;
336 take(encoding?: string): any;
337
338 toString(): string;
339
340 // Events
341 on(event: "advance", cb: (n: number) => void): this;
342 on(event: "write", cb: (buf: Buffer) => void): this;
343 addListener(event: "advance", cb: (n: number) => void): this;
344 addListener(event: "write", cb: (buf: Buffer) => void): this;
345}
346
347export class connection extends events.EventEmitter {
348 static CLOSE_REASON_NORMAL: number;
349 static CLOSE_REASON_GOING_AWAY: number;
350 static CLOSE_REASON_PROTOCOL_ERROR: number;
351 static CLOSE_REASON_UNPROCESSABLE_INPUT: number;
352 static CLOSE_REASON_RESERVED: number;
353 static CLOSE_REASON_NOT_PROVIDED: number;
354 static CLOSE_REASON_ABNORMAL: number;
355 static CLOSE_REASON_INVALID_DATA: number;
356 static CLOSE_REASON_POLICY_VIOLATION: number;
357 static CLOSE_REASON_MESSAGE_TOO_BIG: number;
358 static CLOSE_REASON_EXTENSION_REQUIRED: number;
359
360 static CLOSE_DESCRIPTIONS: { [code: number]: string };
361
362 /**
363 * After the connection is closed, contains a textual description of the reason for
364 * the connection closure, or `null` if the connection is still open.
365 */
366 closeDescription: string;
367
368 /**
369 * After the connection is closed, contains the numeric close reason status code,
370 * or `-1` if the connection is still open.
371 */
372 closeReasonCode: number;
373
374 /**
375 * The subprotocol that was chosen to be spoken on this connection. This field
376 * will have been converted to lower case.
377 */
378 protocol: string;
379
380 config: IConfig;
381 socket: net.Socket;
382 maskOutgoingPackets: boolean;
383 maskBytes: Buffer;
384 frameHeader: Buffer;
385 bufferList: IBufferList;
386 currentFrame: frame;
387 fragmentationSize: number;
388 frameQueue: frame[];
389 state: string;
390 waitingForCloseResponse: boolean;
391 receivedEnd: boolean;
392 closeTimeout: number;
393 assembleFragments: number;
394 maxReceivedMessageSize: number;
395 outputBufferFull: boolean;
396 inputPaused: boolean;
397 bytesWaitingToFlush: number;
398 socketHadError: boolean;
399
400 /** An array of extensions that were negotiated for this connection */
401 extensions: IExtension[];
402
403 /**
404 * The IP address of the remote peer as a string. In the case of a server,
405 * the `X-Forwarded-For` header will be respected and preferred for the purposes
406 * of populating this field. If you need to get to the actual remote IP address,
407 * `socket.remoteAddress` will provide it.
408 */
409 remoteAddress: string;
410
411 /** The version of the WebSocket protocol requested by the client */
412 webSocketVersion: number;
413 /** Whether or not the connection is still connected. Read-only */
414 connected: boolean;
415
416 _pingListenerCount: number;
417
418 constructor(
419 socket: net.Socket,
420 extensions: IExtension[],
421 protocol: string,
422 maskOutgoingPackets: boolean,
423 config: IConfig,
424 );
425
426 /**
427 * Close the connection. A close frame will be sent to the remote peer indicating
428 * that we wish to close the connection, and we will then wait for up to
429 * `config.closeTimeout` milliseconds for an acknowledgment from the remote peer
430 * before terminating the underlying socket connection.
431 */
432 close(reasonCode?: number, description?: string): void;
433
434 /**
435 * Send a close frame to the remote peer and immediately close the socket without
436 * waiting for a response. This should generally be used only in error conditions.
437 */
438 drop(reasonCode?: number, description?: string, skipCloseFrame?: boolean): void;
439
440 /**
441 * Immediately sends the specified string as a UTF-8 WebSocket message to the remote
442 * peer. If `config.fragmentOutgoingMessages` is true the message may be sent as
443 * multiple fragments if it exceeds `config.fragmentationThreshold` bytes.
444 */
445 sendUTF(data: IStringified, cb?: (err?: Error) => void): void;
446
447 /**
448 * Immediately sends the specified Node Buffer object as a Binary WebSocket message
449 * to the remote peer. If config.fragmentOutgoingMessages is true the message may be
450 * sent as multiple fragments if it exceeds config.fragmentationThreshold bytes.
451 */
452 sendBytes(buffer: Buffer, cb?: (err?: Error) => void): void;
453
454 /** Auto-detect the data type and send UTF-8 or Binary message */
455 send(data: Buffer | IStringified, cb?: (err?: Error) => void): void;
456
457 /** Sends a ping frame. Ping frames must not exceed 125 bytes in length. */
458 ping(data: Buffer | IStringified): void;
459
460 /**
461 * Sends a pong frame. Pong frames may be sent unsolicited and such pong frames will
462 * trigger no action on the receiving peer. Pong frames sent in response to a ping
463 * frame must mirror the payload data of the ping frame exactly.
464 * The `connection` object handles this internally for you, so there should
465 * be no need to use this method to respond to pings.
466 * Pong frames must not exceed 125 bytes in length.
467 */
468 pong(buffer: Buffer): void;
469
470 /**
471 * Serializes a `frame` object into binary data and immediately sends it to
472 * the remote peer. This is an advanced function, requiring you to manually compose
473 * your own `frame`. You should probably use sendUTF or sendBytes instead.
474 */
475 sendFrame(frame: frame, cb?: (err?: Error) => void): void;
476
477 /** Set or reset the `keepalive` timer when data is received */
478 setKeepaliveTimer(): void;
479 clearKeepaliveTimer(): void;
480 handleKeepaliveTimer(): void;
481 setGracePeriodTimer(): void;
482 clearGracePeriodTimer(): void;
483 handleGracePeriodTimer(): void;
484 handleSocketData(data: Buffer): void;
485 processReceivedData(): void;
486 handleSocketError(error: Error): void;
487 handleSocketEnd(): void;
488 handleSocketClose(hadError: boolean): void;
489 handleSocketDrain(): void;
490 handleSocketPause(): void;
491 handleSocketResume(): void;
492 pause(): void;
493 resume(): void;
494
495 setCloseTimer(): void;
496 clearCloseTimer(): void;
497 handleCloseTimer(): void;
498 processFrame(frame: frame): void;
499 fragmentAndSend(frame: frame, cb?: (err: Error) => void): void;
500 sendCloseFrame(reasonCode?: number, reasonText?: string, cb?: (err?: Error) => void): void;
501
502 _addSocketEventListeners(): void;
503
504 // Events
505 on(event: "message", cb: (data: Message) => void): this;
506 on(event: "frame", cb: (frame: frame) => void): this;
507 on(event: "close", cb: (code: number, desc: string) => void): this;
508 on(event: "error", cb: (err: Error) => void): this;
509 on(event: "drain" | "pause" | "resume", cb: () => void): this;
510 on(event: "ping", cb: (cancel: () => void, binaryPayload: Buffer) => void): this;
511 on(event: "pong", cb: (binaryPayload: Buffer) => void): this;
512 addListener(event: "message", cb: (data: Message) => void): this;
513 addListener(event: "frame", cb: (frame: frame) => void): this;
514 addListener(event: "close", cb: (code: number, desc: string) => void): this;
515 addListener(event: "error", cb: (err: Error) => void): this;
516 addListener(event: "drain" | "pause" | "resume", cb: () => void): this;
517 addListener(event: "ping", cb: (cancel: () => void, binaryPayload: Buffer) => void): this;
518 addListener(event: "pong", cb: (binaryPayload: Buffer) => void): this;
519}
520
521export class frame {
522 /** Whether or not this is last frame in a fragmentation sequence */
523 fin: boolean;
524
525 /**
526 * Represents the RSV1 field in the framing. Setting this to true will result in
527 * a Protocol Error on the receiving peer.
528 */
529 rsv1: boolean;
530
531 /**
532 * Represents the RSV1 field in the framing. Setting this to true will result in
533 * a Protocol Error on the receiving peer.
534 */
535 rsv2: boolean;
536
537 /**
538 * Represents the RSV1 field in the framing. Setting this to true will result in
539 * a Protocol Error on the receiving peer.
540 */
541 rsv3: boolean;
542
543 /**
544 * Whether or not this frame is (or should be) masked. For outgoing frames, when
545 * connected as a client, this flag is automatically forced to true by `connection`.
546 * Outgoing frames sent from the server-side of a connection are not masked.
547 */
548 mask: number;
549
550 /**
551 * Identifies which kind of frame this is.
552 *
553 * Hex - Dec - Description
554 * 0x00 - 0 - Continuation
555 * 0x01 - 1 - Text Frame
556 * 0x02 - 2 - Binary Frame
557 * 0x08 - 8 - Close Frame
558 * 0x09 - 9 - Ping Frame
559 * 0x0A - 10 - Pong Frame
560 */
561 opcode: number;
562
563 /**
564 * Identifies the length of the payload data on a received frame.
565 * When sending a frame, will be automatically calculated from `binaryPayload` object.
566 */
567 length: number;
568
569 /**
570 * The binary payload data.
571 * Even text frames are sent with a Buffer providing the binary payload data.
572 */
573 binaryPayload: Buffer;
574
575 maskBytes: Buffer;
576 frameHeader: Buffer;
577 config: IConfig;
578 maxReceivedFrameSize: number;
579 protocolError: boolean;
580 dropReason: string;
581 frameTooLarge: boolean;
582 invalidCloseFrameLength: boolean;
583 parseState: number;
584 closeStatus: number;
585
586 addData(bufferList: IBufferList): boolean;
587 throwAwayPayload(bufferList: IBufferList): boolean;
588 toBuffer(nullMask: boolean): Buffer;
589 toString(): string;
590}
591
592export interface IClientConfig extends IConfig {
593 /**
594 * Which version of the WebSocket protocol to use when making the connection.
595 * Currently supported values are 8 and 13. This option will be removed once the
596 * protocol is finalized by the IETF It is only available to ease the transition
597 * through the intermediate draft protocol versions. The only thing this affects
598 * the name of the Origin header.
599 * @default 13
600 */
601 webSocketVersion?: number | undefined;
602
603 /**
604 * Options to pass to `https.request` if connecting via TLS.
605 * @see https://nodejs.org/api/https.html#https_https_request_options_callback
606 */
607 tlsOptions?: https.RequestOptions | undefined;
608}
609
610export class client extends events.EventEmitter {
611 constructor(ClientConfig?: IClientConfig);
612
613 /**
614 * Establish a connection. The remote server will select the best subprotocol that
615 * it supports and send that back when establishing the connection.
616 *
617 * @param requestUrl should be a standard websocket url
618 * @param [requestedProtocols] list of subprotocols supported by the client.
619 * The remote server will select the best subprotocol that it supports and send that back when establishing the connection.
620 * @param [origin] Used in user-agent scenarios to identify the page containing
621 * any scripting content that caused the connection to be requested.
622 * @param [headers] additional arbitrary HTTP request headers to send along with the request.
623 * This may be used to pass things like access tokens, etc. so that the server can verify authentication/authorization
624 * before deciding to accept and open the full WebSocket connection.
625 * @param [extraRequestOptions] additional configuration options to be passed to `http.request` or `https.request`.
626 * This can be used to pass a custom `agent` to enable `client` usage from behind an HTTP or HTTPS proxy server
627 * using {@link https://github.com/koichik/node-tunnel|koichik/node-tunnel} or similar.
628 * @example client.connect('ws://www.mygreatapp.com:1234/websocketapp/')
629 */
630 connect(
631 requestUrl: url.Url | string,
632 requestedProtocols?: string | string[],
633 origin?: string,
634 headers?: http.OutgoingHttpHeaders,
635 extraRequestOptions?: http.RequestOptions,
636 ): void;
637
638 /**
639 * Will cancel an in-progress connection request before either the `connect` event or the `connectFailed` event has been emitted.
640 * If the `connect` or `connectFailed` event has already been emitted, calling `abort()` will do nothing.
641 */
642 abort(): void;
643
644 // Events
645 on(event: "connect", cb: (connection: connection) => void): this;
646 on(event: "connectFailed", cb: (err: Error) => void): this;
647 on(event: "httpResponse", cb: (response: http.IncomingMessage, client: client) => void): this;
648 addListener(event: "connect", cb: (connection: connection) => void): this;
649 addListener(event: "connectFailed", cb: (err: Error) => void): this;
650 addListener(event: "httpResponse", cb: (response: http.IncomingMessage, client: client) => void): this;
651}
652
653export interface IRouterRequest extends events.EventEmitter {
654 webSocketRequest: request;
655 protocol: string | null;
656
657 /**
658 * If the client is a web browser, origin will be a string containing the URL
659 * of the page containing the script that opened the connection.
660 * If the client is not a web browser, origin may be `null` or "*".
661 */
662 origin: string;
663
664 /** A string containing the path that was requested by the client */
665 resource: string;
666 /** Parsed resource, including the query string parameters */
667 resourceURL: url.UrlWithParsedQuery;
668
669 /** A reference to the original Node HTTP request object */
670 httpRequest: http.IncomingMessage;
671
672 /**
673 * Client's IP. If an `X-Forwarded-For` header is present, the value will be taken
674 * from that header to facilitate WebSocket servers that live behind a reverse-proxy
675 */
676 remoteAddress: string;
677
678 /** The version of the WebSocket protocol requested by the client */
679 webSocketVersion: number;
680 /** An array containing a list of extensions requested by the client */
681 requestedExtensions: any[];
682
683 cookies: ICookie[];
684
685 /**
686 * After inspecting the `request` properties, call this function on the
687 * request object to accept the connection. If you don't have a particular subprotocol
688 * you wish to speak, you may pass `null` for the `acceptedProtocol` parameter.
689 *
690 * @param [acceptedProtocol] case-insensitive value that was requested by the client
691 */
692 accept(acceptedProtocol?: string, allowedOrigin?: string, cookies?: ICookie[]): connection;
693
694 /**
695 * Reject connection.
696 * You may optionally pass in an HTTP Status code (such as 404) and a textual
697 * description that will be sent to the client in the form of an
698 * `X-WebSocket-Reject-Reason` header.
699 */
700 reject(httpStatus?: number, reason?: string): void;
701
702 // Events
703 on(event: "requestAccepted", cb: (connection: connection) => void): this;
704 on(event: "requestRejected", cb: (request: this) => void): this;
705 addListener(event: "requestAccepted", cb: (connection: connection) => void): this;
706 addListener(event: "requestRejected", cb: (request: this) => void): this;
707}
708
709export interface IRouterConfig {
710 /*
711 * The WebSocketServer instance to attach to.
712 */
713 server: server;
714}
715
716export interface IRouterHandler {
717 path: string;
718 pathString: string;
719 protocol: string;
720 callback: (request: IRouterRequest) => void;
721}
722
723export class router extends events.EventEmitter {
724 handlers: IRouterHandler[];
725
726 constructor(config?: IRouterConfig);
727
728 /** Attach to WebSocket server */
729 attachServer(server: server): void;
730
731 /** Detach from WebSocket server */
732 detachServer(): void;
733
734 mount(path: string | RegExp, protocol: string | null, callback: (request: IRouterRequest) => void): void;
735
736 unmount(path: string | RegExp, protocol?: string): void;
737
738 findHandlerIndex(pathString: string, protocol: string): number;
739
740 pathToRegExp(path: string): RegExp;
741 pathToRegEx(path: RegExp): RegExp;
742
743 handleRequest(request: request): void;
744}
745
746export interface ICloseEvent {
747 code: number;
748 reason: string;
749 wasClean: boolean;
750}
751
752export interface IMessageEvent {
753 data: string | Buffer | ArrayBuffer;
754}
755
756export class w3cwebsocket {
757 static CONNECTING: number;
758 static OPEN: number;
759 static CLOSING: number;
760 static CLOSED: number;
761
762 _url: string;
763 _readyState: number;
764 _protocol?: string | undefined;
765 _extensions: IExtension[];
766 _bufferedAmount: number;
767 _binaryType: "arraybuffer";
768 _connection?: connection | undefined;
769 _client: client;
770
771 url: string;
772 readyState: number;
773 protocol?: string | undefined;
774 extensions: IExtension[];
775 bufferedAmount: number;
776
777 binaryType: "arraybuffer";
778
779 CONNECTING: number;
780 OPEN: number;
781 CLOSING: number;
782 CLOSED: number;
783
784 onopen: () => void;
785 onerror: (error: Error) => void;
786 onclose: (event: ICloseEvent) => void;
787 onmessage: (message: IMessageEvent) => void;
788
789 constructor(
790 url: string,
791 protocols?: string | string[],
792 origin?: string,
793 headers?: http.OutgoingHttpHeaders,
794 requestOptions?: object,
795 IClientConfig?: IClientConfig,
796 );
797
798 send(data: ArrayBufferView | ArrayBuffer | Buffer | IStringified): void;
799 close(code?: number, reason?: string): void;
800}
801
802export const deprecation: {
803 disableWarnings: boolean;
804 deprecationWarningMap: { [name: string]: string };
805 warn(deprecationName: string): void;
806};
807
808export const version: string;