llonebot-dist 6.6.4

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 (134) hide show
  1. dist/default_config.json +68 -0
  2. dist/llonebot.js +48348 -0
  3. dist/llonebot.js.map +1 -0
  4. dist/node_modules/@borewit/text-codec/LICENSE.txt +9 -0
  5. dist/node_modules/@borewit/text-codec/README.md +76 -0
  6. dist/node_modules/@borewit/text-codec/lib/index.d.ts +8 -0
  7. dist/node_modules/@borewit/text-codec/lib/index.js +161 -0
  8. dist/node_modules/@borewit/text-codec/package.json +68 -0
  9. dist/node_modules/@minatojs/sql.js/LICENSE +44 -0
  10. dist/node_modules/@minatojs/sql.js/README.md +357 -0
  11. dist/node_modules/@minatojs/sql.js/dist/sql-wasm.d.ts +316 -0
  12. dist/node_modules/@minatojs/sql.js/dist/sql-wasm.js +225 -0
  13. dist/node_modules/@minatojs/sql.js/dist/sql-wasm.wasm +0 -0
  14. dist/node_modules/@minatojs/sql.js/package.json +58 -0
  15. dist/node_modules/@tokenizer/inflate/LICENSE +15 -0
  16. dist/node_modules/@tokenizer/inflate/README.md +114 -0
  17. dist/node_modules/@tokenizer/inflate/lib/GzipHandler.d.ts +6 -0
  18. dist/node_modules/@tokenizer/inflate/lib/GzipHandler.js +19 -0
  19. dist/node_modules/@tokenizer/inflate/lib/ZipHandler.d.ts +26 -0
  20. dist/node_modules/@tokenizer/inflate/lib/ZipHandler.js +233 -0
  21. dist/node_modules/@tokenizer/inflate/lib/ZipToken.d.ts +94 -0
  22. dist/node_modules/@tokenizer/inflate/lib/ZipToken.js +117 -0
  23. dist/node_modules/@tokenizer/inflate/lib/index.d.ts +3 -0
  24. dist/node_modules/@tokenizer/inflate/lib/index.js +2 -0
  25. dist/node_modules/@tokenizer/inflate/package.json +76 -0
  26. dist/node_modules/@tokenizer/token/README.md +19 -0
  27. dist/node_modules/@tokenizer/token/index.d.ts +30 -0
  28. dist/node_modules/@tokenizer/token/package.json +33 -0
  29. dist/node_modules/debug/LICENSE +20 -0
  30. dist/node_modules/debug/README.md +481 -0
  31. dist/node_modules/debug/package.json +64 -0
  32. dist/node_modules/debug/src/browser.js +272 -0
  33. dist/node_modules/debug/src/common.js +292 -0
  34. dist/node_modules/debug/src/index.js +10 -0
  35. dist/node_modules/debug/src/node.js +263 -0
  36. dist/node_modules/file-type/core.d.ts +253 -0
  37. dist/node_modules/file-type/core.js +1899 -0
  38. dist/node_modules/file-type/index.d.ts +98 -0
  39. dist/node_modules/file-type/index.js +86 -0
  40. dist/node_modules/file-type/license +9 -0
  41. dist/node_modules/file-type/package.json +288 -0
  42. dist/node_modules/file-type/readme.md +674 -0
  43. dist/node_modules/file-type/supported.js +356 -0
  44. dist/node_modules/file-type/util.js +60 -0
  45. dist/node_modules/ieee754/LICENSE +11 -0
  46. dist/node_modules/ieee754/README.md +51 -0
  47. dist/node_modules/ieee754/index.d.ts +10 -0
  48. dist/node_modules/ieee754/index.js +85 -0
  49. dist/node_modules/ieee754/package.json +52 -0
  50. dist/node_modules/ms/index.js +162 -0
  51. dist/node_modules/ms/license.md +21 -0
  52. dist/node_modules/ms/package.json +38 -0
  53. dist/node_modules/ms/readme.md +59 -0
  54. dist/node_modules/silk-wasm/LICENSE +21 -0
  55. dist/node_modules/silk-wasm/README.md +85 -0
  56. dist/node_modules/silk-wasm/lib/index.cjs +16 -0
  57. dist/node_modules/silk-wasm/lib/index.d.ts +70 -0
  58. dist/node_modules/silk-wasm/lib/index.mjs +16 -0
  59. dist/node_modules/silk-wasm/lib/silk.wasm +0 -0
  60. dist/node_modules/silk-wasm/lib/utils.d.ts +4 -0
  61. dist/node_modules/silk-wasm/package.json +39 -0
  62. dist/node_modules/strtok3/LICENSE.txt +21 -0
  63. dist/node_modules/strtok3/README.md +399 -0
  64. dist/node_modules/strtok3/lib/AbstractTokenizer.d.ts +76 -0
  65. dist/node_modules/strtok3/lib/AbstractTokenizer.js +108 -0
  66. dist/node_modules/strtok3/lib/BlobTokenizer.d.ts +29 -0
  67. dist/node_modules/strtok3/lib/BlobTokenizer.js +53 -0
  68. dist/node_modules/strtok3/lib/BufferTokenizer.d.ts +29 -0
  69. dist/node_modules/strtok3/lib/BufferTokenizer.js +52 -0
  70. dist/node_modules/strtok3/lib/FileTokenizer.d.ts +37 -0
  71. dist/node_modules/strtok3/lib/FileTokenizer.js +61 -0
  72. dist/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts +31 -0
  73. dist/node_modules/strtok3/lib/ReadStreamTokenizer.js +102 -0
  74. dist/node_modules/strtok3/lib/core.d.ts +40 -0
  75. dist/node_modules/strtok3/lib/core.js +62 -0
  76. dist/node_modules/strtok3/lib/index.d.ts +16 -0
  77. dist/node_modules/strtok3/lib/index.js +22 -0
  78. dist/node_modules/strtok3/lib/stream/AbstractStreamReader.d.ts +54 -0
  79. dist/node_modules/strtok3/lib/stream/AbstractStreamReader.js +71 -0
  80. dist/node_modules/strtok3/lib/stream/Deferred.d.ts +6 -0
  81. dist/node_modules/strtok3/lib/stream/Deferred.js +10 -0
  82. dist/node_modules/strtok3/lib/stream/Errors.d.ts +10 -0
  83. dist/node_modules/strtok3/lib/stream/Errors.js +16 -0
  84. dist/node_modules/strtok3/lib/stream/StreamReader.d.ts +29 -0
  85. dist/node_modules/strtok3/lib/stream/StreamReader.js +83 -0
  86. dist/node_modules/strtok3/lib/stream/WebStreamByobReader.d.ts +14 -0
  87. dist/node_modules/strtok3/lib/stream/WebStreamByobReader.js +27 -0
  88. dist/node_modules/strtok3/lib/stream/WebStreamDefaultReader.d.ts +19 -0
  89. dist/node_modules/strtok3/lib/stream/WebStreamDefaultReader.js +62 -0
  90. dist/node_modules/strtok3/lib/stream/WebStreamReader.d.ts +14 -0
  91. dist/node_modules/strtok3/lib/stream/WebStreamReader.js +13 -0
  92. dist/node_modules/strtok3/lib/stream/WebStreamReaderFactory.d.ts +5 -0
  93. dist/node_modules/strtok3/lib/stream/WebStreamReaderFactory.js +19 -0
  94. dist/node_modules/strtok3/lib/stream/index.d.ts +6 -0
  95. dist/node_modules/strtok3/lib/stream/index.js +5 -0
  96. dist/node_modules/strtok3/lib/types.d.ts +139 -0
  97. dist/node_modules/strtok3/lib/types.js +1 -0
  98. dist/node_modules/strtok3/package.json +94 -0
  99. dist/node_modules/token-types/LICENSE.txt +9 -0
  100. dist/node_modules/token-types/README.md +120 -0
  101. dist/node_modules/token-types/lib/index.d.ts +135 -0
  102. dist/node_modules/token-types/lib/index.js +401 -0
  103. dist/node_modules/token-types/package.json +81 -0
  104. dist/node_modules/uint8array-extras/index.d.ts +312 -0
  105. dist/node_modules/uint8array-extras/index.js +321 -0
  106. dist/node_modules/uint8array-extras/license +9 -0
  107. dist/node_modules/uint8array-extras/package.json +54 -0
  108. dist/node_modules/uint8array-extras/readme.md +301 -0
  109. dist/node_modules/ws/LICENSE +20 -0
  110. dist/node_modules/ws/README.md +548 -0
  111. dist/node_modules/ws/browser.js +8 -0
  112. dist/node_modules/ws/index.js +13 -0
  113. dist/node_modules/ws/lib/buffer-util.js +131 -0
  114. dist/node_modules/ws/lib/constants.js +18 -0
  115. dist/node_modules/ws/lib/event-target.js +292 -0
  116. dist/node_modules/ws/lib/extension.js +203 -0
  117. dist/node_modules/ws/lib/limiter.js +55 -0
  118. dist/node_modules/ws/lib/permessage-deflate.js +528 -0
  119. dist/node_modules/ws/lib/receiver.js +706 -0
  120. dist/node_modules/ws/lib/sender.js +602 -0
  121. dist/node_modules/ws/lib/stream.js +161 -0
  122. dist/node_modules/ws/lib/subprotocol.js +62 -0
  123. dist/node_modules/ws/lib/validation.js +152 -0
  124. dist/node_modules/ws/lib/websocket-server.js +550 -0
  125. dist/node_modules/ws/lib/websocket.js +1388 -0
  126. dist/node_modules/ws/package.json +69 -0
  127. dist/node_modules/ws/wrapper.mjs +8 -0
  128. dist/package.json +1 -0
  129. dist/webui/assets/index-B9vGhdCO.js +256 -0
  130. dist/webui/assets/index-DaqFU7JR.css +1 -0
  131. dist/webui/index.html +13 -0
  132. dist/webui/logo.jpg +0 -0
  133. dist//344/275/277/347/224/250/350/257/264/346/230/216.txt +11 -0
  134. dist//346/233/264/346/226/260/346/227/245/345/277/227.txt +399 -0
