@ai-development-environment/control-agent 0.0.46 → 0.0.47
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.
- package/dist/control-agent.js +4037 -163
- package/package.json +5 -1
package/dist/control-agent.js
CHANGED
|
@@ -1,4 +1,3709 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
9
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
10
|
+
}) : x)(function(x) {
|
|
11
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
12
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
13
|
+
});
|
|
14
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
15
|
+
try {
|
|
16
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
17
|
+
} catch (e) {
|
|
18
|
+
throw mod = 0, e;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var __copyProps = (to, from, except, desc) => {
|
|
22
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
23
|
+
for (let key of __getOwnPropNames(from))
|
|
24
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
25
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
26
|
+
}
|
|
27
|
+
return to;
|
|
28
|
+
};
|
|
29
|
+
var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
30
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
31
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
32
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
33
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
34
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
|
|
35
|
+
mod
|
|
36
|
+
));
|
|
37
|
+
|
|
38
|
+
// ../../node_modules/ws/lib/constants.js
|
|
39
|
+
var require_constants = __commonJS({
|
|
40
|
+
"../../node_modules/ws/lib/constants.js"(exports, module) {
|
|
41
|
+
"use strict";
|
|
42
|
+
var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
|
|
43
|
+
var hasBlob = typeof Blob !== "undefined";
|
|
44
|
+
if (hasBlob) BINARY_TYPES.push("blob");
|
|
45
|
+
module.exports = {
|
|
46
|
+
BINARY_TYPES,
|
|
47
|
+
CLOSE_TIMEOUT: 3e4,
|
|
48
|
+
EMPTY_BUFFER: Buffer.alloc(0),
|
|
49
|
+
GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
|
|
50
|
+
hasBlob,
|
|
51
|
+
kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
|
|
52
|
+
kListener: /* @__PURE__ */ Symbol("kListener"),
|
|
53
|
+
kStatusCode: /* @__PURE__ */ Symbol("status-code"),
|
|
54
|
+
kWebSocket: /* @__PURE__ */ Symbol("websocket"),
|
|
55
|
+
NOOP: () => {
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// ../../node_modules/ws/lib/buffer-util.js
|
|
62
|
+
var require_buffer_util = __commonJS({
|
|
63
|
+
"../../node_modules/ws/lib/buffer-util.js"(exports, module) {
|
|
64
|
+
"use strict";
|
|
65
|
+
var { EMPTY_BUFFER } = require_constants();
|
|
66
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
67
|
+
function concat(list, totalLength) {
|
|
68
|
+
if (list.length === 0) return EMPTY_BUFFER;
|
|
69
|
+
if (list.length === 1) return list[0];
|
|
70
|
+
const target2 = Buffer.allocUnsafe(totalLength);
|
|
71
|
+
let offset = 0;
|
|
72
|
+
for (let i = 0; i < list.length; i++) {
|
|
73
|
+
const buf = list[i];
|
|
74
|
+
target2.set(buf, offset);
|
|
75
|
+
offset += buf.length;
|
|
76
|
+
}
|
|
77
|
+
if (offset < totalLength) {
|
|
78
|
+
return new FastBuffer(target2.buffer, target2.byteOffset, offset);
|
|
79
|
+
}
|
|
80
|
+
return target2;
|
|
81
|
+
}
|
|
82
|
+
function _mask(source, mask, output, offset, length) {
|
|
83
|
+
for (let i = 0; i < length; i++) {
|
|
84
|
+
output[offset + i] = source[i] ^ mask[i & 3];
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function _unmask(buffer, mask) {
|
|
88
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
89
|
+
buffer[i] ^= mask[i & 3];
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function toArrayBuffer(buf) {
|
|
93
|
+
if (buf.length === buf.buffer.byteLength) {
|
|
94
|
+
return buf.buffer;
|
|
95
|
+
}
|
|
96
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
|
|
97
|
+
}
|
|
98
|
+
function toBuffer(data) {
|
|
99
|
+
toBuffer.readOnly = true;
|
|
100
|
+
if (Buffer.isBuffer(data)) return data;
|
|
101
|
+
let buf;
|
|
102
|
+
if (data instanceof ArrayBuffer) {
|
|
103
|
+
buf = new FastBuffer(data);
|
|
104
|
+
} else if (ArrayBuffer.isView(data)) {
|
|
105
|
+
buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
|
|
106
|
+
} else {
|
|
107
|
+
buf = Buffer.from(data);
|
|
108
|
+
toBuffer.readOnly = false;
|
|
109
|
+
}
|
|
110
|
+
return buf;
|
|
111
|
+
}
|
|
112
|
+
module.exports = {
|
|
113
|
+
concat,
|
|
114
|
+
mask: _mask,
|
|
115
|
+
toArrayBuffer,
|
|
116
|
+
toBuffer,
|
|
117
|
+
unmask: _unmask
|
|
118
|
+
};
|
|
119
|
+
if (!process.env.WS_NO_BUFFER_UTIL) {
|
|
120
|
+
try {
|
|
121
|
+
const bufferUtil = __require("bufferutil");
|
|
122
|
+
module.exports.mask = function(source, mask, output, offset, length) {
|
|
123
|
+
if (length < 48) _mask(source, mask, output, offset, length);
|
|
124
|
+
else bufferUtil.mask(source, mask, output, offset, length);
|
|
125
|
+
};
|
|
126
|
+
module.exports.unmask = function(buffer, mask) {
|
|
127
|
+
if (buffer.length < 32) _unmask(buffer, mask);
|
|
128
|
+
else bufferUtil.unmask(buffer, mask);
|
|
129
|
+
};
|
|
130
|
+
} catch (e) {
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// ../../node_modules/ws/lib/limiter.js
|
|
137
|
+
var require_limiter = __commonJS({
|
|
138
|
+
"../../node_modules/ws/lib/limiter.js"(exports, module) {
|
|
139
|
+
"use strict";
|
|
140
|
+
var kDone = /* @__PURE__ */ Symbol("kDone");
|
|
141
|
+
var kRun = /* @__PURE__ */ Symbol("kRun");
|
|
142
|
+
var Limiter = class {
|
|
143
|
+
/**
|
|
144
|
+
* Creates a new `Limiter`.
|
|
145
|
+
*
|
|
146
|
+
* @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
|
|
147
|
+
* to run concurrently
|
|
148
|
+
*/
|
|
149
|
+
constructor(concurrency) {
|
|
150
|
+
this[kDone] = () => {
|
|
151
|
+
this.pending--;
|
|
152
|
+
this[kRun]();
|
|
153
|
+
};
|
|
154
|
+
this.concurrency = concurrency || Infinity;
|
|
155
|
+
this.jobs = [];
|
|
156
|
+
this.pending = 0;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Adds a job to the queue.
|
|
160
|
+
*
|
|
161
|
+
* @param {Function} job The job to run
|
|
162
|
+
* @public
|
|
163
|
+
*/
|
|
164
|
+
add(job) {
|
|
165
|
+
this.jobs.push(job);
|
|
166
|
+
this[kRun]();
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Removes a job from the queue and runs it if possible.
|
|
170
|
+
*
|
|
171
|
+
* @private
|
|
172
|
+
*/
|
|
173
|
+
[kRun]() {
|
|
174
|
+
if (this.pending === this.concurrency) return;
|
|
175
|
+
if (this.jobs.length) {
|
|
176
|
+
const job = this.jobs.shift();
|
|
177
|
+
this.pending++;
|
|
178
|
+
job(this[kDone]);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
module.exports = Limiter;
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
// ../../node_modules/ws/lib/permessage-deflate.js
|
|
187
|
+
var require_permessage_deflate = __commonJS({
|
|
188
|
+
"../../node_modules/ws/lib/permessage-deflate.js"(exports, module) {
|
|
189
|
+
"use strict";
|
|
190
|
+
var zlib = __require("zlib");
|
|
191
|
+
var bufferUtil = require_buffer_util();
|
|
192
|
+
var Limiter = require_limiter();
|
|
193
|
+
var { kStatusCode } = require_constants();
|
|
194
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
195
|
+
var TRAILER = Buffer.from([0, 0, 255, 255]);
|
|
196
|
+
var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
|
|
197
|
+
var kTotalLength = /* @__PURE__ */ Symbol("total-length");
|
|
198
|
+
var kCallback = /* @__PURE__ */ Symbol("callback");
|
|
199
|
+
var kBuffers = /* @__PURE__ */ Symbol("buffers");
|
|
200
|
+
var kError = /* @__PURE__ */ Symbol("error");
|
|
201
|
+
var zlibLimiter;
|
|
202
|
+
var PerMessageDeflate2 = class {
|
|
203
|
+
/**
|
|
204
|
+
* Creates a PerMessageDeflate instance.
|
|
205
|
+
*
|
|
206
|
+
* @param {Object} [options] Configuration options
|
|
207
|
+
* @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
|
|
208
|
+
* for, or request, a custom client window size
|
|
209
|
+
* @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
|
|
210
|
+
* acknowledge disabling of client context takeover
|
|
211
|
+
* @param {Number} [options.concurrencyLimit=10] The number of concurrent
|
|
212
|
+
* calls to zlib
|
|
213
|
+
* @param {Boolean} [options.isServer=false] Create the instance in either
|
|
214
|
+
* server or client mode
|
|
215
|
+
* @param {Number} [options.maxPayload=0] The maximum allowed message length
|
|
216
|
+
* @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
|
|
217
|
+
* use of a custom server window size
|
|
218
|
+
* @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
|
|
219
|
+
* disabling of server context takeover
|
|
220
|
+
* @param {Number} [options.threshold=1024] Size (in bytes) below which
|
|
221
|
+
* messages should not be compressed if context takeover is disabled
|
|
222
|
+
* @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
|
|
223
|
+
* deflate
|
|
224
|
+
* @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
|
|
225
|
+
* inflate
|
|
226
|
+
*/
|
|
227
|
+
constructor(options) {
|
|
228
|
+
this._options = options || {};
|
|
229
|
+
this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
|
|
230
|
+
this._maxPayload = this._options.maxPayload | 0;
|
|
231
|
+
this._isServer = !!this._options.isServer;
|
|
232
|
+
this._deflate = null;
|
|
233
|
+
this._inflate = null;
|
|
234
|
+
this.params = null;
|
|
235
|
+
if (!zlibLimiter) {
|
|
236
|
+
const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
|
|
237
|
+
zlibLimiter = new Limiter(concurrency);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* @type {String}
|
|
242
|
+
*/
|
|
243
|
+
static get extensionName() {
|
|
244
|
+
return "permessage-deflate";
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Create an extension negotiation offer.
|
|
248
|
+
*
|
|
249
|
+
* @return {Object} Extension parameters
|
|
250
|
+
* @public
|
|
251
|
+
*/
|
|
252
|
+
offer() {
|
|
253
|
+
const params = {};
|
|
254
|
+
if (this._options.serverNoContextTakeover) {
|
|
255
|
+
params.server_no_context_takeover = true;
|
|
256
|
+
}
|
|
257
|
+
if (this._options.clientNoContextTakeover) {
|
|
258
|
+
params.client_no_context_takeover = true;
|
|
259
|
+
}
|
|
260
|
+
if (this._options.serverMaxWindowBits) {
|
|
261
|
+
params.server_max_window_bits = this._options.serverMaxWindowBits;
|
|
262
|
+
}
|
|
263
|
+
if (this._options.clientMaxWindowBits) {
|
|
264
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
265
|
+
} else if (this._options.clientMaxWindowBits == null) {
|
|
266
|
+
params.client_max_window_bits = true;
|
|
267
|
+
}
|
|
268
|
+
return params;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Accept an extension negotiation offer/response.
|
|
272
|
+
*
|
|
273
|
+
* @param {Array} configurations The extension negotiation offers/reponse
|
|
274
|
+
* @return {Object} Accepted configuration
|
|
275
|
+
* @public
|
|
276
|
+
*/
|
|
277
|
+
accept(configurations) {
|
|
278
|
+
configurations = this.normalizeParams(configurations);
|
|
279
|
+
this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
|
|
280
|
+
return this.params;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Releases all resources used by the extension.
|
|
284
|
+
*
|
|
285
|
+
* @public
|
|
286
|
+
*/
|
|
287
|
+
cleanup() {
|
|
288
|
+
if (this._inflate) {
|
|
289
|
+
this._inflate.close();
|
|
290
|
+
this._inflate = null;
|
|
291
|
+
}
|
|
292
|
+
if (this._deflate) {
|
|
293
|
+
const callback = this._deflate[kCallback];
|
|
294
|
+
this._deflate.close();
|
|
295
|
+
this._deflate = null;
|
|
296
|
+
if (callback) {
|
|
297
|
+
callback(
|
|
298
|
+
new Error(
|
|
299
|
+
"The deflate stream was closed while data was being processed"
|
|
300
|
+
)
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Accept an extension negotiation offer.
|
|
307
|
+
*
|
|
308
|
+
* @param {Array} offers The extension negotiation offers
|
|
309
|
+
* @return {Object} Accepted configuration
|
|
310
|
+
* @private
|
|
311
|
+
*/
|
|
312
|
+
acceptAsServer(offers) {
|
|
313
|
+
const opts = this._options;
|
|
314
|
+
const accepted = offers.find((params) => {
|
|
315
|
+
if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
|
|
316
|
+
return false;
|
|
317
|
+
}
|
|
318
|
+
return true;
|
|
319
|
+
});
|
|
320
|
+
if (!accepted) {
|
|
321
|
+
throw new Error("None of the extension offers can be accepted");
|
|
322
|
+
}
|
|
323
|
+
if (opts.serverNoContextTakeover) {
|
|
324
|
+
accepted.server_no_context_takeover = true;
|
|
325
|
+
}
|
|
326
|
+
if (opts.clientNoContextTakeover) {
|
|
327
|
+
accepted.client_no_context_takeover = true;
|
|
328
|
+
}
|
|
329
|
+
if (typeof opts.serverMaxWindowBits === "number") {
|
|
330
|
+
accepted.server_max_window_bits = opts.serverMaxWindowBits;
|
|
331
|
+
}
|
|
332
|
+
if (typeof opts.clientMaxWindowBits === "number") {
|
|
333
|
+
accepted.client_max_window_bits = opts.clientMaxWindowBits;
|
|
334
|
+
} else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
|
|
335
|
+
delete accepted.client_max_window_bits;
|
|
336
|
+
}
|
|
337
|
+
return accepted;
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Accept the extension negotiation response.
|
|
341
|
+
*
|
|
342
|
+
* @param {Array} response The extension negotiation response
|
|
343
|
+
* @return {Object} Accepted configuration
|
|
344
|
+
* @private
|
|
345
|
+
*/
|
|
346
|
+
acceptAsClient(response) {
|
|
347
|
+
const params = response[0];
|
|
348
|
+
if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
|
|
349
|
+
throw new Error('Unexpected parameter "client_no_context_takeover"');
|
|
350
|
+
}
|
|
351
|
+
if (!params.client_max_window_bits) {
|
|
352
|
+
if (typeof this._options.clientMaxWindowBits === "number") {
|
|
353
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
354
|
+
}
|
|
355
|
+
} else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
|
|
356
|
+
throw new Error(
|
|
357
|
+
'Unexpected or invalid parameter "client_max_window_bits"'
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
return params;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Normalize parameters.
|
|
364
|
+
*
|
|
365
|
+
* @param {Array} configurations The extension negotiation offers/reponse
|
|
366
|
+
* @return {Array} The offers/response with normalized parameters
|
|
367
|
+
* @private
|
|
368
|
+
*/
|
|
369
|
+
normalizeParams(configurations) {
|
|
370
|
+
configurations.forEach((params) => {
|
|
371
|
+
Object.keys(params).forEach((key) => {
|
|
372
|
+
let value = params[key];
|
|
373
|
+
if (value.length > 1) {
|
|
374
|
+
throw new Error(`Parameter "${key}" must have only a single value`);
|
|
375
|
+
}
|
|
376
|
+
value = value[0];
|
|
377
|
+
if (key === "client_max_window_bits") {
|
|
378
|
+
if (value !== true) {
|
|
379
|
+
const num = +value;
|
|
380
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
381
|
+
throw new TypeError(
|
|
382
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
value = num;
|
|
386
|
+
} else if (!this._isServer) {
|
|
387
|
+
throw new TypeError(
|
|
388
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
} else if (key === "server_max_window_bits") {
|
|
392
|
+
const num = +value;
|
|
393
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
394
|
+
throw new TypeError(
|
|
395
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
396
|
+
);
|
|
397
|
+
}
|
|
398
|
+
value = num;
|
|
399
|
+
} else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
|
|
400
|
+
if (value !== true) {
|
|
401
|
+
throw new TypeError(
|
|
402
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
} else {
|
|
406
|
+
throw new Error(`Unknown parameter "${key}"`);
|
|
407
|
+
}
|
|
408
|
+
params[key] = value;
|
|
409
|
+
});
|
|
410
|
+
});
|
|
411
|
+
return configurations;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Decompress data. Concurrency limited.
|
|
415
|
+
*
|
|
416
|
+
* @param {Buffer} data Compressed data
|
|
417
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
418
|
+
* @param {Function} callback Callback
|
|
419
|
+
* @public
|
|
420
|
+
*/
|
|
421
|
+
decompress(data, fin, callback) {
|
|
422
|
+
zlibLimiter.add((done) => {
|
|
423
|
+
this._decompress(data, fin, (err, result) => {
|
|
424
|
+
done();
|
|
425
|
+
callback(err, result);
|
|
426
|
+
});
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Compress data. Concurrency limited.
|
|
431
|
+
*
|
|
432
|
+
* @param {(Buffer|String)} data Data to compress
|
|
433
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
434
|
+
* @param {Function} callback Callback
|
|
435
|
+
* @public
|
|
436
|
+
*/
|
|
437
|
+
compress(data, fin, callback) {
|
|
438
|
+
zlibLimiter.add((done) => {
|
|
439
|
+
this._compress(data, fin, (err, result) => {
|
|
440
|
+
done();
|
|
441
|
+
callback(err, result);
|
|
442
|
+
});
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Decompress data.
|
|
447
|
+
*
|
|
448
|
+
* @param {Buffer} data Compressed data
|
|
449
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
450
|
+
* @param {Function} callback Callback
|
|
451
|
+
* @private
|
|
452
|
+
*/
|
|
453
|
+
_decompress(data, fin, callback) {
|
|
454
|
+
const endpoint = this._isServer ? "client" : "server";
|
|
455
|
+
if (!this._inflate) {
|
|
456
|
+
const key = `${endpoint}_max_window_bits`;
|
|
457
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
458
|
+
this._inflate = zlib.createInflateRaw({
|
|
459
|
+
...this._options.zlibInflateOptions,
|
|
460
|
+
windowBits
|
|
461
|
+
});
|
|
462
|
+
this._inflate[kPerMessageDeflate] = this;
|
|
463
|
+
this._inflate[kTotalLength] = 0;
|
|
464
|
+
this._inflate[kBuffers] = [];
|
|
465
|
+
this._inflate.on("error", inflateOnError);
|
|
466
|
+
this._inflate.on("data", inflateOnData);
|
|
467
|
+
}
|
|
468
|
+
this._inflate[kCallback] = callback;
|
|
469
|
+
this._inflate.write(data);
|
|
470
|
+
if (fin) this._inflate.write(TRAILER);
|
|
471
|
+
this._inflate.flush(() => {
|
|
472
|
+
const err = this._inflate[kError];
|
|
473
|
+
if (err) {
|
|
474
|
+
this._inflate.close();
|
|
475
|
+
this._inflate = null;
|
|
476
|
+
callback(err);
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
const data2 = bufferUtil.concat(
|
|
480
|
+
this._inflate[kBuffers],
|
|
481
|
+
this._inflate[kTotalLength]
|
|
482
|
+
);
|
|
483
|
+
if (this._inflate._readableState.endEmitted) {
|
|
484
|
+
this._inflate.close();
|
|
485
|
+
this._inflate = null;
|
|
486
|
+
} else {
|
|
487
|
+
this._inflate[kTotalLength] = 0;
|
|
488
|
+
this._inflate[kBuffers] = [];
|
|
489
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
490
|
+
this._inflate.reset();
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
callback(null, data2);
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Compress data.
|
|
498
|
+
*
|
|
499
|
+
* @param {(Buffer|String)} data Data to compress
|
|
500
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
501
|
+
* @param {Function} callback Callback
|
|
502
|
+
* @private
|
|
503
|
+
*/
|
|
504
|
+
_compress(data, fin, callback) {
|
|
505
|
+
const endpoint = this._isServer ? "server" : "client";
|
|
506
|
+
if (!this._deflate) {
|
|
507
|
+
const key = `${endpoint}_max_window_bits`;
|
|
508
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
509
|
+
this._deflate = zlib.createDeflateRaw({
|
|
510
|
+
...this._options.zlibDeflateOptions,
|
|
511
|
+
windowBits
|
|
512
|
+
});
|
|
513
|
+
this._deflate[kTotalLength] = 0;
|
|
514
|
+
this._deflate[kBuffers] = [];
|
|
515
|
+
this._deflate.on("data", deflateOnData);
|
|
516
|
+
}
|
|
517
|
+
this._deflate[kCallback] = callback;
|
|
518
|
+
this._deflate.write(data);
|
|
519
|
+
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
|
|
520
|
+
if (!this._deflate) {
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
let data2 = bufferUtil.concat(
|
|
524
|
+
this._deflate[kBuffers],
|
|
525
|
+
this._deflate[kTotalLength]
|
|
526
|
+
);
|
|
527
|
+
if (fin) {
|
|
528
|
+
data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
|
|
529
|
+
}
|
|
530
|
+
this._deflate[kCallback] = null;
|
|
531
|
+
this._deflate[kTotalLength] = 0;
|
|
532
|
+
this._deflate[kBuffers] = [];
|
|
533
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
534
|
+
this._deflate.reset();
|
|
535
|
+
}
|
|
536
|
+
callback(null, data2);
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
module.exports = PerMessageDeflate2;
|
|
541
|
+
function deflateOnData(chunk) {
|
|
542
|
+
this[kBuffers].push(chunk);
|
|
543
|
+
this[kTotalLength] += chunk.length;
|
|
544
|
+
}
|
|
545
|
+
function inflateOnData(chunk) {
|
|
546
|
+
this[kTotalLength] += chunk.length;
|
|
547
|
+
if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
|
|
548
|
+
this[kBuffers].push(chunk);
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
this[kError] = new RangeError("Max payload size exceeded");
|
|
552
|
+
this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
|
|
553
|
+
this[kError][kStatusCode] = 1009;
|
|
554
|
+
this.removeListener("data", inflateOnData);
|
|
555
|
+
this.reset();
|
|
556
|
+
}
|
|
557
|
+
function inflateOnError(err) {
|
|
558
|
+
this[kPerMessageDeflate]._inflate = null;
|
|
559
|
+
if (this[kError]) {
|
|
560
|
+
this[kCallback](this[kError]);
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
err[kStatusCode] = 1007;
|
|
564
|
+
this[kCallback](err);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
// ../../node_modules/ws/lib/validation.js
|
|
570
|
+
var require_validation = __commonJS({
|
|
571
|
+
"../../node_modules/ws/lib/validation.js"(exports, module) {
|
|
572
|
+
"use strict";
|
|
573
|
+
var { isUtf8 } = __require("buffer");
|
|
574
|
+
var { hasBlob } = require_constants();
|
|
575
|
+
var tokenChars = [
|
|
576
|
+
0,
|
|
577
|
+
0,
|
|
578
|
+
0,
|
|
579
|
+
0,
|
|
580
|
+
0,
|
|
581
|
+
0,
|
|
582
|
+
0,
|
|
583
|
+
0,
|
|
584
|
+
0,
|
|
585
|
+
0,
|
|
586
|
+
0,
|
|
587
|
+
0,
|
|
588
|
+
0,
|
|
589
|
+
0,
|
|
590
|
+
0,
|
|
591
|
+
0,
|
|
592
|
+
// 0 - 15
|
|
593
|
+
0,
|
|
594
|
+
0,
|
|
595
|
+
0,
|
|
596
|
+
0,
|
|
597
|
+
0,
|
|
598
|
+
0,
|
|
599
|
+
0,
|
|
600
|
+
0,
|
|
601
|
+
0,
|
|
602
|
+
0,
|
|
603
|
+
0,
|
|
604
|
+
0,
|
|
605
|
+
0,
|
|
606
|
+
0,
|
|
607
|
+
0,
|
|
608
|
+
0,
|
|
609
|
+
// 16 - 31
|
|
610
|
+
0,
|
|
611
|
+
1,
|
|
612
|
+
0,
|
|
613
|
+
1,
|
|
614
|
+
1,
|
|
615
|
+
1,
|
|
616
|
+
1,
|
|
617
|
+
1,
|
|
618
|
+
0,
|
|
619
|
+
0,
|
|
620
|
+
1,
|
|
621
|
+
1,
|
|
622
|
+
0,
|
|
623
|
+
1,
|
|
624
|
+
1,
|
|
625
|
+
0,
|
|
626
|
+
// 32 - 47
|
|
627
|
+
1,
|
|
628
|
+
1,
|
|
629
|
+
1,
|
|
630
|
+
1,
|
|
631
|
+
1,
|
|
632
|
+
1,
|
|
633
|
+
1,
|
|
634
|
+
1,
|
|
635
|
+
1,
|
|
636
|
+
1,
|
|
637
|
+
0,
|
|
638
|
+
0,
|
|
639
|
+
0,
|
|
640
|
+
0,
|
|
641
|
+
0,
|
|
642
|
+
0,
|
|
643
|
+
// 48 - 63
|
|
644
|
+
0,
|
|
645
|
+
1,
|
|
646
|
+
1,
|
|
647
|
+
1,
|
|
648
|
+
1,
|
|
649
|
+
1,
|
|
650
|
+
1,
|
|
651
|
+
1,
|
|
652
|
+
1,
|
|
653
|
+
1,
|
|
654
|
+
1,
|
|
655
|
+
1,
|
|
656
|
+
1,
|
|
657
|
+
1,
|
|
658
|
+
1,
|
|
659
|
+
1,
|
|
660
|
+
// 64 - 79
|
|
661
|
+
1,
|
|
662
|
+
1,
|
|
663
|
+
1,
|
|
664
|
+
1,
|
|
665
|
+
1,
|
|
666
|
+
1,
|
|
667
|
+
1,
|
|
668
|
+
1,
|
|
669
|
+
1,
|
|
670
|
+
1,
|
|
671
|
+
1,
|
|
672
|
+
0,
|
|
673
|
+
0,
|
|
674
|
+
0,
|
|
675
|
+
1,
|
|
676
|
+
1,
|
|
677
|
+
// 80 - 95
|
|
678
|
+
1,
|
|
679
|
+
1,
|
|
680
|
+
1,
|
|
681
|
+
1,
|
|
682
|
+
1,
|
|
683
|
+
1,
|
|
684
|
+
1,
|
|
685
|
+
1,
|
|
686
|
+
1,
|
|
687
|
+
1,
|
|
688
|
+
1,
|
|
689
|
+
1,
|
|
690
|
+
1,
|
|
691
|
+
1,
|
|
692
|
+
1,
|
|
693
|
+
1,
|
|
694
|
+
// 96 - 111
|
|
695
|
+
1,
|
|
696
|
+
1,
|
|
697
|
+
1,
|
|
698
|
+
1,
|
|
699
|
+
1,
|
|
700
|
+
1,
|
|
701
|
+
1,
|
|
702
|
+
1,
|
|
703
|
+
1,
|
|
704
|
+
1,
|
|
705
|
+
1,
|
|
706
|
+
0,
|
|
707
|
+
1,
|
|
708
|
+
0,
|
|
709
|
+
1,
|
|
710
|
+
0
|
|
711
|
+
// 112 - 127
|
|
712
|
+
];
|
|
713
|
+
function isValidStatusCode(code) {
|
|
714
|
+
return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
|
|
715
|
+
}
|
|
716
|
+
function _isValidUTF8(buf) {
|
|
717
|
+
const len = buf.length;
|
|
718
|
+
let i = 0;
|
|
719
|
+
while (i < len) {
|
|
720
|
+
if ((buf[i] & 128) === 0) {
|
|
721
|
+
i++;
|
|
722
|
+
} else if ((buf[i] & 224) === 192) {
|
|
723
|
+
if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
|
|
724
|
+
return false;
|
|
725
|
+
}
|
|
726
|
+
i += 2;
|
|
727
|
+
} else if ((buf[i] & 240) === 224) {
|
|
728
|
+
if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
|
|
729
|
+
buf[i] === 237 && (buf[i + 1] & 224) === 160) {
|
|
730
|
+
return false;
|
|
731
|
+
}
|
|
732
|
+
i += 3;
|
|
733
|
+
} else if ((buf[i] & 248) === 240) {
|
|
734
|
+
if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
|
|
735
|
+
buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
|
|
736
|
+
return false;
|
|
737
|
+
}
|
|
738
|
+
i += 4;
|
|
739
|
+
} else {
|
|
740
|
+
return false;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
return true;
|
|
744
|
+
}
|
|
745
|
+
function isBlob(value) {
|
|
746
|
+
return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
|
|
747
|
+
}
|
|
748
|
+
module.exports = {
|
|
749
|
+
isBlob,
|
|
750
|
+
isValidStatusCode,
|
|
751
|
+
isValidUTF8: _isValidUTF8,
|
|
752
|
+
tokenChars
|
|
753
|
+
};
|
|
754
|
+
if (isUtf8) {
|
|
755
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
756
|
+
return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
|
|
757
|
+
};
|
|
758
|
+
} else if (!process.env.WS_NO_UTF_8_VALIDATE) {
|
|
759
|
+
try {
|
|
760
|
+
const isValidUTF8 = __require("utf-8-validate");
|
|
761
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
762
|
+
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
|
|
763
|
+
};
|
|
764
|
+
} catch (e) {
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
|
|
770
|
+
// ../../node_modules/ws/lib/receiver.js
|
|
771
|
+
var require_receiver = __commonJS({
|
|
772
|
+
"../../node_modules/ws/lib/receiver.js"(exports, module) {
|
|
773
|
+
"use strict";
|
|
774
|
+
var { Writable } = __require("stream");
|
|
775
|
+
var PerMessageDeflate2 = require_permessage_deflate();
|
|
776
|
+
var {
|
|
777
|
+
BINARY_TYPES,
|
|
778
|
+
EMPTY_BUFFER,
|
|
779
|
+
kStatusCode,
|
|
780
|
+
kWebSocket
|
|
781
|
+
} = require_constants();
|
|
782
|
+
var { concat, toArrayBuffer, unmask } = require_buffer_util();
|
|
783
|
+
var { isValidStatusCode, isValidUTF8 } = require_validation();
|
|
784
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
785
|
+
var GET_INFO = 0;
|
|
786
|
+
var GET_PAYLOAD_LENGTH_16 = 1;
|
|
787
|
+
var GET_PAYLOAD_LENGTH_64 = 2;
|
|
788
|
+
var GET_MASK = 3;
|
|
789
|
+
var GET_DATA = 4;
|
|
790
|
+
var INFLATING = 5;
|
|
791
|
+
var DEFER_EVENT = 6;
|
|
792
|
+
var Receiver2 = class extends Writable {
|
|
793
|
+
/**
|
|
794
|
+
* Creates a Receiver instance.
|
|
795
|
+
*
|
|
796
|
+
* @param {Object} [options] Options object
|
|
797
|
+
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
|
|
798
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
799
|
+
* multiple times in the same tick
|
|
800
|
+
* @param {String} [options.binaryType=nodebuffer] The type for binary data
|
|
801
|
+
* @param {Object} [options.extensions] An object containing the negotiated
|
|
802
|
+
* extensions
|
|
803
|
+
* @param {Boolean} [options.isServer=false] Specifies whether to operate in
|
|
804
|
+
* client or server mode
|
|
805
|
+
* @param {Number} [options.maxBufferedChunks=0] The maximum number of
|
|
806
|
+
* buffered data chunks
|
|
807
|
+
* @param {Number} [options.maxFragments=0] The maximum number of message
|
|
808
|
+
* fragments
|
|
809
|
+
* @param {Number} [options.maxPayload=0] The maximum allowed message length
|
|
810
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
811
|
+
* not to skip UTF-8 validation for text and close messages
|
|
812
|
+
*/
|
|
813
|
+
constructor(options = {}) {
|
|
814
|
+
super();
|
|
815
|
+
this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
|
|
816
|
+
this._binaryType = options.binaryType || BINARY_TYPES[0];
|
|
817
|
+
this._extensions = options.extensions || {};
|
|
818
|
+
this._isServer = !!options.isServer;
|
|
819
|
+
this._maxBufferedChunks = options.maxBufferedChunks | 0;
|
|
820
|
+
this._maxFragments = options.maxFragments | 0;
|
|
821
|
+
this._maxPayload = options.maxPayload | 0;
|
|
822
|
+
this._skipUTF8Validation = !!options.skipUTF8Validation;
|
|
823
|
+
this[kWebSocket] = void 0;
|
|
824
|
+
this._bufferedBytes = 0;
|
|
825
|
+
this._buffers = [];
|
|
826
|
+
this._compressed = false;
|
|
827
|
+
this._payloadLength = 0;
|
|
828
|
+
this._mask = void 0;
|
|
829
|
+
this._fragmented = 0;
|
|
830
|
+
this._masked = false;
|
|
831
|
+
this._fin = false;
|
|
832
|
+
this._opcode = 0;
|
|
833
|
+
this._totalPayloadLength = 0;
|
|
834
|
+
this._messageLength = 0;
|
|
835
|
+
this._numFragments = 0;
|
|
836
|
+
this._fragments = [];
|
|
837
|
+
this._errored = false;
|
|
838
|
+
this._loop = false;
|
|
839
|
+
this._state = GET_INFO;
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Implements `Writable.prototype._write()`.
|
|
843
|
+
*
|
|
844
|
+
* @param {Buffer} chunk The chunk of data to write
|
|
845
|
+
* @param {String} encoding The character encoding of `chunk`
|
|
846
|
+
* @param {Function} cb Callback
|
|
847
|
+
* @private
|
|
848
|
+
*/
|
|
849
|
+
_write(chunk, encoding, cb) {
|
|
850
|
+
if (this._opcode === 8 && this._state == GET_INFO) return cb();
|
|
851
|
+
if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
|
|
852
|
+
cb(
|
|
853
|
+
this.createError(
|
|
854
|
+
RangeError,
|
|
855
|
+
"Too many buffered chunks",
|
|
856
|
+
false,
|
|
857
|
+
1008,
|
|
858
|
+
"WS_ERR_TOO_MANY_BUFFERED_PARTS"
|
|
859
|
+
)
|
|
860
|
+
);
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
this._bufferedBytes += chunk.length;
|
|
864
|
+
this._buffers.push(chunk);
|
|
865
|
+
this.startLoop(cb);
|
|
866
|
+
}
|
|
867
|
+
/**
|
|
868
|
+
* Consumes `n` bytes from the buffered data.
|
|
869
|
+
*
|
|
870
|
+
* @param {Number} n The number of bytes to consume
|
|
871
|
+
* @return {Buffer} The consumed bytes
|
|
872
|
+
* @private
|
|
873
|
+
*/
|
|
874
|
+
consume(n) {
|
|
875
|
+
this._bufferedBytes -= n;
|
|
876
|
+
if (n === this._buffers[0].length) return this._buffers.shift();
|
|
877
|
+
if (n < this._buffers[0].length) {
|
|
878
|
+
const buf = this._buffers[0];
|
|
879
|
+
this._buffers[0] = new FastBuffer(
|
|
880
|
+
buf.buffer,
|
|
881
|
+
buf.byteOffset + n,
|
|
882
|
+
buf.length - n
|
|
883
|
+
);
|
|
884
|
+
return new FastBuffer(buf.buffer, buf.byteOffset, n);
|
|
885
|
+
}
|
|
886
|
+
const dst = Buffer.allocUnsafe(n);
|
|
887
|
+
do {
|
|
888
|
+
const buf = this._buffers[0];
|
|
889
|
+
const offset = dst.length - n;
|
|
890
|
+
if (n >= buf.length) {
|
|
891
|
+
dst.set(this._buffers.shift(), offset);
|
|
892
|
+
} else {
|
|
893
|
+
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
|
|
894
|
+
this._buffers[0] = new FastBuffer(
|
|
895
|
+
buf.buffer,
|
|
896
|
+
buf.byteOffset + n,
|
|
897
|
+
buf.length - n
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
n -= buf.length;
|
|
901
|
+
} while (n > 0);
|
|
902
|
+
return dst;
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Starts the parsing loop.
|
|
906
|
+
*
|
|
907
|
+
* @param {Function} cb Callback
|
|
908
|
+
* @private
|
|
909
|
+
*/
|
|
910
|
+
startLoop(cb) {
|
|
911
|
+
this._loop = true;
|
|
912
|
+
do {
|
|
913
|
+
switch (this._state) {
|
|
914
|
+
case GET_INFO:
|
|
915
|
+
this.getInfo(cb);
|
|
916
|
+
break;
|
|
917
|
+
case GET_PAYLOAD_LENGTH_16:
|
|
918
|
+
this.getPayloadLength16(cb);
|
|
919
|
+
break;
|
|
920
|
+
case GET_PAYLOAD_LENGTH_64:
|
|
921
|
+
this.getPayloadLength64(cb);
|
|
922
|
+
break;
|
|
923
|
+
case GET_MASK:
|
|
924
|
+
this.getMask();
|
|
925
|
+
break;
|
|
926
|
+
case GET_DATA:
|
|
927
|
+
this.getData(cb);
|
|
928
|
+
break;
|
|
929
|
+
case INFLATING:
|
|
930
|
+
case DEFER_EVENT:
|
|
931
|
+
this._loop = false;
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
} while (this._loop);
|
|
935
|
+
if (!this._errored) cb();
|
|
936
|
+
}
|
|
937
|
+
/**
|
|
938
|
+
* Reads the first two bytes of a frame.
|
|
939
|
+
*
|
|
940
|
+
* @param {Function} cb Callback
|
|
941
|
+
* @private
|
|
942
|
+
*/
|
|
943
|
+
getInfo(cb) {
|
|
944
|
+
if (this._bufferedBytes < 2) {
|
|
945
|
+
this._loop = false;
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
const buf = this.consume(2);
|
|
949
|
+
if ((buf[0] & 48) !== 0) {
|
|
950
|
+
const error = this.createError(
|
|
951
|
+
RangeError,
|
|
952
|
+
"RSV2 and RSV3 must be clear",
|
|
953
|
+
true,
|
|
954
|
+
1002,
|
|
955
|
+
"WS_ERR_UNEXPECTED_RSV_2_3"
|
|
956
|
+
);
|
|
957
|
+
cb(error);
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
const compressed = (buf[0] & 64) === 64;
|
|
961
|
+
if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
|
|
962
|
+
const error = this.createError(
|
|
963
|
+
RangeError,
|
|
964
|
+
"RSV1 must be clear",
|
|
965
|
+
true,
|
|
966
|
+
1002,
|
|
967
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
968
|
+
);
|
|
969
|
+
cb(error);
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
this._fin = (buf[0] & 128) === 128;
|
|
973
|
+
this._opcode = buf[0] & 15;
|
|
974
|
+
this._payloadLength = buf[1] & 127;
|
|
975
|
+
if (this._opcode === 0) {
|
|
976
|
+
if (compressed) {
|
|
977
|
+
const error = this.createError(
|
|
978
|
+
RangeError,
|
|
979
|
+
"RSV1 must be clear",
|
|
980
|
+
true,
|
|
981
|
+
1002,
|
|
982
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
983
|
+
);
|
|
984
|
+
cb(error);
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
if (!this._fragmented) {
|
|
988
|
+
const error = this.createError(
|
|
989
|
+
RangeError,
|
|
990
|
+
"invalid opcode 0",
|
|
991
|
+
true,
|
|
992
|
+
1002,
|
|
993
|
+
"WS_ERR_INVALID_OPCODE"
|
|
994
|
+
);
|
|
995
|
+
cb(error);
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
this._opcode = this._fragmented;
|
|
999
|
+
} else if (this._opcode === 1 || this._opcode === 2) {
|
|
1000
|
+
if (this._fragmented) {
|
|
1001
|
+
const error = this.createError(
|
|
1002
|
+
RangeError,
|
|
1003
|
+
`invalid opcode ${this._opcode}`,
|
|
1004
|
+
true,
|
|
1005
|
+
1002,
|
|
1006
|
+
"WS_ERR_INVALID_OPCODE"
|
|
1007
|
+
);
|
|
1008
|
+
cb(error);
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
this._compressed = compressed;
|
|
1012
|
+
} else if (this._opcode > 7 && this._opcode < 11) {
|
|
1013
|
+
if (!this._fin) {
|
|
1014
|
+
const error = this.createError(
|
|
1015
|
+
RangeError,
|
|
1016
|
+
"FIN must be set",
|
|
1017
|
+
true,
|
|
1018
|
+
1002,
|
|
1019
|
+
"WS_ERR_EXPECTED_FIN"
|
|
1020
|
+
);
|
|
1021
|
+
cb(error);
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
if (compressed) {
|
|
1025
|
+
const error = this.createError(
|
|
1026
|
+
RangeError,
|
|
1027
|
+
"RSV1 must be clear",
|
|
1028
|
+
true,
|
|
1029
|
+
1002,
|
|
1030
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
1031
|
+
);
|
|
1032
|
+
cb(error);
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
|
|
1036
|
+
const error = this.createError(
|
|
1037
|
+
RangeError,
|
|
1038
|
+
`invalid payload length ${this._payloadLength}`,
|
|
1039
|
+
true,
|
|
1040
|
+
1002,
|
|
1041
|
+
"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
|
|
1042
|
+
);
|
|
1043
|
+
cb(error);
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
} else {
|
|
1047
|
+
const error = this.createError(
|
|
1048
|
+
RangeError,
|
|
1049
|
+
`invalid opcode ${this._opcode}`,
|
|
1050
|
+
true,
|
|
1051
|
+
1002,
|
|
1052
|
+
"WS_ERR_INVALID_OPCODE"
|
|
1053
|
+
);
|
|
1054
|
+
cb(error);
|
|
1055
|
+
return;
|
|
1056
|
+
}
|
|
1057
|
+
if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
|
|
1058
|
+
this._masked = (buf[1] & 128) === 128;
|
|
1059
|
+
if (this._isServer) {
|
|
1060
|
+
if (!this._masked) {
|
|
1061
|
+
const error = this.createError(
|
|
1062
|
+
RangeError,
|
|
1063
|
+
"MASK must be set",
|
|
1064
|
+
true,
|
|
1065
|
+
1002,
|
|
1066
|
+
"WS_ERR_EXPECTED_MASK"
|
|
1067
|
+
);
|
|
1068
|
+
cb(error);
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
} else if (this._masked) {
|
|
1072
|
+
const error = this.createError(
|
|
1073
|
+
RangeError,
|
|
1074
|
+
"MASK must be clear",
|
|
1075
|
+
true,
|
|
1076
|
+
1002,
|
|
1077
|
+
"WS_ERR_UNEXPECTED_MASK"
|
|
1078
|
+
);
|
|
1079
|
+
cb(error);
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
|
|
1083
|
+
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
|
|
1084
|
+
else this.haveLength(cb);
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* Gets extended payload length (7+16).
|
|
1088
|
+
*
|
|
1089
|
+
* @param {Function} cb Callback
|
|
1090
|
+
* @private
|
|
1091
|
+
*/
|
|
1092
|
+
getPayloadLength16(cb) {
|
|
1093
|
+
if (this._bufferedBytes < 2) {
|
|
1094
|
+
this._loop = false;
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
this._payloadLength = this.consume(2).readUInt16BE(0);
|
|
1098
|
+
this.haveLength(cb);
|
|
1099
|
+
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Gets extended payload length (7+64).
|
|
1102
|
+
*
|
|
1103
|
+
* @param {Function} cb Callback
|
|
1104
|
+
* @private
|
|
1105
|
+
*/
|
|
1106
|
+
getPayloadLength64(cb) {
|
|
1107
|
+
if (this._bufferedBytes < 8) {
|
|
1108
|
+
this._loop = false;
|
|
1109
|
+
return;
|
|
1110
|
+
}
|
|
1111
|
+
const buf = this.consume(8);
|
|
1112
|
+
const num = buf.readUInt32BE(0);
|
|
1113
|
+
if (num > Math.pow(2, 53 - 32) - 1) {
|
|
1114
|
+
const error = this.createError(
|
|
1115
|
+
RangeError,
|
|
1116
|
+
"Unsupported WebSocket frame: payload length > 2^53 - 1",
|
|
1117
|
+
false,
|
|
1118
|
+
1009,
|
|
1119
|
+
"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
|
|
1120
|
+
);
|
|
1121
|
+
cb(error);
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
|
|
1125
|
+
this.haveLength(cb);
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Payload length has been read.
|
|
1129
|
+
*
|
|
1130
|
+
* @param {Function} cb Callback
|
|
1131
|
+
* @private
|
|
1132
|
+
*/
|
|
1133
|
+
haveLength(cb) {
|
|
1134
|
+
if (this._payloadLength && this._opcode < 8) {
|
|
1135
|
+
this._totalPayloadLength += this._payloadLength;
|
|
1136
|
+
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
|
|
1137
|
+
const error = this.createError(
|
|
1138
|
+
RangeError,
|
|
1139
|
+
"Max payload size exceeded",
|
|
1140
|
+
false,
|
|
1141
|
+
1009,
|
|
1142
|
+
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
|
|
1143
|
+
);
|
|
1144
|
+
cb(error);
|
|
1145
|
+
return;
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
if (this._masked) this._state = GET_MASK;
|
|
1149
|
+
else this._state = GET_DATA;
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Reads mask bytes.
|
|
1153
|
+
*
|
|
1154
|
+
* @private
|
|
1155
|
+
*/
|
|
1156
|
+
getMask() {
|
|
1157
|
+
if (this._bufferedBytes < 4) {
|
|
1158
|
+
this._loop = false;
|
|
1159
|
+
return;
|
|
1160
|
+
}
|
|
1161
|
+
this._mask = this.consume(4);
|
|
1162
|
+
this._state = GET_DATA;
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* Reads data bytes.
|
|
1166
|
+
*
|
|
1167
|
+
* @param {Function} cb Callback
|
|
1168
|
+
* @private
|
|
1169
|
+
*/
|
|
1170
|
+
getData(cb) {
|
|
1171
|
+
let data = EMPTY_BUFFER;
|
|
1172
|
+
if (this._payloadLength) {
|
|
1173
|
+
if (this._bufferedBytes < this._payloadLength) {
|
|
1174
|
+
this._loop = false;
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
data = this.consume(this._payloadLength);
|
|
1178
|
+
if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
|
|
1179
|
+
unmask(data, this._mask);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
if (this._opcode > 7) {
|
|
1183
|
+
this.controlMessage(data, cb);
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
|
|
1187
|
+
const error = this.createError(
|
|
1188
|
+
RangeError,
|
|
1189
|
+
"Too many message fragments",
|
|
1190
|
+
false,
|
|
1191
|
+
1008,
|
|
1192
|
+
"WS_ERR_TOO_MANY_BUFFERED_PARTS"
|
|
1193
|
+
);
|
|
1194
|
+
cb(error);
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
if (this._compressed) {
|
|
1198
|
+
this._state = INFLATING;
|
|
1199
|
+
this.decompress(data, cb);
|
|
1200
|
+
return;
|
|
1201
|
+
}
|
|
1202
|
+
if (data.length) {
|
|
1203
|
+
this._messageLength = this._totalPayloadLength;
|
|
1204
|
+
this._fragments.push(data);
|
|
1205
|
+
}
|
|
1206
|
+
this.dataMessage(cb);
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* Decompresses data.
|
|
1210
|
+
*
|
|
1211
|
+
* @param {Buffer} data Compressed data
|
|
1212
|
+
* @param {Function} cb Callback
|
|
1213
|
+
* @private
|
|
1214
|
+
*/
|
|
1215
|
+
decompress(data, cb) {
|
|
1216
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
|
|
1217
|
+
perMessageDeflate.decompress(data, this._fin, (err, buf) => {
|
|
1218
|
+
if (err) return cb(err);
|
|
1219
|
+
if (buf.length) {
|
|
1220
|
+
this._messageLength += buf.length;
|
|
1221
|
+
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
|
|
1222
|
+
const error = this.createError(
|
|
1223
|
+
RangeError,
|
|
1224
|
+
"Max payload size exceeded",
|
|
1225
|
+
false,
|
|
1226
|
+
1009,
|
|
1227
|
+
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
|
|
1228
|
+
);
|
|
1229
|
+
cb(error);
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
this._fragments.push(buf);
|
|
1233
|
+
}
|
|
1234
|
+
this.dataMessage(cb);
|
|
1235
|
+
if (this._state === GET_INFO) this.startLoop(cb);
|
|
1236
|
+
});
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Handles a data message.
|
|
1240
|
+
*
|
|
1241
|
+
* @param {Function} cb Callback
|
|
1242
|
+
* @private
|
|
1243
|
+
*/
|
|
1244
|
+
dataMessage(cb) {
|
|
1245
|
+
if (!this._fin) {
|
|
1246
|
+
this._state = GET_INFO;
|
|
1247
|
+
return;
|
|
1248
|
+
}
|
|
1249
|
+
const messageLength = this._messageLength;
|
|
1250
|
+
const fragments = this._fragments;
|
|
1251
|
+
this._totalPayloadLength = 0;
|
|
1252
|
+
this._messageLength = 0;
|
|
1253
|
+
this._fragmented = 0;
|
|
1254
|
+
this._numFragments = 0;
|
|
1255
|
+
this._fragments = [];
|
|
1256
|
+
if (this._opcode === 2) {
|
|
1257
|
+
let data;
|
|
1258
|
+
if (this._binaryType === "nodebuffer") {
|
|
1259
|
+
data = concat(fragments, messageLength);
|
|
1260
|
+
} else if (this._binaryType === "arraybuffer") {
|
|
1261
|
+
data = toArrayBuffer(concat(fragments, messageLength));
|
|
1262
|
+
} else if (this._binaryType === "blob") {
|
|
1263
|
+
data = new Blob(fragments);
|
|
1264
|
+
} else {
|
|
1265
|
+
data = fragments;
|
|
1266
|
+
}
|
|
1267
|
+
if (this._allowSynchronousEvents) {
|
|
1268
|
+
this.emit("message", data, true);
|
|
1269
|
+
this._state = GET_INFO;
|
|
1270
|
+
} else {
|
|
1271
|
+
this._state = DEFER_EVENT;
|
|
1272
|
+
setImmediate(() => {
|
|
1273
|
+
this.emit("message", data, true);
|
|
1274
|
+
this._state = GET_INFO;
|
|
1275
|
+
this.startLoop(cb);
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
} else {
|
|
1279
|
+
const buf = concat(fragments, messageLength);
|
|
1280
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
1281
|
+
const error = this.createError(
|
|
1282
|
+
Error,
|
|
1283
|
+
"invalid UTF-8 sequence",
|
|
1284
|
+
true,
|
|
1285
|
+
1007,
|
|
1286
|
+
"WS_ERR_INVALID_UTF8"
|
|
1287
|
+
);
|
|
1288
|
+
cb(error);
|
|
1289
|
+
return;
|
|
1290
|
+
}
|
|
1291
|
+
if (this._state === INFLATING || this._allowSynchronousEvents) {
|
|
1292
|
+
this.emit("message", buf, false);
|
|
1293
|
+
this._state = GET_INFO;
|
|
1294
|
+
} else {
|
|
1295
|
+
this._state = DEFER_EVENT;
|
|
1296
|
+
setImmediate(() => {
|
|
1297
|
+
this.emit("message", buf, false);
|
|
1298
|
+
this._state = GET_INFO;
|
|
1299
|
+
this.startLoop(cb);
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
/**
|
|
1305
|
+
* Handles a control message.
|
|
1306
|
+
*
|
|
1307
|
+
* @param {Buffer} data Data to handle
|
|
1308
|
+
* @return {(Error|RangeError|undefined)} A possible error
|
|
1309
|
+
* @private
|
|
1310
|
+
*/
|
|
1311
|
+
controlMessage(data, cb) {
|
|
1312
|
+
if (this._opcode === 8) {
|
|
1313
|
+
if (data.length === 0) {
|
|
1314
|
+
this._loop = false;
|
|
1315
|
+
this.emit("conclude", 1005, EMPTY_BUFFER);
|
|
1316
|
+
this.end();
|
|
1317
|
+
} else {
|
|
1318
|
+
const code = data.readUInt16BE(0);
|
|
1319
|
+
if (!isValidStatusCode(code)) {
|
|
1320
|
+
const error = this.createError(
|
|
1321
|
+
RangeError,
|
|
1322
|
+
`invalid status code ${code}`,
|
|
1323
|
+
true,
|
|
1324
|
+
1002,
|
|
1325
|
+
"WS_ERR_INVALID_CLOSE_CODE"
|
|
1326
|
+
);
|
|
1327
|
+
cb(error);
|
|
1328
|
+
return;
|
|
1329
|
+
}
|
|
1330
|
+
const buf = new FastBuffer(
|
|
1331
|
+
data.buffer,
|
|
1332
|
+
data.byteOffset + 2,
|
|
1333
|
+
data.length - 2
|
|
1334
|
+
);
|
|
1335
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
1336
|
+
const error = this.createError(
|
|
1337
|
+
Error,
|
|
1338
|
+
"invalid UTF-8 sequence",
|
|
1339
|
+
true,
|
|
1340
|
+
1007,
|
|
1341
|
+
"WS_ERR_INVALID_UTF8"
|
|
1342
|
+
);
|
|
1343
|
+
cb(error);
|
|
1344
|
+
return;
|
|
1345
|
+
}
|
|
1346
|
+
this._loop = false;
|
|
1347
|
+
this.emit("conclude", code, buf);
|
|
1348
|
+
this.end();
|
|
1349
|
+
}
|
|
1350
|
+
this._state = GET_INFO;
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
if (this._allowSynchronousEvents) {
|
|
1354
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
1355
|
+
this._state = GET_INFO;
|
|
1356
|
+
} else {
|
|
1357
|
+
this._state = DEFER_EVENT;
|
|
1358
|
+
setImmediate(() => {
|
|
1359
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
1360
|
+
this._state = GET_INFO;
|
|
1361
|
+
this.startLoop(cb);
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
/**
|
|
1366
|
+
* Builds an error object.
|
|
1367
|
+
*
|
|
1368
|
+
* @param {function(new:Error|RangeError)} ErrorCtor The error constructor
|
|
1369
|
+
* @param {String} message The error message
|
|
1370
|
+
* @param {Boolean} prefix Specifies whether or not to add a default prefix to
|
|
1371
|
+
* `message`
|
|
1372
|
+
* @param {Number} statusCode The status code
|
|
1373
|
+
* @param {String} errorCode The exposed error code
|
|
1374
|
+
* @return {(Error|RangeError)} The error
|
|
1375
|
+
* @private
|
|
1376
|
+
*/
|
|
1377
|
+
createError(ErrorCtor, message, prefix, statusCode, errorCode) {
|
|
1378
|
+
this._loop = false;
|
|
1379
|
+
this._errored = true;
|
|
1380
|
+
const err = new ErrorCtor(
|
|
1381
|
+
prefix ? `Invalid WebSocket frame: ${message}` : message
|
|
1382
|
+
);
|
|
1383
|
+
Error.captureStackTrace(err, this.createError);
|
|
1384
|
+
err.code = errorCode;
|
|
1385
|
+
err[kStatusCode] = statusCode;
|
|
1386
|
+
return err;
|
|
1387
|
+
}
|
|
1388
|
+
};
|
|
1389
|
+
module.exports = Receiver2;
|
|
1390
|
+
}
|
|
1391
|
+
});
|
|
1392
|
+
|
|
1393
|
+
// ../../node_modules/ws/lib/sender.js
|
|
1394
|
+
var require_sender = __commonJS({
|
|
1395
|
+
"../../node_modules/ws/lib/sender.js"(exports, module) {
|
|
1396
|
+
"use strict";
|
|
1397
|
+
var { Duplex } = __require("stream");
|
|
1398
|
+
var { randomFillSync } = __require("crypto");
|
|
1399
|
+
var {
|
|
1400
|
+
types: { isUint8Array }
|
|
1401
|
+
} = __require("util");
|
|
1402
|
+
var PerMessageDeflate2 = require_permessage_deflate();
|
|
1403
|
+
var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
|
|
1404
|
+
var { isBlob, isValidStatusCode } = require_validation();
|
|
1405
|
+
var { mask: applyMask, toBuffer } = require_buffer_util();
|
|
1406
|
+
var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
|
|
1407
|
+
var maskBuffer = Buffer.alloc(4);
|
|
1408
|
+
var RANDOM_POOL_SIZE = 8 * 1024;
|
|
1409
|
+
var randomPool;
|
|
1410
|
+
var randomPoolPointer = RANDOM_POOL_SIZE;
|
|
1411
|
+
var DEFAULT = 0;
|
|
1412
|
+
var DEFLATING = 1;
|
|
1413
|
+
var GET_BLOB_DATA = 2;
|
|
1414
|
+
var Sender2 = class _Sender {
|
|
1415
|
+
/**
|
|
1416
|
+
* Creates a Sender instance.
|
|
1417
|
+
*
|
|
1418
|
+
* @param {Duplex} socket The connection socket
|
|
1419
|
+
* @param {Object} [extensions] An object containing the negotiated extensions
|
|
1420
|
+
* @param {Function} [generateMask] The function used to generate the masking
|
|
1421
|
+
* key
|
|
1422
|
+
*/
|
|
1423
|
+
constructor(socket, extensions, generateMask) {
|
|
1424
|
+
this._extensions = extensions || {};
|
|
1425
|
+
if (generateMask) {
|
|
1426
|
+
this._generateMask = generateMask;
|
|
1427
|
+
this._maskBuffer = Buffer.alloc(4);
|
|
1428
|
+
}
|
|
1429
|
+
this._socket = socket;
|
|
1430
|
+
this._firstFragment = true;
|
|
1431
|
+
this._compress = false;
|
|
1432
|
+
this._bufferedBytes = 0;
|
|
1433
|
+
this._queue = [];
|
|
1434
|
+
this._state = DEFAULT;
|
|
1435
|
+
this.onerror = NOOP;
|
|
1436
|
+
this[kWebSocket] = void 0;
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* Frames a piece of data according to the HyBi WebSocket protocol.
|
|
1440
|
+
*
|
|
1441
|
+
* @param {(Buffer|String)} data The data to frame
|
|
1442
|
+
* @param {Object} options Options object
|
|
1443
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
1444
|
+
* FIN bit
|
|
1445
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
1446
|
+
* masking key
|
|
1447
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1448
|
+
* `data`
|
|
1449
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
1450
|
+
* key
|
|
1451
|
+
* @param {Number} options.opcode The opcode
|
|
1452
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
1453
|
+
* modified
|
|
1454
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
1455
|
+
* RSV1 bit
|
|
1456
|
+
* @return {(Buffer|String)[]} The framed data
|
|
1457
|
+
* @public
|
|
1458
|
+
*/
|
|
1459
|
+
static frame(data, options) {
|
|
1460
|
+
let mask;
|
|
1461
|
+
let merge = false;
|
|
1462
|
+
let offset = 2;
|
|
1463
|
+
let skipMasking = false;
|
|
1464
|
+
if (options.mask) {
|
|
1465
|
+
mask = options.maskBuffer || maskBuffer;
|
|
1466
|
+
if (options.generateMask) {
|
|
1467
|
+
options.generateMask(mask);
|
|
1468
|
+
} else {
|
|
1469
|
+
if (randomPoolPointer === RANDOM_POOL_SIZE) {
|
|
1470
|
+
if (randomPool === void 0) {
|
|
1471
|
+
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
|
|
1472
|
+
}
|
|
1473
|
+
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
|
|
1474
|
+
randomPoolPointer = 0;
|
|
1475
|
+
}
|
|
1476
|
+
mask[0] = randomPool[randomPoolPointer++];
|
|
1477
|
+
mask[1] = randomPool[randomPoolPointer++];
|
|
1478
|
+
mask[2] = randomPool[randomPoolPointer++];
|
|
1479
|
+
mask[3] = randomPool[randomPoolPointer++];
|
|
1480
|
+
}
|
|
1481
|
+
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
|
|
1482
|
+
offset = 6;
|
|
1483
|
+
}
|
|
1484
|
+
let dataLength;
|
|
1485
|
+
if (typeof data === "string") {
|
|
1486
|
+
if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
|
|
1487
|
+
dataLength = options[kByteLength];
|
|
1488
|
+
} else {
|
|
1489
|
+
data = Buffer.from(data);
|
|
1490
|
+
dataLength = data.length;
|
|
1491
|
+
}
|
|
1492
|
+
} else {
|
|
1493
|
+
dataLength = data.length;
|
|
1494
|
+
merge = options.mask && options.readOnly && !skipMasking;
|
|
1495
|
+
}
|
|
1496
|
+
let payloadLength = dataLength;
|
|
1497
|
+
if (dataLength >= 65536) {
|
|
1498
|
+
offset += 8;
|
|
1499
|
+
payloadLength = 127;
|
|
1500
|
+
} else if (dataLength > 125) {
|
|
1501
|
+
offset += 2;
|
|
1502
|
+
payloadLength = 126;
|
|
1503
|
+
}
|
|
1504
|
+
const target2 = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
|
|
1505
|
+
target2[0] = options.fin ? options.opcode | 128 : options.opcode;
|
|
1506
|
+
if (options.rsv1) target2[0] |= 64;
|
|
1507
|
+
target2[1] = payloadLength;
|
|
1508
|
+
if (payloadLength === 126) {
|
|
1509
|
+
target2.writeUInt16BE(dataLength, 2);
|
|
1510
|
+
} else if (payloadLength === 127) {
|
|
1511
|
+
target2[2] = target2[3] = 0;
|
|
1512
|
+
target2.writeUIntBE(dataLength, 4, 6);
|
|
1513
|
+
}
|
|
1514
|
+
if (!options.mask) return [target2, data];
|
|
1515
|
+
target2[1] |= 128;
|
|
1516
|
+
target2[offset - 4] = mask[0];
|
|
1517
|
+
target2[offset - 3] = mask[1];
|
|
1518
|
+
target2[offset - 2] = mask[2];
|
|
1519
|
+
target2[offset - 1] = mask[3];
|
|
1520
|
+
if (skipMasking) return [target2, data];
|
|
1521
|
+
if (merge) {
|
|
1522
|
+
applyMask(data, mask, target2, offset, dataLength);
|
|
1523
|
+
return [target2];
|
|
1524
|
+
}
|
|
1525
|
+
applyMask(data, mask, data, 0, dataLength);
|
|
1526
|
+
return [target2, data];
|
|
1527
|
+
}
|
|
1528
|
+
/**
|
|
1529
|
+
* Sends a close message to the other peer.
|
|
1530
|
+
*
|
|
1531
|
+
* @param {Number} [code] The status code component of the body
|
|
1532
|
+
* @param {(String|Buffer)} [data] The message component of the body
|
|
1533
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask the message
|
|
1534
|
+
* @param {Function} [cb] Callback
|
|
1535
|
+
* @public
|
|
1536
|
+
*/
|
|
1537
|
+
close(code, data, mask, cb) {
|
|
1538
|
+
let buf;
|
|
1539
|
+
if (code === void 0) {
|
|
1540
|
+
buf = EMPTY_BUFFER;
|
|
1541
|
+
} else if (typeof code !== "number" || !isValidStatusCode(code)) {
|
|
1542
|
+
throw new TypeError("First argument must be a valid error code number");
|
|
1543
|
+
} else if (data === void 0 || !data.length) {
|
|
1544
|
+
buf = Buffer.allocUnsafe(2);
|
|
1545
|
+
buf.writeUInt16BE(code, 0);
|
|
1546
|
+
} else {
|
|
1547
|
+
const length = Buffer.byteLength(data);
|
|
1548
|
+
if (length > 123) {
|
|
1549
|
+
throw new RangeError("The message must not be greater than 123 bytes");
|
|
1550
|
+
}
|
|
1551
|
+
buf = Buffer.allocUnsafe(2 + length);
|
|
1552
|
+
buf.writeUInt16BE(code, 0);
|
|
1553
|
+
if (typeof data === "string") {
|
|
1554
|
+
buf.write(data, 2);
|
|
1555
|
+
} else if (isUint8Array(data)) {
|
|
1556
|
+
buf.set(data, 2);
|
|
1557
|
+
} else {
|
|
1558
|
+
throw new TypeError("Second argument must be a string or a Uint8Array");
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
const options = {
|
|
1562
|
+
[kByteLength]: buf.length,
|
|
1563
|
+
fin: true,
|
|
1564
|
+
generateMask: this._generateMask,
|
|
1565
|
+
mask,
|
|
1566
|
+
maskBuffer: this._maskBuffer,
|
|
1567
|
+
opcode: 8,
|
|
1568
|
+
readOnly: false,
|
|
1569
|
+
rsv1: false
|
|
1570
|
+
};
|
|
1571
|
+
if (this._state !== DEFAULT) {
|
|
1572
|
+
this.enqueue([this.dispatch, buf, false, options, cb]);
|
|
1573
|
+
} else {
|
|
1574
|
+
this.sendFrame(_Sender.frame(buf, options), cb);
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
/**
|
|
1578
|
+
* Sends a ping message to the other peer.
|
|
1579
|
+
*
|
|
1580
|
+
* @param {*} data The message to send
|
|
1581
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
|
|
1582
|
+
* @param {Function} [cb] Callback
|
|
1583
|
+
* @public
|
|
1584
|
+
*/
|
|
1585
|
+
ping(data, mask, cb) {
|
|
1586
|
+
let byteLength;
|
|
1587
|
+
let readOnly;
|
|
1588
|
+
if (typeof data === "string") {
|
|
1589
|
+
byteLength = Buffer.byteLength(data);
|
|
1590
|
+
readOnly = false;
|
|
1591
|
+
} else if (isBlob(data)) {
|
|
1592
|
+
byteLength = data.size;
|
|
1593
|
+
readOnly = false;
|
|
1594
|
+
} else {
|
|
1595
|
+
data = toBuffer(data);
|
|
1596
|
+
byteLength = data.length;
|
|
1597
|
+
readOnly = toBuffer.readOnly;
|
|
1598
|
+
}
|
|
1599
|
+
if (byteLength > 125) {
|
|
1600
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1601
|
+
}
|
|
1602
|
+
const options = {
|
|
1603
|
+
[kByteLength]: byteLength,
|
|
1604
|
+
fin: true,
|
|
1605
|
+
generateMask: this._generateMask,
|
|
1606
|
+
mask,
|
|
1607
|
+
maskBuffer: this._maskBuffer,
|
|
1608
|
+
opcode: 9,
|
|
1609
|
+
readOnly,
|
|
1610
|
+
rsv1: false
|
|
1611
|
+
};
|
|
1612
|
+
if (isBlob(data)) {
|
|
1613
|
+
if (this._state !== DEFAULT) {
|
|
1614
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1615
|
+
} else {
|
|
1616
|
+
this.getBlobData(data, false, options, cb);
|
|
1617
|
+
}
|
|
1618
|
+
} else if (this._state !== DEFAULT) {
|
|
1619
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1620
|
+
} else {
|
|
1621
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* Sends a pong message to the other peer.
|
|
1626
|
+
*
|
|
1627
|
+
* @param {*} data The message to send
|
|
1628
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
|
|
1629
|
+
* @param {Function} [cb] Callback
|
|
1630
|
+
* @public
|
|
1631
|
+
*/
|
|
1632
|
+
pong(data, mask, cb) {
|
|
1633
|
+
let byteLength;
|
|
1634
|
+
let readOnly;
|
|
1635
|
+
if (typeof data === "string") {
|
|
1636
|
+
byteLength = Buffer.byteLength(data);
|
|
1637
|
+
readOnly = false;
|
|
1638
|
+
} else if (isBlob(data)) {
|
|
1639
|
+
byteLength = data.size;
|
|
1640
|
+
readOnly = false;
|
|
1641
|
+
} else {
|
|
1642
|
+
data = toBuffer(data);
|
|
1643
|
+
byteLength = data.length;
|
|
1644
|
+
readOnly = toBuffer.readOnly;
|
|
1645
|
+
}
|
|
1646
|
+
if (byteLength > 125) {
|
|
1647
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1648
|
+
}
|
|
1649
|
+
const options = {
|
|
1650
|
+
[kByteLength]: byteLength,
|
|
1651
|
+
fin: true,
|
|
1652
|
+
generateMask: this._generateMask,
|
|
1653
|
+
mask,
|
|
1654
|
+
maskBuffer: this._maskBuffer,
|
|
1655
|
+
opcode: 10,
|
|
1656
|
+
readOnly,
|
|
1657
|
+
rsv1: false
|
|
1658
|
+
};
|
|
1659
|
+
if (isBlob(data)) {
|
|
1660
|
+
if (this._state !== DEFAULT) {
|
|
1661
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1662
|
+
} else {
|
|
1663
|
+
this.getBlobData(data, false, options, cb);
|
|
1664
|
+
}
|
|
1665
|
+
} else if (this._state !== DEFAULT) {
|
|
1666
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1667
|
+
} else {
|
|
1668
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
/**
|
|
1672
|
+
* Sends a data message to the other peer.
|
|
1673
|
+
*
|
|
1674
|
+
* @param {*} data The message to send
|
|
1675
|
+
* @param {Object} options Options object
|
|
1676
|
+
* @param {Boolean} [options.binary=false] Specifies whether `data` is binary
|
|
1677
|
+
* or text
|
|
1678
|
+
* @param {Boolean} [options.compress=false] Specifies whether or not to
|
|
1679
|
+
* compress `data`
|
|
1680
|
+
* @param {Boolean} [options.fin=false] Specifies whether the fragment is the
|
|
1681
|
+
* last one
|
|
1682
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1683
|
+
* `data`
|
|
1684
|
+
* @param {Function} [cb] Callback
|
|
1685
|
+
* @public
|
|
1686
|
+
*/
|
|
1687
|
+
send(data, options, cb) {
|
|
1688
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
|
|
1689
|
+
let opcode = options.binary ? 2 : 1;
|
|
1690
|
+
let rsv1 = options.compress;
|
|
1691
|
+
let byteLength;
|
|
1692
|
+
let readOnly;
|
|
1693
|
+
if (typeof data === "string") {
|
|
1694
|
+
byteLength = Buffer.byteLength(data);
|
|
1695
|
+
readOnly = false;
|
|
1696
|
+
} else if (isBlob(data)) {
|
|
1697
|
+
byteLength = data.size;
|
|
1698
|
+
readOnly = false;
|
|
1699
|
+
} else {
|
|
1700
|
+
data = toBuffer(data);
|
|
1701
|
+
byteLength = data.length;
|
|
1702
|
+
readOnly = toBuffer.readOnly;
|
|
1703
|
+
}
|
|
1704
|
+
if (this._firstFragment) {
|
|
1705
|
+
this._firstFragment = false;
|
|
1706
|
+
if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
|
|
1707
|
+
rsv1 = byteLength >= perMessageDeflate._threshold;
|
|
1708
|
+
}
|
|
1709
|
+
this._compress = rsv1;
|
|
1710
|
+
} else {
|
|
1711
|
+
rsv1 = false;
|
|
1712
|
+
opcode = 0;
|
|
1713
|
+
}
|
|
1714
|
+
if (options.fin) this._firstFragment = true;
|
|
1715
|
+
const opts = {
|
|
1716
|
+
[kByteLength]: byteLength,
|
|
1717
|
+
fin: options.fin,
|
|
1718
|
+
generateMask: this._generateMask,
|
|
1719
|
+
mask: options.mask,
|
|
1720
|
+
maskBuffer: this._maskBuffer,
|
|
1721
|
+
opcode,
|
|
1722
|
+
readOnly,
|
|
1723
|
+
rsv1
|
|
1724
|
+
};
|
|
1725
|
+
if (isBlob(data)) {
|
|
1726
|
+
if (this._state !== DEFAULT) {
|
|
1727
|
+
this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
|
|
1728
|
+
} else {
|
|
1729
|
+
this.getBlobData(data, this._compress, opts, cb);
|
|
1730
|
+
}
|
|
1731
|
+
} else if (this._state !== DEFAULT) {
|
|
1732
|
+
this.enqueue([this.dispatch, data, this._compress, opts, cb]);
|
|
1733
|
+
} else {
|
|
1734
|
+
this.dispatch(data, this._compress, opts, cb);
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
/**
|
|
1738
|
+
* Gets the contents of a blob as binary data.
|
|
1739
|
+
*
|
|
1740
|
+
* @param {Blob} blob The blob
|
|
1741
|
+
* @param {Boolean} [compress=false] Specifies whether or not to compress
|
|
1742
|
+
* the data
|
|
1743
|
+
* @param {Object} options Options object
|
|
1744
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
1745
|
+
* FIN bit
|
|
1746
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
1747
|
+
* masking key
|
|
1748
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1749
|
+
* `data`
|
|
1750
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
1751
|
+
* key
|
|
1752
|
+
* @param {Number} options.opcode The opcode
|
|
1753
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
1754
|
+
* modified
|
|
1755
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
1756
|
+
* RSV1 bit
|
|
1757
|
+
* @param {Function} [cb] Callback
|
|
1758
|
+
* @private
|
|
1759
|
+
*/
|
|
1760
|
+
getBlobData(blob, compress, options, cb) {
|
|
1761
|
+
this._bufferedBytes += options[kByteLength];
|
|
1762
|
+
this._state = GET_BLOB_DATA;
|
|
1763
|
+
blob.arrayBuffer().then((arrayBuffer) => {
|
|
1764
|
+
if (this._socket.destroyed) {
|
|
1765
|
+
const err = new Error(
|
|
1766
|
+
"The socket was closed while the blob was being read"
|
|
1767
|
+
);
|
|
1768
|
+
process.nextTick(callCallbacks, this, err, cb);
|
|
1769
|
+
return;
|
|
1770
|
+
}
|
|
1771
|
+
this._bufferedBytes -= options[kByteLength];
|
|
1772
|
+
const data = toBuffer(arrayBuffer);
|
|
1773
|
+
if (!compress) {
|
|
1774
|
+
this._state = DEFAULT;
|
|
1775
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1776
|
+
this.dequeue();
|
|
1777
|
+
} else {
|
|
1778
|
+
this.dispatch(data, compress, options, cb);
|
|
1779
|
+
}
|
|
1780
|
+
}).catch((err) => {
|
|
1781
|
+
process.nextTick(onError, this, err, cb);
|
|
1782
|
+
});
|
|
1783
|
+
}
|
|
1784
|
+
/**
|
|
1785
|
+
* Dispatches a message.
|
|
1786
|
+
*
|
|
1787
|
+
* @param {(Buffer|String)} data The message to send
|
|
1788
|
+
* @param {Boolean} [compress=false] Specifies whether or not to compress
|
|
1789
|
+
* `data`
|
|
1790
|
+
* @param {Object} options Options object
|
|
1791
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
1792
|
+
* FIN bit
|
|
1793
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
1794
|
+
* masking key
|
|
1795
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1796
|
+
* `data`
|
|
1797
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
1798
|
+
* key
|
|
1799
|
+
* @param {Number} options.opcode The opcode
|
|
1800
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
1801
|
+
* modified
|
|
1802
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
1803
|
+
* RSV1 bit
|
|
1804
|
+
* @param {Function} [cb] Callback
|
|
1805
|
+
* @private
|
|
1806
|
+
*/
|
|
1807
|
+
dispatch(data, compress, options, cb) {
|
|
1808
|
+
if (!compress) {
|
|
1809
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1810
|
+
return;
|
|
1811
|
+
}
|
|
1812
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
|
|
1813
|
+
this._bufferedBytes += options[kByteLength];
|
|
1814
|
+
this._state = DEFLATING;
|
|
1815
|
+
perMessageDeflate.compress(data, options.fin, (_, buf) => {
|
|
1816
|
+
if (this._socket.destroyed) {
|
|
1817
|
+
const err = new Error(
|
|
1818
|
+
"The socket was closed while data was being compressed"
|
|
1819
|
+
);
|
|
1820
|
+
callCallbacks(this, err, cb);
|
|
1821
|
+
return;
|
|
1822
|
+
}
|
|
1823
|
+
this._bufferedBytes -= options[kByteLength];
|
|
1824
|
+
this._state = DEFAULT;
|
|
1825
|
+
options.readOnly = false;
|
|
1826
|
+
this.sendFrame(_Sender.frame(buf, options), cb);
|
|
1827
|
+
this.dequeue();
|
|
1828
|
+
});
|
|
1829
|
+
}
|
|
1830
|
+
/**
|
|
1831
|
+
* Executes queued send operations.
|
|
1832
|
+
*
|
|
1833
|
+
* @private
|
|
1834
|
+
*/
|
|
1835
|
+
dequeue() {
|
|
1836
|
+
while (this._state === DEFAULT && this._queue.length) {
|
|
1837
|
+
const params = this._queue.shift();
|
|
1838
|
+
this._bufferedBytes -= params[3][kByteLength];
|
|
1839
|
+
Reflect.apply(params[0], this, params.slice(1));
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
/**
|
|
1843
|
+
* Enqueues a send operation.
|
|
1844
|
+
*
|
|
1845
|
+
* @param {Array} params Send operation parameters.
|
|
1846
|
+
* @private
|
|
1847
|
+
*/
|
|
1848
|
+
enqueue(params) {
|
|
1849
|
+
this._bufferedBytes += params[3][kByteLength];
|
|
1850
|
+
this._queue.push(params);
|
|
1851
|
+
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Sends a frame.
|
|
1854
|
+
*
|
|
1855
|
+
* @param {(Buffer | String)[]} list The frame to send
|
|
1856
|
+
* @param {Function} [cb] Callback
|
|
1857
|
+
* @private
|
|
1858
|
+
*/
|
|
1859
|
+
sendFrame(list, cb) {
|
|
1860
|
+
if (list.length === 2) {
|
|
1861
|
+
this._socket.cork();
|
|
1862
|
+
this._socket.write(list[0]);
|
|
1863
|
+
this._socket.write(list[1], cb);
|
|
1864
|
+
this._socket.uncork();
|
|
1865
|
+
} else {
|
|
1866
|
+
this._socket.write(list[0], cb);
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
};
|
|
1870
|
+
module.exports = Sender2;
|
|
1871
|
+
function callCallbacks(sender, err, cb) {
|
|
1872
|
+
if (typeof cb === "function") cb(err);
|
|
1873
|
+
for (let i = 0; i < sender._queue.length; i++) {
|
|
1874
|
+
const params = sender._queue[i];
|
|
1875
|
+
const callback = params[params.length - 1];
|
|
1876
|
+
if (typeof callback === "function") callback(err);
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
function onError(sender, err, cb) {
|
|
1880
|
+
callCallbacks(sender, err, cb);
|
|
1881
|
+
sender.onerror(err);
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
});
|
|
1885
|
+
|
|
1886
|
+
// ../../node_modules/ws/lib/event-target.js
|
|
1887
|
+
var require_event_target = __commonJS({
|
|
1888
|
+
"../../node_modules/ws/lib/event-target.js"(exports, module) {
|
|
1889
|
+
"use strict";
|
|
1890
|
+
var { kForOnEventAttribute, kListener } = require_constants();
|
|
1891
|
+
var kCode = /* @__PURE__ */ Symbol("kCode");
|
|
1892
|
+
var kData = /* @__PURE__ */ Symbol("kData");
|
|
1893
|
+
var kError = /* @__PURE__ */ Symbol("kError");
|
|
1894
|
+
var kMessage = /* @__PURE__ */ Symbol("kMessage");
|
|
1895
|
+
var kReason = /* @__PURE__ */ Symbol("kReason");
|
|
1896
|
+
var kTarget = /* @__PURE__ */ Symbol("kTarget");
|
|
1897
|
+
var kType = /* @__PURE__ */ Symbol("kType");
|
|
1898
|
+
var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
|
|
1899
|
+
var Event = class {
|
|
1900
|
+
/**
|
|
1901
|
+
* Create a new `Event`.
|
|
1902
|
+
*
|
|
1903
|
+
* @param {String} type The name of the event
|
|
1904
|
+
* @throws {TypeError} If the `type` argument is not specified
|
|
1905
|
+
*/
|
|
1906
|
+
constructor(type) {
|
|
1907
|
+
this[kTarget] = null;
|
|
1908
|
+
this[kType] = type;
|
|
1909
|
+
}
|
|
1910
|
+
/**
|
|
1911
|
+
* @type {*}
|
|
1912
|
+
*/
|
|
1913
|
+
get target() {
|
|
1914
|
+
return this[kTarget];
|
|
1915
|
+
}
|
|
1916
|
+
/**
|
|
1917
|
+
* @type {String}
|
|
1918
|
+
*/
|
|
1919
|
+
get type() {
|
|
1920
|
+
return this[kType];
|
|
1921
|
+
}
|
|
1922
|
+
};
|
|
1923
|
+
Object.defineProperty(Event.prototype, "target", { enumerable: true });
|
|
1924
|
+
Object.defineProperty(Event.prototype, "type", { enumerable: true });
|
|
1925
|
+
var CloseEvent = class extends Event {
|
|
1926
|
+
/**
|
|
1927
|
+
* Create a new `CloseEvent`.
|
|
1928
|
+
*
|
|
1929
|
+
* @param {String} type The name of the event
|
|
1930
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
1931
|
+
* attributes via object members of the same name
|
|
1932
|
+
* @param {Number} [options.code=0] The status code explaining why the
|
|
1933
|
+
* connection was closed
|
|
1934
|
+
* @param {String} [options.reason=''] A human-readable string explaining why
|
|
1935
|
+
* the connection was closed
|
|
1936
|
+
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
|
|
1937
|
+
* connection was cleanly closed
|
|
1938
|
+
*/
|
|
1939
|
+
constructor(type, options = {}) {
|
|
1940
|
+
super(type);
|
|
1941
|
+
this[kCode] = options.code === void 0 ? 0 : options.code;
|
|
1942
|
+
this[kReason] = options.reason === void 0 ? "" : options.reason;
|
|
1943
|
+
this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
|
|
1944
|
+
}
|
|
1945
|
+
/**
|
|
1946
|
+
* @type {Number}
|
|
1947
|
+
*/
|
|
1948
|
+
get code() {
|
|
1949
|
+
return this[kCode];
|
|
1950
|
+
}
|
|
1951
|
+
/**
|
|
1952
|
+
* @type {String}
|
|
1953
|
+
*/
|
|
1954
|
+
get reason() {
|
|
1955
|
+
return this[kReason];
|
|
1956
|
+
}
|
|
1957
|
+
/**
|
|
1958
|
+
* @type {Boolean}
|
|
1959
|
+
*/
|
|
1960
|
+
get wasClean() {
|
|
1961
|
+
return this[kWasClean];
|
|
1962
|
+
}
|
|
1963
|
+
};
|
|
1964
|
+
Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
|
|
1965
|
+
Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
|
|
1966
|
+
Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
|
|
1967
|
+
var ErrorEvent = class extends Event {
|
|
1968
|
+
/**
|
|
1969
|
+
* Create a new `ErrorEvent`.
|
|
1970
|
+
*
|
|
1971
|
+
* @param {String} type The name of the event
|
|
1972
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
1973
|
+
* attributes via object members of the same name
|
|
1974
|
+
* @param {*} [options.error=null] The error that generated this event
|
|
1975
|
+
* @param {String} [options.message=''] The error message
|
|
1976
|
+
*/
|
|
1977
|
+
constructor(type, options = {}) {
|
|
1978
|
+
super(type);
|
|
1979
|
+
this[kError] = options.error === void 0 ? null : options.error;
|
|
1980
|
+
this[kMessage] = options.message === void 0 ? "" : options.message;
|
|
1981
|
+
}
|
|
1982
|
+
/**
|
|
1983
|
+
* @type {*}
|
|
1984
|
+
*/
|
|
1985
|
+
get error() {
|
|
1986
|
+
return this[kError];
|
|
1987
|
+
}
|
|
1988
|
+
/**
|
|
1989
|
+
* @type {String}
|
|
1990
|
+
*/
|
|
1991
|
+
get message() {
|
|
1992
|
+
return this[kMessage];
|
|
1993
|
+
}
|
|
1994
|
+
};
|
|
1995
|
+
Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
|
|
1996
|
+
Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
|
|
1997
|
+
var MessageEvent = class extends Event {
|
|
1998
|
+
/**
|
|
1999
|
+
* Create a new `MessageEvent`.
|
|
2000
|
+
*
|
|
2001
|
+
* @param {String} type The name of the event
|
|
2002
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
2003
|
+
* attributes via object members of the same name
|
|
2004
|
+
* @param {*} [options.data=null] The message content
|
|
2005
|
+
*/
|
|
2006
|
+
constructor(type, options = {}) {
|
|
2007
|
+
super(type);
|
|
2008
|
+
this[kData] = options.data === void 0 ? null : options.data;
|
|
2009
|
+
}
|
|
2010
|
+
/**
|
|
2011
|
+
* @type {*}
|
|
2012
|
+
*/
|
|
2013
|
+
get data() {
|
|
2014
|
+
return this[kData];
|
|
2015
|
+
}
|
|
2016
|
+
};
|
|
2017
|
+
Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
|
|
2018
|
+
var EventTarget = {
|
|
2019
|
+
/**
|
|
2020
|
+
* Register an event listener.
|
|
2021
|
+
*
|
|
2022
|
+
* @param {String} type A string representing the event type to listen for
|
|
2023
|
+
* @param {(Function|Object)} handler The listener to add
|
|
2024
|
+
* @param {Object} [options] An options object specifies characteristics about
|
|
2025
|
+
* the event listener
|
|
2026
|
+
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
|
|
2027
|
+
* listener should be invoked at most once after being added. If `true`,
|
|
2028
|
+
* the listener would be automatically removed when invoked.
|
|
2029
|
+
* @public
|
|
2030
|
+
*/
|
|
2031
|
+
addEventListener(type, handler, options = {}) {
|
|
2032
|
+
for (const listener of this.listeners(type)) {
|
|
2033
|
+
if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
2034
|
+
return;
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
let wrapper;
|
|
2038
|
+
if (type === "message") {
|
|
2039
|
+
wrapper = function onMessage(data, isBinary) {
|
|
2040
|
+
const event = new MessageEvent("message", {
|
|
2041
|
+
data: isBinary ? data : data.toString()
|
|
2042
|
+
});
|
|
2043
|
+
event[kTarget] = this;
|
|
2044
|
+
callListener(handler, this, event);
|
|
2045
|
+
};
|
|
2046
|
+
} else if (type === "close") {
|
|
2047
|
+
wrapper = function onClose(code, message) {
|
|
2048
|
+
const event = new CloseEvent("close", {
|
|
2049
|
+
code,
|
|
2050
|
+
reason: message.toString(),
|
|
2051
|
+
wasClean: this._closeFrameReceived && this._closeFrameSent
|
|
2052
|
+
});
|
|
2053
|
+
event[kTarget] = this;
|
|
2054
|
+
callListener(handler, this, event);
|
|
2055
|
+
};
|
|
2056
|
+
} else if (type === "error") {
|
|
2057
|
+
wrapper = function onError(error) {
|
|
2058
|
+
const event = new ErrorEvent("error", {
|
|
2059
|
+
error,
|
|
2060
|
+
message: error.message
|
|
2061
|
+
});
|
|
2062
|
+
event[kTarget] = this;
|
|
2063
|
+
callListener(handler, this, event);
|
|
2064
|
+
};
|
|
2065
|
+
} else if (type === "open") {
|
|
2066
|
+
wrapper = function onOpen() {
|
|
2067
|
+
const event = new Event("open");
|
|
2068
|
+
event[kTarget] = this;
|
|
2069
|
+
callListener(handler, this, event);
|
|
2070
|
+
};
|
|
2071
|
+
} else {
|
|
2072
|
+
return;
|
|
2073
|
+
}
|
|
2074
|
+
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
|
|
2075
|
+
wrapper[kListener] = handler;
|
|
2076
|
+
if (options.once) {
|
|
2077
|
+
this.once(type, wrapper);
|
|
2078
|
+
} else {
|
|
2079
|
+
this.on(type, wrapper);
|
|
2080
|
+
}
|
|
2081
|
+
},
|
|
2082
|
+
/**
|
|
2083
|
+
* Remove an event listener.
|
|
2084
|
+
*
|
|
2085
|
+
* @param {String} type A string representing the event type to remove
|
|
2086
|
+
* @param {(Function|Object)} handler The listener to remove
|
|
2087
|
+
* @public
|
|
2088
|
+
*/
|
|
2089
|
+
removeEventListener(type, handler) {
|
|
2090
|
+
for (const listener of this.listeners(type)) {
|
|
2091
|
+
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
2092
|
+
this.removeListener(type, listener);
|
|
2093
|
+
break;
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
2097
|
+
};
|
|
2098
|
+
module.exports = {
|
|
2099
|
+
CloseEvent,
|
|
2100
|
+
ErrorEvent,
|
|
2101
|
+
Event,
|
|
2102
|
+
EventTarget,
|
|
2103
|
+
MessageEvent
|
|
2104
|
+
};
|
|
2105
|
+
function callListener(listener, thisArg, event) {
|
|
2106
|
+
if (typeof listener === "object" && listener.handleEvent) {
|
|
2107
|
+
listener.handleEvent.call(listener, event);
|
|
2108
|
+
} else {
|
|
2109
|
+
listener.call(thisArg, event);
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
});
|
|
2114
|
+
|
|
2115
|
+
// ../../node_modules/ws/lib/extension.js
|
|
2116
|
+
var require_extension = __commonJS({
|
|
2117
|
+
"../../node_modules/ws/lib/extension.js"(exports, module) {
|
|
2118
|
+
"use strict";
|
|
2119
|
+
var { tokenChars } = require_validation();
|
|
2120
|
+
function push(dest, name, elem) {
|
|
2121
|
+
if (dest[name] === void 0) dest[name] = [elem];
|
|
2122
|
+
else dest[name].push(elem);
|
|
2123
|
+
}
|
|
2124
|
+
function parse(header) {
|
|
2125
|
+
const offers = /* @__PURE__ */ Object.create(null);
|
|
2126
|
+
let params = /* @__PURE__ */ Object.create(null);
|
|
2127
|
+
let mustUnescape = false;
|
|
2128
|
+
let isEscaping = false;
|
|
2129
|
+
let inQuotes = false;
|
|
2130
|
+
let extensionName;
|
|
2131
|
+
let paramName;
|
|
2132
|
+
let start = -1;
|
|
2133
|
+
let code = -1;
|
|
2134
|
+
let end = -1;
|
|
2135
|
+
let i = 0;
|
|
2136
|
+
for (; i < header.length; i++) {
|
|
2137
|
+
code = header.charCodeAt(i);
|
|
2138
|
+
if (extensionName === void 0) {
|
|
2139
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
2140
|
+
if (start === -1) start = i;
|
|
2141
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
2142
|
+
if (end === -1 && start !== -1) end = i;
|
|
2143
|
+
} else if (code === 59 || code === 44) {
|
|
2144
|
+
if (start === -1) {
|
|
2145
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2146
|
+
}
|
|
2147
|
+
if (end === -1) end = i;
|
|
2148
|
+
const name = header.slice(start, end);
|
|
2149
|
+
if (code === 44) {
|
|
2150
|
+
push(offers, name, params);
|
|
2151
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2152
|
+
} else {
|
|
2153
|
+
extensionName = name;
|
|
2154
|
+
}
|
|
2155
|
+
start = end = -1;
|
|
2156
|
+
} else {
|
|
2157
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2158
|
+
}
|
|
2159
|
+
} else if (paramName === void 0) {
|
|
2160
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
2161
|
+
if (start === -1) start = i;
|
|
2162
|
+
} else if (code === 32 || code === 9) {
|
|
2163
|
+
if (end === -1 && start !== -1) end = i;
|
|
2164
|
+
} else if (code === 59 || code === 44) {
|
|
2165
|
+
if (start === -1) {
|
|
2166
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2167
|
+
}
|
|
2168
|
+
if (end === -1) end = i;
|
|
2169
|
+
push(params, header.slice(start, end), true);
|
|
2170
|
+
if (code === 44) {
|
|
2171
|
+
push(offers, extensionName, params);
|
|
2172
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2173
|
+
extensionName = void 0;
|
|
2174
|
+
}
|
|
2175
|
+
start = end = -1;
|
|
2176
|
+
} else if (code === 61 && start !== -1 && end === -1) {
|
|
2177
|
+
paramName = header.slice(start, i);
|
|
2178
|
+
start = end = -1;
|
|
2179
|
+
} else {
|
|
2180
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2181
|
+
}
|
|
2182
|
+
} else {
|
|
2183
|
+
if (isEscaping) {
|
|
2184
|
+
if (tokenChars[code] !== 1) {
|
|
2185
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2186
|
+
}
|
|
2187
|
+
if (start === -1) start = i;
|
|
2188
|
+
else if (!mustUnescape) mustUnescape = true;
|
|
2189
|
+
isEscaping = false;
|
|
2190
|
+
} else if (inQuotes) {
|
|
2191
|
+
if (tokenChars[code] === 1) {
|
|
2192
|
+
if (start === -1) start = i;
|
|
2193
|
+
} else if (code === 34 && start !== -1) {
|
|
2194
|
+
inQuotes = false;
|
|
2195
|
+
end = i;
|
|
2196
|
+
} else if (code === 92) {
|
|
2197
|
+
isEscaping = true;
|
|
2198
|
+
} else {
|
|
2199
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2200
|
+
}
|
|
2201
|
+
} else if (code === 34 && header.charCodeAt(i - 1) === 61) {
|
|
2202
|
+
inQuotes = true;
|
|
2203
|
+
} else if (end === -1 && tokenChars[code] === 1) {
|
|
2204
|
+
if (start === -1) start = i;
|
|
2205
|
+
} else if (start !== -1 && (code === 32 || code === 9)) {
|
|
2206
|
+
if (end === -1) end = i;
|
|
2207
|
+
} else if (code === 59 || code === 44) {
|
|
2208
|
+
if (start === -1) {
|
|
2209
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2210
|
+
}
|
|
2211
|
+
if (end === -1) end = i;
|
|
2212
|
+
let value = header.slice(start, end);
|
|
2213
|
+
if (mustUnescape) {
|
|
2214
|
+
value = value.replace(/\\/g, "");
|
|
2215
|
+
mustUnescape = false;
|
|
2216
|
+
}
|
|
2217
|
+
push(params, paramName, value);
|
|
2218
|
+
if (code === 44) {
|
|
2219
|
+
push(offers, extensionName, params);
|
|
2220
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2221
|
+
extensionName = void 0;
|
|
2222
|
+
}
|
|
2223
|
+
paramName = void 0;
|
|
2224
|
+
start = end = -1;
|
|
2225
|
+
} else {
|
|
2226
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
}
|
|
2230
|
+
if (start === -1 || inQuotes || code === 32 || code === 9) {
|
|
2231
|
+
throw new SyntaxError("Unexpected end of input");
|
|
2232
|
+
}
|
|
2233
|
+
if (end === -1) end = i;
|
|
2234
|
+
const token = header.slice(start, end);
|
|
2235
|
+
if (extensionName === void 0) {
|
|
2236
|
+
push(offers, token, params);
|
|
2237
|
+
} else {
|
|
2238
|
+
if (paramName === void 0) {
|
|
2239
|
+
push(params, token, true);
|
|
2240
|
+
} else if (mustUnescape) {
|
|
2241
|
+
push(params, paramName, token.replace(/\\/g, ""));
|
|
2242
|
+
} else {
|
|
2243
|
+
push(params, paramName, token);
|
|
2244
|
+
}
|
|
2245
|
+
push(offers, extensionName, params);
|
|
2246
|
+
}
|
|
2247
|
+
return offers;
|
|
2248
|
+
}
|
|
2249
|
+
function format(extensions) {
|
|
2250
|
+
return Object.keys(extensions).map((extension2) => {
|
|
2251
|
+
let configurations = extensions[extension2];
|
|
2252
|
+
if (!Array.isArray(configurations)) configurations = [configurations];
|
|
2253
|
+
return configurations.map((params) => {
|
|
2254
|
+
return [extension2].concat(
|
|
2255
|
+
Object.keys(params).map((k) => {
|
|
2256
|
+
let values = params[k];
|
|
2257
|
+
if (!Array.isArray(values)) values = [values];
|
|
2258
|
+
return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
|
|
2259
|
+
})
|
|
2260
|
+
).join("; ");
|
|
2261
|
+
}).join(", ");
|
|
2262
|
+
}).join(", ");
|
|
2263
|
+
}
|
|
2264
|
+
module.exports = { format, parse };
|
|
2265
|
+
}
|
|
2266
|
+
});
|
|
2267
|
+
|
|
2268
|
+
// ../../node_modules/ws/lib/websocket.js
|
|
2269
|
+
var require_websocket = __commonJS({
|
|
2270
|
+
"../../node_modules/ws/lib/websocket.js"(exports, module) {
|
|
2271
|
+
"use strict";
|
|
2272
|
+
var EventEmitter = __require("events");
|
|
2273
|
+
var https = __require("https");
|
|
2274
|
+
var http = __require("http");
|
|
2275
|
+
var net = __require("net");
|
|
2276
|
+
var tls = __require("tls");
|
|
2277
|
+
var { randomBytes, createHash: createHash5 } = __require("crypto");
|
|
2278
|
+
var { Duplex, Readable: Readable2 } = __require("stream");
|
|
2279
|
+
var { URL: URL2 } = __require("url");
|
|
2280
|
+
var PerMessageDeflate2 = require_permessage_deflate();
|
|
2281
|
+
var Receiver2 = require_receiver();
|
|
2282
|
+
var Sender2 = require_sender();
|
|
2283
|
+
var { isBlob } = require_validation();
|
|
2284
|
+
var {
|
|
2285
|
+
BINARY_TYPES,
|
|
2286
|
+
CLOSE_TIMEOUT,
|
|
2287
|
+
EMPTY_BUFFER,
|
|
2288
|
+
GUID,
|
|
2289
|
+
kForOnEventAttribute,
|
|
2290
|
+
kListener,
|
|
2291
|
+
kStatusCode,
|
|
2292
|
+
kWebSocket,
|
|
2293
|
+
NOOP
|
|
2294
|
+
} = require_constants();
|
|
2295
|
+
var {
|
|
2296
|
+
EventTarget: { addEventListener, removeEventListener }
|
|
2297
|
+
} = require_event_target();
|
|
2298
|
+
var { format, parse } = require_extension();
|
|
2299
|
+
var { toBuffer } = require_buffer_util();
|
|
2300
|
+
var kAborted = /* @__PURE__ */ Symbol("kAborted");
|
|
2301
|
+
var protocolVersions = [8, 13];
|
|
2302
|
+
var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
|
|
2303
|
+
var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
|
|
2304
|
+
var WebSocket3 = class _WebSocket extends EventEmitter {
|
|
2305
|
+
/**
|
|
2306
|
+
* Create a new `WebSocket`.
|
|
2307
|
+
*
|
|
2308
|
+
* @param {(String|URL)} address The URL to which to connect
|
|
2309
|
+
* @param {(String|String[])} [protocols] The subprotocols
|
|
2310
|
+
* @param {Object} [options] Connection options
|
|
2311
|
+
*/
|
|
2312
|
+
constructor(address, protocols, options) {
|
|
2313
|
+
super();
|
|
2314
|
+
this._binaryType = BINARY_TYPES[0];
|
|
2315
|
+
this._closeCode = 1006;
|
|
2316
|
+
this._closeFrameReceived = false;
|
|
2317
|
+
this._closeFrameSent = false;
|
|
2318
|
+
this._closeMessage = EMPTY_BUFFER;
|
|
2319
|
+
this._closeTimer = null;
|
|
2320
|
+
this._errorEmitted = false;
|
|
2321
|
+
this._extensions = {};
|
|
2322
|
+
this._paused = false;
|
|
2323
|
+
this._protocol = "";
|
|
2324
|
+
this._readyState = _WebSocket.CONNECTING;
|
|
2325
|
+
this._receiver = null;
|
|
2326
|
+
this._sender = null;
|
|
2327
|
+
this._socket = null;
|
|
2328
|
+
if (address !== null) {
|
|
2329
|
+
this._bufferedAmount = 0;
|
|
2330
|
+
this._isServer = false;
|
|
2331
|
+
this._redirects = 0;
|
|
2332
|
+
if (protocols === void 0) {
|
|
2333
|
+
protocols = [];
|
|
2334
|
+
} else if (!Array.isArray(protocols)) {
|
|
2335
|
+
if (typeof protocols === "object" && protocols !== null) {
|
|
2336
|
+
options = protocols;
|
|
2337
|
+
protocols = [];
|
|
2338
|
+
} else {
|
|
2339
|
+
protocols = [protocols];
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
initAsClient(this, address, protocols, options);
|
|
2343
|
+
} else {
|
|
2344
|
+
this._autoPong = options.autoPong;
|
|
2345
|
+
this._closeTimeout = options.closeTimeout;
|
|
2346
|
+
this._isServer = true;
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
/**
|
|
2350
|
+
* For historical reasons, the custom "nodebuffer" type is used by the default
|
|
2351
|
+
* instead of "blob".
|
|
2352
|
+
*
|
|
2353
|
+
* @type {String}
|
|
2354
|
+
*/
|
|
2355
|
+
get binaryType() {
|
|
2356
|
+
return this._binaryType;
|
|
2357
|
+
}
|
|
2358
|
+
set binaryType(type) {
|
|
2359
|
+
if (!BINARY_TYPES.includes(type)) return;
|
|
2360
|
+
this._binaryType = type;
|
|
2361
|
+
if (this._receiver) this._receiver._binaryType = type;
|
|
2362
|
+
}
|
|
2363
|
+
/**
|
|
2364
|
+
* @type {Number}
|
|
2365
|
+
*/
|
|
2366
|
+
get bufferedAmount() {
|
|
2367
|
+
if (!this._socket) return this._bufferedAmount;
|
|
2368
|
+
return this._socket._writableState.length + this._sender._bufferedBytes;
|
|
2369
|
+
}
|
|
2370
|
+
/**
|
|
2371
|
+
* @type {String}
|
|
2372
|
+
*/
|
|
2373
|
+
get extensions() {
|
|
2374
|
+
return Object.keys(this._extensions).join();
|
|
2375
|
+
}
|
|
2376
|
+
/**
|
|
2377
|
+
* @type {Boolean}
|
|
2378
|
+
*/
|
|
2379
|
+
get isPaused() {
|
|
2380
|
+
return this._paused;
|
|
2381
|
+
}
|
|
2382
|
+
/**
|
|
2383
|
+
* @type {Function}
|
|
2384
|
+
*/
|
|
2385
|
+
/* istanbul ignore next */
|
|
2386
|
+
get onclose() {
|
|
2387
|
+
return null;
|
|
2388
|
+
}
|
|
2389
|
+
/**
|
|
2390
|
+
* @type {Function}
|
|
2391
|
+
*/
|
|
2392
|
+
/* istanbul ignore next */
|
|
2393
|
+
get onerror() {
|
|
2394
|
+
return null;
|
|
2395
|
+
}
|
|
2396
|
+
/**
|
|
2397
|
+
* @type {Function}
|
|
2398
|
+
*/
|
|
2399
|
+
/* istanbul ignore next */
|
|
2400
|
+
get onopen() {
|
|
2401
|
+
return null;
|
|
2402
|
+
}
|
|
2403
|
+
/**
|
|
2404
|
+
* @type {Function}
|
|
2405
|
+
*/
|
|
2406
|
+
/* istanbul ignore next */
|
|
2407
|
+
get onmessage() {
|
|
2408
|
+
return null;
|
|
2409
|
+
}
|
|
2410
|
+
/**
|
|
2411
|
+
* @type {String}
|
|
2412
|
+
*/
|
|
2413
|
+
get protocol() {
|
|
2414
|
+
return this._protocol;
|
|
2415
|
+
}
|
|
2416
|
+
/**
|
|
2417
|
+
* @type {Number}
|
|
2418
|
+
*/
|
|
2419
|
+
get readyState() {
|
|
2420
|
+
return this._readyState;
|
|
2421
|
+
}
|
|
2422
|
+
/**
|
|
2423
|
+
* @type {String}
|
|
2424
|
+
*/
|
|
2425
|
+
get url() {
|
|
2426
|
+
return this._url;
|
|
2427
|
+
}
|
|
2428
|
+
/**
|
|
2429
|
+
* Set up the socket and the internal resources.
|
|
2430
|
+
*
|
|
2431
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
2432
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
2433
|
+
* @param {Object} options Options object
|
|
2434
|
+
* @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
|
|
2435
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
2436
|
+
* multiple times in the same tick
|
|
2437
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
2438
|
+
* masking key
|
|
2439
|
+
* @param {Number} [options.maxBufferedChunks=0] The maximum number of
|
|
2440
|
+
* buffered data chunks
|
|
2441
|
+
* @param {Number} [options.maxFragments=0] The maximum number of message
|
|
2442
|
+
* fragments
|
|
2443
|
+
* @param {Number} [options.maxPayload=0] The maximum allowed message size
|
|
2444
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
2445
|
+
* not to skip UTF-8 validation for text and close messages
|
|
2446
|
+
* @private
|
|
2447
|
+
*/
|
|
2448
|
+
setSocket(socket, head, options) {
|
|
2449
|
+
const receiver = new Receiver2({
|
|
2450
|
+
allowSynchronousEvents: options.allowSynchronousEvents,
|
|
2451
|
+
binaryType: this.binaryType,
|
|
2452
|
+
extensions: this._extensions,
|
|
2453
|
+
isServer: this._isServer,
|
|
2454
|
+
maxBufferedChunks: options.maxBufferedChunks,
|
|
2455
|
+
maxFragments: options.maxFragments,
|
|
2456
|
+
maxPayload: options.maxPayload,
|
|
2457
|
+
skipUTF8Validation: options.skipUTF8Validation
|
|
2458
|
+
});
|
|
2459
|
+
const sender = new Sender2(socket, this._extensions, options.generateMask);
|
|
2460
|
+
this._receiver = receiver;
|
|
2461
|
+
this._sender = sender;
|
|
2462
|
+
this._socket = socket;
|
|
2463
|
+
receiver[kWebSocket] = this;
|
|
2464
|
+
sender[kWebSocket] = this;
|
|
2465
|
+
socket[kWebSocket] = this;
|
|
2466
|
+
receiver.on("conclude", receiverOnConclude);
|
|
2467
|
+
receiver.on("drain", receiverOnDrain);
|
|
2468
|
+
receiver.on("error", receiverOnError);
|
|
2469
|
+
receiver.on("message", receiverOnMessage);
|
|
2470
|
+
receiver.on("ping", receiverOnPing);
|
|
2471
|
+
receiver.on("pong", receiverOnPong);
|
|
2472
|
+
sender.onerror = senderOnError;
|
|
2473
|
+
if (socket.setTimeout) socket.setTimeout(0);
|
|
2474
|
+
if (socket.setNoDelay) socket.setNoDelay();
|
|
2475
|
+
if (head.length > 0) socket.unshift(head);
|
|
2476
|
+
socket.on("close", socketOnClose);
|
|
2477
|
+
socket.on("data", socketOnData);
|
|
2478
|
+
socket.on("end", socketOnEnd);
|
|
2479
|
+
socket.on("error", socketOnError);
|
|
2480
|
+
this._readyState = _WebSocket.OPEN;
|
|
2481
|
+
this.emit("open");
|
|
2482
|
+
}
|
|
2483
|
+
/**
|
|
2484
|
+
* Emit the `'close'` event.
|
|
2485
|
+
*
|
|
2486
|
+
* @private
|
|
2487
|
+
*/
|
|
2488
|
+
emitClose() {
|
|
2489
|
+
if (!this._socket) {
|
|
2490
|
+
this._readyState = _WebSocket.CLOSED;
|
|
2491
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
2492
|
+
return;
|
|
2493
|
+
}
|
|
2494
|
+
if (this._extensions[PerMessageDeflate2.extensionName]) {
|
|
2495
|
+
this._extensions[PerMessageDeflate2.extensionName].cleanup();
|
|
2496
|
+
}
|
|
2497
|
+
this._receiver.removeAllListeners();
|
|
2498
|
+
this._readyState = _WebSocket.CLOSED;
|
|
2499
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
2500
|
+
}
|
|
2501
|
+
/**
|
|
2502
|
+
* Start a closing handshake.
|
|
2503
|
+
*
|
|
2504
|
+
* +----------+ +-----------+ +----------+
|
|
2505
|
+
* - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
|
|
2506
|
+
* | +----------+ +-----------+ +----------+ |
|
|
2507
|
+
* +----------+ +-----------+ |
|
|
2508
|
+
* CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
|
|
2509
|
+
* +----------+ +-----------+ |
|
|
2510
|
+
* | | | +---+ |
|
|
2511
|
+
* +------------------------+-->|fin| - - - -
|
|
2512
|
+
* | +---+ | +---+
|
|
2513
|
+
* - - - - -|fin|<---------------------+
|
|
2514
|
+
* +---+
|
|
2515
|
+
*
|
|
2516
|
+
* @param {Number} [code] Status code explaining why the connection is closing
|
|
2517
|
+
* @param {(String|Buffer)} [data] The reason why the connection is
|
|
2518
|
+
* closing
|
|
2519
|
+
* @public
|
|
2520
|
+
*/
|
|
2521
|
+
close(code, data) {
|
|
2522
|
+
if (this.readyState === _WebSocket.CLOSED) return;
|
|
2523
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2524
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
2525
|
+
abortHandshake(this, this._req, msg);
|
|
2526
|
+
return;
|
|
2527
|
+
}
|
|
2528
|
+
if (this.readyState === _WebSocket.CLOSING) {
|
|
2529
|
+
if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
|
|
2530
|
+
this._socket.end();
|
|
2531
|
+
}
|
|
2532
|
+
return;
|
|
2533
|
+
}
|
|
2534
|
+
this._readyState = _WebSocket.CLOSING;
|
|
2535
|
+
this._sender.close(code, data, !this._isServer, (err) => {
|
|
2536
|
+
if (err) return;
|
|
2537
|
+
this._closeFrameSent = true;
|
|
2538
|
+
if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
|
|
2539
|
+
this._socket.end();
|
|
2540
|
+
}
|
|
2541
|
+
});
|
|
2542
|
+
setCloseTimer(this);
|
|
2543
|
+
}
|
|
2544
|
+
/**
|
|
2545
|
+
* Pause the socket.
|
|
2546
|
+
*
|
|
2547
|
+
* @public
|
|
2548
|
+
*/
|
|
2549
|
+
pause() {
|
|
2550
|
+
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
|
|
2551
|
+
return;
|
|
2552
|
+
}
|
|
2553
|
+
this._paused = true;
|
|
2554
|
+
this._socket.pause();
|
|
2555
|
+
}
|
|
2556
|
+
/**
|
|
2557
|
+
* Send a ping.
|
|
2558
|
+
*
|
|
2559
|
+
* @param {*} [data] The data to send
|
|
2560
|
+
* @param {Boolean} [mask] Indicates whether or not to mask `data`
|
|
2561
|
+
* @param {Function} [cb] Callback which is executed when the ping is sent
|
|
2562
|
+
* @public
|
|
2563
|
+
*/
|
|
2564
|
+
ping(data, mask, cb) {
|
|
2565
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2566
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2567
|
+
}
|
|
2568
|
+
if (typeof data === "function") {
|
|
2569
|
+
cb = data;
|
|
2570
|
+
data = mask = void 0;
|
|
2571
|
+
} else if (typeof mask === "function") {
|
|
2572
|
+
cb = mask;
|
|
2573
|
+
mask = void 0;
|
|
2574
|
+
}
|
|
2575
|
+
if (typeof data === "number") data = data.toString();
|
|
2576
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2577
|
+
sendAfterClose(this, data, cb);
|
|
2578
|
+
return;
|
|
2579
|
+
}
|
|
2580
|
+
if (mask === void 0) mask = !this._isServer;
|
|
2581
|
+
this._sender.ping(data || EMPTY_BUFFER, mask, cb);
|
|
2582
|
+
}
|
|
2583
|
+
/**
|
|
2584
|
+
* Send a pong.
|
|
2585
|
+
*
|
|
2586
|
+
* @param {*} [data] The data to send
|
|
2587
|
+
* @param {Boolean} [mask] Indicates whether or not to mask `data`
|
|
2588
|
+
* @param {Function} [cb] Callback which is executed when the pong is sent
|
|
2589
|
+
* @public
|
|
2590
|
+
*/
|
|
2591
|
+
pong(data, mask, cb) {
|
|
2592
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2593
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2594
|
+
}
|
|
2595
|
+
if (typeof data === "function") {
|
|
2596
|
+
cb = data;
|
|
2597
|
+
data = mask = void 0;
|
|
2598
|
+
} else if (typeof mask === "function") {
|
|
2599
|
+
cb = mask;
|
|
2600
|
+
mask = void 0;
|
|
2601
|
+
}
|
|
2602
|
+
if (typeof data === "number") data = data.toString();
|
|
2603
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2604
|
+
sendAfterClose(this, data, cb);
|
|
2605
|
+
return;
|
|
2606
|
+
}
|
|
2607
|
+
if (mask === void 0) mask = !this._isServer;
|
|
2608
|
+
this._sender.pong(data || EMPTY_BUFFER, mask, cb);
|
|
2609
|
+
}
|
|
2610
|
+
/**
|
|
2611
|
+
* Resume the socket.
|
|
2612
|
+
*
|
|
2613
|
+
* @public
|
|
2614
|
+
*/
|
|
2615
|
+
resume() {
|
|
2616
|
+
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
|
|
2617
|
+
return;
|
|
2618
|
+
}
|
|
2619
|
+
this._paused = false;
|
|
2620
|
+
if (!this._receiver._writableState.needDrain) this._socket.resume();
|
|
2621
|
+
}
|
|
2622
|
+
/**
|
|
2623
|
+
* Send a data message.
|
|
2624
|
+
*
|
|
2625
|
+
* @param {*} data The message to send
|
|
2626
|
+
* @param {Object} [options] Options object
|
|
2627
|
+
* @param {Boolean} [options.binary] Specifies whether `data` is binary or
|
|
2628
|
+
* text
|
|
2629
|
+
* @param {Boolean} [options.compress] Specifies whether or not to compress
|
|
2630
|
+
* `data`
|
|
2631
|
+
* @param {Boolean} [options.fin=true] Specifies whether the fragment is the
|
|
2632
|
+
* last one
|
|
2633
|
+
* @param {Boolean} [options.mask] Specifies whether or not to mask `data`
|
|
2634
|
+
* @param {Function} [cb] Callback which is executed when data is written out
|
|
2635
|
+
* @public
|
|
2636
|
+
*/
|
|
2637
|
+
send(data, options, cb) {
|
|
2638
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2639
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2640
|
+
}
|
|
2641
|
+
if (typeof options === "function") {
|
|
2642
|
+
cb = options;
|
|
2643
|
+
options = {};
|
|
2644
|
+
}
|
|
2645
|
+
if (typeof data === "number") data = data.toString();
|
|
2646
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2647
|
+
sendAfterClose(this, data, cb);
|
|
2648
|
+
return;
|
|
2649
|
+
}
|
|
2650
|
+
const opts = {
|
|
2651
|
+
binary: typeof data !== "string",
|
|
2652
|
+
mask: !this._isServer,
|
|
2653
|
+
compress: true,
|
|
2654
|
+
fin: true,
|
|
2655
|
+
...options
|
|
2656
|
+
};
|
|
2657
|
+
if (!this._extensions[PerMessageDeflate2.extensionName]) {
|
|
2658
|
+
opts.compress = false;
|
|
2659
|
+
}
|
|
2660
|
+
this._sender.send(data || EMPTY_BUFFER, opts, cb);
|
|
2661
|
+
}
|
|
2662
|
+
/**
|
|
2663
|
+
* Forcibly close the connection.
|
|
2664
|
+
*
|
|
2665
|
+
* @public
|
|
2666
|
+
*/
|
|
2667
|
+
terminate() {
|
|
2668
|
+
if (this.readyState === _WebSocket.CLOSED) return;
|
|
2669
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2670
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
2671
|
+
abortHandshake(this, this._req, msg);
|
|
2672
|
+
return;
|
|
2673
|
+
}
|
|
2674
|
+
if (this._socket) {
|
|
2675
|
+
this._readyState = _WebSocket.CLOSING;
|
|
2676
|
+
this._socket.destroy();
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
};
|
|
2680
|
+
Object.defineProperty(WebSocket3, "CONNECTING", {
|
|
2681
|
+
enumerable: true,
|
|
2682
|
+
value: readyStates.indexOf("CONNECTING")
|
|
2683
|
+
});
|
|
2684
|
+
Object.defineProperty(WebSocket3.prototype, "CONNECTING", {
|
|
2685
|
+
enumerable: true,
|
|
2686
|
+
value: readyStates.indexOf("CONNECTING")
|
|
2687
|
+
});
|
|
2688
|
+
Object.defineProperty(WebSocket3, "OPEN", {
|
|
2689
|
+
enumerable: true,
|
|
2690
|
+
value: readyStates.indexOf("OPEN")
|
|
2691
|
+
});
|
|
2692
|
+
Object.defineProperty(WebSocket3.prototype, "OPEN", {
|
|
2693
|
+
enumerable: true,
|
|
2694
|
+
value: readyStates.indexOf("OPEN")
|
|
2695
|
+
});
|
|
2696
|
+
Object.defineProperty(WebSocket3, "CLOSING", {
|
|
2697
|
+
enumerable: true,
|
|
2698
|
+
value: readyStates.indexOf("CLOSING")
|
|
2699
|
+
});
|
|
2700
|
+
Object.defineProperty(WebSocket3.prototype, "CLOSING", {
|
|
2701
|
+
enumerable: true,
|
|
2702
|
+
value: readyStates.indexOf("CLOSING")
|
|
2703
|
+
});
|
|
2704
|
+
Object.defineProperty(WebSocket3, "CLOSED", {
|
|
2705
|
+
enumerable: true,
|
|
2706
|
+
value: readyStates.indexOf("CLOSED")
|
|
2707
|
+
});
|
|
2708
|
+
Object.defineProperty(WebSocket3.prototype, "CLOSED", {
|
|
2709
|
+
enumerable: true,
|
|
2710
|
+
value: readyStates.indexOf("CLOSED")
|
|
2711
|
+
});
|
|
2712
|
+
[
|
|
2713
|
+
"binaryType",
|
|
2714
|
+
"bufferedAmount",
|
|
2715
|
+
"extensions",
|
|
2716
|
+
"isPaused",
|
|
2717
|
+
"protocol",
|
|
2718
|
+
"readyState",
|
|
2719
|
+
"url"
|
|
2720
|
+
].forEach((property) => {
|
|
2721
|
+
Object.defineProperty(WebSocket3.prototype, property, { enumerable: true });
|
|
2722
|
+
});
|
|
2723
|
+
["open", "error", "close", "message"].forEach((method) => {
|
|
2724
|
+
Object.defineProperty(WebSocket3.prototype, `on${method}`, {
|
|
2725
|
+
enumerable: true,
|
|
2726
|
+
get() {
|
|
2727
|
+
for (const listener of this.listeners(method)) {
|
|
2728
|
+
if (listener[kForOnEventAttribute]) return listener[kListener];
|
|
2729
|
+
}
|
|
2730
|
+
return null;
|
|
2731
|
+
},
|
|
2732
|
+
set(handler) {
|
|
2733
|
+
for (const listener of this.listeners(method)) {
|
|
2734
|
+
if (listener[kForOnEventAttribute]) {
|
|
2735
|
+
this.removeListener(method, listener);
|
|
2736
|
+
break;
|
|
2737
|
+
}
|
|
2738
|
+
}
|
|
2739
|
+
if (typeof handler !== "function") return;
|
|
2740
|
+
this.addEventListener(method, handler, {
|
|
2741
|
+
[kForOnEventAttribute]: true
|
|
2742
|
+
});
|
|
2743
|
+
}
|
|
2744
|
+
});
|
|
2745
|
+
});
|
|
2746
|
+
WebSocket3.prototype.addEventListener = addEventListener;
|
|
2747
|
+
WebSocket3.prototype.removeEventListener = removeEventListener;
|
|
2748
|
+
module.exports = WebSocket3;
|
|
2749
|
+
function initAsClient(websocket, address, protocols, options) {
|
|
2750
|
+
const opts = {
|
|
2751
|
+
allowSynchronousEvents: true,
|
|
2752
|
+
autoPong: true,
|
|
2753
|
+
closeTimeout: CLOSE_TIMEOUT,
|
|
2754
|
+
protocolVersion: protocolVersions[1],
|
|
2755
|
+
maxBufferedChunks: 256 * 1024,
|
|
2756
|
+
maxFragments: 16 * 1024,
|
|
2757
|
+
maxPayload: 100 * 1024 * 1024,
|
|
2758
|
+
skipUTF8Validation: false,
|
|
2759
|
+
perMessageDeflate: true,
|
|
2760
|
+
followRedirects: false,
|
|
2761
|
+
maxRedirects: 10,
|
|
2762
|
+
...options,
|
|
2763
|
+
socketPath: void 0,
|
|
2764
|
+
hostname: void 0,
|
|
2765
|
+
protocol: void 0,
|
|
2766
|
+
timeout: void 0,
|
|
2767
|
+
method: "GET",
|
|
2768
|
+
host: void 0,
|
|
2769
|
+
path: void 0,
|
|
2770
|
+
port: void 0
|
|
2771
|
+
};
|
|
2772
|
+
websocket._autoPong = opts.autoPong;
|
|
2773
|
+
websocket._closeTimeout = opts.closeTimeout;
|
|
2774
|
+
if (!protocolVersions.includes(opts.protocolVersion)) {
|
|
2775
|
+
throw new RangeError(
|
|
2776
|
+
`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
|
|
2777
|
+
);
|
|
2778
|
+
}
|
|
2779
|
+
let parsedUrl;
|
|
2780
|
+
if (address instanceof URL2) {
|
|
2781
|
+
parsedUrl = address;
|
|
2782
|
+
} else {
|
|
2783
|
+
try {
|
|
2784
|
+
parsedUrl = new URL2(address);
|
|
2785
|
+
} catch {
|
|
2786
|
+
throw new SyntaxError(`Invalid URL: ${address}`);
|
|
2787
|
+
}
|
|
2788
|
+
}
|
|
2789
|
+
if (parsedUrl.protocol === "http:") {
|
|
2790
|
+
parsedUrl.protocol = "ws:";
|
|
2791
|
+
} else if (parsedUrl.protocol === "https:") {
|
|
2792
|
+
parsedUrl.protocol = "wss:";
|
|
2793
|
+
}
|
|
2794
|
+
websocket._url = parsedUrl.href;
|
|
2795
|
+
const isSecure = parsedUrl.protocol === "wss:";
|
|
2796
|
+
const isIpcUrl = parsedUrl.protocol === "ws+unix:";
|
|
2797
|
+
let invalidUrlMessage;
|
|
2798
|
+
if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
|
|
2799
|
+
invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
|
|
2800
|
+
} else if (isIpcUrl && !parsedUrl.pathname) {
|
|
2801
|
+
invalidUrlMessage = "The URL's pathname is empty";
|
|
2802
|
+
} else if (parsedUrl.hash) {
|
|
2803
|
+
invalidUrlMessage = "The URL contains a fragment identifier";
|
|
2804
|
+
}
|
|
2805
|
+
if (invalidUrlMessage) {
|
|
2806
|
+
const err = new SyntaxError(invalidUrlMessage);
|
|
2807
|
+
if (websocket._redirects === 0) {
|
|
2808
|
+
throw err;
|
|
2809
|
+
} else {
|
|
2810
|
+
emitErrorAndClose(websocket, err);
|
|
2811
|
+
return;
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
const defaultPort = isSecure ? 443 : 80;
|
|
2815
|
+
const key = randomBytes(16).toString("base64");
|
|
2816
|
+
const request = isSecure ? https.request : http.request;
|
|
2817
|
+
const protocolSet = /* @__PURE__ */ new Set();
|
|
2818
|
+
let perMessageDeflate;
|
|
2819
|
+
opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
|
|
2820
|
+
opts.defaultPort = opts.defaultPort || defaultPort;
|
|
2821
|
+
opts.port = parsedUrl.port || defaultPort;
|
|
2822
|
+
opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
|
|
2823
|
+
opts.headers = {
|
|
2824
|
+
...opts.headers,
|
|
2825
|
+
"Sec-WebSocket-Version": opts.protocolVersion,
|
|
2826
|
+
"Sec-WebSocket-Key": key,
|
|
2827
|
+
Connection: "Upgrade",
|
|
2828
|
+
Upgrade: "websocket"
|
|
2829
|
+
};
|
|
2830
|
+
opts.path = parsedUrl.pathname + parsedUrl.search;
|
|
2831
|
+
opts.timeout = opts.handshakeTimeout;
|
|
2832
|
+
if (opts.perMessageDeflate) {
|
|
2833
|
+
perMessageDeflate = new PerMessageDeflate2({
|
|
2834
|
+
...opts.perMessageDeflate,
|
|
2835
|
+
isServer: false,
|
|
2836
|
+
maxPayload: opts.maxPayload
|
|
2837
|
+
});
|
|
2838
|
+
opts.headers["Sec-WebSocket-Extensions"] = format({
|
|
2839
|
+
[PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
|
|
2840
|
+
});
|
|
2841
|
+
}
|
|
2842
|
+
if (protocols.length) {
|
|
2843
|
+
for (const protocol of protocols) {
|
|
2844
|
+
if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
|
|
2845
|
+
throw new SyntaxError(
|
|
2846
|
+
"An invalid or duplicated subprotocol was specified"
|
|
2847
|
+
);
|
|
2848
|
+
}
|
|
2849
|
+
protocolSet.add(protocol);
|
|
2850
|
+
}
|
|
2851
|
+
opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
|
|
2852
|
+
}
|
|
2853
|
+
if (opts.origin) {
|
|
2854
|
+
if (opts.protocolVersion < 13) {
|
|
2855
|
+
opts.headers["Sec-WebSocket-Origin"] = opts.origin;
|
|
2856
|
+
} else {
|
|
2857
|
+
opts.headers.Origin = opts.origin;
|
|
2858
|
+
}
|
|
2859
|
+
}
|
|
2860
|
+
if (parsedUrl.username || parsedUrl.password) {
|
|
2861
|
+
opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
|
|
2862
|
+
}
|
|
2863
|
+
if (isIpcUrl) {
|
|
2864
|
+
const parts = opts.path.split(":");
|
|
2865
|
+
opts.socketPath = parts[0];
|
|
2866
|
+
opts.path = parts[1];
|
|
2867
|
+
}
|
|
2868
|
+
let req;
|
|
2869
|
+
if (opts.followRedirects) {
|
|
2870
|
+
if (websocket._redirects === 0) {
|
|
2871
|
+
websocket._originalIpc = isIpcUrl;
|
|
2872
|
+
websocket._originalSecure = isSecure;
|
|
2873
|
+
websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
|
|
2874
|
+
const headers = options && options.headers;
|
|
2875
|
+
options = { ...options, headers: {} };
|
|
2876
|
+
if (headers) {
|
|
2877
|
+
for (const [key2, value] of Object.entries(headers)) {
|
|
2878
|
+
options.headers[key2.toLowerCase()] = value;
|
|
2879
|
+
}
|
|
2880
|
+
}
|
|
2881
|
+
} else if (websocket.listenerCount("redirect") === 0) {
|
|
2882
|
+
const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
|
|
2883
|
+
if (!isSameHost || websocket._originalSecure && !isSecure) {
|
|
2884
|
+
delete opts.headers.authorization;
|
|
2885
|
+
delete opts.headers.cookie;
|
|
2886
|
+
if (!isSameHost) delete opts.headers.host;
|
|
2887
|
+
opts.auth = void 0;
|
|
2888
|
+
}
|
|
2889
|
+
}
|
|
2890
|
+
if (opts.auth && !options.headers.authorization) {
|
|
2891
|
+
options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
|
|
2892
|
+
}
|
|
2893
|
+
req = websocket._req = request(opts);
|
|
2894
|
+
if (websocket._redirects) {
|
|
2895
|
+
websocket.emit("redirect", websocket.url, req);
|
|
2896
|
+
}
|
|
2897
|
+
} else {
|
|
2898
|
+
req = websocket._req = request(opts);
|
|
2899
|
+
}
|
|
2900
|
+
if (opts.timeout) {
|
|
2901
|
+
req.on("timeout", () => {
|
|
2902
|
+
abortHandshake(websocket, req, "Opening handshake has timed out");
|
|
2903
|
+
});
|
|
2904
|
+
}
|
|
2905
|
+
req.on("error", (err) => {
|
|
2906
|
+
if (req === null || req[kAborted]) return;
|
|
2907
|
+
req = websocket._req = null;
|
|
2908
|
+
emitErrorAndClose(websocket, err);
|
|
2909
|
+
});
|
|
2910
|
+
req.on("response", (res) => {
|
|
2911
|
+
const location = res.headers.location;
|
|
2912
|
+
const statusCode = res.statusCode;
|
|
2913
|
+
if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
|
|
2914
|
+
if (++websocket._redirects > opts.maxRedirects) {
|
|
2915
|
+
abortHandshake(websocket, req, "Maximum redirects exceeded");
|
|
2916
|
+
return;
|
|
2917
|
+
}
|
|
2918
|
+
req.abort();
|
|
2919
|
+
let addr;
|
|
2920
|
+
try {
|
|
2921
|
+
addr = new URL2(location, address);
|
|
2922
|
+
} catch (e) {
|
|
2923
|
+
const err = new SyntaxError(`Invalid URL: ${location}`);
|
|
2924
|
+
emitErrorAndClose(websocket, err);
|
|
2925
|
+
return;
|
|
2926
|
+
}
|
|
2927
|
+
initAsClient(websocket, addr, protocols, options);
|
|
2928
|
+
} else if (!websocket.emit("unexpected-response", req, res)) {
|
|
2929
|
+
abortHandshake(
|
|
2930
|
+
websocket,
|
|
2931
|
+
req,
|
|
2932
|
+
`Unexpected server response: ${res.statusCode}`
|
|
2933
|
+
);
|
|
2934
|
+
}
|
|
2935
|
+
});
|
|
2936
|
+
req.on("upgrade", (res, socket, head) => {
|
|
2937
|
+
websocket.emit("upgrade", res);
|
|
2938
|
+
if (websocket.readyState !== WebSocket3.CONNECTING) return;
|
|
2939
|
+
req = websocket._req = null;
|
|
2940
|
+
const upgrade = res.headers.upgrade;
|
|
2941
|
+
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
|
|
2942
|
+
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
2943
|
+
return;
|
|
2944
|
+
}
|
|
2945
|
+
const digest = createHash5("sha1").update(key + GUID).digest("base64");
|
|
2946
|
+
if (res.headers["sec-websocket-accept"] !== digest) {
|
|
2947
|
+
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
2948
|
+
return;
|
|
2949
|
+
}
|
|
2950
|
+
const serverProt = res.headers["sec-websocket-protocol"];
|
|
2951
|
+
let protError;
|
|
2952
|
+
if (serverProt !== void 0) {
|
|
2953
|
+
if (!protocolSet.size) {
|
|
2954
|
+
protError = "Server sent a subprotocol but none was requested";
|
|
2955
|
+
} else if (!protocolSet.has(serverProt)) {
|
|
2956
|
+
protError = "Server sent an invalid subprotocol";
|
|
2957
|
+
}
|
|
2958
|
+
} else if (protocolSet.size) {
|
|
2959
|
+
protError = "Server sent no subprotocol";
|
|
2960
|
+
}
|
|
2961
|
+
if (protError) {
|
|
2962
|
+
abortHandshake(websocket, socket, protError);
|
|
2963
|
+
return;
|
|
2964
|
+
}
|
|
2965
|
+
if (serverProt) websocket._protocol = serverProt;
|
|
2966
|
+
const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
|
|
2967
|
+
if (secWebSocketExtensions !== void 0) {
|
|
2968
|
+
if (!perMessageDeflate) {
|
|
2969
|
+
const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
|
|
2970
|
+
abortHandshake(websocket, socket, message);
|
|
2971
|
+
return;
|
|
2972
|
+
}
|
|
2973
|
+
let extensions;
|
|
2974
|
+
try {
|
|
2975
|
+
extensions = parse(secWebSocketExtensions);
|
|
2976
|
+
} catch (err) {
|
|
2977
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
2978
|
+
abortHandshake(websocket, socket, message);
|
|
2979
|
+
return;
|
|
2980
|
+
}
|
|
2981
|
+
const extensionNames = Object.keys(extensions);
|
|
2982
|
+
if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
|
|
2983
|
+
const message = "Server indicated an extension that was not requested";
|
|
2984
|
+
abortHandshake(websocket, socket, message);
|
|
2985
|
+
return;
|
|
2986
|
+
}
|
|
2987
|
+
try {
|
|
2988
|
+
perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
|
|
2989
|
+
} catch (err) {
|
|
2990
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
2991
|
+
abortHandshake(websocket, socket, message);
|
|
2992
|
+
return;
|
|
2993
|
+
}
|
|
2994
|
+
websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
|
|
2995
|
+
}
|
|
2996
|
+
websocket.setSocket(socket, head, {
|
|
2997
|
+
allowSynchronousEvents: opts.allowSynchronousEvents,
|
|
2998
|
+
generateMask: opts.generateMask,
|
|
2999
|
+
maxBufferedChunks: opts.maxBufferedChunks,
|
|
3000
|
+
maxFragments: opts.maxFragments,
|
|
3001
|
+
maxPayload: opts.maxPayload,
|
|
3002
|
+
skipUTF8Validation: opts.skipUTF8Validation
|
|
3003
|
+
});
|
|
3004
|
+
});
|
|
3005
|
+
if (opts.finishRequest) {
|
|
3006
|
+
opts.finishRequest(req, websocket);
|
|
3007
|
+
} else {
|
|
3008
|
+
req.end();
|
|
3009
|
+
}
|
|
3010
|
+
}
|
|
3011
|
+
function emitErrorAndClose(websocket, err) {
|
|
3012
|
+
websocket._readyState = WebSocket3.CLOSING;
|
|
3013
|
+
websocket._errorEmitted = true;
|
|
3014
|
+
websocket.emit("error", err);
|
|
3015
|
+
websocket.emitClose();
|
|
3016
|
+
}
|
|
3017
|
+
function netConnect(options) {
|
|
3018
|
+
options.path = options.socketPath;
|
|
3019
|
+
return net.connect(options);
|
|
3020
|
+
}
|
|
3021
|
+
function tlsConnect(options) {
|
|
3022
|
+
options.path = void 0;
|
|
3023
|
+
if (!options.servername && options.servername !== "") {
|
|
3024
|
+
options.servername = net.isIP(options.host) ? "" : options.host;
|
|
3025
|
+
}
|
|
3026
|
+
return tls.connect(options);
|
|
3027
|
+
}
|
|
3028
|
+
function abortHandshake(websocket, stream, message) {
|
|
3029
|
+
websocket._readyState = WebSocket3.CLOSING;
|
|
3030
|
+
const err = new Error(message);
|
|
3031
|
+
Error.captureStackTrace(err, abortHandshake);
|
|
3032
|
+
if (stream.setHeader) {
|
|
3033
|
+
stream[kAborted] = true;
|
|
3034
|
+
stream.abort();
|
|
3035
|
+
if (stream.socket && !stream.socket.destroyed) {
|
|
3036
|
+
stream.socket.destroy();
|
|
3037
|
+
}
|
|
3038
|
+
process.nextTick(emitErrorAndClose, websocket, err);
|
|
3039
|
+
} else {
|
|
3040
|
+
stream.destroy(err);
|
|
3041
|
+
stream.once("error", websocket.emit.bind(websocket, "error"));
|
|
3042
|
+
stream.once("close", websocket.emitClose.bind(websocket));
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
function sendAfterClose(websocket, data, cb) {
|
|
3046
|
+
if (data) {
|
|
3047
|
+
const length = isBlob(data) ? data.size : toBuffer(data).length;
|
|
3048
|
+
if (websocket._socket) websocket._sender._bufferedBytes += length;
|
|
3049
|
+
else websocket._bufferedAmount += length;
|
|
3050
|
+
}
|
|
3051
|
+
if (cb) {
|
|
3052
|
+
const err = new Error(
|
|
3053
|
+
`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
|
|
3054
|
+
);
|
|
3055
|
+
process.nextTick(cb, err);
|
|
3056
|
+
}
|
|
3057
|
+
}
|
|
3058
|
+
function receiverOnConclude(code, reason) {
|
|
3059
|
+
const websocket = this[kWebSocket];
|
|
3060
|
+
websocket._closeFrameReceived = true;
|
|
3061
|
+
websocket._closeMessage = reason;
|
|
3062
|
+
websocket._closeCode = code;
|
|
3063
|
+
if (websocket._socket[kWebSocket] === void 0) return;
|
|
3064
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
3065
|
+
process.nextTick(resume, websocket._socket);
|
|
3066
|
+
if (code === 1005) websocket.close();
|
|
3067
|
+
else websocket.close(code, reason);
|
|
3068
|
+
}
|
|
3069
|
+
function receiverOnDrain() {
|
|
3070
|
+
const websocket = this[kWebSocket];
|
|
3071
|
+
if (!websocket.isPaused) websocket._socket.resume();
|
|
3072
|
+
}
|
|
3073
|
+
function receiverOnError(err) {
|
|
3074
|
+
const websocket = this[kWebSocket];
|
|
3075
|
+
if (websocket._socket[kWebSocket] !== void 0) {
|
|
3076
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
3077
|
+
process.nextTick(resume, websocket._socket);
|
|
3078
|
+
websocket.close(err[kStatusCode]);
|
|
3079
|
+
}
|
|
3080
|
+
if (!websocket._errorEmitted) {
|
|
3081
|
+
websocket._errorEmitted = true;
|
|
3082
|
+
websocket.emit("error", err);
|
|
3083
|
+
}
|
|
3084
|
+
}
|
|
3085
|
+
function receiverOnFinish() {
|
|
3086
|
+
this[kWebSocket].emitClose();
|
|
3087
|
+
}
|
|
3088
|
+
function receiverOnMessage(data, isBinary) {
|
|
3089
|
+
this[kWebSocket].emit("message", data, isBinary);
|
|
3090
|
+
}
|
|
3091
|
+
function receiverOnPing(data) {
|
|
3092
|
+
const websocket = this[kWebSocket];
|
|
3093
|
+
if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
|
|
3094
|
+
websocket.emit("ping", data);
|
|
3095
|
+
}
|
|
3096
|
+
function receiverOnPong(data) {
|
|
3097
|
+
this[kWebSocket].emit("pong", data);
|
|
3098
|
+
}
|
|
3099
|
+
function resume(stream) {
|
|
3100
|
+
stream.resume();
|
|
3101
|
+
}
|
|
3102
|
+
function senderOnError(err) {
|
|
3103
|
+
const websocket = this[kWebSocket];
|
|
3104
|
+
if (websocket.readyState === WebSocket3.CLOSED) return;
|
|
3105
|
+
if (websocket.readyState === WebSocket3.OPEN) {
|
|
3106
|
+
websocket._readyState = WebSocket3.CLOSING;
|
|
3107
|
+
setCloseTimer(websocket);
|
|
3108
|
+
}
|
|
3109
|
+
this._socket.end();
|
|
3110
|
+
if (!websocket._errorEmitted) {
|
|
3111
|
+
websocket._errorEmitted = true;
|
|
3112
|
+
websocket.emit("error", err);
|
|
3113
|
+
}
|
|
3114
|
+
}
|
|
3115
|
+
function setCloseTimer(websocket) {
|
|
3116
|
+
websocket._closeTimer = setTimeout(
|
|
3117
|
+
websocket._socket.destroy.bind(websocket._socket),
|
|
3118
|
+
websocket._closeTimeout
|
|
3119
|
+
);
|
|
3120
|
+
}
|
|
3121
|
+
function socketOnClose() {
|
|
3122
|
+
const websocket = this[kWebSocket];
|
|
3123
|
+
this.removeListener("close", socketOnClose);
|
|
3124
|
+
this.removeListener("data", socketOnData);
|
|
3125
|
+
this.removeListener("end", socketOnEnd);
|
|
3126
|
+
websocket._readyState = WebSocket3.CLOSING;
|
|
3127
|
+
if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
|
|
3128
|
+
const chunk = this.read(this._readableState.length);
|
|
3129
|
+
websocket._receiver.write(chunk);
|
|
3130
|
+
}
|
|
3131
|
+
websocket._receiver.end();
|
|
3132
|
+
this[kWebSocket] = void 0;
|
|
3133
|
+
clearTimeout(websocket._closeTimer);
|
|
3134
|
+
if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
|
|
3135
|
+
websocket.emitClose();
|
|
3136
|
+
} else {
|
|
3137
|
+
websocket._receiver.on("error", receiverOnFinish);
|
|
3138
|
+
websocket._receiver.on("finish", receiverOnFinish);
|
|
3139
|
+
}
|
|
3140
|
+
}
|
|
3141
|
+
function socketOnData(chunk) {
|
|
3142
|
+
if (!this[kWebSocket]._receiver.write(chunk)) {
|
|
3143
|
+
this.pause();
|
|
3144
|
+
}
|
|
3145
|
+
}
|
|
3146
|
+
function socketOnEnd() {
|
|
3147
|
+
const websocket = this[kWebSocket];
|
|
3148
|
+
websocket._readyState = WebSocket3.CLOSING;
|
|
3149
|
+
websocket._receiver.end();
|
|
3150
|
+
this.end();
|
|
3151
|
+
}
|
|
3152
|
+
function socketOnError() {
|
|
3153
|
+
const websocket = this[kWebSocket];
|
|
3154
|
+
this.removeListener("error", socketOnError);
|
|
3155
|
+
this.on("error", NOOP);
|
|
3156
|
+
if (websocket) {
|
|
3157
|
+
websocket._readyState = WebSocket3.CLOSING;
|
|
3158
|
+
this.destroy();
|
|
3159
|
+
}
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
});
|
|
3163
|
+
|
|
3164
|
+
// ../../node_modules/ws/lib/stream.js
|
|
3165
|
+
var require_stream = __commonJS({
|
|
3166
|
+
"../../node_modules/ws/lib/stream.js"(exports, module) {
|
|
3167
|
+
"use strict";
|
|
3168
|
+
var WebSocket3 = require_websocket();
|
|
3169
|
+
var { Duplex } = __require("stream");
|
|
3170
|
+
function emitClose(stream) {
|
|
3171
|
+
stream.emit("close");
|
|
3172
|
+
}
|
|
3173
|
+
function duplexOnEnd() {
|
|
3174
|
+
if (!this.destroyed && this._writableState.finished) {
|
|
3175
|
+
this.destroy();
|
|
3176
|
+
}
|
|
3177
|
+
}
|
|
3178
|
+
function duplexOnError(err) {
|
|
3179
|
+
this.removeListener("error", duplexOnError);
|
|
3180
|
+
this.destroy();
|
|
3181
|
+
if (this.listenerCount("error") === 0) {
|
|
3182
|
+
this.emit("error", err);
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
function createWebSocketStream2(ws, options) {
|
|
3186
|
+
let terminateOnDestroy = true;
|
|
3187
|
+
const duplex = new Duplex({
|
|
3188
|
+
...options,
|
|
3189
|
+
autoDestroy: false,
|
|
3190
|
+
emitClose: false,
|
|
3191
|
+
objectMode: false,
|
|
3192
|
+
writableObjectMode: false
|
|
3193
|
+
});
|
|
3194
|
+
ws.on("message", function message(msg, isBinary) {
|
|
3195
|
+
const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
|
|
3196
|
+
if (!duplex.push(data)) ws.pause();
|
|
3197
|
+
});
|
|
3198
|
+
ws.once("error", function error(err) {
|
|
3199
|
+
if (duplex.destroyed) return;
|
|
3200
|
+
terminateOnDestroy = false;
|
|
3201
|
+
duplex.destroy(err);
|
|
3202
|
+
});
|
|
3203
|
+
ws.once("close", function close() {
|
|
3204
|
+
if (duplex.destroyed) return;
|
|
3205
|
+
duplex.push(null);
|
|
3206
|
+
});
|
|
3207
|
+
duplex._destroy = function(err, callback) {
|
|
3208
|
+
if (ws.readyState === ws.CLOSED) {
|
|
3209
|
+
callback(err);
|
|
3210
|
+
process.nextTick(emitClose, duplex);
|
|
3211
|
+
return;
|
|
3212
|
+
}
|
|
3213
|
+
let called = false;
|
|
3214
|
+
ws.once("error", function error(err2) {
|
|
3215
|
+
called = true;
|
|
3216
|
+
callback(err2);
|
|
3217
|
+
});
|
|
3218
|
+
ws.once("close", function close() {
|
|
3219
|
+
if (!called) callback(err);
|
|
3220
|
+
process.nextTick(emitClose, duplex);
|
|
3221
|
+
});
|
|
3222
|
+
if (terminateOnDestroy) ws.terminate();
|
|
3223
|
+
};
|
|
3224
|
+
duplex._final = function(callback) {
|
|
3225
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
3226
|
+
ws.once("open", function open3() {
|
|
3227
|
+
duplex._final(callback);
|
|
3228
|
+
});
|
|
3229
|
+
return;
|
|
3230
|
+
}
|
|
3231
|
+
if (ws._socket === null) return;
|
|
3232
|
+
if (ws._socket._writableState.finished) {
|
|
3233
|
+
callback();
|
|
3234
|
+
if (duplex._readableState.endEmitted) duplex.destroy();
|
|
3235
|
+
} else {
|
|
3236
|
+
ws._socket.once("finish", function finish() {
|
|
3237
|
+
callback();
|
|
3238
|
+
});
|
|
3239
|
+
ws.close();
|
|
3240
|
+
}
|
|
3241
|
+
};
|
|
3242
|
+
duplex._read = function() {
|
|
3243
|
+
if (ws.isPaused) ws.resume();
|
|
3244
|
+
};
|
|
3245
|
+
duplex._write = function(chunk, encoding, callback) {
|
|
3246
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
3247
|
+
ws.once("open", function open3() {
|
|
3248
|
+
duplex._write(chunk, encoding, callback);
|
|
3249
|
+
});
|
|
3250
|
+
return;
|
|
3251
|
+
}
|
|
3252
|
+
ws.send(chunk, callback);
|
|
3253
|
+
};
|
|
3254
|
+
duplex.on("end", duplexOnEnd);
|
|
3255
|
+
duplex.on("error", duplexOnError);
|
|
3256
|
+
return duplex;
|
|
3257
|
+
}
|
|
3258
|
+
module.exports = createWebSocketStream2;
|
|
3259
|
+
}
|
|
3260
|
+
});
|
|
3261
|
+
|
|
3262
|
+
// ../../node_modules/ws/lib/subprotocol.js
|
|
3263
|
+
var require_subprotocol = __commonJS({
|
|
3264
|
+
"../../node_modules/ws/lib/subprotocol.js"(exports, module) {
|
|
3265
|
+
"use strict";
|
|
3266
|
+
var { tokenChars } = require_validation();
|
|
3267
|
+
function parse(header) {
|
|
3268
|
+
const protocols = /* @__PURE__ */ new Set();
|
|
3269
|
+
let start = -1;
|
|
3270
|
+
let end = -1;
|
|
3271
|
+
let i = 0;
|
|
3272
|
+
for (i; i < header.length; i++) {
|
|
3273
|
+
const code = header.charCodeAt(i);
|
|
3274
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
3275
|
+
if (start === -1) start = i;
|
|
3276
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
3277
|
+
if (end === -1 && start !== -1) end = i;
|
|
3278
|
+
} else if (code === 44) {
|
|
3279
|
+
if (start === -1) {
|
|
3280
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
3281
|
+
}
|
|
3282
|
+
if (end === -1) end = i;
|
|
3283
|
+
const protocol2 = header.slice(start, end);
|
|
3284
|
+
if (protocols.has(protocol2)) {
|
|
3285
|
+
throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
|
|
3286
|
+
}
|
|
3287
|
+
protocols.add(protocol2);
|
|
3288
|
+
start = end = -1;
|
|
3289
|
+
} else {
|
|
3290
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
3291
|
+
}
|
|
3292
|
+
}
|
|
3293
|
+
if (start === -1 || end !== -1) {
|
|
3294
|
+
throw new SyntaxError("Unexpected end of input");
|
|
3295
|
+
}
|
|
3296
|
+
const protocol = header.slice(start, i);
|
|
3297
|
+
if (protocols.has(protocol)) {
|
|
3298
|
+
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
|
|
3299
|
+
}
|
|
3300
|
+
protocols.add(protocol);
|
|
3301
|
+
return protocols;
|
|
3302
|
+
}
|
|
3303
|
+
module.exports = { parse };
|
|
3304
|
+
}
|
|
3305
|
+
});
|
|
3306
|
+
|
|
3307
|
+
// ../../node_modules/ws/lib/websocket-server.js
|
|
3308
|
+
var require_websocket_server = __commonJS({
|
|
3309
|
+
"../../node_modules/ws/lib/websocket-server.js"(exports, module) {
|
|
3310
|
+
"use strict";
|
|
3311
|
+
var EventEmitter = __require("events");
|
|
3312
|
+
var http = __require("http");
|
|
3313
|
+
var { Duplex } = __require("stream");
|
|
3314
|
+
var { createHash: createHash5 } = __require("crypto");
|
|
3315
|
+
var extension2 = require_extension();
|
|
3316
|
+
var PerMessageDeflate2 = require_permessage_deflate();
|
|
3317
|
+
var subprotocol2 = require_subprotocol();
|
|
3318
|
+
var WebSocket3 = require_websocket();
|
|
3319
|
+
var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
|
|
3320
|
+
var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
|
|
3321
|
+
var RUNNING = 0;
|
|
3322
|
+
var CLOSING = 1;
|
|
3323
|
+
var CLOSED = 2;
|
|
3324
|
+
var WebSocketServer2 = class extends EventEmitter {
|
|
3325
|
+
/**
|
|
3326
|
+
* Create a `WebSocketServer` instance.
|
|
3327
|
+
*
|
|
3328
|
+
* @param {Object} options Configuration options
|
|
3329
|
+
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
|
|
3330
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
3331
|
+
* multiple times in the same tick
|
|
3332
|
+
* @param {Boolean} [options.autoPong=true] Specifies whether or not to
|
|
3333
|
+
* automatically send a pong in response to a ping
|
|
3334
|
+
* @param {Number} [options.backlog=511] The maximum length of the queue of
|
|
3335
|
+
* pending connections
|
|
3336
|
+
* @param {Boolean} [options.clientTracking=true] Specifies whether or not to
|
|
3337
|
+
* track clients
|
|
3338
|
+
* @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
|
|
3339
|
+
* wait for the closing handshake to finish after `websocket.close()` is
|
|
3340
|
+
* called
|
|
3341
|
+
* @param {Function} [options.handleProtocols] A hook to handle protocols
|
|
3342
|
+
* @param {String} [options.host] The hostname where to bind the server
|
|
3343
|
+
* @param {Number} [options.maxBufferedChunks=262144] The maximum number of
|
|
3344
|
+
* buffered data chunks
|
|
3345
|
+
* @param {Number} [options.maxFragments=16384] The maximum number of message
|
|
3346
|
+
* fragments
|
|
3347
|
+
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
|
|
3348
|
+
* size
|
|
3349
|
+
* @param {Boolean} [options.noServer=false] Enable no server mode
|
|
3350
|
+
* @param {String} [options.path] Accept only connections matching this path
|
|
3351
|
+
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
|
|
3352
|
+
* permessage-deflate
|
|
3353
|
+
* @param {Number} [options.port] The port where to bind the server
|
|
3354
|
+
* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
|
|
3355
|
+
* server to use
|
|
3356
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
3357
|
+
* not to skip UTF-8 validation for text and close messages
|
|
3358
|
+
* @param {Function} [options.verifyClient] A hook to reject connections
|
|
3359
|
+
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
|
|
3360
|
+
* class to use. It must be the `WebSocket` class or class that extends it
|
|
3361
|
+
* @param {Function} [callback] A listener for the `listening` event
|
|
3362
|
+
*/
|
|
3363
|
+
constructor(options, callback) {
|
|
3364
|
+
super();
|
|
3365
|
+
options = {
|
|
3366
|
+
allowSynchronousEvents: true,
|
|
3367
|
+
autoPong: true,
|
|
3368
|
+
maxBufferedChunks: 256 * 1024,
|
|
3369
|
+
maxFragments: 16 * 1024,
|
|
3370
|
+
maxPayload: 100 * 1024 * 1024,
|
|
3371
|
+
skipUTF8Validation: false,
|
|
3372
|
+
perMessageDeflate: false,
|
|
3373
|
+
handleProtocols: null,
|
|
3374
|
+
clientTracking: true,
|
|
3375
|
+
closeTimeout: CLOSE_TIMEOUT,
|
|
3376
|
+
verifyClient: null,
|
|
3377
|
+
noServer: false,
|
|
3378
|
+
backlog: null,
|
|
3379
|
+
// use default (511 as implemented in net.js)
|
|
3380
|
+
server: null,
|
|
3381
|
+
host: null,
|
|
3382
|
+
path: null,
|
|
3383
|
+
port: null,
|
|
3384
|
+
WebSocket: WebSocket3,
|
|
3385
|
+
...options
|
|
3386
|
+
};
|
|
3387
|
+
if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
|
|
3388
|
+
throw new TypeError(
|
|
3389
|
+
'One and only one of the "port", "server", or "noServer" options must be specified'
|
|
3390
|
+
);
|
|
3391
|
+
}
|
|
3392
|
+
if (options.port != null) {
|
|
3393
|
+
this._server = http.createServer((req, res) => {
|
|
3394
|
+
const body = http.STATUS_CODES[426];
|
|
3395
|
+
res.writeHead(426, {
|
|
3396
|
+
"Content-Length": body.length,
|
|
3397
|
+
"Content-Type": "text/plain"
|
|
3398
|
+
});
|
|
3399
|
+
res.end(body);
|
|
3400
|
+
});
|
|
3401
|
+
this._server.listen(
|
|
3402
|
+
options.port,
|
|
3403
|
+
options.host,
|
|
3404
|
+
options.backlog,
|
|
3405
|
+
callback
|
|
3406
|
+
);
|
|
3407
|
+
} else if (options.server) {
|
|
3408
|
+
this._server = options.server;
|
|
3409
|
+
}
|
|
3410
|
+
if (this._server) {
|
|
3411
|
+
const emitConnection = this.emit.bind(this, "connection");
|
|
3412
|
+
this._removeListeners = addListeners(this._server, {
|
|
3413
|
+
listening: this.emit.bind(this, "listening"),
|
|
3414
|
+
error: this.emit.bind(this, "error"),
|
|
3415
|
+
upgrade: (req, socket, head) => {
|
|
3416
|
+
this.handleUpgrade(req, socket, head, emitConnection);
|
|
3417
|
+
}
|
|
3418
|
+
});
|
|
3419
|
+
}
|
|
3420
|
+
if (options.perMessageDeflate === true) options.perMessageDeflate = {};
|
|
3421
|
+
if (options.clientTracking) {
|
|
3422
|
+
this.clients = /* @__PURE__ */ new Set();
|
|
3423
|
+
this._shouldEmitClose = false;
|
|
3424
|
+
}
|
|
3425
|
+
this.options = options;
|
|
3426
|
+
this._state = RUNNING;
|
|
3427
|
+
}
|
|
3428
|
+
/**
|
|
3429
|
+
* Returns the bound address, the address family name, and port of the server
|
|
3430
|
+
* as reported by the operating system if listening on an IP socket.
|
|
3431
|
+
* If the server is listening on a pipe or UNIX domain socket, the name is
|
|
3432
|
+
* returned as a string.
|
|
3433
|
+
*
|
|
3434
|
+
* @return {(Object|String|null)} The address of the server
|
|
3435
|
+
* @public
|
|
3436
|
+
*/
|
|
3437
|
+
address() {
|
|
3438
|
+
if (this.options.noServer) {
|
|
3439
|
+
throw new Error('The server is operating in "noServer" mode');
|
|
3440
|
+
}
|
|
3441
|
+
if (!this._server) return null;
|
|
3442
|
+
return this._server.address();
|
|
3443
|
+
}
|
|
3444
|
+
/**
|
|
3445
|
+
* Stop the server from accepting new connections and emit the `'close'` event
|
|
3446
|
+
* when all existing connections are closed.
|
|
3447
|
+
*
|
|
3448
|
+
* @param {Function} [cb] A one-time listener for the `'close'` event
|
|
3449
|
+
* @public
|
|
3450
|
+
*/
|
|
3451
|
+
close(cb) {
|
|
3452
|
+
if (this._state === CLOSED) {
|
|
3453
|
+
if (cb) {
|
|
3454
|
+
this.once("close", () => {
|
|
3455
|
+
cb(new Error("The server is not running"));
|
|
3456
|
+
});
|
|
3457
|
+
}
|
|
3458
|
+
process.nextTick(emitClose, this);
|
|
3459
|
+
return;
|
|
3460
|
+
}
|
|
3461
|
+
if (cb) this.once("close", cb);
|
|
3462
|
+
if (this._state === CLOSING) return;
|
|
3463
|
+
this._state = CLOSING;
|
|
3464
|
+
if (this.options.noServer || this.options.server) {
|
|
3465
|
+
if (this._server) {
|
|
3466
|
+
this._removeListeners();
|
|
3467
|
+
this._removeListeners = this._server = null;
|
|
3468
|
+
}
|
|
3469
|
+
if (this.clients) {
|
|
3470
|
+
if (!this.clients.size) {
|
|
3471
|
+
process.nextTick(emitClose, this);
|
|
3472
|
+
} else {
|
|
3473
|
+
this._shouldEmitClose = true;
|
|
3474
|
+
}
|
|
3475
|
+
} else {
|
|
3476
|
+
process.nextTick(emitClose, this);
|
|
3477
|
+
}
|
|
3478
|
+
} else {
|
|
3479
|
+
const server = this._server;
|
|
3480
|
+
this._removeListeners();
|
|
3481
|
+
this._removeListeners = this._server = null;
|
|
3482
|
+
server.close(() => {
|
|
3483
|
+
emitClose(this);
|
|
3484
|
+
});
|
|
3485
|
+
}
|
|
3486
|
+
}
|
|
3487
|
+
/**
|
|
3488
|
+
* See if a given request should be handled by this server instance.
|
|
3489
|
+
*
|
|
3490
|
+
* @param {http.IncomingMessage} req Request object to inspect
|
|
3491
|
+
* @return {Boolean} `true` if the request is valid, else `false`
|
|
3492
|
+
* @public
|
|
3493
|
+
*/
|
|
3494
|
+
shouldHandle(req) {
|
|
3495
|
+
if (this.options.path) {
|
|
3496
|
+
const index = req.url.indexOf("?");
|
|
3497
|
+
const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
|
|
3498
|
+
if (pathname !== this.options.path) return false;
|
|
3499
|
+
}
|
|
3500
|
+
return true;
|
|
3501
|
+
}
|
|
3502
|
+
/**
|
|
3503
|
+
* Handle a HTTP Upgrade request.
|
|
3504
|
+
*
|
|
3505
|
+
* @param {http.IncomingMessage} req The request object
|
|
3506
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
3507
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
3508
|
+
* @param {Function} cb Callback
|
|
3509
|
+
* @public
|
|
3510
|
+
*/
|
|
3511
|
+
handleUpgrade(req, socket, head, cb) {
|
|
3512
|
+
socket.on("error", socketOnError);
|
|
3513
|
+
const key = req.headers["sec-websocket-key"];
|
|
3514
|
+
const upgrade = req.headers.upgrade;
|
|
3515
|
+
const version = +req.headers["sec-websocket-version"];
|
|
3516
|
+
if (req.method !== "GET") {
|
|
3517
|
+
const message = "Invalid HTTP method";
|
|
3518
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
|
|
3519
|
+
return;
|
|
3520
|
+
}
|
|
3521
|
+
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
|
|
3522
|
+
const message = "Invalid Upgrade header";
|
|
3523
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3524
|
+
return;
|
|
3525
|
+
}
|
|
3526
|
+
if (key === void 0 || !keyRegex.test(key)) {
|
|
3527
|
+
const message = "Missing or invalid Sec-WebSocket-Key header";
|
|
3528
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3529
|
+
return;
|
|
3530
|
+
}
|
|
3531
|
+
if (version !== 13 && version !== 8) {
|
|
3532
|
+
const message = "Missing or invalid Sec-WebSocket-Version header";
|
|
3533
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
|
|
3534
|
+
"Sec-WebSocket-Version": "13, 8"
|
|
3535
|
+
});
|
|
3536
|
+
return;
|
|
3537
|
+
}
|
|
3538
|
+
if (!this.shouldHandle(req)) {
|
|
3539
|
+
abortHandshake(socket, 400);
|
|
3540
|
+
return;
|
|
3541
|
+
}
|
|
3542
|
+
const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
|
|
3543
|
+
let protocols = /* @__PURE__ */ new Set();
|
|
3544
|
+
if (secWebSocketProtocol !== void 0) {
|
|
3545
|
+
try {
|
|
3546
|
+
protocols = subprotocol2.parse(secWebSocketProtocol);
|
|
3547
|
+
} catch (err) {
|
|
3548
|
+
const message = "Invalid Sec-WebSocket-Protocol header";
|
|
3549
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3550
|
+
return;
|
|
3551
|
+
}
|
|
3552
|
+
}
|
|
3553
|
+
const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
|
|
3554
|
+
const extensions = {};
|
|
3555
|
+
if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
|
|
3556
|
+
const perMessageDeflate = new PerMessageDeflate2({
|
|
3557
|
+
...this.options.perMessageDeflate,
|
|
3558
|
+
isServer: true,
|
|
3559
|
+
maxPayload: this.options.maxPayload
|
|
3560
|
+
});
|
|
3561
|
+
try {
|
|
3562
|
+
const offers = extension2.parse(secWebSocketExtensions);
|
|
3563
|
+
if (offers[PerMessageDeflate2.extensionName]) {
|
|
3564
|
+
perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
|
|
3565
|
+
extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
|
|
3566
|
+
}
|
|
3567
|
+
} catch (err) {
|
|
3568
|
+
const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
|
|
3569
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3570
|
+
return;
|
|
3571
|
+
}
|
|
3572
|
+
}
|
|
3573
|
+
if (this.options.verifyClient) {
|
|
3574
|
+
const info = {
|
|
3575
|
+
origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
|
|
3576
|
+
secure: !!(req.socket.authorized || req.socket.encrypted),
|
|
3577
|
+
req
|
|
3578
|
+
};
|
|
3579
|
+
if (this.options.verifyClient.length === 2) {
|
|
3580
|
+
this.options.verifyClient(info, (verified, code, message, headers) => {
|
|
3581
|
+
if (!verified) {
|
|
3582
|
+
return abortHandshake(socket, code || 401, message, headers);
|
|
3583
|
+
}
|
|
3584
|
+
this.completeUpgrade(
|
|
3585
|
+
extensions,
|
|
3586
|
+
key,
|
|
3587
|
+
protocols,
|
|
3588
|
+
req,
|
|
3589
|
+
socket,
|
|
3590
|
+
head,
|
|
3591
|
+
cb
|
|
3592
|
+
);
|
|
3593
|
+
});
|
|
3594
|
+
return;
|
|
3595
|
+
}
|
|
3596
|
+
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
|
|
3597
|
+
}
|
|
3598
|
+
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
|
|
3599
|
+
}
|
|
3600
|
+
/**
|
|
3601
|
+
* Upgrade the connection to WebSocket.
|
|
3602
|
+
*
|
|
3603
|
+
* @param {Object} extensions The accepted extensions
|
|
3604
|
+
* @param {String} key The value of the `Sec-WebSocket-Key` header
|
|
3605
|
+
* @param {Set} protocols The subprotocols
|
|
3606
|
+
* @param {http.IncomingMessage} req The request object
|
|
3607
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
3608
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
3609
|
+
* @param {Function} cb Callback
|
|
3610
|
+
* @throws {Error} If called more than once with the same socket
|
|
3611
|
+
* @private
|
|
3612
|
+
*/
|
|
3613
|
+
completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
|
|
3614
|
+
if (!socket.readable || !socket.writable) return socket.destroy();
|
|
3615
|
+
if (socket[kWebSocket]) {
|
|
3616
|
+
throw new Error(
|
|
3617
|
+
"server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
|
|
3618
|
+
);
|
|
3619
|
+
}
|
|
3620
|
+
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
3621
|
+
const digest = createHash5("sha1").update(key + GUID).digest("base64");
|
|
3622
|
+
const headers = [
|
|
3623
|
+
"HTTP/1.1 101 Switching Protocols",
|
|
3624
|
+
"Upgrade: websocket",
|
|
3625
|
+
"Connection: Upgrade",
|
|
3626
|
+
`Sec-WebSocket-Accept: ${digest}`
|
|
3627
|
+
];
|
|
3628
|
+
const ws = new this.options.WebSocket(null, void 0, this.options);
|
|
3629
|
+
if (protocols.size) {
|
|
3630
|
+
const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
|
|
3631
|
+
if (protocol) {
|
|
3632
|
+
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
|
|
3633
|
+
ws._protocol = protocol;
|
|
3634
|
+
}
|
|
3635
|
+
}
|
|
3636
|
+
if (extensions[PerMessageDeflate2.extensionName]) {
|
|
3637
|
+
const params = extensions[PerMessageDeflate2.extensionName].params;
|
|
3638
|
+
const value = extension2.format({
|
|
3639
|
+
[PerMessageDeflate2.extensionName]: [params]
|
|
3640
|
+
});
|
|
3641
|
+
headers.push(`Sec-WebSocket-Extensions: ${value}`);
|
|
3642
|
+
ws._extensions = extensions;
|
|
3643
|
+
}
|
|
3644
|
+
this.emit("headers", headers, req);
|
|
3645
|
+
socket.write(headers.concat("\r\n").join("\r\n"));
|
|
3646
|
+
socket.removeListener("error", socketOnError);
|
|
3647
|
+
ws.setSocket(socket, head, {
|
|
3648
|
+
allowSynchronousEvents: this.options.allowSynchronousEvents,
|
|
3649
|
+
maxBufferedChunks: this.options.maxBufferedChunks,
|
|
3650
|
+
maxFragments: this.options.maxFragments,
|
|
3651
|
+
maxPayload: this.options.maxPayload,
|
|
3652
|
+
skipUTF8Validation: this.options.skipUTF8Validation
|
|
3653
|
+
});
|
|
3654
|
+
if (this.clients) {
|
|
3655
|
+
this.clients.add(ws);
|
|
3656
|
+
ws.on("close", () => {
|
|
3657
|
+
this.clients.delete(ws);
|
|
3658
|
+
if (this._shouldEmitClose && !this.clients.size) {
|
|
3659
|
+
process.nextTick(emitClose, this);
|
|
3660
|
+
}
|
|
3661
|
+
});
|
|
3662
|
+
}
|
|
3663
|
+
cb(ws, req);
|
|
3664
|
+
}
|
|
3665
|
+
};
|
|
3666
|
+
module.exports = WebSocketServer2;
|
|
3667
|
+
function addListeners(server, map) {
|
|
3668
|
+
for (const event of Object.keys(map)) server.on(event, map[event]);
|
|
3669
|
+
return function removeListeners() {
|
|
3670
|
+
for (const event of Object.keys(map)) {
|
|
3671
|
+
server.removeListener(event, map[event]);
|
|
3672
|
+
}
|
|
3673
|
+
};
|
|
3674
|
+
}
|
|
3675
|
+
function emitClose(server) {
|
|
3676
|
+
server._state = CLOSED;
|
|
3677
|
+
server.emit("close");
|
|
3678
|
+
}
|
|
3679
|
+
function socketOnError() {
|
|
3680
|
+
this.destroy();
|
|
3681
|
+
}
|
|
3682
|
+
function abortHandshake(socket, code, message, headers) {
|
|
3683
|
+
message = message || http.STATUS_CODES[code];
|
|
3684
|
+
headers = {
|
|
3685
|
+
Connection: "close",
|
|
3686
|
+
"Content-Type": "text/html",
|
|
3687
|
+
"Content-Length": Buffer.byteLength(message),
|
|
3688
|
+
...headers
|
|
3689
|
+
};
|
|
3690
|
+
socket.once("finish", socket.destroy);
|
|
3691
|
+
socket.end(
|
|
3692
|
+
`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
|
|
3693
|
+
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
|
|
3694
|
+
);
|
|
3695
|
+
}
|
|
3696
|
+
function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
|
|
3697
|
+
if (server.listenerCount("wsClientError")) {
|
|
3698
|
+
const err = new Error(message);
|
|
3699
|
+
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
|
|
3700
|
+
server.emit("wsClientError", err, socket, req);
|
|
3701
|
+
} else {
|
|
3702
|
+
abortHandshake(socket, code, message, headers);
|
|
3703
|
+
}
|
|
3704
|
+
}
|
|
3705
|
+
}
|
|
3706
|
+
});
|
|
2
3707
|
|
|
3
3708
|
// src/index.ts
|
|
4
3709
|
import { execFile as execFile2 } from "node:child_process";
|
|
@@ -18,36 +3723,138 @@ function normalizeServer(value) {
|
|
|
18
3723
|
url.pathname = url.pathname.replace(/\/$/, "");
|
|
19
3724
|
return url.toString().replace(/\/$/, "");
|
|
20
3725
|
}
|
|
21
|
-
function defaultWebSocketServer(server) {
|
|
22
|
-
const url = new URL(server);
|
|
23
|
-
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
24
|
-
url.
|
|
25
|
-
url.
|
|
26
|
-
url.
|
|
27
|
-
url.
|
|
28
|
-
|
|
3726
|
+
function defaultWebSocketServer(server) {
|
|
3727
|
+
const url = new URL(server);
|
|
3728
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
3729
|
+
url.pathname = "/graphql";
|
|
3730
|
+
url.search = "";
|
|
3731
|
+
url.hash = "";
|
|
3732
|
+
return url.toString();
|
|
3733
|
+
}
|
|
3734
|
+
async function loadConfig(path = configPath()) {
|
|
3735
|
+
try {
|
|
3736
|
+
const value = JSON.parse(await readFile(path, "utf8"));
|
|
3737
|
+
if (!value.server || !value.websocketServer || !value.agentId || !value.credential) {
|
|
3738
|
+
throw new Error("configuration is incomplete");
|
|
3739
|
+
}
|
|
3740
|
+
return value;
|
|
3741
|
+
} catch (error) {
|
|
3742
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
3743
|
+
throw new Error(`Agent is not enrolled (${path}): ${detail}`);
|
|
3744
|
+
}
|
|
3745
|
+
}
|
|
3746
|
+
async function saveConfig(config, path = configPath()) {
|
|
3747
|
+
await mkdir(dirname(path), { recursive: true, mode: 448 });
|
|
3748
|
+
const temporaryPath = `${path}.${process.pid}.tmp`;
|
|
3749
|
+
await writeFile(temporaryPath, `${JSON.stringify(config, null, 2)}
|
|
3750
|
+
`, {
|
|
3751
|
+
mode: 384
|
|
3752
|
+
});
|
|
3753
|
+
await chmod(temporaryPath, 384);
|
|
3754
|
+
await rename(temporaryPath, path);
|
|
3755
|
+
}
|
|
3756
|
+
|
|
3757
|
+
// ../agent-contract/src/index.ts
|
|
3758
|
+
var TUNNEL_NAME_PATTERN = "[A-Za-z0-9][A-Za-z0-9_-]{0,127}";
|
|
3759
|
+
var TUNNEL_NAME_REGEX = new RegExp(`^${TUNNEL_NAME_PATTERN}$`);
|
|
3760
|
+
var CCUSAGE_REPORT_JOB_KIND = "ccusage.report";
|
|
3761
|
+
var DEFAULT_AGENT_HEARTBEAT_INTERVAL_SECONDS = 15;
|
|
3762
|
+
var MIN_AGENT_HEARTBEAT_INTERVAL_SECONDS = 5;
|
|
3763
|
+
var MAX_AGENT_HEARTBEAT_INTERVAL_SECONDS = 300;
|
|
3764
|
+
var DEFAULT_AGENT_JOB_RECONCILIATION_INTERVAL_SECONDS = 15;
|
|
3765
|
+
var MIN_AGENT_JOB_RECONCILIATION_INTERVAL_SECONDS = 5;
|
|
3766
|
+
var MAX_AGENT_JOB_RECONCILIATION_INTERVAL_SECONDS = 3600;
|
|
3767
|
+
function objectValue(value, name) {
|
|
3768
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
3769
|
+
throw new Error(`${name} must be an object`);
|
|
3770
|
+
}
|
|
3771
|
+
return value;
|
|
3772
|
+
}
|
|
3773
|
+
function numericValue(value, name) {
|
|
3774
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
3775
|
+
throw new Error(`${name} must be a non-negative finite number`);
|
|
3776
|
+
}
|
|
3777
|
+
return value;
|
|
3778
|
+
}
|
|
3779
|
+
function stringValue(value, name) {
|
|
3780
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
3781
|
+
throw new Error(`${name} must be a non-empty string`);
|
|
3782
|
+
}
|
|
3783
|
+
return value;
|
|
3784
|
+
}
|
|
3785
|
+
function stringArray(value, name) {
|
|
3786
|
+
if (!Array.isArray(value)) throw new Error(`${name} must be an array`);
|
|
3787
|
+
return value.map((item, index) => stringValue(item, `${name}[${index}]`));
|
|
3788
|
+
}
|
|
3789
|
+
function tokenTotals(value, name) {
|
|
3790
|
+
return {
|
|
3791
|
+
inputTokens: numericValue(value.inputTokens, `${name}.inputTokens`),
|
|
3792
|
+
outputTokens: numericValue(value.outputTokens, `${name}.outputTokens`),
|
|
3793
|
+
cacheCreationTokens: numericValue(
|
|
3794
|
+
value.cacheCreationTokens,
|
|
3795
|
+
`${name}.cacheCreationTokens`
|
|
3796
|
+
),
|
|
3797
|
+
cacheReadTokens: numericValue(
|
|
3798
|
+
value.cacheReadTokens,
|
|
3799
|
+
`${name}.cacheReadTokens`
|
|
3800
|
+
),
|
|
3801
|
+
totalTokens: numericValue(value.totalTokens, `${name}.totalTokens`),
|
|
3802
|
+
totalCost: numericValue(value.totalCost, `${name}.totalCost`)
|
|
3803
|
+
};
|
|
3804
|
+
}
|
|
3805
|
+
function modelBreakdown(value, name) {
|
|
3806
|
+
const model = objectValue(value, name);
|
|
3807
|
+
return {
|
|
3808
|
+
modelName: stringValue(model.modelName, `${name}.modelName`),
|
|
3809
|
+
inputTokens: numericValue(model.inputTokens, `${name}.inputTokens`),
|
|
3810
|
+
outputTokens: numericValue(model.outputTokens, `${name}.outputTokens`),
|
|
3811
|
+
cacheCreationTokens: numericValue(
|
|
3812
|
+
model.cacheCreationTokens,
|
|
3813
|
+
`${name}.cacheCreationTokens`
|
|
3814
|
+
),
|
|
3815
|
+
cacheReadTokens: numericValue(
|
|
3816
|
+
model.cacheReadTokens,
|
|
3817
|
+
`${name}.cacheReadTokens`
|
|
3818
|
+
),
|
|
3819
|
+
cost: numericValue(model.cost, `${name}.cost`)
|
|
3820
|
+
};
|
|
29
3821
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
throw new Error(
|
|
3822
|
+
function dailyEntry(value, index) {
|
|
3823
|
+
const name = `ccusage.daily[${index}]`;
|
|
3824
|
+
const entry = objectValue(value, name);
|
|
3825
|
+
const metadata = objectValue(entry.metadata, `${name}.metadata`);
|
|
3826
|
+
if (!Array.isArray(entry.modelBreakdowns)) {
|
|
3827
|
+
throw new Error(`${name}.modelBreakdowns must be an array`);
|
|
3828
|
+
}
|
|
3829
|
+
const period = stringValue(entry.period, `${name}.period`);
|
|
3830
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(period)) {
|
|
3831
|
+
throw new Error(`${name}.period must use YYYY-MM-DD`);
|
|
40
3832
|
}
|
|
3833
|
+
return {
|
|
3834
|
+
...tokenTotals(entry, name),
|
|
3835
|
+
agent: stringValue(entry.agent, `${name}.agent`),
|
|
3836
|
+
period,
|
|
3837
|
+
metadata: {
|
|
3838
|
+
agents: stringArray(metadata.agents, `${name}.metadata.agents`)
|
|
3839
|
+
},
|
|
3840
|
+
modelBreakdowns: entry.modelBreakdowns.map(
|
|
3841
|
+
(model, modelIndex) => modelBreakdown(model, `${name}.modelBreakdowns[${modelIndex}]`)
|
|
3842
|
+
),
|
|
3843
|
+
modelsUsed: stringArray(entry.modelsUsed, `${name}.modelsUsed`)
|
|
3844
|
+
};
|
|
41
3845
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
3846
|
+
function parseCcusageReport(value) {
|
|
3847
|
+
const report = objectValue(value, "ccusage report");
|
|
3848
|
+
if (!Array.isArray(report.daily)) {
|
|
3849
|
+
throw new Error("ccusage.daily must be an array");
|
|
3850
|
+
}
|
|
3851
|
+
return {
|
|
3852
|
+
daily: report.daily.map((entry, index) => dailyEntry(entry, index)),
|
|
3853
|
+
totals: tokenTotals(
|
|
3854
|
+
objectValue(report.totals, "ccusage.totals"),
|
|
3855
|
+
"ccusage.totals"
|
|
3856
|
+
)
|
|
3857
|
+
};
|
|
51
3858
|
}
|
|
52
3859
|
|
|
53
3860
|
// src/graphql-client.ts
|
|
@@ -744,23 +4551,49 @@ function isWebSocket(val) {
|
|
|
744
4551
|
return typeof val === "function" && "constructor" in val && "CLOSED" in val && "CLOSING" in val && "CONNECTING" in val && "OPEN" in val;
|
|
745
4552
|
}
|
|
746
4553
|
|
|
4554
|
+
// ../../node_modules/ws/wrapper.mjs
|
|
4555
|
+
var import_stream = __toESM(require_stream(), 1);
|
|
4556
|
+
var import_extension = __toESM(require_extension(), 1);
|
|
4557
|
+
var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
|
|
4558
|
+
var import_receiver = __toESM(require_receiver(), 1);
|
|
4559
|
+
var import_sender = __toESM(require_sender(), 1);
|
|
4560
|
+
var import_subprotocol = __toESM(require_subprotocol(), 1);
|
|
4561
|
+
var import_websocket = __toESM(require_websocket(), 1);
|
|
4562
|
+
var import_websocket_server = __toESM(require_websocket_server(), 1);
|
|
4563
|
+
var wrapper_default = import_websocket.default;
|
|
4564
|
+
|
|
747
4565
|
// src/graphql-client.ts
|
|
4566
|
+
function mergeHeaders(custom, owned) {
|
|
4567
|
+
const ownedNames = new Set(
|
|
4568
|
+
Object.keys(owned).map((name) => name.toLowerCase())
|
|
4569
|
+
);
|
|
4570
|
+
return {
|
|
4571
|
+
...Object.fromEntries(
|
|
4572
|
+
Object.entries(custom).filter(
|
|
4573
|
+
([name]) => !ownedNames.has(name.toLowerCase())
|
|
4574
|
+
)
|
|
4575
|
+
),
|
|
4576
|
+
...owned
|
|
4577
|
+
};
|
|
4578
|
+
}
|
|
748
4579
|
var AgentGraphQLClient = class {
|
|
749
4580
|
server;
|
|
750
4581
|
credential;
|
|
751
4582
|
requestTimeoutMs;
|
|
752
|
-
|
|
4583
|
+
headers;
|
|
4584
|
+
constructor(server, credential = null, requestTimeoutMs = 1e4, headers = {}) {
|
|
753
4585
|
this.server = server.replace(/\/$/, "");
|
|
754
4586
|
this.credential = credential;
|
|
755
4587
|
this.requestTimeoutMs = requestTimeoutMs;
|
|
4588
|
+
this.headers = { ...headers };
|
|
756
4589
|
}
|
|
757
4590
|
async request(query, variables) {
|
|
758
4591
|
const response = await fetch(`${this.server}/api/graphql`, {
|
|
759
4592
|
method: "POST",
|
|
760
|
-
headers: {
|
|
4593
|
+
headers: mergeHeaders(this.headers, {
|
|
761
4594
|
"content-type": "application/json",
|
|
762
4595
|
...this.credential ? { authorization: `Bearer ${this.credential}` } : {}
|
|
763
|
-
},
|
|
4596
|
+
}),
|
|
764
4597
|
body: JSON.stringify({ query, variables }),
|
|
765
4598
|
signal: AbortSignal.timeout(this.requestTimeoutMs)
|
|
766
4599
|
});
|
|
@@ -833,6 +4666,21 @@ var AgentGraphQLClient = class {
|
|
|
833
4666
|
(job) => job.status === "QUEUED" || job.status === "RUNNING" || job.status === "CANCELLED"
|
|
834
4667
|
);
|
|
835
4668
|
}
|
|
4669
|
+
async cadenceSettings(agentId) {
|
|
4670
|
+
const data = await this.request(
|
|
4671
|
+
`query AgentCadenceSettings($agentId: ID!) {
|
|
4672
|
+
agentCadenceSettings(agentId: $agentId) {
|
|
4673
|
+
agentId
|
|
4674
|
+
codebaseScanIntervalSeconds
|
|
4675
|
+
jobReconciliationIntervalSeconds
|
|
4676
|
+
gitFetchIntervalSeconds
|
|
4677
|
+
heartbeatIntervalSeconds
|
|
4678
|
+
}
|
|
4679
|
+
}`,
|
|
4680
|
+
{ agentId }
|
|
4681
|
+
);
|
|
4682
|
+
return data.agentCadenceSettings;
|
|
4683
|
+
}
|
|
836
4684
|
async claimJob(jobId) {
|
|
837
4685
|
const data = await this.request(
|
|
838
4686
|
`mutation ClaimJob($jobId: ID!) {
|
|
@@ -884,12 +4732,12 @@ var AgentGraphQLClient = class {
|
|
|
884
4732
|
`${this.server}/api/build-artifact-uploads/${encodeURIComponent(input.uploadId)}`,
|
|
885
4733
|
{
|
|
886
4734
|
method: "POST",
|
|
887
|
-
headers: {
|
|
4735
|
+
headers: mergeHeaders(this.headers, {
|
|
888
4736
|
...this.credential ? { authorization: `Bearer ${this.credential}` } : {},
|
|
889
4737
|
"content-length": String(information.size),
|
|
890
4738
|
"content-type": input.contentType,
|
|
891
4739
|
"x-artifact-filename": encodeURIComponent(input.filename)
|
|
892
|
-
},
|
|
4740
|
+
}),
|
|
893
4741
|
body: Readable.toWeb(createReadStream(input.path)),
|
|
894
4742
|
duplex: "half"
|
|
895
4743
|
}
|
|
@@ -963,10 +4811,22 @@ var AgentGraphQLClient = class {
|
|
|
963
4811
|
);
|
|
964
4812
|
}
|
|
965
4813
|
};
|
|
4814
|
+
function agentWebSocketHeaders(config) {
|
|
4815
|
+
return mergeHeaders(config.headers ?? {}, {
|
|
4816
|
+
authorization: `Bearer ${config.credential}`
|
|
4817
|
+
});
|
|
4818
|
+
}
|
|
966
4819
|
function createAgentSubscriptionClient(config) {
|
|
4820
|
+
const headers = agentWebSocketHeaders(config);
|
|
4821
|
+
class AgentWebSocket extends wrapper_default {
|
|
4822
|
+
constructor(address, protocols) {
|
|
4823
|
+
super(address, protocols, { headers });
|
|
4824
|
+
}
|
|
4825
|
+
}
|
|
967
4826
|
return createClient({
|
|
968
4827
|
url: config.websocketServer,
|
|
969
4828
|
connectionParams: { authorization: `Bearer ${config.credential}` },
|
|
4829
|
+
webSocketImpl: AgentWebSocket,
|
|
970
4830
|
lazy: false,
|
|
971
4831
|
retryAttempts: Infinity,
|
|
972
4832
|
shouldRetry: () => true,
|
|
@@ -1031,103 +4891,6 @@ function subscribeToAgentEvents(client, agentId, onEvent) {
|
|
|
1031
4891
|
import { statfsSync } from "node:fs";
|
|
1032
4892
|
import { arch, cpus, freemem, hostname, release, totalmem } from "node:os";
|
|
1033
4893
|
|
|
1034
|
-
// ../agent-contract/src/index.ts
|
|
1035
|
-
var TUNNEL_NAME_PATTERN = "[A-Za-z0-9][A-Za-z0-9_-]{0,127}";
|
|
1036
|
-
var TUNNEL_NAME_REGEX = new RegExp(`^${TUNNEL_NAME_PATTERN}$`);
|
|
1037
|
-
var CCUSAGE_REPORT_JOB_KIND = "ccusage.report";
|
|
1038
|
-
function objectValue(value, name) {
|
|
1039
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
1040
|
-
throw new Error(`${name} must be an object`);
|
|
1041
|
-
}
|
|
1042
|
-
return value;
|
|
1043
|
-
}
|
|
1044
|
-
function numericValue(value, name) {
|
|
1045
|
-
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
1046
|
-
throw new Error(`${name} must be a non-negative finite number`);
|
|
1047
|
-
}
|
|
1048
|
-
return value;
|
|
1049
|
-
}
|
|
1050
|
-
function stringValue(value, name) {
|
|
1051
|
-
if (typeof value !== "string" || value.length === 0) {
|
|
1052
|
-
throw new Error(`${name} must be a non-empty string`);
|
|
1053
|
-
}
|
|
1054
|
-
return value;
|
|
1055
|
-
}
|
|
1056
|
-
function stringArray(value, name) {
|
|
1057
|
-
if (!Array.isArray(value)) throw new Error(`${name} must be an array`);
|
|
1058
|
-
return value.map((item, index) => stringValue(item, `${name}[${index}]`));
|
|
1059
|
-
}
|
|
1060
|
-
function tokenTotals(value, name) {
|
|
1061
|
-
return {
|
|
1062
|
-
inputTokens: numericValue(value.inputTokens, `${name}.inputTokens`),
|
|
1063
|
-
outputTokens: numericValue(value.outputTokens, `${name}.outputTokens`),
|
|
1064
|
-
cacheCreationTokens: numericValue(
|
|
1065
|
-
value.cacheCreationTokens,
|
|
1066
|
-
`${name}.cacheCreationTokens`
|
|
1067
|
-
),
|
|
1068
|
-
cacheReadTokens: numericValue(
|
|
1069
|
-
value.cacheReadTokens,
|
|
1070
|
-
`${name}.cacheReadTokens`
|
|
1071
|
-
),
|
|
1072
|
-
totalTokens: numericValue(value.totalTokens, `${name}.totalTokens`),
|
|
1073
|
-
totalCost: numericValue(value.totalCost, `${name}.totalCost`)
|
|
1074
|
-
};
|
|
1075
|
-
}
|
|
1076
|
-
function modelBreakdown(value, name) {
|
|
1077
|
-
const model = objectValue(value, name);
|
|
1078
|
-
return {
|
|
1079
|
-
modelName: stringValue(model.modelName, `${name}.modelName`),
|
|
1080
|
-
inputTokens: numericValue(model.inputTokens, `${name}.inputTokens`),
|
|
1081
|
-
outputTokens: numericValue(model.outputTokens, `${name}.outputTokens`),
|
|
1082
|
-
cacheCreationTokens: numericValue(
|
|
1083
|
-
model.cacheCreationTokens,
|
|
1084
|
-
`${name}.cacheCreationTokens`
|
|
1085
|
-
),
|
|
1086
|
-
cacheReadTokens: numericValue(
|
|
1087
|
-
model.cacheReadTokens,
|
|
1088
|
-
`${name}.cacheReadTokens`
|
|
1089
|
-
),
|
|
1090
|
-
cost: numericValue(model.cost, `${name}.cost`)
|
|
1091
|
-
};
|
|
1092
|
-
}
|
|
1093
|
-
function dailyEntry(value, index) {
|
|
1094
|
-
const name = `ccusage.daily[${index}]`;
|
|
1095
|
-
const entry = objectValue(value, name);
|
|
1096
|
-
const metadata = objectValue(entry.metadata, `${name}.metadata`);
|
|
1097
|
-
if (!Array.isArray(entry.modelBreakdowns)) {
|
|
1098
|
-
throw new Error(`${name}.modelBreakdowns must be an array`);
|
|
1099
|
-
}
|
|
1100
|
-
const period = stringValue(entry.period, `${name}.period`);
|
|
1101
|
-
if (!/^\d{4}-\d{2}-\d{2}$/.test(period)) {
|
|
1102
|
-
throw new Error(`${name}.period must use YYYY-MM-DD`);
|
|
1103
|
-
}
|
|
1104
|
-
return {
|
|
1105
|
-
...tokenTotals(entry, name),
|
|
1106
|
-
agent: stringValue(entry.agent, `${name}.agent`),
|
|
1107
|
-
period,
|
|
1108
|
-
metadata: {
|
|
1109
|
-
agents: stringArray(metadata.agents, `${name}.metadata.agents`)
|
|
1110
|
-
},
|
|
1111
|
-
modelBreakdowns: entry.modelBreakdowns.map(
|
|
1112
|
-
(model, modelIndex) => modelBreakdown(model, `${name}.modelBreakdowns[${modelIndex}]`)
|
|
1113
|
-
),
|
|
1114
|
-
modelsUsed: stringArray(entry.modelsUsed, `${name}.modelsUsed`)
|
|
1115
|
-
};
|
|
1116
|
-
}
|
|
1117
|
-
function parseCcusageReport(value) {
|
|
1118
|
-
const report = objectValue(value, "ccusage report");
|
|
1119
|
-
if (!Array.isArray(report.daily)) {
|
|
1120
|
-
throw new Error("ccusage.daily must be an array");
|
|
1121
|
-
}
|
|
1122
|
-
return {
|
|
1123
|
-
daily: report.daily.map((entry, index) => dailyEntry(entry, index)),
|
|
1124
|
-
totals: tokenTotals(
|
|
1125
|
-
objectValue(report.totals, "ccusage.totals"),
|
|
1126
|
-
"ccusage.totals"
|
|
1127
|
-
)
|
|
1128
|
-
};
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
4894
|
// ../agent-contract/src/build-data.ts
|
|
1132
4895
|
var BUILD_DATA_SCAN_JOB_KIND = "buildData.scan";
|
|
1133
4896
|
var BUILD_DATA_SIZE_JOB_KIND = "buildData.size";
|
|
@@ -6221,8 +9984,8 @@ async function inspectChanges(folder, timeoutMs, signal) {
|
|
|
6221
9984
|
return { changes: changes.slice(0, 500), truncated: changes.length > 500 };
|
|
6222
9985
|
}
|
|
6223
9986
|
function imagePath(path) {
|
|
6224
|
-
const
|
|
6225
|
-
return IMAGE_EXTENSIONS.has(
|
|
9987
|
+
const extension2 = path.slice(path.lastIndexOf(".")).toLocaleLowerCase();
|
|
9988
|
+
return IMAGE_EXTENSIONS.has(extension2);
|
|
6226
9989
|
}
|
|
6227
9990
|
function parseNameStatus(value) {
|
|
6228
9991
|
const entries = value.split("\0").filter(Boolean);
|
|
@@ -6621,7 +10384,7 @@ var inspectWorktreeDiff = async (payload, timeoutMs, signal) => {
|
|
|
6621
10384
|
};
|
|
6622
10385
|
};
|
|
6623
10386
|
function imageContentType(path) {
|
|
6624
|
-
const
|
|
10387
|
+
const extension2 = path.slice(path.lastIndexOf(".")).toLocaleLowerCase();
|
|
6625
10388
|
return {
|
|
6626
10389
|
".png": "image/png",
|
|
6627
10390
|
".jpg": "image/jpeg",
|
|
@@ -6630,7 +10393,7 @@ function imageContentType(path) {
|
|
|
6630
10393
|
".webp": "image/webp",
|
|
6631
10394
|
".avif": "image/avif",
|
|
6632
10395
|
".bmp": "image/bmp"
|
|
6633
|
-
}[
|
|
10396
|
+
}[extension2] ?? "application/octet-stream";
|
|
6634
10397
|
}
|
|
6635
10398
|
async function writeGitObject(folder, specification, destination, timeoutMs, signal) {
|
|
6636
10399
|
await new Promise((resolvePromise, rejectPromise) => {
|
|
@@ -10373,13 +14136,25 @@ var CodebaseMonitor = class {
|
|
|
10373
14136
|
};
|
|
10374
14137
|
|
|
10375
14138
|
// src/agent-runtime.ts
|
|
10376
|
-
|
|
14139
|
+
function configuredIntervalMs(value, fallbackSeconds, minSeconds, maxSeconds) {
|
|
14140
|
+
return (Number.isInteger(value) && value >= minSeconds && value <= maxSeconds ? value : fallbackSeconds) * 1e3;
|
|
14141
|
+
}
|
|
10377
14142
|
async function runAgent(config, signal) {
|
|
10378
|
-
const client = new AgentGraphQLClient(
|
|
14143
|
+
const client = new AgentGraphQLClient(
|
|
14144
|
+
config.server,
|
|
14145
|
+
config.credential,
|
|
14146
|
+
1e4,
|
|
14147
|
+
config.headers
|
|
14148
|
+
);
|
|
10379
14149
|
const repositoryCoordinator = new RepositoryCoordinator();
|
|
10380
14150
|
const executor = new JobExecutor(client, repositoryCoordinator);
|
|
10381
14151
|
const codebaseMonitor = new CodebaseMonitor(client, repositoryCoordinator);
|
|
10382
|
-
let
|
|
14152
|
+
let heartbeatIntervalMs = DEFAULT_AGENT_HEARTBEAT_INTERVAL_SECONDS * 1e3;
|
|
14153
|
+
let jobReconciliationIntervalMs = DEFAULT_AGENT_JOB_RECONCILIATION_INTERVAL_SECONDS * 1e3;
|
|
14154
|
+
let heartbeatRunning = false;
|
|
14155
|
+
let jobReconciliationRunning = false;
|
|
14156
|
+
let heartbeatTimer;
|
|
14157
|
+
let jobReconciliationTimer;
|
|
10383
14158
|
let codebaseTimer;
|
|
10384
14159
|
let startupRecoveryPending = true;
|
|
10385
14160
|
const interruptedJobs = /* @__PURE__ */ new Set();
|
|
@@ -10423,23 +14198,72 @@ async function runAgent(config, signal) {
|
|
|
10423
14198
|
);
|
|
10424
14199
|
return true;
|
|
10425
14200
|
};
|
|
14201
|
+
const refreshCadence = async () => {
|
|
14202
|
+
try {
|
|
14203
|
+
const settings = await client.cadenceSettings(config.agentId);
|
|
14204
|
+
heartbeatIntervalMs = configuredIntervalMs(
|
|
14205
|
+
settings.heartbeatIntervalSeconds,
|
|
14206
|
+
DEFAULT_AGENT_HEARTBEAT_INTERVAL_SECONDS,
|
|
14207
|
+
MIN_AGENT_HEARTBEAT_INTERVAL_SECONDS,
|
|
14208
|
+
MAX_AGENT_HEARTBEAT_INTERVAL_SECONDS
|
|
14209
|
+
);
|
|
14210
|
+
jobReconciliationIntervalMs = configuredIntervalMs(
|
|
14211
|
+
settings.jobReconciliationIntervalSeconds,
|
|
14212
|
+
DEFAULT_AGENT_JOB_RECONCILIATION_INTERVAL_SECONDS,
|
|
14213
|
+
MIN_AGENT_JOB_RECONCILIATION_INTERVAL_SECONDS,
|
|
14214
|
+
MAX_AGENT_JOB_RECONCILIATION_INTERVAL_SECONDS
|
|
14215
|
+
);
|
|
14216
|
+
} catch (error) {
|
|
14217
|
+
console.error(
|
|
14218
|
+
"Agent cadence configuration failed:",
|
|
14219
|
+
error instanceof Error ? error.message : error
|
|
14220
|
+
);
|
|
14221
|
+
}
|
|
14222
|
+
};
|
|
14223
|
+
const scheduleHeartbeat = () => {
|
|
14224
|
+
if (heartbeatTimer) clearTimeout(heartbeatTimer);
|
|
14225
|
+
if (!signal.aborted) {
|
|
14226
|
+
heartbeatTimer = setTimeout(() => void heartbeat(), heartbeatIntervalMs);
|
|
14227
|
+
}
|
|
14228
|
+
};
|
|
10426
14229
|
const heartbeat = async () => {
|
|
10427
|
-
if (
|
|
10428
|
-
|
|
14230
|
+
if (heartbeatRunning) return;
|
|
14231
|
+
heartbeatRunning = true;
|
|
14232
|
+
if (heartbeatTimer) clearTimeout(heartbeatTimer);
|
|
14233
|
+
heartbeatTimer = void 0;
|
|
14234
|
+
try {
|
|
14235
|
+
await client.heartbeat(collectInventory());
|
|
14236
|
+
} catch (error) {
|
|
14237
|
+
console.error(
|
|
14238
|
+
"Heartbeat failed:",
|
|
14239
|
+
error instanceof Error ? error.message : error
|
|
14240
|
+
);
|
|
14241
|
+
} finally {
|
|
14242
|
+
heartbeatRunning = false;
|
|
14243
|
+
scheduleHeartbeat();
|
|
14244
|
+
}
|
|
14245
|
+
};
|
|
14246
|
+
const scheduleJobReconciliation = () => {
|
|
14247
|
+
if (jobReconciliationTimer) clearTimeout(jobReconciliationTimer);
|
|
14248
|
+
if (!signal.aborted) {
|
|
14249
|
+
jobReconciliationTimer = setTimeout(
|
|
14250
|
+
() => void runJobReconciliation(),
|
|
14251
|
+
jobReconciliationIntervalMs
|
|
14252
|
+
);
|
|
14253
|
+
}
|
|
14254
|
+
};
|
|
14255
|
+
const runJobReconciliation = async () => {
|
|
14256
|
+
if (jobReconciliationRunning) return;
|
|
14257
|
+
jobReconciliationRunning = true;
|
|
14258
|
+
if (jobReconciliationTimer) clearTimeout(jobReconciliationTimer);
|
|
14259
|
+
jobReconciliationTimer = void 0;
|
|
10429
14260
|
try {
|
|
10430
|
-
try {
|
|
10431
|
-
await client.heartbeat(collectInventory());
|
|
10432
|
-
} catch (error) {
|
|
10433
|
-
console.error(
|
|
10434
|
-
"Heartbeat failed:",
|
|
10435
|
-
error instanceof Error ? error.message : error
|
|
10436
|
-
);
|
|
10437
|
-
}
|
|
10438
14261
|
if (await reconcileJobs(startupRecoveryPending)) {
|
|
10439
14262
|
startupRecoveryPending = false;
|
|
10440
14263
|
}
|
|
10441
14264
|
} finally {
|
|
10442
|
-
|
|
14265
|
+
jobReconciliationRunning = false;
|
|
14266
|
+
scheduleJobReconciliation();
|
|
10443
14267
|
}
|
|
10444
14268
|
};
|
|
10445
14269
|
let codebaseReconciling = false;
|
|
@@ -10479,7 +14303,9 @@ async function runAgent(config, signal) {
|
|
|
10479
14303
|
codebaseTimer = void 0;
|
|
10480
14304
|
void reconcileCodebases();
|
|
10481
14305
|
};
|
|
14306
|
+
await refreshCadence();
|
|
10482
14307
|
await heartbeat();
|
|
14308
|
+
await runJobReconciliation();
|
|
10483
14309
|
void reconcileCodebases();
|
|
10484
14310
|
const subscriptionClient = createAgentSubscriptionClient(config);
|
|
10485
14311
|
const unsubscribe = subscribeToAgentEvents(
|
|
@@ -10489,20 +14315,23 @@ async function runAgent(config, signal) {
|
|
|
10489
14315
|
if (event.type === "JOB_AVAILABLE") executor.execute(event.job);
|
|
10490
14316
|
else if (event.type === "JOB_CANCEL_REQUESTED") {
|
|
10491
14317
|
executor.cancel(event.job.id);
|
|
10492
|
-
} else {
|
|
14318
|
+
} else if (event.type === "CODEBASE_RECONCILE_REQUESTED") {
|
|
10493
14319
|
requestCodebaseReconcile();
|
|
14320
|
+
} else {
|
|
14321
|
+
void refreshCadence().then(() => {
|
|
14322
|
+
scheduleHeartbeat();
|
|
14323
|
+
scheduleJobReconciliation();
|
|
14324
|
+
requestCodebaseReconcile();
|
|
14325
|
+
});
|
|
10494
14326
|
}
|
|
10495
14327
|
}
|
|
10496
14328
|
);
|
|
10497
|
-
const heartbeatTimer = setInterval(
|
|
10498
|
-
() => void heartbeat(),
|
|
10499
|
-
HEARTBEAT_INTERVAL_MS
|
|
10500
|
-
);
|
|
10501
14329
|
await new Promise((resolve6) => {
|
|
10502
14330
|
if (signal.aborted) resolve6();
|
|
10503
14331
|
else signal.addEventListener("abort", () => resolve6(), { once: true });
|
|
10504
14332
|
});
|
|
10505
|
-
|
|
14333
|
+
if (heartbeatTimer) clearTimeout(heartbeatTimer);
|
|
14334
|
+
if (jobReconciliationTimer) clearTimeout(jobReconciliationTimer);
|
|
10506
14335
|
if (codebaseTimer) clearTimeout(codebaseTimer);
|
|
10507
14336
|
unsubscribe();
|
|
10508
14337
|
await subscriptionClient.dispose();
|
|
@@ -10611,47 +14440,81 @@ async function runDevelopmentAgent(options, signal) {
|
|
|
10611
14440
|
await runAgent(config, signal);
|
|
10612
14441
|
}
|
|
10613
14442
|
|
|
14443
|
+
// src/request-headers.ts
|
|
14444
|
+
function parseRequestHeader(value) {
|
|
14445
|
+
const separator = value.indexOf(":");
|
|
14446
|
+
if (separator <= 0) {
|
|
14447
|
+
throw new Error('--header must use the format "Name: value"');
|
|
14448
|
+
}
|
|
14449
|
+
const name = value.slice(0, separator).trim();
|
|
14450
|
+
const headerValue = value.slice(separator + 1).trim();
|
|
14451
|
+
if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) {
|
|
14452
|
+
throw new Error(`Invalid HTTP header name: ${name || "(empty)"}`);
|
|
14453
|
+
}
|
|
14454
|
+
if (!headerValue || /[^\t\x20-\x7e\x80-\xff]/.test(headerValue)) {
|
|
14455
|
+
throw new Error(`Invalid value for HTTP header ${name}`);
|
|
14456
|
+
}
|
|
14457
|
+
return [name, headerValue];
|
|
14458
|
+
}
|
|
14459
|
+
function requestHeaders(values) {
|
|
14460
|
+
const headers = {};
|
|
14461
|
+
for (const value of values) {
|
|
14462
|
+
const [name, headerValue] = parseRequestHeader(value);
|
|
14463
|
+
headers[name] = headerValue;
|
|
14464
|
+
}
|
|
14465
|
+
return headers;
|
|
14466
|
+
}
|
|
14467
|
+
function redactedRequestHeaders(headers) {
|
|
14468
|
+
return Object.fromEntries(
|
|
14469
|
+
Object.keys(headers ?? {}).map((name) => [name, "[redacted]"])
|
|
14470
|
+
);
|
|
14471
|
+
}
|
|
14472
|
+
|
|
10614
14473
|
// src/index.ts
|
|
10615
14474
|
var execFileAsync = promisify2(execFile2);
|
|
10616
14475
|
function flags(args) {
|
|
10617
14476
|
const result = {};
|
|
14477
|
+
const headerValues = [];
|
|
10618
14478
|
for (let index = 0; index < args.length; index += 1) {
|
|
10619
14479
|
const argument = args[index];
|
|
10620
14480
|
if (!argument.startsWith("--")) continue;
|
|
10621
14481
|
const value = args[index + 1];
|
|
10622
14482
|
if (!value || value.startsWith("--"))
|
|
10623
14483
|
throw new Error(`Missing value for ${argument}`);
|
|
10624
|
-
|
|
14484
|
+
if (argument === "--header") headerValues.push(value);
|
|
14485
|
+
else result[argument.slice(2)] = value;
|
|
10625
14486
|
index += 1;
|
|
10626
14487
|
}
|
|
10627
|
-
return result;
|
|
14488
|
+
return { values: result, headers: requestHeaders(headerValues) };
|
|
10628
14489
|
}
|
|
10629
14490
|
function usage() {
|
|
10630
14491
|
console.log(`control-agent <command>
|
|
10631
14492
|
|
|
10632
14493
|
Commands:
|
|
10633
|
-
enroll --enrollment-token <token> [--server http://127.0.0.1:3090] [--websocket-server ws://127.0.0.1:
|
|
14494
|
+
enroll --enrollment-token <token> [--server http://127.0.0.1:3090] [--websocket-server ws://127.0.0.1:3090/graphql] [--name <name>] [--header "Name: value"]...
|
|
10634
14495
|
dev [--server http://127.0.0.1:3000] [--websocket-server ws://127.0.0.1:3092/graphql] [--name <name>]
|
|
10635
14496
|
run
|
|
10636
14497
|
status
|
|
10637
14498
|
doctor`);
|
|
10638
14499
|
}
|
|
10639
14500
|
async function enroll(args) {
|
|
10640
|
-
const
|
|
14501
|
+
const parsed = flags(args);
|
|
14502
|
+
const options = parsed.values;
|
|
10641
14503
|
const enrollmentToken = options["enrollment-token"];
|
|
10642
14504
|
if (!enrollmentToken) throw new Error("--enrollment-token is required");
|
|
10643
14505
|
const server = normalizeServer(options.server ?? "http://127.0.0.1:3090");
|
|
10644
14506
|
const websocketServer = options["websocket-server"] ?? defaultWebSocketServer(server);
|
|
10645
14507
|
const inventory = collectInventory();
|
|
10646
14508
|
const name = options.name ?? inventory.hostname;
|
|
10647
|
-
const client = new AgentGraphQLClient(server);
|
|
14509
|
+
const client = new AgentGraphQLClient(server, null, 1e4, parsed.headers);
|
|
10648
14510
|
const response = await client.enroll({ ...inventory, enrollmentToken, name });
|
|
10649
14511
|
await saveConfig({
|
|
10650
14512
|
server,
|
|
10651
14513
|
websocketServer,
|
|
10652
14514
|
agentId: response.enrollAgent.agent.id,
|
|
10653
14515
|
credential: response.enrollAgent.credential,
|
|
10654
|
-
name
|
|
14516
|
+
name,
|
|
14517
|
+
headers: parsed.headers
|
|
10655
14518
|
});
|
|
10656
14519
|
console.log(`Enrolled agent ${name} (${response.enrollAgent.agent.id})`);
|
|
10657
14520
|
}
|
|
@@ -10659,12 +14522,18 @@ async function status() {
|
|
|
10659
14522
|
const config = await loadConfig();
|
|
10660
14523
|
const response = await new AgentGraphQLClient(
|
|
10661
14524
|
config.server,
|
|
10662
|
-
config.credential
|
|
14525
|
+
config.credential,
|
|
14526
|
+
1e4,
|
|
14527
|
+
config.headers
|
|
10663
14528
|
).self();
|
|
10664
14529
|
console.log(
|
|
10665
14530
|
JSON.stringify(
|
|
10666
14531
|
{
|
|
10667
|
-
config: {
|
|
14532
|
+
config: {
|
|
14533
|
+
...config,
|
|
14534
|
+
credential: "[redacted]",
|
|
14535
|
+
headers: redactedRequestHeaders(config.headers)
|
|
14536
|
+
},
|
|
10668
14537
|
agent: response.agentSelf
|
|
10669
14538
|
},
|
|
10670
14539
|
null,
|
|
@@ -10687,7 +14556,12 @@ async function doctor() {
|
|
|
10687
14556
|
}
|
|
10688
14557
|
try {
|
|
10689
14558
|
const server = config?.server ?? "http://127.0.0.1:3090";
|
|
10690
|
-
const health = await new AgentGraphQLClient(
|
|
14559
|
+
const health = await new AgentGraphQLClient(
|
|
14560
|
+
server,
|
|
14561
|
+
null,
|
|
14562
|
+
1e4,
|
|
14563
|
+
config?.headers
|
|
14564
|
+
).health();
|
|
10691
14565
|
checks.push({
|
|
10692
14566
|
check: "control plane",
|
|
10693
14567
|
ok: health.health === "ok",
|
|
@@ -10736,7 +14610,7 @@ async function main() {
|
|
|
10736
14610
|
process.once("SIGINT", () => controller.abort());
|
|
10737
14611
|
process.once("SIGTERM", () => controller.abort());
|
|
10738
14612
|
if (command3 === "dev") {
|
|
10739
|
-
const options = flags(args);
|
|
14613
|
+
const options = flags(args).values;
|
|
10740
14614
|
const server = options.server ?? process.env.CONTROL_AGENT_DEV_SERVER ?? `http://127.0.0.1:${process.env.PORT ?? "3000"}`;
|
|
10741
14615
|
return runDevelopmentAgent(
|
|
10742
14616
|
{
|