dragonfly_chrome_headless 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (228) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +10 -0
  3. data/.travis.yml +12 -0
  4. data/Gemfile +4 -0
  5. data/README.md +53 -0
  6. data/Rakefile +10 -0
  7. data/bin/console +14 -0
  8. data/bin/setup +8 -0
  9. data/dragonfly_chrome_headless.gemspec +27 -0
  10. data/lib/dragonfly_chrome_headless.rb +9 -0
  11. data/lib/dragonfly_chrome_headless/plugin.rb +17 -0
  12. data/lib/dragonfly_chrome_headless/processors/rasterize.rb +33 -0
  13. data/lib/dragonfly_chrome_headless/version.rb +3 -0
  14. data/node_modules/.bin/chrome-remote-interface +1 -0
  15. data/node_modules/.bin/mkdirp +1 -0
  16. data/node_modules/.bin/rimraf +1 -0
  17. data/node_modules/@types/core-js/LICENSE +21 -0
  18. data/node_modules/@types/core-js/README.md +16 -0
  19. data/node_modules/@types/core-js/index.d.ts +2452 -0
  20. data/node_modules/@types/core-js/package.json +85 -0
  21. data/node_modules/@types/mkdirp/README.md +18 -0
  22. data/node_modules/@types/mkdirp/index.d.ts +14 -0
  23. data/node_modules/@types/mkdirp/package.json +77 -0
  24. data/node_modules/@types/mkdirp/types-metadata.json +25 -0
  25. data/node_modules/@types/node/README.md +16 -0
  26. data/node_modules/@types/node/index.d.ts +4132 -0
  27. data/node_modules/@types/node/package.json +84 -0
  28. data/node_modules/balanced-match/.npmignore +5 -0
  29. data/node_modules/balanced-match/LICENSE.md +21 -0
  30. data/node_modules/balanced-match/README.md +91 -0
  31. data/node_modules/balanced-match/index.js +59 -0
  32. data/node_modules/balanced-match/package.json +112 -0
  33. data/node_modules/brace-expansion/README.md +123 -0
  34. data/node_modules/brace-expansion/index.js +201 -0
  35. data/node_modules/brace-expansion/package.json +114 -0
  36. data/node_modules/chrome-launcher/.clang-format +6 -0
  37. data/node_modules/chrome-launcher/.npmignore +11 -0
  38. data/node_modules/chrome-launcher/README.md +123 -0
  39. data/node_modules/chrome-launcher/ask.js +32 -0
  40. data/node_modules/chrome-launcher/ask.ts +35 -0
  41. data/node_modules/chrome-launcher/chrome-finder.js +157 -0
  42. data/node_modules/chrome-launcher/chrome-finder.ts +186 -0
  43. data/node_modules/chrome-launcher/chrome-launcher.js +245 -0
  44. data/node_modules/chrome-launcher/chrome-launcher.ts +312 -0
  45. data/node_modules/chrome-launcher/compiled-check.js +14 -0
  46. data/node_modules/chrome-launcher/flags.js +27 -0
  47. data/node_modules/chrome-launcher/flags.ts +26 -0
  48. data/node_modules/chrome-launcher/index.js +7 -0
  49. data/node_modules/chrome-launcher/index.ts +1 -0
  50. data/node_modules/chrome-launcher/manual-chrome-launcher.js +30 -0
  51. data/node_modules/chrome-launcher/package.json +116 -0
  52. data/node_modules/chrome-launcher/random-port.js +24 -0
  53. data/node_modules/chrome-launcher/random-port.ts +23 -0
  54. data/node_modules/chrome-launcher/tsconfig.json +19 -0
  55. data/node_modules/chrome-launcher/utils.js +52 -0
  56. data/node_modules/chrome-launcher/utils.ts +44 -0
  57. data/node_modules/chrome-launcher/yarn.lock +1486 -0
  58. data/node_modules/chrome-remote-interface/LICENSE +18 -0
  59. data/node_modules/chrome-remote-interface/README.md +849 -0
  60. data/node_modules/chrome-remote-interface/bin/client.js +337 -0
  61. data/node_modules/chrome-remote-interface/chrome-remote-interface.js +11 -0
  62. data/node_modules/chrome-remote-interface/index.js +39 -0
  63. data/node_modules/chrome-remote-interface/lib/api.js +84 -0
  64. data/node_modules/chrome-remote-interface/lib/chrome.js +307 -0
  65. data/node_modules/chrome-remote-interface/lib/defaults.js +4 -0
  66. data/node_modules/chrome-remote-interface/lib/devtools.js +245 -0
  67. data/node_modules/chrome-remote-interface/lib/external-request.js +28 -0
  68. data/node_modules/chrome-remote-interface/lib/protocol.json +13780 -0
  69. data/node_modules/chrome-remote-interface/lib/websocket-wrapper.js +32 -0
  70. data/node_modules/chrome-remote-interface/package.json +128 -0
  71. data/node_modules/chrome-remote-interface/webpack.config.js +55 -0
  72. data/node_modules/commander/Readme.md +195 -0
  73. data/node_modules/commander/index.js +851 -0
  74. data/node_modules/commander/package.json +92 -0
  75. data/node_modules/concat-map/.travis.yml +4 -0
  76. data/node_modules/concat-map/LICENSE +18 -0
  77. data/node_modules/concat-map/README.markdown +62 -0
  78. data/node_modules/concat-map/example/map.js +6 -0
  79. data/node_modules/concat-map/index.js +13 -0
  80. data/node_modules/concat-map/package.json +117 -0
  81. data/node_modules/concat-map/test/map.js +39 -0
  82. data/node_modules/debug/.coveralls.yml +1 -0
  83. data/node_modules/debug/.eslintrc +11 -0
  84. data/node_modules/debug/.npmignore +9 -0
  85. data/node_modules/debug/.travis.yml +14 -0
  86. data/node_modules/debug/CHANGELOG.md +357 -0
  87. data/node_modules/debug/LICENSE +19 -0
  88. data/node_modules/debug/Makefile +50 -0
  89. data/node_modules/debug/Readme.md +312 -0
  90. data/node_modules/debug/component.json +19 -0
  91. data/node_modules/debug/karma.conf.js +70 -0
  92. data/node_modules/debug/node.js +1 -0
  93. data/node_modules/debug/package.json +124 -0
  94. data/node_modules/debug/src/browser.js +185 -0
  95. data/node_modules/debug/src/debug.js +202 -0
  96. data/node_modules/debug/src/index.js +10 -0
  97. data/node_modules/debug/src/node.js +246 -0
  98. data/node_modules/fs.realpath/LICENSE +43 -0
  99. data/node_modules/fs.realpath/README.md +33 -0
  100. data/node_modules/fs.realpath/index.js +66 -0
  101. data/node_modules/fs.realpath/old.js +303 -0
  102. data/node_modules/fs.realpath/package.json +94 -0
  103. data/node_modules/glob/LICENSE +15 -0
  104. data/node_modules/glob/README.md +368 -0
  105. data/node_modules/glob/changelog.md +67 -0
  106. data/node_modules/glob/common.js +240 -0
  107. data/node_modules/glob/glob.js +790 -0
  108. data/node_modules/glob/package.json +112 -0
  109. data/node_modules/glob/sync.js +486 -0
  110. data/node_modules/html-pdf-chrome/.npmignore +9 -0
  111. data/node_modules/html-pdf-chrome/LICENSE +21 -0
  112. data/node_modules/html-pdf-chrome/README.md +165 -0
  113. data/node_modules/html-pdf-chrome/lib/src/ChromePrintOptions.d.ts +87 -0
  114. data/node_modules/html-pdf-chrome/lib/src/ChromePrintOptions.js +4 -0
  115. data/node_modules/html-pdf-chrome/lib/src/ChromePrintOptions.js.map +1 -0
  116. data/node_modules/html-pdf-chrome/lib/src/CompletionTrigger.d.ts +120 -0
  117. data/node_modules/html-pdf-chrome/lib/src/CompletionTrigger.js +206 -0
  118. data/node_modules/html-pdf-chrome/lib/src/CompletionTrigger.js.map +1 -0
  119. data/node_modules/html-pdf-chrome/lib/src/CreateResult.d.ts +70 -0
  120. data/node_modules/html-pdf-chrome/lib/src/CreateResult.js +98 -0
  121. data/node_modules/html-pdf-chrome/lib/src/CreateResult.js.map +1 -0
  122. data/node_modules/html-pdf-chrome/lib/src/index.d.ts +72 -0
  123. data/node_modules/html-pdf-chrome/lib/src/index.js +123 -0
  124. data/node_modules/html-pdf-chrome/lib/src/index.js.map +1 -0
  125. data/node_modules/html-pdf-chrome/package.json +133 -0
  126. data/node_modules/html-pdf-chrome/src/ChromePrintOptions.ts +99 -0
  127. data/node_modules/html-pdf-chrome/src/CompletionTrigger.ts +201 -0
  128. data/node_modules/html-pdf-chrome/src/CreateResult.ts +100 -0
  129. data/node_modules/html-pdf-chrome/src/index.ts +179 -0
  130. data/node_modules/inflight/LICENSE +15 -0
  131. data/node_modules/inflight/README.md +37 -0
  132. data/node_modules/inflight/inflight.js +54 -0
  133. data/node_modules/inflight/package.json +105 -0
  134. data/node_modules/inherits/LICENSE +16 -0
  135. data/node_modules/inherits/README.md +42 -0
  136. data/node_modules/inherits/inherits.js +7 -0
  137. data/node_modules/inherits/inherits_browser.js +23 -0
  138. data/node_modules/inherits/package.json +97 -0
  139. data/node_modules/lighthouse-logger/README.md +4 -0
  140. data/node_modules/lighthouse-logger/index.js +212 -0
  141. data/node_modules/lighthouse-logger/package.json +69 -0
  142. data/node_modules/lighthouse-logger/yarn.lock +13 -0
  143. data/node_modules/minimatch/LICENSE +15 -0
  144. data/node_modules/minimatch/README.md +209 -0
  145. data/node_modules/minimatch/minimatch.js +923 -0
  146. data/node_modules/minimatch/package.json +99 -0
  147. data/node_modules/minimist/.travis.yml +4 -0
  148. data/node_modules/minimist/LICENSE +18 -0
  149. data/node_modules/minimist/example/parse.js +2 -0
  150. data/node_modules/minimist/index.js +187 -0
  151. data/node_modules/minimist/package.json +101 -0
  152. data/node_modules/minimist/readme.markdown +73 -0
  153. data/node_modules/minimist/test/dash.js +24 -0
  154. data/node_modules/minimist/test/default_bool.js +20 -0
  155. data/node_modules/minimist/test/dotted.js +16 -0
  156. data/node_modules/minimist/test/long.js +31 -0
  157. data/node_modules/minimist/test/parse.js +318 -0
  158. data/node_modules/minimist/test/parse_modified.js +9 -0
  159. data/node_modules/minimist/test/short.js +67 -0
  160. data/node_modules/minimist/test/whitespace.js +8 -0
  161. data/node_modules/mkdirp/.travis.yml +8 -0
  162. data/node_modules/mkdirp/LICENSE +21 -0
  163. data/node_modules/mkdirp/bin/cmd.js +33 -0
  164. data/node_modules/mkdirp/bin/usage.txt +12 -0
  165. data/node_modules/mkdirp/examples/pow.js +6 -0
  166. data/node_modules/mkdirp/index.js +98 -0
  167. data/node_modules/mkdirp/package.json +93 -0
  168. data/node_modules/mkdirp/readme.markdown +100 -0
  169. data/node_modules/mkdirp/test/chmod.js +41 -0
  170. data/node_modules/mkdirp/test/clobber.js +38 -0
  171. data/node_modules/mkdirp/test/mkdirp.js +28 -0
  172. data/node_modules/mkdirp/test/opts_fs.js +29 -0
  173. data/node_modules/mkdirp/test/opts_fs_sync.js +27 -0
  174. data/node_modules/mkdirp/test/perm.js +32 -0
  175. data/node_modules/mkdirp/test/perm_sync.js +36 -0
  176. data/node_modules/mkdirp/test/race.js +37 -0
  177. data/node_modules/mkdirp/test/rel.js +32 -0
  178. data/node_modules/mkdirp/test/return.js +25 -0
  179. data/node_modules/mkdirp/test/return_sync.js +24 -0
  180. data/node_modules/mkdirp/test/root.js +19 -0
  181. data/node_modules/mkdirp/test/sync.js +32 -0
  182. data/node_modules/mkdirp/test/umask.js +28 -0
  183. data/node_modules/mkdirp/test/umask_sync.js +32 -0
  184. data/node_modules/ms/README.md +51 -0
  185. data/node_modules/ms/index.js +152 -0
  186. data/node_modules/ms/license.md +21 -0
  187. data/node_modules/ms/package.json +109 -0
  188. data/node_modules/once/LICENSE +15 -0
  189. data/node_modules/once/README.md +79 -0
  190. data/node_modules/once/once.js +42 -0
  191. data/node_modules/once/package.json +101 -0
  192. data/node_modules/path-is-absolute/index.js +20 -0
  193. data/node_modules/path-is-absolute/license +21 -0
  194. data/node_modules/path-is-absolute/package.json +111 -0
  195. data/node_modules/path-is-absolute/readme.md +59 -0
  196. data/node_modules/rimraf/LICENSE +15 -0
  197. data/node_modules/rimraf/README.md +101 -0
  198. data/node_modules/rimraf/bin.js +50 -0
  199. data/node_modules/rimraf/package.json +99 -0
  200. data/node_modules/rimraf/rimraf.js +363 -0
  201. data/node_modules/ultron/LICENSE +22 -0
  202. data/node_modules/ultron/index.js +138 -0
  203. data/node_modules/ultron/package.json +112 -0
  204. data/node_modules/wrappy/LICENSE +15 -0
  205. data/node_modules/wrappy/README.md +36 -0
  206. data/node_modules/wrappy/package.json +97 -0
  207. data/node_modules/wrappy/wrappy.js +33 -0
  208. data/node_modules/ws/LICENSE +21 -0
  209. data/node_modules/ws/README.md +259 -0
  210. data/node_modules/ws/SECURITY.md +33 -0
  211. data/node_modules/ws/index.js +15 -0
  212. data/node_modules/ws/lib/BufferUtil.fallback.js +56 -0
  213. data/node_modules/ws/lib/BufferUtil.js +15 -0
  214. data/node_modules/ws/lib/ErrorCodes.js +28 -0
  215. data/node_modules/ws/lib/EventTarget.js +158 -0
  216. data/node_modules/ws/lib/Extensions.js +69 -0
  217. data/node_modules/ws/lib/PerMessageDeflate.js +339 -0
  218. data/node_modules/ws/lib/Receiver.js +520 -0
  219. data/node_modules/ws/lib/Sender.js +438 -0
  220. data/node_modules/ws/lib/Validation.fallback.js +9 -0
  221. data/node_modules/ws/lib/Validation.js +17 -0
  222. data/node_modules/ws/lib/WebSocket.js +705 -0
  223. data/node_modules/ws/lib/WebSocketServer.js +336 -0
  224. data/node_modules/ws/package.json +122 -0
  225. data/package.json +26 -0
  226. data/samples/sample.html +13 -0
  227. data/script/rasterize.js +18 -0
  228. metadata +325 -0