@@ -0,0 +1,550 @@
1
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
2
+
3
+ 'use strict';
4
+
5
+ const EventEmitter = require('events');
6
+ const http = require('http');
7
+ const { Duplex } = require('stream');
8
+ const { createHash } = require('crypto');
9
+
10
+ const extension = require('./extension');
11
+ const PerMessageDeflate = require('./permessage-deflate');
12
+ const subprotocol = require('./subprotocol');
13
+ const WebSocket = require('./websocket');
14
+ const { GUID, kWebSocket } = require('./constants');
15
+
16
+ const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
17
+
18
+ const RUNNING = 0;
19
+ const CLOSING = 1;
20
+ const CLOSED = 2;
21
+
22
+ /**
23
+ * Class representing a WebSocket server.
24
+ *
25
+ * @extends EventEmitter
26
+ */
27
+ class WebSocketServer extends EventEmitter {
28
+ /**
29
+ * Create a `WebSocketServer` instance.
30
+ *
31
+ * @param {Object} options Configuration options
32
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
33
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
34
+ * multiple times in the same tick
35
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
36
+ * automatically send a pong in response to a ping
37
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
38
+ * pending connections
39
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
40
+ * track clients
41
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
42
+ * @param {String} [options.host] The hostname where to bind the server
43
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
44
+ * size
45
+ * @param {Boolean} [options.noServer=false] Enable no server mode
46
+ * @param {String} [options.path] Accept only connections matching this path
47
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
48
+ * permessage-deflate
49
+ * @param {Number} [options.port] The port where to bind the server
50
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
51
+ * server to use
52
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
53
+ * not to skip UTF-8 validation for text and close messages
54
+ * @param {Function} [options.verifyClient] A hook to reject connections
55
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
56
+ * class to use. It must be the `WebSocket` class or class that extends it
57
+ * @param {Function} [callback] A listener for the `listening` event
58
+ */
59
+ constructor(options, callback) {
60
+ super();
61
+
62
+ options = {
63
+ allowSynchronousEvents: true,
64
+ autoPong: true,
65
+ maxPayload: 100 * 1024 * 1024,
66
+ skipUTF8Validation: false,
67
+ perMessageDeflate: false,
68
+ handleProtocols: null,
69
+ clientTracking: true,
70
+ verifyClient: null,
71
+ noServer: false,
72
+ backlog: null, // use default (511 as implemented in net.js)
73
+ server: null,
74
+ host: null,
75
+ path: null,
76
+ port: null,
77
+ WebSocket,
78
+ ...options
79
+ };
80
+
81
+ if (
82
+ (options.port == null && !options.server && !options.noServer) ||
83
+ (options.port != null && (options.server || options.noServer)) ||
84
+ (options.server && options.noServer)
85
+ ) {
86
+ throw new TypeError(
87
+ 'One and only one of the "port", "server", or "noServer" options ' +
88
+ 'must be specified'
89
+ );
90
+ }
91
+
92
+ if (options.port != null) {
93
+ this._server = http.createServer((req, res) => {
94
+ const body = http.STATUS_CODES[426];
95
+
96
+ res.writeHead(426, {
97
+ 'Content-Length': body.length,
98
+ 'Content-Type': 'text/plain'
99
+ });
100
+ res.end(body);
101
+ });
102
+ this._server.listen(
103
+ options.port,
104
+ options.host,
105
+ options.backlog,
106
+ callback
107
+ );
108
+ } else if (options.server) {
109
+ this._server = options.server;
110
+ }
111
+
112
+ if (this._server) {
113
+ const emitConnection = this.emit.bind(this, 'connection');
114
+
115
+ this._removeListeners = addListeners(this._server, {
116
+ listening: this.emit.bind(this, 'listening'),
117
+ error: this.emit.bind(this, 'error'),
118
+ upgrade: (req, socket, head) => {
119
+ this.handleUpgrade(req, socket, head, emitConnection);
120
+ }
121
+ });
122
+ }
123
+
124
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
125
+ if (options.clientTracking) {
126
+ this.clients = new Set();
127
+ this._shouldEmitClose = false;
128
+ }
129
+
130
+ this.options = options;
131
+ this._state = RUNNING;
132
+ }
133
+
134
+ /**
135
+ * Returns the bound address, the address family name, and port of the server
136
+ * as reported by the operating system if listening on an IP socket.
137
+ * If the server is listening on a pipe or UNIX domain socket, the name is
138
+ * returned as a string.
139
+ *
140
+ * @return {(Object|String|null)} The address of the server
141
+ * @public
142
+ */
143
+ address() {
144
+ if (this.options.noServer) {
145
+ throw new Error('The server is operating in "noServer" mode');
146
+ }
147
+
148
+ if (!this._server) return null;
149
+ return this._server.address();
150
+ }
151
+
152
+ /**
153
+ * Stop the server from accepting new connections and emit the `'close'` event
154
+ * when all existing connections are closed.
155
+ *
156
+ * @param {Function} [cb] A one-time listener for the `'close'` event
157
+ * @public
158
+ */
159
+ close(cb) {
160
+ if (this._state === CLOSED) {
161
+ if (cb) {
162
+ this.once('close', () => {
163
+ cb(new Error('The server is not running'));
164
+ });
165
+ }
166
+
167
+ process.nextTick(emitClose, this);
168
+ return;
169
+ }
170
+
171
+ if (cb) this.once('close', cb);
172
+
173
+ if (this._state === CLOSING) return;
174
+ this._state = CLOSING;
175
+
176
+ if (this.options.noServer || this.options.server) {
177
+ if (this._server) {
178
+ this._removeListeners();
179
+ this._removeListeners = this._server = null;
180
+ }
181
+
182
+ if (this.clients) {
183
+ if (!this.clients.size) {
184
+ process.nextTick(emitClose, this);
185
+ } else {
186
+ this._shouldEmitClose = true;
187
+ }
188
+ } else {
189
+ process.nextTick(emitClose, this);
190
+ }
191
+ } else {
192
+ const server = this._server;
193
+
194
+ this._removeListeners();
195
+ this._removeListeners = this._server = null;
196
+
197
+ //
198
+ // The HTTP/S server was created internally. Close it, and rely on its
199
+ // `'close'` event.
200
+ //
201
+ server.close(() => {
202
+ emitClose(this);
203
+ });
204
+ }
205
+ }
206
+
207
+ /**
208
+ * See if a given request should be handled by this server instance.
209
+ *
210
+ * @param {http.IncomingMessage} req Request object to inspect
211
+ * @return {Boolean} `true` if the request is valid, else `false`
212
+ * @public
213
+ */
214
+ shouldHandle(req) {
215
+ if (this.options.path) {
216
+ const index = req.url.indexOf('?');
217
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
218
+
219
+ if (pathname !== this.options.path) return false;
220
+ }
221
+
222
+ return true;
223
+ }
224
+
225
+ /**
226
+ * Handle a HTTP Upgrade request.
227
+ *
228
+ * @param {http.IncomingMessage} req The request object
229
+ * @param {Duplex} socket The network socket between the server and client
230
+ * @param {Buffer} head The first packet of the upgraded stream
231
+ * @param {Function} cb Callback
232
+ * @public
233
+ */
234
+ handleUpgrade(req, socket, head, cb) {
235
+ socket.on('error', socketOnError);
236
+
237
+ const key = req.headers['sec-websocket-key'];
238
+ const upgrade = req.headers.upgrade;
239
+ const version = +req.headers['sec-websocket-version'];
240
+
241
+ if (req.method !== 'GET') {
242
+ const message = 'Invalid HTTP method';
243
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
244
+ return;
245
+ }
246
+
247
+ if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
248
+ const message = 'Invalid Upgrade header';
249
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
250
+ return;
251
+ }
252
+
253
+ if (key === undefined || !keyRegex.test(key)) {
254
+ const message = 'Missing or invalid Sec-WebSocket-Key header';
255
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
256
+ return;
257
+ }
258
+
259
+ if (version !== 13 && version !== 8) {
260
+ const message = 'Missing or invalid Sec-WebSocket-Version header';
261
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
262
+ 'Sec-WebSocket-Version': '13, 8'
263
+ });
264
+ return;
265
+ }
266
+
267
+ if (!this.shouldHandle(req)) {
268
+ abortHandshake(socket, 400);
269
+ return;
270
+ }
271
+
272
+ const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
273
+ let protocols = new Set();
274
+
275
+ if (secWebSocketProtocol !== undefined) {
276
+ try {
277
+ protocols = subprotocol.parse(secWebSocketProtocol);
278
+ } catch (err) {
279
+ const message = 'Invalid Sec-WebSocket-Protocol header';
280
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
281
+ return;
282
+ }
283
+ }
284
+
285
+ const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
286
+ const extensions = {};
287
+
288
+ if (
289
+ this.options.perMessageDeflate &&
290
+ secWebSocketExtensions !== undefined
291
+ ) {
292
+ const perMessageDeflate = new PerMessageDeflate(
293
+ this.options.perMessageDeflate,
294
+ true,
295
+ this.options.maxPayload
296
+ );
297
+
298
+ try {
299
+ const offers = extension.parse(secWebSocketExtensions);
300
+
301
+ if (offers[PerMessageDeflate.extensionName]) {
302
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
303
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
304
+ }
305
+ } catch (err) {
306
+ const message =
307
+ 'Invalid or unacceptable Sec-WebSocket-Extensions header';
308
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
309
+ return;
310
+ }
311
+ }
312
+
313
+ //
314
+ // Optionally call external client verification handler.
315
+ //
316
+ if (this.options.verifyClient) {
317
+ const info = {
318
+ origin:
319
+ req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
320
+ secure: !!(req.socket.authorized || req.socket.encrypted),
321
+ req
322
+ };
323
+
324
+ if (this.options.verifyClient.length === 2) {
325
+ this.options.verifyClient(info, (verified, code, message, headers) => {
326
+ if (!verified) {
327
+ return abortHandshake(socket, code || 401, message, headers);
328
+ }
329
+
330
+ this.completeUpgrade(
331
+ extensions,
332
+ key,
333
+ protocols,
334
+ req,
335
+ socket,
336
+ head,
337
+ cb
338
+ );
339
+ });
340
+ return;
341
+ }
342
+
343
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
344
+ }
345
+
346
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
347
+ }
348
+
349
+ /**
350
+ * Upgrade the connection to WebSocket.
351
+ *
352
+ * @param {Object} extensions The accepted extensions
353
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
354
+ * @param {Set} protocols The subprotocols
355
+ * @param {http.IncomingMessage} req The request object
356
+ * @param {Duplex} socket The network socket between the server and client
357
+ * @param {Buffer} head The first packet of the upgraded stream
358
+ * @param {Function} cb Callback
359
+ * @throws {Error} If called more than once with the same socket
360
+ * @private
361
+ */
362
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
363
+ //
364
+ // Destroy the socket if the client has already sent a FIN packet.
365
+ //
366
+ if (!socket.readable || !socket.writable) return socket.destroy();
367
+
368
+ if (socket[kWebSocket]) {
369
+ throw new Error(
370
+ 'server.handleUpgrade() was called more than once with the same ' +
371
+ 'socket, possibly due to a misconfiguration'
372
+ );
373
+ }
374
+
375
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
376
+
377
+ const digest = createHash('sha1')
378
+ .update(key + GUID)
379
+ .digest('base64');
380
+
381
+ const headers = [
382
+ 'HTTP/1.1 101 Switching Protocols',
383
+ 'Upgrade: websocket',
384
+ 'Connection: Upgrade',
385
+ `Sec-WebSocket-Accept: ${digest}`
386
+ ];
387
+
388
+ const ws = new this.options.WebSocket(null, undefined, this.options);
389
+
390
+ if (protocols.size) {
391
+ //
392
+ // Optionally call external protocol selection handler.
393
+ //
394
+ const protocol = this.options.handleProtocols
395
+ ? this.options.handleProtocols(protocols, req)
396
+ : protocols.values().next().value;
397
+
398
+ if (protocol) {
399
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
400
+ ws._protocol = protocol;
401
+ }
402
+ }
403
+
404
+ if (extensions[PerMessageDeflate.extensionName]) {
405
+ const params = extensions[PerMessageDeflate.extensionName].params;
406
+ const value = extension.format({
407
+ [PerMessageDeflate.extensionName]: [params]
408
+ });
409
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
410
+ ws._extensions = extensions;
411
+ }
412
+
413
+ //
414
+ // Allow external modification/inspection of handshake headers.
415
+ //
416
+ this.emit('headers', headers, req);
417
+
418
+ socket.write(headers.concat('\r\n').join('\r\n'));
419
+ socket.removeListener('error', socketOnError);
420
+
421
+ ws.setSocket(socket, head, {
422
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
423
+ maxPayload: this.options.maxPayload,
424
+ skipUTF8Validation: this.options.skipUTF8Validation
425
+ });
426
+
427
+ if (this.clients) {
428
+ this.clients.add(ws);
429
+ ws.on('close', () => {
430
+ this.clients.delete(ws);
431
+
432
+ if (this._shouldEmitClose && !this.clients.size) {
433
+ process.nextTick(emitClose, this);
434
+ }
435
+ });
436
+ }
437
+
438
+ cb(ws, req);
439
+ }
440
+ }
441
+
442
+ module.exports = WebSocketServer;
443
+
444
+ /**
445
+ * Add event listeners on an `EventEmitter` using a map of <event, listener>
446
+ * pairs.
447
+ *
448
+ * @param {EventEmitter} server The event emitter
449
+ * @param {Object.<String, Function>} map The listeners to add
450
+ * @return {Function} A function that will remove the added listeners when
451
+ * called
452
+ * @private
453
+ */
454
+ function addListeners(server, map) {
455
+ for (const event of Object.keys(map)) server.on(event, map[event]);
456
+
457
+ return function removeListeners() {
458
+ for (const event of Object.keys(map)) {
459
+ server.removeListener(event, map[event]);
460
+ }
461
+ };
462
+ }
463
+
464
+ /**
465
+ * Emit a `'close'` event on an `EventEmitter`.
466
+ *
467
+ * @param {EventEmitter} server The event emitter
468
+ * @private
469
+ */
470
+ function emitClose(server) {
471
+ server._state = CLOSED;
472
+ server.emit('close');
473
+ }
474
+
475
+ /**
476
+ * Handle socket errors.
477
+ *
478
+ * @private
479
+ */
480
+ function socketOnError() {
481
+ this.destroy();
482
+ }
483
+
484
+ /**
485
+ * Close the connection when preconditions are not fulfilled.
486
+ *
487
+ * @param {Duplex} socket The socket of the upgrade request
488
+ * @param {Number} code The HTTP response status code
489
+ * @param {String} [message] The HTTP response body
490
+ * @param {Object} [headers] Additional HTTP response headers
491
+ * @private
492
+ */
493
+ function abortHandshake(socket, code, message, headers) {
494
+ //
495
+ // The socket is writable unless the user destroyed or ended it before calling
496
+ // `server.handleUpgrade()` or in the `verifyClient` function, which is a user
497
+ // error. Handling this does not make much sense as the worst that can happen
498
+ // is that some of the data written by the user might be discarded due to the
499
+ // call to `socket.end()` below, which triggers an `'error'` event that in
500
+ // turn causes the socket to be destroyed.
501
+ //
502
+ message = message || http.STATUS_CODES[code];
503
+ headers = {
504
+ Connection: 'close',
505
+ 'Content-Type': 'text/html',
506
+ 'Content-Length': Buffer.byteLength(message),
507
+ ...headers
508
+ };
509
+
510
+ socket.once('finish', socket.destroy);
511
+
512
+ socket.end(
513
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
514
+ Object.keys(headers)
515
+ .map((h) => `${h}: ${headers[h]}`)
516
+ .join('\r\n') +
517
+ '\r\n\r\n' +
518
+ message
519
+ );
520
+ }
521
+
522
+ /**
523
+ * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
524
+ * one listener for it, otherwise call `abortHandshake()`.
525
+ *
526
+ * @param {WebSocketServer} server The WebSocket server
527
+ * @param {http.IncomingMessage} req The request object
528
+ * @param {Duplex} socket The socket of the upgrade request
529
+ * @param {Number} code The HTTP response status code
530
+ * @param {String} message The HTTP response body
531
+ * @param {Object} [headers] The HTTP response headers
532
+ * @private
533
+ */
534
+ function abortHandshakeOrEmitwsClientError(
535
+ server,
536
+ req,
537
+ socket,
538
+ code,
539
+ message,
540
+ headers
541
+ ) {
542
+ if (server.listenerCount('wsClientError')) {
543
+ const err = new Error(message);
544
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
545
+
546
+ server.emit('wsClientError', err, socket, req);
547
+ } else {
548
+ abortHandshake(socket, code, message, headers);
549
+ }
550
+ }