@fairwords/websocket 1.0.36 → 1.0.37

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