@@ -0,0 +1,705 @@
1
+ /*!
2
+ * ws: a node.js websocket client
3
+ * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
4
+ * MIT Licensed
5
+ */
6
+
7
+ 'use strict';
8
+
9
+ const EventEmitter = require('events');
10
+ const crypto = require('crypto');
11
+ const Ultron = require('ultron');
12
+ const https = require('https');
13
+ const http = require('http');
14
+ const url = require('url');
15
+
16
+ const PerMessageDeflate = require('./PerMessageDeflate');
17
+ const EventTarget = require('./EventTarget');
18
+ const Extensions = require('./Extensions');
19
+ const Receiver = require('./Receiver');
20
+ const Sender = require('./Sender');
21
+
22
+ const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
23
+ const closeTimeout = 30 * 1000; // Allow 30 seconds to terminate the connection cleanly.
24
+ const protocolVersion = 13;
25
+ const noop = () => {};
26
+
27
+ /**
28
+ * Class representing a WebSocket.
29
+ *
30
+ * @extends EventEmitter
31
+ */
32
+ class WebSocket extends EventEmitter {
33
+ /**
34
+ * Create a new `WebSocket`.
35
+ *
36
+ * @param {String} address The URL to which to connect
37
+ * @param {(String|String[])} protocols The subprotocols
38
+ * @param {Object} options Connection options
39
+ */
40
+ constructor (address, protocols, options) {
41
+ super();
42
+
43
+ if (typeof protocols === 'object' && !Array.isArray(protocols)) {
44
+ options = protocols;
45
+ protocols = null;
46
+ }
47
+
48
+ if (typeof protocols === 'string') protocols = [protocols];
49
+ if (!Array.isArray(protocols)) protocols = [];
50
+
51
+ this.readyState = WebSocket.CONNECTING;
52
+ this.bytesReceived = 0;
53
+ this.extensions = {};
54
+ this.protocol = '';
55
+
56
+ this._finalize = this.finalize.bind(this);
57
+ this._binaryType = 'nodebuffer';
58
+ this._finalizeCalled = false;
59
+ this._closeMessage = null;
60
+ this._closeTimer = null;
61
+ this._closeCode = null;
62
+ this._receiver = null;
63
+ this._sender = null;
64
+ this._socket = null;
65
+ this._ultron = null;
66
+
67
+ if (Array.isArray(address)) {
68
+ initAsServerClient.call(this, address[0], address[1], address[2], options);
69
+ } else {
70
+ initAsClient.call(this, address, protocols, options);
71
+ }
72
+ }
73
+
74
+ get CONNECTING () { return WebSocket.CONNECTING; }
75
+ get CLOSING () { return WebSocket.CLOSING; }
76
+ get CLOSED () { return WebSocket.CLOSED; }
77
+ get OPEN () { return WebSocket.OPEN; }
78
+
79
+ /**
80
+ * @type {Number}
81
+ */
82
+ get bufferedAmount () {
83
+ var amount = 0;
84
+
85
+ if (this._socket) {
86
+ amount = this._socket.bufferSize + this._sender.bufferedBytes;
87
+ }
88
+ return amount;
89
+ }
90
+
91
+ /**
92
+ * This deviates from the WHATWG interface since ws doesn't support the required
93
+ * default "blob" type (instead we define a custom "nodebuffer" type).
94
+ *
95
+ * @type {String}
96
+ */
97
+ get binaryType () {
98
+ return this._binaryType;
99
+ }
100
+
101
+ set binaryType (type) {
102
+ if (type === 'arraybuffer' || type === 'nodebuffer') {
103
+ this._binaryType = type;
104
+ } else {
105
+ throw new SyntaxError('unsupported binaryType: must be either "nodebuffer" or "arraybuffer"');
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Set up the socket and the internal resources.
111
+ *
112
+ * @param {net.Socket} socket The network socket between the server and client
113
+ * @param {Buffer} head The first packet of the upgraded stream
114
+ * @private
115
+ */
116
+ setSocket (socket, head) {
117
+ socket.setTimeout(0);
118
+ socket.setNoDelay();
119
+
120
+ this._receiver = new Receiver(this.extensions, this.maxPayload);
121
+ this._sender = new Sender(socket, this.extensions);
122
+ this._ultron = new Ultron(socket);
123
+ this._socket = socket;
124
+
125
+ // socket cleanup handlers
126
+ this._ultron.on('close', this._finalize);
127
+ this._ultron.on('error', this._finalize);
128
+ this._ultron.on('end', this._finalize);
129
+
130
+ // ensure that the head is added to the receiver
131
+ if (head && head.length > 0) {
132
+ socket.unshift(head);
133
+ head = null;
134
+ }
135
+
136
+ // subsequent packets are pushed to the receiver
137
+ this._ultron.on('data', (data) => {
138
+ this.bytesReceived += data.length;
139
+ this._receiver.add(data);
140
+ });
141
+
142
+ // receiver event handlers
143
+ this._receiver.onmessage = (data, flags) => this.emit('message', data, flags);
144
+ this._receiver.onping = (data, flags) => {
145
+ this.pong(data, !this._isServer, true);
146
+ this.emit('ping', data, flags);
147
+ };
148
+ this._receiver.onpong = (data, flags) => this.emit('pong', data, flags);
149
+ this._receiver.onclose = (code, reason) => {
150
+ this._closeMessage = reason;
151
+ this._closeCode = code;
152
+ this.close(code, reason);
153
+ };
154
+ this._receiver.onerror = (error, code) => {
155
+ // close the connection when the receiver reports a HyBi error code
156
+ this.close(code, '');
157
+ this.emit('error', error);
158
+ };
159
+
160
+ // sender event handlers
161
+ this._sender.onerror = (error) => {
162
+ this.close(1002, '');
163
+ this.emit('error', error);
164
+ };
165
+
166
+ this.readyState = WebSocket.OPEN;
167
+ this.emit('open');
168
+ }
169
+
170
+ /**
171
+ * Clean up and release internal resources.
172
+ *
173
+ * @param {(Boolean|Error)} Indicates whether or not an error occurred
174
+ * @private
175
+ */
176
+ finalize (error) {
177
+ if (this._finalizeCalled) return;
178
+
179
+ this.readyState = WebSocket.CLOSING;
180
+ this._finalizeCalled = true;
181
+
182
+ clearTimeout(this._closeTimer);
183
+ this._closeTimer = null;
184
+
185
+ //
186
+ // If the connection was closed abnormally (with an error), or if the close
187
+ // control frame was malformed or not received then the close code must be
188
+ // 1006.
189
+ //
190
+ if (error) this._closeCode = 1006;
191
+
192
+ if (this._socket) {
193
+ this._ultron.destroy();
194
+ this._socket.on('error', function onerror () {
195
+ this.destroy();
196
+ });
197
+
198
+ if (!error) this._socket.end();
199
+ else this._socket.destroy();
200
+
201
+ this._socket = null;
202
+ this._ultron = null;
203
+ }
204
+
205
+ if (this._sender) {
206
+ this._sender = this._sender.onerror = null;
207
+ }
208
+
209
+ if (this._receiver) {
210
+ this._receiver.cleanup(() => this.emitClose());
211
+ this._receiver = null;
212
+ } else {
213
+ this.emitClose();
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Emit the `close` event.
219
+ *
220
+ * @private
221
+ */
222
+ emitClose () {
223
+ this.readyState = WebSocket.CLOSED;
224
+ this.emit('close', this._closeCode || 1006, this._closeMessage || '');
225
+
226
+ if (this.extensions[PerMessageDeflate.extensionName]) {
227
+ this.extensions[PerMessageDeflate.extensionName].cleanup();
228
+ }
229
+
230
+ this.extensions = null;
231
+
232
+ this.removeAllListeners();
233
+ this.on('error', noop); // Catch all errors after this.
234
+ }
235
+
236
+ /**
237
+ * Pause the socket stream.
238
+ *
239
+ * @public
240
+ */
241
+ pause () {
242
+ if (this.readyState !== WebSocket.OPEN) throw new Error('not opened');
243
+
244
+ this._socket.pause();
245
+ }
246
+
247
+ /**
248
+ * Resume the socket stream
249
+ *
250
+ * @public
251
+ */
252
+ resume () {
253
+ if (this.readyState !== WebSocket.OPEN) throw new Error('not opened');
254
+
255
+ this._socket.resume();
256
+ }
257
+
258
+ /**
259
+ * Start a closing handshake.
260
+ *
261
+ * @param {Number} code Status code explaining why the connection is closing
262
+ * @param {String} data A string explaining why the connection is closing
263
+ * @public
264
+ */
265
+ close (code, data) {
266
+ if (this.readyState === WebSocket.CLOSED) return;
267
+ if (this.readyState === WebSocket.CONNECTING) {
268
+ if (this._req && !this._req.aborted) {
269
+ this._req.abort();
270
+ this.emit('error', new Error('closed before the connection is established'));
271
+ this.finalize(true);
272
+ }
273
+ return;
274
+ }
275
+
276
+ if (this.readyState === WebSocket.CLOSING) {
277
+ if (this._closeCode) this.terminate();
278
+ return;
279
+ }
280
+
281
+ this.readyState = WebSocket.CLOSING;
282
+ this._sender.close(code, data, !this._isServer, (err) => {
283
+ if (err) this.emit('error', err);
284
+
285
+ if (this._closeCode) {
286
+ this.terminate();
287
+ } else {
288
+ //
289
+ // Ensure that the connection is cleaned up even when the closing
290
+ // handshake fails.
291
+ //
292
+ clearTimeout(this._closeTimer);
293
+ this._closeTimer = setTimeout(this._finalize, closeTimeout, true);
294
+ }
295
+ });
296
+ }
297
+
298
+ /**
299
+ * Send a ping message.
300
+ *
301
+ * @param {*} data The message to send
302
+ * @param {Boolean} mask Indicates whether or not to mask `data`
303
+ * @param {Boolean} failSilently Indicates whether or not to throw if `readyState` isn't `OPEN`
304
+ * @public
305
+ */
306
+ ping (data, mask, failSilently) {
307
+ if (this.readyState !== WebSocket.OPEN) {
308
+ if (failSilently) return;
309
+ throw new Error('not opened');
310
+ }
311
+
312
+ if (typeof data === 'number') data = data.toString();
313
+ if (mask === undefined) mask = !this._isServer;
314
+ this._sender.ping(data, mask);
315
+ }
316
+
317
+ /**
318
+ * Send a pong message.
319
+ *
320
+ * @param {*} data The message to send
321
+ * @param {Boolean} mask Indicates whether or not to mask `data`
322
+ * @param {Boolean} failSilently Indicates whether or not to throw if `readyState` isn't `OPEN`
323
+ * @public
324
+ */
325
+ pong (data, mask, failSilently) {
326
+ if (this.readyState !== WebSocket.OPEN) {
327
+ if (failSilently) return;
328
+ throw new Error('not opened');
329
+ }
330
+
331
+ if (typeof data === 'number') data = data.toString();
332
+ if (mask === undefined) mask = !this._isServer;
333
+ this._sender.pong(data, mask);
334
+ }
335
+
336
+ /**
337
+ * Send a data message.
338
+ *
339
+ * @param {*} data The message to send
340
+ * @param {Object} options Options object
341
+ * @param {Boolean} options.compress Specifies whether or not to compress `data`
342
+ * @param {Boolean} options.binary Specifies whether `data` is binary or text
343
+ * @param {Boolean} options.fin Specifies whether the fragment is the last one
344
+ * @param {Boolean} options.mask Specifies whether or not to mask `data`
345
+ * @param {Function} cb Callback which is executed when data is written out
346
+ * @public
347
+ */
348
+ send (data, options, cb) {
349
+ if (typeof options === 'function') {
350
+ cb = options;
351
+ options = {};
352
+ }
353
+
354
+ if (this.readyState !== WebSocket.OPEN) {
355
+ if (cb) cb(new Error('not opened'));
356
+ else throw new Error('not opened');
357
+ return;
358
+ }
359
+
360
+ if (typeof data === 'number') data = data.toString();
361
+ else if (!data) data = '';
362
+
363
+ const opts = Object.assign({
364
+ fin: true,
365
+ binary: typeof data !== 'string',
366
+ mask: !this._isServer,
367
+ compress: true
368
+ }, options);
369
+
370
+ if (!this.extensions[PerMessageDeflate.extensionName]) {
371
+ opts.compress = false;
372
+ }
373
+
374
+ this._sender.send(data, opts, cb);
375
+ }
376
+
377
+ /**
378
+ * Half-close the socket sending a FIN packet.
379
+ *
380
+ * @public
381
+ */
382
+ terminate () {
383
+ if (this.readyState === WebSocket.CLOSED) return;
384
+ if (this.readyState === WebSocket.CONNECTING) {
385
+ if (this._req && !this._req.aborted) {
386
+ this._req.abort();
387
+ this.emit('error', new Error('closed before the connection is established'));
388
+ this.finalize(true);
389
+ }
390
+ return;
391
+ }
392
+
393
+ if (this._socket) {
394
+ this.readyState = WebSocket.CLOSING;
395
+ this._socket.end();
396
+
397
+ //
398
+ // Add a timeout to ensure that the connection is completely cleaned up
399
+ // within 30 seconds, even if the other peer does not send a FIN packet.
400
+ //
401
+ clearTimeout(this._closeTimer);
402
+ this._closeTimer = setTimeout(this._finalize, closeTimeout, true);
403
+ }
404
+ }
405
+ }
406
+
407
+ WebSocket.CONNECTING = 0;
408
+ WebSocket.OPEN = 1;
409
+ WebSocket.CLOSING = 2;
410
+ WebSocket.CLOSED = 3;
411
+
412
+ //
413
+ // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
414
+ // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
415
+ //
416
+ ['open', 'error', 'close', 'message'].forEach((method) => {
417
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
418
+ /**
419
+ * Return the listener of the event.
420
+ *
421
+ * @return {(Function|undefined)} The event listener or `undefined`
422
+ * @public
423
+ */
424
+ get () {
425
+ const listeners = this.listeners(method);
426
+ for (var i = 0; i < listeners.length; i++) {
427
+ if (listeners[i]._listener) return listeners[i]._listener;
428
+ }
429
+ },
430
+ /**
431
+ * Add a listener for the event.
432
+ *
433
+ * @param {Function} listener The listener to add
434
+ * @public
435
+ */
436
+ set (listener) {
437
+ const listeners = this.listeners(method);
438
+ for (var i = 0; i < listeners.length; i++) {
439
+ //
440
+ // Remove only the listeners added via `addEventListener`.
441
+ //
442
+ if (listeners[i]._listener) this.removeListener(method, listeners[i]);
443
+ }
444
+ this.addEventListener(method, listener);
445
+ }
446
+ });
447
+ });
448
+
449
+ WebSocket.prototype.addEventListener = EventTarget.addEventListener;
450
+ WebSocket.prototype.removeEventListener = EventTarget.removeEventListener;
451
+
452
+ module.exports = WebSocket;
453
+
454
+ /**
455
+ * Initialize a WebSocket server client.
456
+ *
457
+ * @param {http.IncomingMessage} req The request object
458
+ * @param {net.Socket} socket The network socket between the server and client
459
+ * @param {Buffer} head The first packet of the upgraded stream
460
+ * @param {Object} options WebSocket attributes
461
+ * @param {Number} options.protocolVersion The WebSocket protocol version
462
+ * @param {Object} options.extensions The negotiated extensions
463
+ * @param {Number} options.maxPayload The maximum allowed message size
464
+ * @param {String} options.protocol The chosen subprotocol
465
+ * @private
466
+ */
467
+ function initAsServerClient (req, socket, head, options) {
468
+ this.protocolVersion = options.protocolVersion;
469
+ this.extensions = options.extensions;
470
+ this.maxPayload = options.maxPayload;
471
+ this.protocol = options.protocol;
472
+
473
+ this.upgradeReq = req;
474
+ this._isServer = true;
475
+
476
+ this.setSocket(socket, head);
477
+ }
478
+
479
+ /**
480
+ * Initialize a WebSocket client.
481
+ *
482
+ * @param {String} address The URL to which to connect
483
+ * @param {String[]} protocols The list of subprotocols
484
+ * @param {Object} options Connection options
485
+ * @param {String} options.protocol Value of the `Sec-WebSocket-Protocol` header
486
+ * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate
487
+ * @param {String} options.localAddress Local interface to bind for network connections
488
+ * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` header
489
+ * @param {Object} options.headers An object containing request headers
490
+ * @param {String} options.origin Value of the `Origin` or `Sec-WebSocket-Origin` header
491
+ * @param {http.Agent} options.agent Use the specified Agent
492
+ * @param {String} options.host Value of the `Host` header
493
+ * @param {Number} options.family IP address family to use during hostname lookup (4 or 6).
494
+ * @param {Function} options.checkServerIdentity A function to validate the server hostname
495
+ * @param {Boolean} options.rejectUnauthorized Verify or not the server certificate
496
+ * @param {String} options.passphrase The passphrase for the private key or pfx
497
+ * @param {String} options.ciphers The ciphers to use or exclude
498
+ * @param {(String|String[]|Buffer|Buffer[])} options.cert The certificate key
499
+ * @param {(String|String[]|Buffer|Buffer[])} options.key The private key
500
+ * @param {(String|Buffer)} options.pfx The private key, certificate, and CA certs
501
+ * @param {(String|String[]|Buffer|Buffer[])} options.ca Trusted certificates
502
+ * @private
503
+ */
504
+ function initAsClient (address, protocols, options) {
505
+ options = Object.assign({
506
+ protocol: protocols.join(','),
507
+ perMessageDeflate: true,
508
+ localAddress: null,
509
+ protocolVersion,
510
+ headers: null,
511
+ origin: null,
512
+ agent: null,
513
+ host: null,
514
+ family: null,
515
+
516
+ //
517
+ // SSL options.
518
+ //
519
+ checkServerIdentity: null,
520
+ rejectUnauthorized: null,
521
+ passphrase: null,
522
+ ciphers: null,
523
+ cert: null,
524
+ key: null,
525
+ pfx: null,
526
+ ca: null
527
+ }, options);
528
+
529
+ if (options.protocolVersion !== 8 && options.protocolVersion !== 13) {
530
+ throw new Error('unsupported protocol version');
531
+ }
532
+
533
+ this.protocolVersion = options.protocolVersion;
534
+ this._isServer = false;
535
+ this.url = address;
536
+
537
+ const serverUrl = url.parse(address);
538
+ const isUnixSocket = serverUrl.protocol === 'ws+unix:';
539
+
540
+ if (!serverUrl.host && !isUnixSocket) throw new Error('invalid url');
541
+
542
+ const isSecure = serverUrl.protocol === 'wss:' || serverUrl.protocol === 'https:';
543
+ const key = crypto.randomBytes(16).toString('base64');
544
+ const port = serverUrl.port || (isSecure ? 443 : 80);
545
+ const httpObj = isSecure ? https : http;
546
+
547
+ //
548
+ // Prepare extensions.
549
+ //
550
+ const extensionsOffer = {};
551
+ var perMessageDeflate;
552
+
553
+ if (options.perMessageDeflate) {
554
+ perMessageDeflate = new PerMessageDeflate(
555
+ options.perMessageDeflate !== true ? options.perMessageDeflate : {},
556
+ false
557
+ );
558
+ extensionsOffer[PerMessageDeflate.extensionName] = perMessageDeflate.offer();
559
+ }
560
+
561
+ const requestOptions = {
562
+ host: serverUrl.hostname,
563
+ port,
564
+ path: '/',
565
+ headers: {
566
+ 'Sec-WebSocket-Version': options.protocolVersion,
567
+ 'Sec-WebSocket-Key': key,
568
+ 'Connection': 'Upgrade',
569
+ 'Upgrade': 'websocket'
570
+ }
571
+ };
572
+
573
+ if (options.headers) Object.assign(requestOptions.headers, options.headers);
574
+ if (Object.keys(extensionsOffer).length) {
575
+ requestOptions.headers['Sec-WebSocket-Extensions'] = Extensions.format(extensionsOffer);
576
+ }
577
+ if (options.protocol) {
578
+ requestOptions.headers['Sec-WebSocket-Protocol'] = options.protocol;
579
+ }
580
+ if (options.origin) {
581
+ if (options.protocolVersion < 13) {
582
+ requestOptions.headers['Sec-WebSocket-Origin'] = options.origin;
583
+ } else {
584
+ requestOptions.headers.Origin = options.origin;
585
+ }
586
+ }
587
+ if (options.host) requestOptions.headers.Host = options.host;
588
+ if (options.family) requestOptions.family = options.family;
589
+
590
+ if (options.localAddress) requestOptions.localAddress = options.localAddress;
591
+ if (isUnixSocket) requestOptions.socketPath = serverUrl.pathname;
592
+ if (serverUrl.auth) requestOptions.auth = serverUrl.auth;
593
+
594
+ //
595
+ // Make sure that path starts with `/`.
596
+ //
597
+ if (serverUrl.path) {
598
+ if (serverUrl.path.charAt(0) !== '/') {
599
+ requestOptions.path = `/${serverUrl.path}`;
600
+ } else {
601
+ requestOptions.path = serverUrl.path;
602
+ }
603
+ }
604
+
605
+ var agent = options.agent;
606
+
607
+ //
608
+ // A custom agent is required for these options.
609
+ //
610
+ if (
611
+ options.rejectUnauthorized != null ||
612
+ options.checkServerIdentity ||
613
+ options.passphrase ||
614
+ options.ciphers ||
615
+ options.cert ||
616
+ options.key ||
617
+ options.pfx ||
618
+ options.ca
619
+ ) {
620
+ if (options.passphrase) requestOptions.passphrase = options.passphrase;
621
+ if (options.ciphers) requestOptions.ciphers = options.ciphers;
622
+ if (options.cert) requestOptions.cert = options.cert;
623
+ if (options.key) requestOptions.key = options.key;
624
+ if (options.pfx) requestOptions.pfx = options.pfx;
625
+ if (options.ca) requestOptions.ca = options.ca;
626
+ if (options.checkServerIdentity) {
627
+ requestOptions.checkServerIdentity = options.checkServerIdentity;
628
+ }
629
+ if (options.rejectUnauthorized != null) {
630
+ requestOptions.rejectUnauthorized = options.rejectUnauthorized;
631
+ }
632
+
633
+ if (!agent) agent = new httpObj.Agent(requestOptions);
634
+ }
635
+
636
+ if (agent) requestOptions.agent = agent;
637
+
638
+ this._req = httpObj.get(requestOptions);
639
+
640
+ this._req.on('error', (error) => {
641
+ if (this._req.aborted) return;
642
+
643
+ this._req = null;
644
+ this.emit('error', error);
645
+ this.finalize(true);
646
+ });
647
+
648
+ this._req.on('response', (res) => {
649
+ if (!this.emit('unexpected-response', this._req, res)) {
650
+ this._req.abort();
651
+ this.emit('error', new Error(`unexpected server response (${res.statusCode})`));
652
+ this.finalize(true);
653
+ }
654
+ });
655
+
656
+ this._req.on('upgrade', (res, socket, head) => {
657
+ this._req = null;
658
+
659
+ const digest = crypto.createHash('sha1')
660
+ .update(key + GUID, 'binary')
661
+ .digest('base64');
662
+
663
+ if (res.headers['sec-websocket-accept'] !== digest) {
664
+ socket.destroy();
665
+ this.emit('error', new Error('invalid server key'));
666
+ return this.finalize(true);
667
+ }
668
+
669
+ const serverProt = res.headers['sec-websocket-protocol'];
670
+ const protList = (options.protocol || '').split(/, */);
671
+ var protError;
672
+
673
+ if (!options.protocol && serverProt) {
674
+ protError = 'server sent a subprotocol even though none requested';
675
+ } else if (options.protocol && !serverProt) {
676
+ protError = 'server sent no subprotocol even though requested';
677
+ } else if (serverProt && protList.indexOf(serverProt) === -1) {
678
+ protError = 'server responded with an invalid protocol';
679
+ }
680
+
681
+ if (protError) {
682
+ socket.destroy();
683
+ this.emit('error', new Error(protError));
684
+ return this.finalize(true);
685
+ }
686
+
687
+ if (serverProt) this.protocol = serverProt;
688
+
689
+ const serverExtensions = Extensions.parse(res.headers['sec-websocket-extensions']);
690
+
691
+ if (perMessageDeflate && serverExtensions[PerMessageDeflate.extensionName]) {
692
+ try {
693
+ perMessageDeflate.accept(serverExtensions[PerMessageDeflate.extensionName]);
694
+ } catch (err) {
695
+ socket.destroy();
696
+ this.emit('error', new Error('invalid extension parameter'));
697
+ return this.finalize(true);
698
+ }
699
+
700
+ this.extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
701
+ }
702
+
703
+ this.setSocket(socket, head);
704
+ });
705
+ }