@lesscap/baton-cli 0.3.2 → 0.4.0
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/baton.mjs +4198 -105
- package/package.json +6 -3
package/dist/baton.mjs
CHANGED
|
@@ -1,4 +1,3714 @@
|
|
|
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
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
16
|
+
};
|
|
17
|
+
var __copyProps = (to, from, except, desc) => {
|
|
18
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
19
|
+
for (let key of __getOwnPropNames(from))
|
|
20
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
21
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
22
|
+
}
|
|
23
|
+
return to;
|
|
24
|
+
};
|
|
25
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
26
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
27
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
28
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
29
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
30
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
31
|
+
mod
|
|
32
|
+
));
|
|
33
|
+
|
|
34
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/constants.js
|
|
35
|
+
var require_constants = __commonJS({
|
|
36
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/constants.js"(exports, module) {
|
|
37
|
+
"use strict";
|
|
38
|
+
var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
|
|
39
|
+
var hasBlob = typeof Blob !== "undefined";
|
|
40
|
+
if (hasBlob) BINARY_TYPES.push("blob");
|
|
41
|
+
module.exports = {
|
|
42
|
+
BINARY_TYPES,
|
|
43
|
+
CLOSE_TIMEOUT: 3e4,
|
|
44
|
+
EMPTY_BUFFER: Buffer.alloc(0),
|
|
45
|
+
GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
|
|
46
|
+
hasBlob,
|
|
47
|
+
kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
|
|
48
|
+
kListener: /* @__PURE__ */ Symbol("kListener"),
|
|
49
|
+
kStatusCode: /* @__PURE__ */ Symbol("status-code"),
|
|
50
|
+
kWebSocket: /* @__PURE__ */ Symbol("websocket"),
|
|
51
|
+
NOOP: () => {
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/buffer-util.js
|
|
58
|
+
var require_buffer_util = __commonJS({
|
|
59
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/buffer-util.js"(exports, module) {
|
|
60
|
+
"use strict";
|
|
61
|
+
var { EMPTY_BUFFER } = require_constants();
|
|
62
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
63
|
+
function concat(list, totalLength) {
|
|
64
|
+
if (list.length === 0) return EMPTY_BUFFER;
|
|
65
|
+
if (list.length === 1) return list[0];
|
|
66
|
+
const target = Buffer.allocUnsafe(totalLength);
|
|
67
|
+
let offset = 0;
|
|
68
|
+
for (let i = 0; i < list.length; i++) {
|
|
69
|
+
const buf = list[i];
|
|
70
|
+
target.set(buf, offset);
|
|
71
|
+
offset += buf.length;
|
|
72
|
+
}
|
|
73
|
+
if (offset < totalLength) {
|
|
74
|
+
return new FastBuffer(target.buffer, target.byteOffset, offset);
|
|
75
|
+
}
|
|
76
|
+
return target;
|
|
77
|
+
}
|
|
78
|
+
function _mask(source, mask, output, offset, length) {
|
|
79
|
+
for (let i = 0; i < length; i++) {
|
|
80
|
+
output[offset + i] = source[i] ^ mask[i & 3];
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function _unmask(buffer, mask) {
|
|
84
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
85
|
+
buffer[i] ^= mask[i & 3];
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function toArrayBuffer(buf) {
|
|
89
|
+
if (buf.length === buf.buffer.byteLength) {
|
|
90
|
+
return buf.buffer;
|
|
91
|
+
}
|
|
92
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
|
|
93
|
+
}
|
|
94
|
+
function toBuffer(data) {
|
|
95
|
+
toBuffer.readOnly = true;
|
|
96
|
+
if (Buffer.isBuffer(data)) return data;
|
|
97
|
+
let buf;
|
|
98
|
+
if (data instanceof ArrayBuffer) {
|
|
99
|
+
buf = new FastBuffer(data);
|
|
100
|
+
} else if (ArrayBuffer.isView(data)) {
|
|
101
|
+
buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
|
|
102
|
+
} else {
|
|
103
|
+
buf = Buffer.from(data);
|
|
104
|
+
toBuffer.readOnly = false;
|
|
105
|
+
}
|
|
106
|
+
return buf;
|
|
107
|
+
}
|
|
108
|
+
module.exports = {
|
|
109
|
+
concat,
|
|
110
|
+
mask: _mask,
|
|
111
|
+
toArrayBuffer,
|
|
112
|
+
toBuffer,
|
|
113
|
+
unmask: _unmask
|
|
114
|
+
};
|
|
115
|
+
if (!process.env.WS_NO_BUFFER_UTIL) {
|
|
116
|
+
try {
|
|
117
|
+
const bufferUtil = __require("bufferutil");
|
|
118
|
+
module.exports.mask = function(source, mask, output, offset, length) {
|
|
119
|
+
if (length < 48) _mask(source, mask, output, offset, length);
|
|
120
|
+
else bufferUtil.mask(source, mask, output, offset, length);
|
|
121
|
+
};
|
|
122
|
+
module.exports.unmask = function(buffer, mask) {
|
|
123
|
+
if (buffer.length < 32) _unmask(buffer, mask);
|
|
124
|
+
else bufferUtil.unmask(buffer, mask);
|
|
125
|
+
};
|
|
126
|
+
} catch (e) {
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/limiter.js
|
|
133
|
+
var require_limiter = __commonJS({
|
|
134
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/limiter.js"(exports, module) {
|
|
135
|
+
"use strict";
|
|
136
|
+
var kDone = /* @__PURE__ */ Symbol("kDone");
|
|
137
|
+
var kRun = /* @__PURE__ */ Symbol("kRun");
|
|
138
|
+
var Limiter = class {
|
|
139
|
+
/**
|
|
140
|
+
* Creates a new `Limiter`.
|
|
141
|
+
*
|
|
142
|
+
* @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
|
|
143
|
+
* to run concurrently
|
|
144
|
+
*/
|
|
145
|
+
constructor(concurrency) {
|
|
146
|
+
this[kDone] = () => {
|
|
147
|
+
this.pending--;
|
|
148
|
+
this[kRun]();
|
|
149
|
+
};
|
|
150
|
+
this.concurrency = concurrency || Infinity;
|
|
151
|
+
this.jobs = [];
|
|
152
|
+
this.pending = 0;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Adds a job to the queue.
|
|
156
|
+
*
|
|
157
|
+
* @param {Function} job The job to run
|
|
158
|
+
* @public
|
|
159
|
+
*/
|
|
160
|
+
add(job) {
|
|
161
|
+
this.jobs.push(job);
|
|
162
|
+
this[kRun]();
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Removes a job from the queue and runs it if possible.
|
|
166
|
+
*
|
|
167
|
+
* @private
|
|
168
|
+
*/
|
|
169
|
+
[kRun]() {
|
|
170
|
+
if (this.pending === this.concurrency) return;
|
|
171
|
+
if (this.jobs.length) {
|
|
172
|
+
const job = this.jobs.shift();
|
|
173
|
+
this.pending++;
|
|
174
|
+
job(this[kDone]);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
module.exports = Limiter;
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/permessage-deflate.js
|
|
183
|
+
var require_permessage_deflate = __commonJS({
|
|
184
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
|
|
185
|
+
"use strict";
|
|
186
|
+
var zlib = __require("zlib");
|
|
187
|
+
var bufferUtil = require_buffer_util();
|
|
188
|
+
var Limiter = require_limiter();
|
|
189
|
+
var { kStatusCode } = require_constants();
|
|
190
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
191
|
+
var TRAILER = Buffer.from([0, 0, 255, 255]);
|
|
192
|
+
var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
|
|
193
|
+
var kTotalLength = /* @__PURE__ */ Symbol("total-length");
|
|
194
|
+
var kCallback = /* @__PURE__ */ Symbol("callback");
|
|
195
|
+
var kBuffers = /* @__PURE__ */ Symbol("buffers");
|
|
196
|
+
var kError = /* @__PURE__ */ Symbol("error");
|
|
197
|
+
var zlibLimiter;
|
|
198
|
+
var PerMessageDeflate2 = class {
|
|
199
|
+
/**
|
|
200
|
+
* Creates a PerMessageDeflate instance.
|
|
201
|
+
*
|
|
202
|
+
* @param {Object} [options] Configuration options
|
|
203
|
+
* @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
|
|
204
|
+
* for, or request, a custom client window size
|
|
205
|
+
* @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
|
|
206
|
+
* acknowledge disabling of client context takeover
|
|
207
|
+
* @param {Number} [options.concurrencyLimit=10] The number of concurrent
|
|
208
|
+
* calls to zlib
|
|
209
|
+
* @param {Boolean} [options.isServer=false] Create the instance in either
|
|
210
|
+
* server or client mode
|
|
211
|
+
* @param {Number} [options.maxPayload=0] The maximum allowed message length
|
|
212
|
+
* @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
|
|
213
|
+
* use of a custom server window size
|
|
214
|
+
* @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
|
|
215
|
+
* disabling of server context takeover
|
|
216
|
+
* @param {Number} [options.threshold=1024] Size (in bytes) below which
|
|
217
|
+
* messages should not be compressed if context takeover is disabled
|
|
218
|
+
* @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
|
|
219
|
+
* deflate
|
|
220
|
+
* @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
|
|
221
|
+
* inflate
|
|
222
|
+
*/
|
|
223
|
+
constructor(options) {
|
|
224
|
+
this._options = options || {};
|
|
225
|
+
this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
|
|
226
|
+
this._maxPayload = this._options.maxPayload | 0;
|
|
227
|
+
this._isServer = !!this._options.isServer;
|
|
228
|
+
this._deflate = null;
|
|
229
|
+
this._inflate = null;
|
|
230
|
+
this.params = null;
|
|
231
|
+
if (!zlibLimiter) {
|
|
232
|
+
const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
|
|
233
|
+
zlibLimiter = new Limiter(concurrency);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* @type {String}
|
|
238
|
+
*/
|
|
239
|
+
static get extensionName() {
|
|
240
|
+
return "permessage-deflate";
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Create an extension negotiation offer.
|
|
244
|
+
*
|
|
245
|
+
* @return {Object} Extension parameters
|
|
246
|
+
* @public
|
|
247
|
+
*/
|
|
248
|
+
offer() {
|
|
249
|
+
const params = {};
|
|
250
|
+
if (this._options.serverNoContextTakeover) {
|
|
251
|
+
params.server_no_context_takeover = true;
|
|
252
|
+
}
|
|
253
|
+
if (this._options.clientNoContextTakeover) {
|
|
254
|
+
params.client_no_context_takeover = true;
|
|
255
|
+
}
|
|
256
|
+
if (this._options.serverMaxWindowBits) {
|
|
257
|
+
params.server_max_window_bits = this._options.serverMaxWindowBits;
|
|
258
|
+
}
|
|
259
|
+
if (this._options.clientMaxWindowBits) {
|
|
260
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
261
|
+
} else if (this._options.clientMaxWindowBits == null) {
|
|
262
|
+
params.client_max_window_bits = true;
|
|
263
|
+
}
|
|
264
|
+
return params;
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Accept an extension negotiation offer/response.
|
|
268
|
+
*
|
|
269
|
+
* @param {Array} configurations The extension negotiation offers/reponse
|
|
270
|
+
* @return {Object} Accepted configuration
|
|
271
|
+
* @public
|
|
272
|
+
*/
|
|
273
|
+
accept(configurations) {
|
|
274
|
+
configurations = this.normalizeParams(configurations);
|
|
275
|
+
this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
|
|
276
|
+
return this.params;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Releases all resources used by the extension.
|
|
280
|
+
*
|
|
281
|
+
* @public
|
|
282
|
+
*/
|
|
283
|
+
cleanup() {
|
|
284
|
+
if (this._inflate) {
|
|
285
|
+
this._inflate.close();
|
|
286
|
+
this._inflate = null;
|
|
287
|
+
}
|
|
288
|
+
if (this._deflate) {
|
|
289
|
+
const callback = this._deflate[kCallback];
|
|
290
|
+
this._deflate.close();
|
|
291
|
+
this._deflate = null;
|
|
292
|
+
if (callback) {
|
|
293
|
+
callback(
|
|
294
|
+
new Error(
|
|
295
|
+
"The deflate stream was closed while data was being processed"
|
|
296
|
+
)
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Accept an extension negotiation offer.
|
|
303
|
+
*
|
|
304
|
+
* @param {Array} offers The extension negotiation offers
|
|
305
|
+
* @return {Object} Accepted configuration
|
|
306
|
+
* @private
|
|
307
|
+
*/
|
|
308
|
+
acceptAsServer(offers) {
|
|
309
|
+
const opts = this._options;
|
|
310
|
+
const accepted = offers.find((params) => {
|
|
311
|
+
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) {
|
|
312
|
+
return false;
|
|
313
|
+
}
|
|
314
|
+
return true;
|
|
315
|
+
});
|
|
316
|
+
if (!accepted) {
|
|
317
|
+
throw new Error("None of the extension offers can be accepted");
|
|
318
|
+
}
|
|
319
|
+
if (opts.serverNoContextTakeover) {
|
|
320
|
+
accepted.server_no_context_takeover = true;
|
|
321
|
+
}
|
|
322
|
+
if (opts.clientNoContextTakeover) {
|
|
323
|
+
accepted.client_no_context_takeover = true;
|
|
324
|
+
}
|
|
325
|
+
if (typeof opts.serverMaxWindowBits === "number") {
|
|
326
|
+
accepted.server_max_window_bits = opts.serverMaxWindowBits;
|
|
327
|
+
}
|
|
328
|
+
if (typeof opts.clientMaxWindowBits === "number") {
|
|
329
|
+
accepted.client_max_window_bits = opts.clientMaxWindowBits;
|
|
330
|
+
} else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
|
|
331
|
+
delete accepted.client_max_window_bits;
|
|
332
|
+
}
|
|
333
|
+
return accepted;
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Accept the extension negotiation response.
|
|
337
|
+
*
|
|
338
|
+
* @param {Array} response The extension negotiation response
|
|
339
|
+
* @return {Object} Accepted configuration
|
|
340
|
+
* @private
|
|
341
|
+
*/
|
|
342
|
+
acceptAsClient(response) {
|
|
343
|
+
const params = response[0];
|
|
344
|
+
if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
|
|
345
|
+
throw new Error('Unexpected parameter "client_no_context_takeover"');
|
|
346
|
+
}
|
|
347
|
+
if (!params.client_max_window_bits) {
|
|
348
|
+
if (typeof this._options.clientMaxWindowBits === "number") {
|
|
349
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
350
|
+
}
|
|
351
|
+
} else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
|
|
352
|
+
throw new Error(
|
|
353
|
+
'Unexpected or invalid parameter "client_max_window_bits"'
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
return params;
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Normalize parameters.
|
|
360
|
+
*
|
|
361
|
+
* @param {Array} configurations The extension negotiation offers/reponse
|
|
362
|
+
* @return {Array} The offers/response with normalized parameters
|
|
363
|
+
* @private
|
|
364
|
+
*/
|
|
365
|
+
normalizeParams(configurations) {
|
|
366
|
+
configurations.forEach((params) => {
|
|
367
|
+
Object.keys(params).forEach((key) => {
|
|
368
|
+
let value = params[key];
|
|
369
|
+
if (value.length > 1) {
|
|
370
|
+
throw new Error(`Parameter "${key}" must have only a single value`);
|
|
371
|
+
}
|
|
372
|
+
value = value[0];
|
|
373
|
+
if (key === "client_max_window_bits") {
|
|
374
|
+
if (value !== true) {
|
|
375
|
+
const num = +value;
|
|
376
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
377
|
+
throw new TypeError(
|
|
378
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
value = num;
|
|
382
|
+
} else if (!this._isServer) {
|
|
383
|
+
throw new TypeError(
|
|
384
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
385
|
+
);
|
|
386
|
+
}
|
|
387
|
+
} else if (key === "server_max_window_bits") {
|
|
388
|
+
const num = +value;
|
|
389
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
390
|
+
throw new TypeError(
|
|
391
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
value = num;
|
|
395
|
+
} else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
|
|
396
|
+
if (value !== true) {
|
|
397
|
+
throw new TypeError(
|
|
398
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
} else {
|
|
402
|
+
throw new Error(`Unknown parameter "${key}"`);
|
|
403
|
+
}
|
|
404
|
+
params[key] = value;
|
|
405
|
+
});
|
|
406
|
+
});
|
|
407
|
+
return configurations;
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Decompress data. Concurrency limited.
|
|
411
|
+
*
|
|
412
|
+
* @param {Buffer} data Compressed data
|
|
413
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
414
|
+
* @param {Function} callback Callback
|
|
415
|
+
* @public
|
|
416
|
+
*/
|
|
417
|
+
decompress(data, fin, callback) {
|
|
418
|
+
zlibLimiter.add((done) => {
|
|
419
|
+
this._decompress(data, fin, (err, result) => {
|
|
420
|
+
done();
|
|
421
|
+
callback(err, result);
|
|
422
|
+
});
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Compress data. Concurrency limited.
|
|
427
|
+
*
|
|
428
|
+
* @param {(Buffer|String)} data Data to compress
|
|
429
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
430
|
+
* @param {Function} callback Callback
|
|
431
|
+
* @public
|
|
432
|
+
*/
|
|
433
|
+
compress(data, fin, callback) {
|
|
434
|
+
zlibLimiter.add((done) => {
|
|
435
|
+
this._compress(data, fin, (err, result) => {
|
|
436
|
+
done();
|
|
437
|
+
callback(err, result);
|
|
438
|
+
});
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Decompress data.
|
|
443
|
+
*
|
|
444
|
+
* @param {Buffer} data Compressed data
|
|
445
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
446
|
+
* @param {Function} callback Callback
|
|
447
|
+
* @private
|
|
448
|
+
*/
|
|
449
|
+
_decompress(data, fin, callback) {
|
|
450
|
+
const endpoint = this._isServer ? "client" : "server";
|
|
451
|
+
if (!this._inflate) {
|
|
452
|
+
const key = `${endpoint}_max_window_bits`;
|
|
453
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
454
|
+
this._inflate = zlib.createInflateRaw({
|
|
455
|
+
...this._options.zlibInflateOptions,
|
|
456
|
+
windowBits
|
|
457
|
+
});
|
|
458
|
+
this._inflate[kPerMessageDeflate] = this;
|
|
459
|
+
this._inflate[kTotalLength] = 0;
|
|
460
|
+
this._inflate[kBuffers] = [];
|
|
461
|
+
this._inflate.on("error", inflateOnError);
|
|
462
|
+
this._inflate.on("data", inflateOnData);
|
|
463
|
+
}
|
|
464
|
+
this._inflate[kCallback] = callback;
|
|
465
|
+
this._inflate.write(data);
|
|
466
|
+
if (fin) this._inflate.write(TRAILER);
|
|
467
|
+
this._inflate.flush(() => {
|
|
468
|
+
const err = this._inflate[kError];
|
|
469
|
+
if (err) {
|
|
470
|
+
this._inflate.close();
|
|
471
|
+
this._inflate = null;
|
|
472
|
+
callback(err);
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
const data2 = bufferUtil.concat(
|
|
476
|
+
this._inflate[kBuffers],
|
|
477
|
+
this._inflate[kTotalLength]
|
|
478
|
+
);
|
|
479
|
+
if (this._inflate._readableState.endEmitted) {
|
|
480
|
+
this._inflate.close();
|
|
481
|
+
this._inflate = null;
|
|
482
|
+
} else {
|
|
483
|
+
this._inflate[kTotalLength] = 0;
|
|
484
|
+
this._inflate[kBuffers] = [];
|
|
485
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
486
|
+
this._inflate.reset();
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
callback(null, data2);
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Compress data.
|
|
494
|
+
*
|
|
495
|
+
* @param {(Buffer|String)} data Data to compress
|
|
496
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
497
|
+
* @param {Function} callback Callback
|
|
498
|
+
* @private
|
|
499
|
+
*/
|
|
500
|
+
_compress(data, fin, callback) {
|
|
501
|
+
const endpoint = this._isServer ? "server" : "client";
|
|
502
|
+
if (!this._deflate) {
|
|
503
|
+
const key = `${endpoint}_max_window_bits`;
|
|
504
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
505
|
+
this._deflate = zlib.createDeflateRaw({
|
|
506
|
+
...this._options.zlibDeflateOptions,
|
|
507
|
+
windowBits
|
|
508
|
+
});
|
|
509
|
+
this._deflate[kTotalLength] = 0;
|
|
510
|
+
this._deflate[kBuffers] = [];
|
|
511
|
+
this._deflate.on("data", deflateOnData);
|
|
512
|
+
}
|
|
513
|
+
this._deflate[kCallback] = callback;
|
|
514
|
+
this._deflate.write(data);
|
|
515
|
+
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
|
|
516
|
+
if (!this._deflate) {
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
let data2 = bufferUtil.concat(
|
|
520
|
+
this._deflate[kBuffers],
|
|
521
|
+
this._deflate[kTotalLength]
|
|
522
|
+
);
|
|
523
|
+
if (fin) {
|
|
524
|
+
data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
|
|
525
|
+
}
|
|
526
|
+
this._deflate[kCallback] = null;
|
|
527
|
+
this._deflate[kTotalLength] = 0;
|
|
528
|
+
this._deflate[kBuffers] = [];
|
|
529
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
530
|
+
this._deflate.reset();
|
|
531
|
+
}
|
|
532
|
+
callback(null, data2);
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
module.exports = PerMessageDeflate2;
|
|
537
|
+
function deflateOnData(chunk) {
|
|
538
|
+
this[kBuffers].push(chunk);
|
|
539
|
+
this[kTotalLength] += chunk.length;
|
|
540
|
+
}
|
|
541
|
+
function inflateOnData(chunk) {
|
|
542
|
+
this[kTotalLength] += chunk.length;
|
|
543
|
+
if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
|
|
544
|
+
this[kBuffers].push(chunk);
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
this[kError] = new RangeError("Max payload size exceeded");
|
|
548
|
+
this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
|
|
549
|
+
this[kError][kStatusCode] = 1009;
|
|
550
|
+
this.removeListener("data", inflateOnData);
|
|
551
|
+
this.reset();
|
|
552
|
+
}
|
|
553
|
+
function inflateOnError(err) {
|
|
554
|
+
this[kPerMessageDeflate]._inflate = null;
|
|
555
|
+
if (this[kError]) {
|
|
556
|
+
this[kCallback](this[kError]);
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
err[kStatusCode] = 1007;
|
|
560
|
+
this[kCallback](err);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/validation.js
|
|
566
|
+
var require_validation = __commonJS({
|
|
567
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/validation.js"(exports, module) {
|
|
568
|
+
"use strict";
|
|
569
|
+
var { isUtf8 } = __require("buffer");
|
|
570
|
+
var { hasBlob } = require_constants();
|
|
571
|
+
var tokenChars = [
|
|
572
|
+
0,
|
|
573
|
+
0,
|
|
574
|
+
0,
|
|
575
|
+
0,
|
|
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 - 15
|
|
589
|
+
0,
|
|
590
|
+
0,
|
|
591
|
+
0,
|
|
592
|
+
0,
|
|
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
|
+
// 16 - 31
|
|
606
|
+
0,
|
|
607
|
+
1,
|
|
608
|
+
0,
|
|
609
|
+
1,
|
|
610
|
+
1,
|
|
611
|
+
1,
|
|
612
|
+
1,
|
|
613
|
+
1,
|
|
614
|
+
0,
|
|
615
|
+
0,
|
|
616
|
+
1,
|
|
617
|
+
1,
|
|
618
|
+
0,
|
|
619
|
+
1,
|
|
620
|
+
1,
|
|
621
|
+
0,
|
|
622
|
+
// 32 - 47
|
|
623
|
+
1,
|
|
624
|
+
1,
|
|
625
|
+
1,
|
|
626
|
+
1,
|
|
627
|
+
1,
|
|
628
|
+
1,
|
|
629
|
+
1,
|
|
630
|
+
1,
|
|
631
|
+
1,
|
|
632
|
+
1,
|
|
633
|
+
0,
|
|
634
|
+
0,
|
|
635
|
+
0,
|
|
636
|
+
0,
|
|
637
|
+
0,
|
|
638
|
+
0,
|
|
639
|
+
// 48 - 63
|
|
640
|
+
0,
|
|
641
|
+
1,
|
|
642
|
+
1,
|
|
643
|
+
1,
|
|
644
|
+
1,
|
|
645
|
+
1,
|
|
646
|
+
1,
|
|
647
|
+
1,
|
|
648
|
+
1,
|
|
649
|
+
1,
|
|
650
|
+
1,
|
|
651
|
+
1,
|
|
652
|
+
1,
|
|
653
|
+
1,
|
|
654
|
+
1,
|
|
655
|
+
1,
|
|
656
|
+
// 64 - 79
|
|
657
|
+
1,
|
|
658
|
+
1,
|
|
659
|
+
1,
|
|
660
|
+
1,
|
|
661
|
+
1,
|
|
662
|
+
1,
|
|
663
|
+
1,
|
|
664
|
+
1,
|
|
665
|
+
1,
|
|
666
|
+
1,
|
|
667
|
+
1,
|
|
668
|
+
0,
|
|
669
|
+
0,
|
|
670
|
+
0,
|
|
671
|
+
1,
|
|
672
|
+
1,
|
|
673
|
+
// 80 - 95
|
|
674
|
+
1,
|
|
675
|
+
1,
|
|
676
|
+
1,
|
|
677
|
+
1,
|
|
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
|
+
// 96 - 111
|
|
691
|
+
1,
|
|
692
|
+
1,
|
|
693
|
+
1,
|
|
694
|
+
1,
|
|
695
|
+
1,
|
|
696
|
+
1,
|
|
697
|
+
1,
|
|
698
|
+
1,
|
|
699
|
+
1,
|
|
700
|
+
1,
|
|
701
|
+
1,
|
|
702
|
+
0,
|
|
703
|
+
1,
|
|
704
|
+
0,
|
|
705
|
+
1,
|
|
706
|
+
0
|
|
707
|
+
// 112 - 127
|
|
708
|
+
];
|
|
709
|
+
function isValidStatusCode(code) {
|
|
710
|
+
return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
|
|
711
|
+
}
|
|
712
|
+
function _isValidUTF8(buf) {
|
|
713
|
+
const len = buf.length;
|
|
714
|
+
let i = 0;
|
|
715
|
+
while (i < len) {
|
|
716
|
+
if ((buf[i] & 128) === 0) {
|
|
717
|
+
i++;
|
|
718
|
+
} else if ((buf[i] & 224) === 192) {
|
|
719
|
+
if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
|
|
720
|
+
return false;
|
|
721
|
+
}
|
|
722
|
+
i += 2;
|
|
723
|
+
} else if ((buf[i] & 240) === 224) {
|
|
724
|
+
if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
|
|
725
|
+
buf[i] === 237 && (buf[i + 1] & 224) === 160) {
|
|
726
|
+
return false;
|
|
727
|
+
}
|
|
728
|
+
i += 3;
|
|
729
|
+
} else if ((buf[i] & 248) === 240) {
|
|
730
|
+
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
|
|
731
|
+
buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
|
|
732
|
+
return false;
|
|
733
|
+
}
|
|
734
|
+
i += 4;
|
|
735
|
+
} else {
|
|
736
|
+
return false;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
return true;
|
|
740
|
+
}
|
|
741
|
+
function isBlob(value) {
|
|
742
|
+
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");
|
|
743
|
+
}
|
|
744
|
+
module.exports = {
|
|
745
|
+
isBlob,
|
|
746
|
+
isValidStatusCode,
|
|
747
|
+
isValidUTF8: _isValidUTF8,
|
|
748
|
+
tokenChars
|
|
749
|
+
};
|
|
750
|
+
if (isUtf8) {
|
|
751
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
752
|
+
return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
|
|
753
|
+
};
|
|
754
|
+
} else if (!process.env.WS_NO_UTF_8_VALIDATE) {
|
|
755
|
+
try {
|
|
756
|
+
const isValidUTF8 = __require("utf-8-validate");
|
|
757
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
758
|
+
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
|
|
759
|
+
};
|
|
760
|
+
} catch (e) {
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
});
|
|
765
|
+
|
|
766
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/receiver.js
|
|
767
|
+
var require_receiver = __commonJS({
|
|
768
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/receiver.js"(exports, module) {
|
|
769
|
+
"use strict";
|
|
770
|
+
var { Writable } = __require("stream");
|
|
771
|
+
var PerMessageDeflate2 = require_permessage_deflate();
|
|
772
|
+
var {
|
|
773
|
+
BINARY_TYPES,
|
|
774
|
+
EMPTY_BUFFER,
|
|
775
|
+
kStatusCode,
|
|
776
|
+
kWebSocket
|
|
777
|
+
} = require_constants();
|
|
778
|
+
var { concat, toArrayBuffer, unmask } = require_buffer_util();
|
|
779
|
+
var { isValidStatusCode, isValidUTF8 } = require_validation();
|
|
780
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
781
|
+
var GET_INFO = 0;
|
|
782
|
+
var GET_PAYLOAD_LENGTH_16 = 1;
|
|
783
|
+
var GET_PAYLOAD_LENGTH_64 = 2;
|
|
784
|
+
var GET_MASK = 3;
|
|
785
|
+
var GET_DATA = 4;
|
|
786
|
+
var INFLATING = 5;
|
|
787
|
+
var DEFER_EVENT = 6;
|
|
788
|
+
var Receiver2 = class extends Writable {
|
|
789
|
+
/**
|
|
790
|
+
* Creates a Receiver instance.
|
|
791
|
+
*
|
|
792
|
+
* @param {Object} [options] Options object
|
|
793
|
+
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
|
|
794
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
795
|
+
* multiple times in the same tick
|
|
796
|
+
* @param {String} [options.binaryType=nodebuffer] The type for binary data
|
|
797
|
+
* @param {Object} [options.extensions] An object containing the negotiated
|
|
798
|
+
* extensions
|
|
799
|
+
* @param {Boolean} [options.isServer=false] Specifies whether to operate in
|
|
800
|
+
* client or server mode
|
|
801
|
+
* @param {Number} [options.maxBufferedChunks=0] The maximum number of
|
|
802
|
+
* buffered data chunks
|
|
803
|
+
* @param {Number} [options.maxFragments=0] The maximum number of message
|
|
804
|
+
* fragments
|
|
805
|
+
* @param {Number} [options.maxPayload=0] The maximum allowed message length
|
|
806
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
807
|
+
* not to skip UTF-8 validation for text and close messages
|
|
808
|
+
*/
|
|
809
|
+
constructor(options = {}) {
|
|
810
|
+
super();
|
|
811
|
+
this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
|
|
812
|
+
this._binaryType = options.binaryType || BINARY_TYPES[0];
|
|
813
|
+
this._extensions = options.extensions || {};
|
|
814
|
+
this._isServer = !!options.isServer;
|
|
815
|
+
this._maxBufferedChunks = options.maxBufferedChunks | 0;
|
|
816
|
+
this._maxFragments = options.maxFragments | 0;
|
|
817
|
+
this._maxPayload = options.maxPayload | 0;
|
|
818
|
+
this._skipUTF8Validation = !!options.skipUTF8Validation;
|
|
819
|
+
this[kWebSocket] = void 0;
|
|
820
|
+
this._bufferedBytes = 0;
|
|
821
|
+
this._buffers = [];
|
|
822
|
+
this._compressed = false;
|
|
823
|
+
this._payloadLength = 0;
|
|
824
|
+
this._mask = void 0;
|
|
825
|
+
this._fragmented = 0;
|
|
826
|
+
this._masked = false;
|
|
827
|
+
this._fin = false;
|
|
828
|
+
this._opcode = 0;
|
|
829
|
+
this._totalPayloadLength = 0;
|
|
830
|
+
this._messageLength = 0;
|
|
831
|
+
this._fragments = [];
|
|
832
|
+
this._errored = false;
|
|
833
|
+
this._loop = false;
|
|
834
|
+
this._state = GET_INFO;
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Implements `Writable.prototype._write()`.
|
|
838
|
+
*
|
|
839
|
+
* @param {Buffer} chunk The chunk of data to write
|
|
840
|
+
* @param {String} encoding The character encoding of `chunk`
|
|
841
|
+
* @param {Function} cb Callback
|
|
842
|
+
* @private
|
|
843
|
+
*/
|
|
844
|
+
_write(chunk, encoding, cb) {
|
|
845
|
+
if (this._opcode === 8 && this._state == GET_INFO) return cb();
|
|
846
|
+
if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
|
|
847
|
+
cb(
|
|
848
|
+
this.createError(
|
|
849
|
+
RangeError,
|
|
850
|
+
"Too many buffered chunks",
|
|
851
|
+
false,
|
|
852
|
+
1008,
|
|
853
|
+
"WS_ERR_TOO_MANY_BUFFERED_PARTS"
|
|
854
|
+
)
|
|
855
|
+
);
|
|
856
|
+
return;
|
|
857
|
+
}
|
|
858
|
+
this._bufferedBytes += chunk.length;
|
|
859
|
+
this._buffers.push(chunk);
|
|
860
|
+
this.startLoop(cb);
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Consumes `n` bytes from the buffered data.
|
|
864
|
+
*
|
|
865
|
+
* @param {Number} n The number of bytes to consume
|
|
866
|
+
* @return {Buffer} The consumed bytes
|
|
867
|
+
* @private
|
|
868
|
+
*/
|
|
869
|
+
consume(n) {
|
|
870
|
+
this._bufferedBytes -= n;
|
|
871
|
+
if (n === this._buffers[0].length) return this._buffers.shift();
|
|
872
|
+
if (n < this._buffers[0].length) {
|
|
873
|
+
const buf = this._buffers[0];
|
|
874
|
+
this._buffers[0] = new FastBuffer(
|
|
875
|
+
buf.buffer,
|
|
876
|
+
buf.byteOffset + n,
|
|
877
|
+
buf.length - n
|
|
878
|
+
);
|
|
879
|
+
return new FastBuffer(buf.buffer, buf.byteOffset, n);
|
|
880
|
+
}
|
|
881
|
+
const dst = Buffer.allocUnsafe(n);
|
|
882
|
+
do {
|
|
883
|
+
const buf = this._buffers[0];
|
|
884
|
+
const offset = dst.length - n;
|
|
885
|
+
if (n >= buf.length) {
|
|
886
|
+
dst.set(this._buffers.shift(), offset);
|
|
887
|
+
} else {
|
|
888
|
+
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
|
|
889
|
+
this._buffers[0] = new FastBuffer(
|
|
890
|
+
buf.buffer,
|
|
891
|
+
buf.byteOffset + n,
|
|
892
|
+
buf.length - n
|
|
893
|
+
);
|
|
894
|
+
}
|
|
895
|
+
n -= buf.length;
|
|
896
|
+
} while (n > 0);
|
|
897
|
+
return dst;
|
|
898
|
+
}
|
|
899
|
+
/**
|
|
900
|
+
* Starts the parsing loop.
|
|
901
|
+
*
|
|
902
|
+
* @param {Function} cb Callback
|
|
903
|
+
* @private
|
|
904
|
+
*/
|
|
905
|
+
startLoop(cb) {
|
|
906
|
+
this._loop = true;
|
|
907
|
+
do {
|
|
908
|
+
switch (this._state) {
|
|
909
|
+
case GET_INFO:
|
|
910
|
+
this.getInfo(cb);
|
|
911
|
+
break;
|
|
912
|
+
case GET_PAYLOAD_LENGTH_16:
|
|
913
|
+
this.getPayloadLength16(cb);
|
|
914
|
+
break;
|
|
915
|
+
case GET_PAYLOAD_LENGTH_64:
|
|
916
|
+
this.getPayloadLength64(cb);
|
|
917
|
+
break;
|
|
918
|
+
case GET_MASK:
|
|
919
|
+
this.getMask();
|
|
920
|
+
break;
|
|
921
|
+
case GET_DATA:
|
|
922
|
+
this.getData(cb);
|
|
923
|
+
break;
|
|
924
|
+
case INFLATING:
|
|
925
|
+
case DEFER_EVENT:
|
|
926
|
+
this._loop = false;
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
} while (this._loop);
|
|
930
|
+
if (!this._errored) cb();
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Reads the first two bytes of a frame.
|
|
934
|
+
*
|
|
935
|
+
* @param {Function} cb Callback
|
|
936
|
+
* @private
|
|
937
|
+
*/
|
|
938
|
+
getInfo(cb) {
|
|
939
|
+
if (this._bufferedBytes < 2) {
|
|
940
|
+
this._loop = false;
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
const buf = this.consume(2);
|
|
944
|
+
if ((buf[0] & 48) !== 0) {
|
|
945
|
+
const error = this.createError(
|
|
946
|
+
RangeError,
|
|
947
|
+
"RSV2 and RSV3 must be clear",
|
|
948
|
+
true,
|
|
949
|
+
1002,
|
|
950
|
+
"WS_ERR_UNEXPECTED_RSV_2_3"
|
|
951
|
+
);
|
|
952
|
+
cb(error);
|
|
953
|
+
return;
|
|
954
|
+
}
|
|
955
|
+
const compressed = (buf[0] & 64) === 64;
|
|
956
|
+
if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
|
|
957
|
+
const error = this.createError(
|
|
958
|
+
RangeError,
|
|
959
|
+
"RSV1 must be clear",
|
|
960
|
+
true,
|
|
961
|
+
1002,
|
|
962
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
963
|
+
);
|
|
964
|
+
cb(error);
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
this._fin = (buf[0] & 128) === 128;
|
|
968
|
+
this._opcode = buf[0] & 15;
|
|
969
|
+
this._payloadLength = buf[1] & 127;
|
|
970
|
+
if (this._opcode === 0) {
|
|
971
|
+
if (compressed) {
|
|
972
|
+
const error = this.createError(
|
|
973
|
+
RangeError,
|
|
974
|
+
"RSV1 must be clear",
|
|
975
|
+
true,
|
|
976
|
+
1002,
|
|
977
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
978
|
+
);
|
|
979
|
+
cb(error);
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
if (!this._fragmented) {
|
|
983
|
+
const error = this.createError(
|
|
984
|
+
RangeError,
|
|
985
|
+
"invalid opcode 0",
|
|
986
|
+
true,
|
|
987
|
+
1002,
|
|
988
|
+
"WS_ERR_INVALID_OPCODE"
|
|
989
|
+
);
|
|
990
|
+
cb(error);
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
this._opcode = this._fragmented;
|
|
994
|
+
} else if (this._opcode === 1 || this._opcode === 2) {
|
|
995
|
+
if (this._fragmented) {
|
|
996
|
+
const error = this.createError(
|
|
997
|
+
RangeError,
|
|
998
|
+
`invalid opcode ${this._opcode}`,
|
|
999
|
+
true,
|
|
1000
|
+
1002,
|
|
1001
|
+
"WS_ERR_INVALID_OPCODE"
|
|
1002
|
+
);
|
|
1003
|
+
cb(error);
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
this._compressed = compressed;
|
|
1007
|
+
} else if (this._opcode > 7 && this._opcode < 11) {
|
|
1008
|
+
if (!this._fin) {
|
|
1009
|
+
const error = this.createError(
|
|
1010
|
+
RangeError,
|
|
1011
|
+
"FIN must be set",
|
|
1012
|
+
true,
|
|
1013
|
+
1002,
|
|
1014
|
+
"WS_ERR_EXPECTED_FIN"
|
|
1015
|
+
);
|
|
1016
|
+
cb(error);
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
if (compressed) {
|
|
1020
|
+
const error = this.createError(
|
|
1021
|
+
RangeError,
|
|
1022
|
+
"RSV1 must be clear",
|
|
1023
|
+
true,
|
|
1024
|
+
1002,
|
|
1025
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
1026
|
+
);
|
|
1027
|
+
cb(error);
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
|
|
1031
|
+
const error = this.createError(
|
|
1032
|
+
RangeError,
|
|
1033
|
+
`invalid payload length ${this._payloadLength}`,
|
|
1034
|
+
true,
|
|
1035
|
+
1002,
|
|
1036
|
+
"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
|
|
1037
|
+
);
|
|
1038
|
+
cb(error);
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
} else {
|
|
1042
|
+
const error = this.createError(
|
|
1043
|
+
RangeError,
|
|
1044
|
+
`invalid opcode ${this._opcode}`,
|
|
1045
|
+
true,
|
|
1046
|
+
1002,
|
|
1047
|
+
"WS_ERR_INVALID_OPCODE"
|
|
1048
|
+
);
|
|
1049
|
+
cb(error);
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
|
|
1053
|
+
this._masked = (buf[1] & 128) === 128;
|
|
1054
|
+
if (this._isServer) {
|
|
1055
|
+
if (!this._masked) {
|
|
1056
|
+
const error = this.createError(
|
|
1057
|
+
RangeError,
|
|
1058
|
+
"MASK must be set",
|
|
1059
|
+
true,
|
|
1060
|
+
1002,
|
|
1061
|
+
"WS_ERR_EXPECTED_MASK"
|
|
1062
|
+
);
|
|
1063
|
+
cb(error);
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
} else if (this._masked) {
|
|
1067
|
+
const error = this.createError(
|
|
1068
|
+
RangeError,
|
|
1069
|
+
"MASK must be clear",
|
|
1070
|
+
true,
|
|
1071
|
+
1002,
|
|
1072
|
+
"WS_ERR_UNEXPECTED_MASK"
|
|
1073
|
+
);
|
|
1074
|
+
cb(error);
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
|
|
1078
|
+
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
|
|
1079
|
+
else this.haveLength(cb);
|
|
1080
|
+
}
|
|
1081
|
+
/**
|
|
1082
|
+
* Gets extended payload length (7+16).
|
|
1083
|
+
*
|
|
1084
|
+
* @param {Function} cb Callback
|
|
1085
|
+
* @private
|
|
1086
|
+
*/
|
|
1087
|
+
getPayloadLength16(cb) {
|
|
1088
|
+
if (this._bufferedBytes < 2) {
|
|
1089
|
+
this._loop = false;
|
|
1090
|
+
return;
|
|
1091
|
+
}
|
|
1092
|
+
this._payloadLength = this.consume(2).readUInt16BE(0);
|
|
1093
|
+
this.haveLength(cb);
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Gets extended payload length (7+64).
|
|
1097
|
+
*
|
|
1098
|
+
* @param {Function} cb Callback
|
|
1099
|
+
* @private
|
|
1100
|
+
*/
|
|
1101
|
+
getPayloadLength64(cb) {
|
|
1102
|
+
if (this._bufferedBytes < 8) {
|
|
1103
|
+
this._loop = false;
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
const buf = this.consume(8);
|
|
1107
|
+
const num = buf.readUInt32BE(0);
|
|
1108
|
+
if (num > Math.pow(2, 53 - 32) - 1) {
|
|
1109
|
+
const error = this.createError(
|
|
1110
|
+
RangeError,
|
|
1111
|
+
"Unsupported WebSocket frame: payload length > 2^53 - 1",
|
|
1112
|
+
false,
|
|
1113
|
+
1009,
|
|
1114
|
+
"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
|
|
1115
|
+
);
|
|
1116
|
+
cb(error);
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
|
|
1120
|
+
this.haveLength(cb);
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* Payload length has been read.
|
|
1124
|
+
*
|
|
1125
|
+
* @param {Function} cb Callback
|
|
1126
|
+
* @private
|
|
1127
|
+
*/
|
|
1128
|
+
haveLength(cb) {
|
|
1129
|
+
if (this._payloadLength && this._opcode < 8) {
|
|
1130
|
+
this._totalPayloadLength += this._payloadLength;
|
|
1131
|
+
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
|
|
1132
|
+
const error = this.createError(
|
|
1133
|
+
RangeError,
|
|
1134
|
+
"Max payload size exceeded",
|
|
1135
|
+
false,
|
|
1136
|
+
1009,
|
|
1137
|
+
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
|
|
1138
|
+
);
|
|
1139
|
+
cb(error);
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
if (this._masked) this._state = GET_MASK;
|
|
1144
|
+
else this._state = GET_DATA;
|
|
1145
|
+
}
|
|
1146
|
+
/**
|
|
1147
|
+
* Reads mask bytes.
|
|
1148
|
+
*
|
|
1149
|
+
* @private
|
|
1150
|
+
*/
|
|
1151
|
+
getMask() {
|
|
1152
|
+
if (this._bufferedBytes < 4) {
|
|
1153
|
+
this._loop = false;
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1156
|
+
this._mask = this.consume(4);
|
|
1157
|
+
this._state = GET_DATA;
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Reads data bytes.
|
|
1161
|
+
*
|
|
1162
|
+
* @param {Function} cb Callback
|
|
1163
|
+
* @private
|
|
1164
|
+
*/
|
|
1165
|
+
getData(cb) {
|
|
1166
|
+
let data = EMPTY_BUFFER;
|
|
1167
|
+
if (this._payloadLength) {
|
|
1168
|
+
if (this._bufferedBytes < this._payloadLength) {
|
|
1169
|
+
this._loop = false;
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
data = this.consume(this._payloadLength);
|
|
1173
|
+
if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
|
|
1174
|
+
unmask(data, this._mask);
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
if (this._opcode > 7) {
|
|
1178
|
+
this.controlMessage(data, cb);
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
if (this._compressed) {
|
|
1182
|
+
this._state = INFLATING;
|
|
1183
|
+
this.decompress(data, cb);
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
if (data.length) {
|
|
1187
|
+
if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
|
|
1188
|
+
const error = this.createError(
|
|
1189
|
+
RangeError,
|
|
1190
|
+
"Too many message fragments",
|
|
1191
|
+
false,
|
|
1192
|
+
1008,
|
|
1193
|
+
"WS_ERR_TOO_MANY_BUFFERED_PARTS"
|
|
1194
|
+
);
|
|
1195
|
+
cb(error);
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
1198
|
+
this._messageLength = this._totalPayloadLength;
|
|
1199
|
+
this._fragments.push(data);
|
|
1200
|
+
}
|
|
1201
|
+
this.dataMessage(cb);
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* Decompresses data.
|
|
1205
|
+
*
|
|
1206
|
+
* @param {Buffer} data Compressed data
|
|
1207
|
+
* @param {Function} cb Callback
|
|
1208
|
+
* @private
|
|
1209
|
+
*/
|
|
1210
|
+
decompress(data, cb) {
|
|
1211
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
|
|
1212
|
+
perMessageDeflate.decompress(data, this._fin, (err, buf) => {
|
|
1213
|
+
if (err) return cb(err);
|
|
1214
|
+
if (buf.length) {
|
|
1215
|
+
this._messageLength += buf.length;
|
|
1216
|
+
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
|
|
1217
|
+
const error = this.createError(
|
|
1218
|
+
RangeError,
|
|
1219
|
+
"Max payload size exceeded",
|
|
1220
|
+
false,
|
|
1221
|
+
1009,
|
|
1222
|
+
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
|
|
1223
|
+
);
|
|
1224
|
+
cb(error);
|
|
1225
|
+
return;
|
|
1226
|
+
}
|
|
1227
|
+
if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
|
|
1228
|
+
const error = this.createError(
|
|
1229
|
+
RangeError,
|
|
1230
|
+
"Too many message fragments",
|
|
1231
|
+
false,
|
|
1232
|
+
1008,
|
|
1233
|
+
"WS_ERR_TOO_MANY_BUFFERED_PARTS"
|
|
1234
|
+
);
|
|
1235
|
+
cb(error);
|
|
1236
|
+
return;
|
|
1237
|
+
}
|
|
1238
|
+
this._fragments.push(buf);
|
|
1239
|
+
}
|
|
1240
|
+
this.dataMessage(cb);
|
|
1241
|
+
if (this._state === GET_INFO) this.startLoop(cb);
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
* Handles a data message.
|
|
1246
|
+
*
|
|
1247
|
+
* @param {Function} cb Callback
|
|
1248
|
+
* @private
|
|
1249
|
+
*/
|
|
1250
|
+
dataMessage(cb) {
|
|
1251
|
+
if (!this._fin) {
|
|
1252
|
+
this._state = GET_INFO;
|
|
1253
|
+
return;
|
|
1254
|
+
}
|
|
1255
|
+
const messageLength = this._messageLength;
|
|
1256
|
+
const fragments = this._fragments;
|
|
1257
|
+
this._totalPayloadLength = 0;
|
|
1258
|
+
this._messageLength = 0;
|
|
1259
|
+
this._fragmented = 0;
|
|
1260
|
+
this._fragments = [];
|
|
1261
|
+
if (this._opcode === 2) {
|
|
1262
|
+
let data;
|
|
1263
|
+
if (this._binaryType === "nodebuffer") {
|
|
1264
|
+
data = concat(fragments, messageLength);
|
|
1265
|
+
} else if (this._binaryType === "arraybuffer") {
|
|
1266
|
+
data = toArrayBuffer(concat(fragments, messageLength));
|
|
1267
|
+
} else if (this._binaryType === "blob") {
|
|
1268
|
+
data = new Blob(fragments);
|
|
1269
|
+
} else {
|
|
1270
|
+
data = fragments;
|
|
1271
|
+
}
|
|
1272
|
+
if (this._allowSynchronousEvents) {
|
|
1273
|
+
this.emit("message", data, true);
|
|
1274
|
+
this._state = GET_INFO;
|
|
1275
|
+
} else {
|
|
1276
|
+
this._state = DEFER_EVENT;
|
|
1277
|
+
setImmediate(() => {
|
|
1278
|
+
this.emit("message", data, true);
|
|
1279
|
+
this._state = GET_INFO;
|
|
1280
|
+
this.startLoop(cb);
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
} else {
|
|
1284
|
+
const buf = concat(fragments, messageLength);
|
|
1285
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
1286
|
+
const error = this.createError(
|
|
1287
|
+
Error,
|
|
1288
|
+
"invalid UTF-8 sequence",
|
|
1289
|
+
true,
|
|
1290
|
+
1007,
|
|
1291
|
+
"WS_ERR_INVALID_UTF8"
|
|
1292
|
+
);
|
|
1293
|
+
cb(error);
|
|
1294
|
+
return;
|
|
1295
|
+
}
|
|
1296
|
+
if (this._state === INFLATING || this._allowSynchronousEvents) {
|
|
1297
|
+
this.emit("message", buf, false);
|
|
1298
|
+
this._state = GET_INFO;
|
|
1299
|
+
} else {
|
|
1300
|
+
this._state = DEFER_EVENT;
|
|
1301
|
+
setImmediate(() => {
|
|
1302
|
+
this.emit("message", buf, false);
|
|
1303
|
+
this._state = GET_INFO;
|
|
1304
|
+
this.startLoop(cb);
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* Handles a control message.
|
|
1311
|
+
*
|
|
1312
|
+
* @param {Buffer} data Data to handle
|
|
1313
|
+
* @return {(Error|RangeError|undefined)} A possible error
|
|
1314
|
+
* @private
|
|
1315
|
+
*/
|
|
1316
|
+
controlMessage(data, cb) {
|
|
1317
|
+
if (this._opcode === 8) {
|
|
1318
|
+
if (data.length === 0) {
|
|
1319
|
+
this._loop = false;
|
|
1320
|
+
this.emit("conclude", 1005, EMPTY_BUFFER);
|
|
1321
|
+
this.end();
|
|
1322
|
+
} else {
|
|
1323
|
+
const code = data.readUInt16BE(0);
|
|
1324
|
+
if (!isValidStatusCode(code)) {
|
|
1325
|
+
const error = this.createError(
|
|
1326
|
+
RangeError,
|
|
1327
|
+
`invalid status code ${code}`,
|
|
1328
|
+
true,
|
|
1329
|
+
1002,
|
|
1330
|
+
"WS_ERR_INVALID_CLOSE_CODE"
|
|
1331
|
+
);
|
|
1332
|
+
cb(error);
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
const buf = new FastBuffer(
|
|
1336
|
+
data.buffer,
|
|
1337
|
+
data.byteOffset + 2,
|
|
1338
|
+
data.length - 2
|
|
1339
|
+
);
|
|
1340
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
1341
|
+
const error = this.createError(
|
|
1342
|
+
Error,
|
|
1343
|
+
"invalid UTF-8 sequence",
|
|
1344
|
+
true,
|
|
1345
|
+
1007,
|
|
1346
|
+
"WS_ERR_INVALID_UTF8"
|
|
1347
|
+
);
|
|
1348
|
+
cb(error);
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
this._loop = false;
|
|
1352
|
+
this.emit("conclude", code, buf);
|
|
1353
|
+
this.end();
|
|
1354
|
+
}
|
|
1355
|
+
this._state = GET_INFO;
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
if (this._allowSynchronousEvents) {
|
|
1359
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
1360
|
+
this._state = GET_INFO;
|
|
1361
|
+
} else {
|
|
1362
|
+
this._state = DEFER_EVENT;
|
|
1363
|
+
setImmediate(() => {
|
|
1364
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
1365
|
+
this._state = GET_INFO;
|
|
1366
|
+
this.startLoop(cb);
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Builds an error object.
|
|
1372
|
+
*
|
|
1373
|
+
* @param {function(new:Error|RangeError)} ErrorCtor The error constructor
|
|
1374
|
+
* @param {String} message The error message
|
|
1375
|
+
* @param {Boolean} prefix Specifies whether or not to add a default prefix to
|
|
1376
|
+
* `message`
|
|
1377
|
+
* @param {Number} statusCode The status code
|
|
1378
|
+
* @param {String} errorCode The exposed error code
|
|
1379
|
+
* @return {(Error|RangeError)} The error
|
|
1380
|
+
* @private
|
|
1381
|
+
*/
|
|
1382
|
+
createError(ErrorCtor, message, prefix, statusCode, errorCode) {
|
|
1383
|
+
this._loop = false;
|
|
1384
|
+
this._errored = true;
|
|
1385
|
+
const err = new ErrorCtor(
|
|
1386
|
+
prefix ? `Invalid WebSocket frame: ${message}` : message
|
|
1387
|
+
);
|
|
1388
|
+
Error.captureStackTrace(err, this.createError);
|
|
1389
|
+
err.code = errorCode;
|
|
1390
|
+
err[kStatusCode] = statusCode;
|
|
1391
|
+
return err;
|
|
1392
|
+
}
|
|
1393
|
+
};
|
|
1394
|
+
module.exports = Receiver2;
|
|
1395
|
+
}
|
|
1396
|
+
});
|
|
1397
|
+
|
|
1398
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/sender.js
|
|
1399
|
+
var require_sender = __commonJS({
|
|
1400
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/sender.js"(exports, module) {
|
|
1401
|
+
"use strict";
|
|
1402
|
+
var { Duplex } = __require("stream");
|
|
1403
|
+
var { randomFillSync } = __require("crypto");
|
|
1404
|
+
var {
|
|
1405
|
+
types: { isUint8Array }
|
|
1406
|
+
} = __require("util");
|
|
1407
|
+
var PerMessageDeflate2 = require_permessage_deflate();
|
|
1408
|
+
var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
|
|
1409
|
+
var { isBlob, isValidStatusCode } = require_validation();
|
|
1410
|
+
var { mask: applyMask, toBuffer } = require_buffer_util();
|
|
1411
|
+
var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
|
|
1412
|
+
var maskBuffer = Buffer.alloc(4);
|
|
1413
|
+
var RANDOM_POOL_SIZE = 8 * 1024;
|
|
1414
|
+
var randomPool;
|
|
1415
|
+
var randomPoolPointer = RANDOM_POOL_SIZE;
|
|
1416
|
+
var DEFAULT = 0;
|
|
1417
|
+
var DEFLATING = 1;
|
|
1418
|
+
var GET_BLOB_DATA = 2;
|
|
1419
|
+
var Sender2 = class _Sender {
|
|
1420
|
+
/**
|
|
1421
|
+
* Creates a Sender instance.
|
|
1422
|
+
*
|
|
1423
|
+
* @param {Duplex} socket The connection socket
|
|
1424
|
+
* @param {Object} [extensions] An object containing the negotiated extensions
|
|
1425
|
+
* @param {Function} [generateMask] The function used to generate the masking
|
|
1426
|
+
* key
|
|
1427
|
+
*/
|
|
1428
|
+
constructor(socket, extensions, generateMask) {
|
|
1429
|
+
this._extensions = extensions || {};
|
|
1430
|
+
if (generateMask) {
|
|
1431
|
+
this._generateMask = generateMask;
|
|
1432
|
+
this._maskBuffer = Buffer.alloc(4);
|
|
1433
|
+
}
|
|
1434
|
+
this._socket = socket;
|
|
1435
|
+
this._firstFragment = true;
|
|
1436
|
+
this._compress = false;
|
|
1437
|
+
this._bufferedBytes = 0;
|
|
1438
|
+
this._queue = [];
|
|
1439
|
+
this._state = DEFAULT;
|
|
1440
|
+
this.onerror = NOOP;
|
|
1441
|
+
this[kWebSocket] = void 0;
|
|
1442
|
+
}
|
|
1443
|
+
/**
|
|
1444
|
+
* Frames a piece of data according to the HyBi WebSocket protocol.
|
|
1445
|
+
*
|
|
1446
|
+
* @param {(Buffer|String)} data The data to frame
|
|
1447
|
+
* @param {Object} options Options object
|
|
1448
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
1449
|
+
* FIN bit
|
|
1450
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
1451
|
+
* masking key
|
|
1452
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1453
|
+
* `data`
|
|
1454
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
1455
|
+
* key
|
|
1456
|
+
* @param {Number} options.opcode The opcode
|
|
1457
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
1458
|
+
* modified
|
|
1459
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
1460
|
+
* RSV1 bit
|
|
1461
|
+
* @return {(Buffer|String)[]} The framed data
|
|
1462
|
+
* @public
|
|
1463
|
+
*/
|
|
1464
|
+
static frame(data, options) {
|
|
1465
|
+
let mask;
|
|
1466
|
+
let merge = false;
|
|
1467
|
+
let offset = 2;
|
|
1468
|
+
let skipMasking = false;
|
|
1469
|
+
if (options.mask) {
|
|
1470
|
+
mask = options.maskBuffer || maskBuffer;
|
|
1471
|
+
if (options.generateMask) {
|
|
1472
|
+
options.generateMask(mask);
|
|
1473
|
+
} else {
|
|
1474
|
+
if (randomPoolPointer === RANDOM_POOL_SIZE) {
|
|
1475
|
+
if (randomPool === void 0) {
|
|
1476
|
+
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
|
|
1477
|
+
}
|
|
1478
|
+
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
|
|
1479
|
+
randomPoolPointer = 0;
|
|
1480
|
+
}
|
|
1481
|
+
mask[0] = randomPool[randomPoolPointer++];
|
|
1482
|
+
mask[1] = randomPool[randomPoolPointer++];
|
|
1483
|
+
mask[2] = randomPool[randomPoolPointer++];
|
|
1484
|
+
mask[3] = randomPool[randomPoolPointer++];
|
|
1485
|
+
}
|
|
1486
|
+
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
|
|
1487
|
+
offset = 6;
|
|
1488
|
+
}
|
|
1489
|
+
let dataLength;
|
|
1490
|
+
if (typeof data === "string") {
|
|
1491
|
+
if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
|
|
1492
|
+
dataLength = options[kByteLength];
|
|
1493
|
+
} else {
|
|
1494
|
+
data = Buffer.from(data);
|
|
1495
|
+
dataLength = data.length;
|
|
1496
|
+
}
|
|
1497
|
+
} else {
|
|
1498
|
+
dataLength = data.length;
|
|
1499
|
+
merge = options.mask && options.readOnly && !skipMasking;
|
|
1500
|
+
}
|
|
1501
|
+
let payloadLength = dataLength;
|
|
1502
|
+
if (dataLength >= 65536) {
|
|
1503
|
+
offset += 8;
|
|
1504
|
+
payloadLength = 127;
|
|
1505
|
+
} else if (dataLength > 125) {
|
|
1506
|
+
offset += 2;
|
|
1507
|
+
payloadLength = 126;
|
|
1508
|
+
}
|
|
1509
|
+
const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
|
|
1510
|
+
target[0] = options.fin ? options.opcode | 128 : options.opcode;
|
|
1511
|
+
if (options.rsv1) target[0] |= 64;
|
|
1512
|
+
target[1] = payloadLength;
|
|
1513
|
+
if (payloadLength === 126) {
|
|
1514
|
+
target.writeUInt16BE(dataLength, 2);
|
|
1515
|
+
} else if (payloadLength === 127) {
|
|
1516
|
+
target[2] = target[3] = 0;
|
|
1517
|
+
target.writeUIntBE(dataLength, 4, 6);
|
|
1518
|
+
}
|
|
1519
|
+
if (!options.mask) return [target, data];
|
|
1520
|
+
target[1] |= 128;
|
|
1521
|
+
target[offset - 4] = mask[0];
|
|
1522
|
+
target[offset - 3] = mask[1];
|
|
1523
|
+
target[offset - 2] = mask[2];
|
|
1524
|
+
target[offset - 1] = mask[3];
|
|
1525
|
+
if (skipMasking) return [target, data];
|
|
1526
|
+
if (merge) {
|
|
1527
|
+
applyMask(data, mask, target, offset, dataLength);
|
|
1528
|
+
return [target];
|
|
1529
|
+
}
|
|
1530
|
+
applyMask(data, mask, data, 0, dataLength);
|
|
1531
|
+
return [target, data];
|
|
1532
|
+
}
|
|
1533
|
+
/**
|
|
1534
|
+
* Sends a close message to the other peer.
|
|
1535
|
+
*
|
|
1536
|
+
* @param {Number} [code] The status code component of the body
|
|
1537
|
+
* @param {(String|Buffer)} [data] The message component of the body
|
|
1538
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask the message
|
|
1539
|
+
* @param {Function} [cb] Callback
|
|
1540
|
+
* @public
|
|
1541
|
+
*/
|
|
1542
|
+
close(code, data, mask, cb) {
|
|
1543
|
+
let buf;
|
|
1544
|
+
if (code === void 0) {
|
|
1545
|
+
buf = EMPTY_BUFFER;
|
|
1546
|
+
} else if (typeof code !== "number" || !isValidStatusCode(code)) {
|
|
1547
|
+
throw new TypeError("First argument must be a valid error code number");
|
|
1548
|
+
} else if (data === void 0 || !data.length) {
|
|
1549
|
+
buf = Buffer.allocUnsafe(2);
|
|
1550
|
+
buf.writeUInt16BE(code, 0);
|
|
1551
|
+
} else {
|
|
1552
|
+
const length = Buffer.byteLength(data);
|
|
1553
|
+
if (length > 123) {
|
|
1554
|
+
throw new RangeError("The message must not be greater than 123 bytes");
|
|
1555
|
+
}
|
|
1556
|
+
buf = Buffer.allocUnsafe(2 + length);
|
|
1557
|
+
buf.writeUInt16BE(code, 0);
|
|
1558
|
+
if (typeof data === "string") {
|
|
1559
|
+
buf.write(data, 2);
|
|
1560
|
+
} else if (isUint8Array(data)) {
|
|
1561
|
+
buf.set(data, 2);
|
|
1562
|
+
} else {
|
|
1563
|
+
throw new TypeError("Second argument must be a string or a Uint8Array");
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
const options = {
|
|
1567
|
+
[kByteLength]: buf.length,
|
|
1568
|
+
fin: true,
|
|
1569
|
+
generateMask: this._generateMask,
|
|
1570
|
+
mask,
|
|
1571
|
+
maskBuffer: this._maskBuffer,
|
|
1572
|
+
opcode: 8,
|
|
1573
|
+
readOnly: false,
|
|
1574
|
+
rsv1: false
|
|
1575
|
+
};
|
|
1576
|
+
if (this._state !== DEFAULT) {
|
|
1577
|
+
this.enqueue([this.dispatch, buf, false, options, cb]);
|
|
1578
|
+
} else {
|
|
1579
|
+
this.sendFrame(_Sender.frame(buf, options), cb);
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
/**
|
|
1583
|
+
* Sends a ping message to the other peer.
|
|
1584
|
+
*
|
|
1585
|
+
* @param {*} data The message to send
|
|
1586
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
|
|
1587
|
+
* @param {Function} [cb] Callback
|
|
1588
|
+
* @public
|
|
1589
|
+
*/
|
|
1590
|
+
ping(data, mask, cb) {
|
|
1591
|
+
let byteLength;
|
|
1592
|
+
let readOnly;
|
|
1593
|
+
if (typeof data === "string") {
|
|
1594
|
+
byteLength = Buffer.byteLength(data);
|
|
1595
|
+
readOnly = false;
|
|
1596
|
+
} else if (isBlob(data)) {
|
|
1597
|
+
byteLength = data.size;
|
|
1598
|
+
readOnly = false;
|
|
1599
|
+
} else {
|
|
1600
|
+
data = toBuffer(data);
|
|
1601
|
+
byteLength = data.length;
|
|
1602
|
+
readOnly = toBuffer.readOnly;
|
|
1603
|
+
}
|
|
1604
|
+
if (byteLength > 125) {
|
|
1605
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1606
|
+
}
|
|
1607
|
+
const options = {
|
|
1608
|
+
[kByteLength]: byteLength,
|
|
1609
|
+
fin: true,
|
|
1610
|
+
generateMask: this._generateMask,
|
|
1611
|
+
mask,
|
|
1612
|
+
maskBuffer: this._maskBuffer,
|
|
1613
|
+
opcode: 9,
|
|
1614
|
+
readOnly,
|
|
1615
|
+
rsv1: false
|
|
1616
|
+
};
|
|
1617
|
+
if (isBlob(data)) {
|
|
1618
|
+
if (this._state !== DEFAULT) {
|
|
1619
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1620
|
+
} else {
|
|
1621
|
+
this.getBlobData(data, false, options, cb);
|
|
1622
|
+
}
|
|
1623
|
+
} else if (this._state !== DEFAULT) {
|
|
1624
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1625
|
+
} else {
|
|
1626
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* Sends a pong message to the other peer.
|
|
1631
|
+
*
|
|
1632
|
+
* @param {*} data The message to send
|
|
1633
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
|
|
1634
|
+
* @param {Function} [cb] Callback
|
|
1635
|
+
* @public
|
|
1636
|
+
*/
|
|
1637
|
+
pong(data, mask, cb) {
|
|
1638
|
+
let byteLength;
|
|
1639
|
+
let readOnly;
|
|
1640
|
+
if (typeof data === "string") {
|
|
1641
|
+
byteLength = Buffer.byteLength(data);
|
|
1642
|
+
readOnly = false;
|
|
1643
|
+
} else if (isBlob(data)) {
|
|
1644
|
+
byteLength = data.size;
|
|
1645
|
+
readOnly = false;
|
|
1646
|
+
} else {
|
|
1647
|
+
data = toBuffer(data);
|
|
1648
|
+
byteLength = data.length;
|
|
1649
|
+
readOnly = toBuffer.readOnly;
|
|
1650
|
+
}
|
|
1651
|
+
if (byteLength > 125) {
|
|
1652
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1653
|
+
}
|
|
1654
|
+
const options = {
|
|
1655
|
+
[kByteLength]: byteLength,
|
|
1656
|
+
fin: true,
|
|
1657
|
+
generateMask: this._generateMask,
|
|
1658
|
+
mask,
|
|
1659
|
+
maskBuffer: this._maskBuffer,
|
|
1660
|
+
opcode: 10,
|
|
1661
|
+
readOnly,
|
|
1662
|
+
rsv1: false
|
|
1663
|
+
};
|
|
1664
|
+
if (isBlob(data)) {
|
|
1665
|
+
if (this._state !== DEFAULT) {
|
|
1666
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1667
|
+
} else {
|
|
1668
|
+
this.getBlobData(data, false, options, cb);
|
|
1669
|
+
}
|
|
1670
|
+
} else if (this._state !== DEFAULT) {
|
|
1671
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1672
|
+
} else {
|
|
1673
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
/**
|
|
1677
|
+
* Sends a data message to the other peer.
|
|
1678
|
+
*
|
|
1679
|
+
* @param {*} data The message to send
|
|
1680
|
+
* @param {Object} options Options object
|
|
1681
|
+
* @param {Boolean} [options.binary=false] Specifies whether `data` is binary
|
|
1682
|
+
* or text
|
|
1683
|
+
* @param {Boolean} [options.compress=false] Specifies whether or not to
|
|
1684
|
+
* compress `data`
|
|
1685
|
+
* @param {Boolean} [options.fin=false] Specifies whether the fragment is the
|
|
1686
|
+
* last one
|
|
1687
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1688
|
+
* `data`
|
|
1689
|
+
* @param {Function} [cb] Callback
|
|
1690
|
+
* @public
|
|
1691
|
+
*/
|
|
1692
|
+
send(data, options, cb) {
|
|
1693
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
|
|
1694
|
+
let opcode = options.binary ? 2 : 1;
|
|
1695
|
+
let rsv1 = options.compress;
|
|
1696
|
+
let byteLength;
|
|
1697
|
+
let readOnly;
|
|
1698
|
+
if (typeof data === "string") {
|
|
1699
|
+
byteLength = Buffer.byteLength(data);
|
|
1700
|
+
readOnly = false;
|
|
1701
|
+
} else if (isBlob(data)) {
|
|
1702
|
+
byteLength = data.size;
|
|
1703
|
+
readOnly = false;
|
|
1704
|
+
} else {
|
|
1705
|
+
data = toBuffer(data);
|
|
1706
|
+
byteLength = data.length;
|
|
1707
|
+
readOnly = toBuffer.readOnly;
|
|
1708
|
+
}
|
|
1709
|
+
if (this._firstFragment) {
|
|
1710
|
+
this._firstFragment = false;
|
|
1711
|
+
if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
|
|
1712
|
+
rsv1 = byteLength >= perMessageDeflate._threshold;
|
|
1713
|
+
}
|
|
1714
|
+
this._compress = rsv1;
|
|
1715
|
+
} else {
|
|
1716
|
+
rsv1 = false;
|
|
1717
|
+
opcode = 0;
|
|
1718
|
+
}
|
|
1719
|
+
if (options.fin) this._firstFragment = true;
|
|
1720
|
+
const opts = {
|
|
1721
|
+
[kByteLength]: byteLength,
|
|
1722
|
+
fin: options.fin,
|
|
1723
|
+
generateMask: this._generateMask,
|
|
1724
|
+
mask: options.mask,
|
|
1725
|
+
maskBuffer: this._maskBuffer,
|
|
1726
|
+
opcode,
|
|
1727
|
+
readOnly,
|
|
1728
|
+
rsv1
|
|
1729
|
+
};
|
|
1730
|
+
if (isBlob(data)) {
|
|
1731
|
+
if (this._state !== DEFAULT) {
|
|
1732
|
+
this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
|
|
1733
|
+
} else {
|
|
1734
|
+
this.getBlobData(data, this._compress, opts, cb);
|
|
1735
|
+
}
|
|
1736
|
+
} else if (this._state !== DEFAULT) {
|
|
1737
|
+
this.enqueue([this.dispatch, data, this._compress, opts, cb]);
|
|
1738
|
+
} else {
|
|
1739
|
+
this.dispatch(data, this._compress, opts, cb);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
/**
|
|
1743
|
+
* Gets the contents of a blob as binary data.
|
|
1744
|
+
*
|
|
1745
|
+
* @param {Blob} blob The blob
|
|
1746
|
+
* @param {Boolean} [compress=false] Specifies whether or not to compress
|
|
1747
|
+
* the data
|
|
1748
|
+
* @param {Object} options Options object
|
|
1749
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
1750
|
+
* FIN bit
|
|
1751
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
1752
|
+
* masking key
|
|
1753
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1754
|
+
* `data`
|
|
1755
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
1756
|
+
* key
|
|
1757
|
+
* @param {Number} options.opcode The opcode
|
|
1758
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
1759
|
+
* modified
|
|
1760
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
1761
|
+
* RSV1 bit
|
|
1762
|
+
* @param {Function} [cb] Callback
|
|
1763
|
+
* @private
|
|
1764
|
+
*/
|
|
1765
|
+
getBlobData(blob, compress, options, cb) {
|
|
1766
|
+
this._bufferedBytes += options[kByteLength];
|
|
1767
|
+
this._state = GET_BLOB_DATA;
|
|
1768
|
+
blob.arrayBuffer().then((arrayBuffer) => {
|
|
1769
|
+
if (this._socket.destroyed) {
|
|
1770
|
+
const err = new Error(
|
|
1771
|
+
"The socket was closed while the blob was being read"
|
|
1772
|
+
);
|
|
1773
|
+
process.nextTick(callCallbacks, this, err, cb);
|
|
1774
|
+
return;
|
|
1775
|
+
}
|
|
1776
|
+
this._bufferedBytes -= options[kByteLength];
|
|
1777
|
+
const data = toBuffer(arrayBuffer);
|
|
1778
|
+
if (!compress) {
|
|
1779
|
+
this._state = DEFAULT;
|
|
1780
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1781
|
+
this.dequeue();
|
|
1782
|
+
} else {
|
|
1783
|
+
this.dispatch(data, compress, options, cb);
|
|
1784
|
+
}
|
|
1785
|
+
}).catch((err) => {
|
|
1786
|
+
process.nextTick(onError, this, err, cb);
|
|
1787
|
+
});
|
|
1788
|
+
}
|
|
1789
|
+
/**
|
|
1790
|
+
* Dispatches a message.
|
|
1791
|
+
*
|
|
1792
|
+
* @param {(Buffer|String)} data The message to send
|
|
1793
|
+
* @param {Boolean} [compress=false] Specifies whether or not to compress
|
|
1794
|
+
* `data`
|
|
1795
|
+
* @param {Object} options Options object
|
|
1796
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
1797
|
+
* FIN bit
|
|
1798
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
1799
|
+
* masking key
|
|
1800
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1801
|
+
* `data`
|
|
1802
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
1803
|
+
* key
|
|
1804
|
+
* @param {Number} options.opcode The opcode
|
|
1805
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
1806
|
+
* modified
|
|
1807
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
1808
|
+
* RSV1 bit
|
|
1809
|
+
* @param {Function} [cb] Callback
|
|
1810
|
+
* @private
|
|
1811
|
+
*/
|
|
1812
|
+
dispatch(data, compress, options, cb) {
|
|
1813
|
+
if (!compress) {
|
|
1814
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1815
|
+
return;
|
|
1816
|
+
}
|
|
1817
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
|
|
1818
|
+
this._bufferedBytes += options[kByteLength];
|
|
1819
|
+
this._state = DEFLATING;
|
|
1820
|
+
perMessageDeflate.compress(data, options.fin, (_, buf) => {
|
|
1821
|
+
if (this._socket.destroyed) {
|
|
1822
|
+
const err = new Error(
|
|
1823
|
+
"The socket was closed while data was being compressed"
|
|
1824
|
+
);
|
|
1825
|
+
callCallbacks(this, err, cb);
|
|
1826
|
+
return;
|
|
1827
|
+
}
|
|
1828
|
+
this._bufferedBytes -= options[kByteLength];
|
|
1829
|
+
this._state = DEFAULT;
|
|
1830
|
+
options.readOnly = false;
|
|
1831
|
+
this.sendFrame(_Sender.frame(buf, options), cb);
|
|
1832
|
+
this.dequeue();
|
|
1833
|
+
});
|
|
1834
|
+
}
|
|
1835
|
+
/**
|
|
1836
|
+
* Executes queued send operations.
|
|
1837
|
+
*
|
|
1838
|
+
* @private
|
|
1839
|
+
*/
|
|
1840
|
+
dequeue() {
|
|
1841
|
+
while (this._state === DEFAULT && this._queue.length) {
|
|
1842
|
+
const params = this._queue.shift();
|
|
1843
|
+
this._bufferedBytes -= params[3][kByteLength];
|
|
1844
|
+
Reflect.apply(params[0], this, params.slice(1));
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
/**
|
|
1848
|
+
* Enqueues a send operation.
|
|
1849
|
+
*
|
|
1850
|
+
* @param {Array} params Send operation parameters.
|
|
1851
|
+
* @private
|
|
1852
|
+
*/
|
|
1853
|
+
enqueue(params) {
|
|
1854
|
+
this._bufferedBytes += params[3][kByteLength];
|
|
1855
|
+
this._queue.push(params);
|
|
1856
|
+
}
|
|
1857
|
+
/**
|
|
1858
|
+
* Sends a frame.
|
|
1859
|
+
*
|
|
1860
|
+
* @param {(Buffer | String)[]} list The frame to send
|
|
1861
|
+
* @param {Function} [cb] Callback
|
|
1862
|
+
* @private
|
|
1863
|
+
*/
|
|
1864
|
+
sendFrame(list, cb) {
|
|
1865
|
+
if (list.length === 2) {
|
|
1866
|
+
this._socket.cork();
|
|
1867
|
+
this._socket.write(list[0]);
|
|
1868
|
+
this._socket.write(list[1], cb);
|
|
1869
|
+
this._socket.uncork();
|
|
1870
|
+
} else {
|
|
1871
|
+
this._socket.write(list[0], cb);
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
};
|
|
1875
|
+
module.exports = Sender2;
|
|
1876
|
+
function callCallbacks(sender, err, cb) {
|
|
1877
|
+
if (typeof cb === "function") cb(err);
|
|
1878
|
+
for (let i = 0; i < sender._queue.length; i++) {
|
|
1879
|
+
const params = sender._queue[i];
|
|
1880
|
+
const callback = params[params.length - 1];
|
|
1881
|
+
if (typeof callback === "function") callback(err);
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
function onError(sender, err, cb) {
|
|
1885
|
+
callCallbacks(sender, err, cb);
|
|
1886
|
+
sender.onerror(err);
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
});
|
|
1890
|
+
|
|
1891
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/event-target.js
|
|
1892
|
+
var require_event_target = __commonJS({
|
|
1893
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/event-target.js"(exports, module) {
|
|
1894
|
+
"use strict";
|
|
1895
|
+
var { kForOnEventAttribute, kListener } = require_constants();
|
|
1896
|
+
var kCode = /* @__PURE__ */ Symbol("kCode");
|
|
1897
|
+
var kData = /* @__PURE__ */ Symbol("kData");
|
|
1898
|
+
var kError = /* @__PURE__ */ Symbol("kError");
|
|
1899
|
+
var kMessage = /* @__PURE__ */ Symbol("kMessage");
|
|
1900
|
+
var kReason = /* @__PURE__ */ Symbol("kReason");
|
|
1901
|
+
var kTarget = /* @__PURE__ */ Symbol("kTarget");
|
|
1902
|
+
var kType = /* @__PURE__ */ Symbol("kType");
|
|
1903
|
+
var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
|
|
1904
|
+
var Event2 = class {
|
|
1905
|
+
/**
|
|
1906
|
+
* Create a new `Event`.
|
|
1907
|
+
*
|
|
1908
|
+
* @param {String} type The name of the event
|
|
1909
|
+
* @throws {TypeError} If the `type` argument is not specified
|
|
1910
|
+
*/
|
|
1911
|
+
constructor(type) {
|
|
1912
|
+
this[kTarget] = null;
|
|
1913
|
+
this[kType] = type;
|
|
1914
|
+
}
|
|
1915
|
+
/**
|
|
1916
|
+
* @type {*}
|
|
1917
|
+
*/
|
|
1918
|
+
get target() {
|
|
1919
|
+
return this[kTarget];
|
|
1920
|
+
}
|
|
1921
|
+
/**
|
|
1922
|
+
* @type {String}
|
|
1923
|
+
*/
|
|
1924
|
+
get type() {
|
|
1925
|
+
return this[kType];
|
|
1926
|
+
}
|
|
1927
|
+
};
|
|
1928
|
+
Object.defineProperty(Event2.prototype, "target", { enumerable: true });
|
|
1929
|
+
Object.defineProperty(Event2.prototype, "type", { enumerable: true });
|
|
1930
|
+
var CloseEvent = class extends Event2 {
|
|
1931
|
+
/**
|
|
1932
|
+
* Create a new `CloseEvent`.
|
|
1933
|
+
*
|
|
1934
|
+
* @param {String} type The name of the event
|
|
1935
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
1936
|
+
* attributes via object members of the same name
|
|
1937
|
+
* @param {Number} [options.code=0] The status code explaining why the
|
|
1938
|
+
* connection was closed
|
|
1939
|
+
* @param {String} [options.reason=''] A human-readable string explaining why
|
|
1940
|
+
* the connection was closed
|
|
1941
|
+
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
|
|
1942
|
+
* connection was cleanly closed
|
|
1943
|
+
*/
|
|
1944
|
+
constructor(type, options = {}) {
|
|
1945
|
+
super(type);
|
|
1946
|
+
this[kCode] = options.code === void 0 ? 0 : options.code;
|
|
1947
|
+
this[kReason] = options.reason === void 0 ? "" : options.reason;
|
|
1948
|
+
this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
|
|
1949
|
+
}
|
|
1950
|
+
/**
|
|
1951
|
+
* @type {Number}
|
|
1952
|
+
*/
|
|
1953
|
+
get code() {
|
|
1954
|
+
return this[kCode];
|
|
1955
|
+
}
|
|
1956
|
+
/**
|
|
1957
|
+
* @type {String}
|
|
1958
|
+
*/
|
|
1959
|
+
get reason() {
|
|
1960
|
+
return this[kReason];
|
|
1961
|
+
}
|
|
1962
|
+
/**
|
|
1963
|
+
* @type {Boolean}
|
|
1964
|
+
*/
|
|
1965
|
+
get wasClean() {
|
|
1966
|
+
return this[kWasClean];
|
|
1967
|
+
}
|
|
1968
|
+
};
|
|
1969
|
+
Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
|
|
1970
|
+
Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
|
|
1971
|
+
Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
|
|
1972
|
+
var ErrorEvent2 = class extends Event2 {
|
|
1973
|
+
/**
|
|
1974
|
+
* Create a new `ErrorEvent`.
|
|
1975
|
+
*
|
|
1976
|
+
* @param {String} type The name of the event
|
|
1977
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
1978
|
+
* attributes via object members of the same name
|
|
1979
|
+
* @param {*} [options.error=null] The error that generated this event
|
|
1980
|
+
* @param {String} [options.message=''] The error message
|
|
1981
|
+
*/
|
|
1982
|
+
constructor(type, options = {}) {
|
|
1983
|
+
super(type);
|
|
1984
|
+
this[kError] = options.error === void 0 ? null : options.error;
|
|
1985
|
+
this[kMessage] = options.message === void 0 ? "" : options.message;
|
|
1986
|
+
}
|
|
1987
|
+
/**
|
|
1988
|
+
* @type {*}
|
|
1989
|
+
*/
|
|
1990
|
+
get error() {
|
|
1991
|
+
return this[kError];
|
|
1992
|
+
}
|
|
1993
|
+
/**
|
|
1994
|
+
* @type {String}
|
|
1995
|
+
*/
|
|
1996
|
+
get message() {
|
|
1997
|
+
return this[kMessage];
|
|
1998
|
+
}
|
|
1999
|
+
};
|
|
2000
|
+
Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: true });
|
|
2001
|
+
Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: true });
|
|
2002
|
+
var MessageEvent2 = class extends Event2 {
|
|
2003
|
+
/**
|
|
2004
|
+
* Create a new `MessageEvent`.
|
|
2005
|
+
*
|
|
2006
|
+
* @param {String} type The name of the event
|
|
2007
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
2008
|
+
* attributes via object members of the same name
|
|
2009
|
+
* @param {*} [options.data=null] The message content
|
|
2010
|
+
*/
|
|
2011
|
+
constructor(type, options = {}) {
|
|
2012
|
+
super(type);
|
|
2013
|
+
this[kData] = options.data === void 0 ? null : options.data;
|
|
2014
|
+
}
|
|
2015
|
+
/**
|
|
2016
|
+
* @type {*}
|
|
2017
|
+
*/
|
|
2018
|
+
get data() {
|
|
2019
|
+
return this[kData];
|
|
2020
|
+
}
|
|
2021
|
+
};
|
|
2022
|
+
Object.defineProperty(MessageEvent2.prototype, "data", { enumerable: true });
|
|
2023
|
+
var EventTarget2 = {
|
|
2024
|
+
/**
|
|
2025
|
+
* Register an event listener.
|
|
2026
|
+
*
|
|
2027
|
+
* @param {String} type A string representing the event type to listen for
|
|
2028
|
+
* @param {(Function|Object)} handler The listener to add
|
|
2029
|
+
* @param {Object} [options] An options object specifies characteristics about
|
|
2030
|
+
* the event listener
|
|
2031
|
+
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
|
|
2032
|
+
* listener should be invoked at most once after being added. If `true`,
|
|
2033
|
+
* the listener would be automatically removed when invoked.
|
|
2034
|
+
* @public
|
|
2035
|
+
*/
|
|
2036
|
+
addEventListener(type, handler, options = {}) {
|
|
2037
|
+
for (const listener of this.listeners(type)) {
|
|
2038
|
+
if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
2039
|
+
return;
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
let wrapper;
|
|
2043
|
+
if (type === "message") {
|
|
2044
|
+
wrapper = function onMessage(data, isBinary) {
|
|
2045
|
+
const event = new MessageEvent2("message", {
|
|
2046
|
+
data: isBinary ? data : data.toString()
|
|
2047
|
+
});
|
|
2048
|
+
event[kTarget] = this;
|
|
2049
|
+
callListener(handler, this, event);
|
|
2050
|
+
};
|
|
2051
|
+
} else if (type === "close") {
|
|
2052
|
+
wrapper = function onClose(code, message) {
|
|
2053
|
+
const event = new CloseEvent("close", {
|
|
2054
|
+
code,
|
|
2055
|
+
reason: message.toString(),
|
|
2056
|
+
wasClean: this._closeFrameReceived && this._closeFrameSent
|
|
2057
|
+
});
|
|
2058
|
+
event[kTarget] = this;
|
|
2059
|
+
callListener(handler, this, event);
|
|
2060
|
+
};
|
|
2061
|
+
} else if (type === "error") {
|
|
2062
|
+
wrapper = function onError(error) {
|
|
2063
|
+
const event = new ErrorEvent2("error", {
|
|
2064
|
+
error,
|
|
2065
|
+
message: error.message
|
|
2066
|
+
});
|
|
2067
|
+
event[kTarget] = this;
|
|
2068
|
+
callListener(handler, this, event);
|
|
2069
|
+
};
|
|
2070
|
+
} else if (type === "open") {
|
|
2071
|
+
wrapper = function onOpen() {
|
|
2072
|
+
const event = new Event2("open");
|
|
2073
|
+
event[kTarget] = this;
|
|
2074
|
+
callListener(handler, this, event);
|
|
2075
|
+
};
|
|
2076
|
+
} else {
|
|
2077
|
+
return;
|
|
2078
|
+
}
|
|
2079
|
+
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
|
|
2080
|
+
wrapper[kListener] = handler;
|
|
2081
|
+
if (options.once) {
|
|
2082
|
+
this.once(type, wrapper);
|
|
2083
|
+
} else {
|
|
2084
|
+
this.on(type, wrapper);
|
|
2085
|
+
}
|
|
2086
|
+
},
|
|
2087
|
+
/**
|
|
2088
|
+
* Remove an event listener.
|
|
2089
|
+
*
|
|
2090
|
+
* @param {String} type A string representing the event type to remove
|
|
2091
|
+
* @param {(Function|Object)} handler The listener to remove
|
|
2092
|
+
* @public
|
|
2093
|
+
*/
|
|
2094
|
+
removeEventListener(type, handler) {
|
|
2095
|
+
for (const listener of this.listeners(type)) {
|
|
2096
|
+
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
2097
|
+
this.removeListener(type, listener);
|
|
2098
|
+
break;
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
};
|
|
2103
|
+
module.exports = {
|
|
2104
|
+
CloseEvent,
|
|
2105
|
+
ErrorEvent: ErrorEvent2,
|
|
2106
|
+
Event: Event2,
|
|
2107
|
+
EventTarget: EventTarget2,
|
|
2108
|
+
MessageEvent: MessageEvent2
|
|
2109
|
+
};
|
|
2110
|
+
function callListener(listener, thisArg, event) {
|
|
2111
|
+
if (typeof listener === "object" && listener.handleEvent) {
|
|
2112
|
+
listener.handleEvent.call(listener, event);
|
|
2113
|
+
} else {
|
|
2114
|
+
listener.call(thisArg, event);
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
});
|
|
2119
|
+
|
|
2120
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/extension.js
|
|
2121
|
+
var require_extension = __commonJS({
|
|
2122
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/extension.js"(exports, module) {
|
|
2123
|
+
"use strict";
|
|
2124
|
+
var { tokenChars } = require_validation();
|
|
2125
|
+
function push(dest, name, elem) {
|
|
2126
|
+
if (dest[name] === void 0) dest[name] = [elem];
|
|
2127
|
+
else dest[name].push(elem);
|
|
2128
|
+
}
|
|
2129
|
+
function parse(header) {
|
|
2130
|
+
const offers = /* @__PURE__ */ Object.create(null);
|
|
2131
|
+
let params = /* @__PURE__ */ Object.create(null);
|
|
2132
|
+
let mustUnescape = false;
|
|
2133
|
+
let isEscaping = false;
|
|
2134
|
+
let inQuotes = false;
|
|
2135
|
+
let extensionName;
|
|
2136
|
+
let paramName;
|
|
2137
|
+
let start = -1;
|
|
2138
|
+
let code = -1;
|
|
2139
|
+
let end = -1;
|
|
2140
|
+
let i = 0;
|
|
2141
|
+
for (; i < header.length; i++) {
|
|
2142
|
+
code = header.charCodeAt(i);
|
|
2143
|
+
if (extensionName === void 0) {
|
|
2144
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
2145
|
+
if (start === -1) start = i;
|
|
2146
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
2147
|
+
if (end === -1 && start !== -1) end = i;
|
|
2148
|
+
} else if (code === 59 || code === 44) {
|
|
2149
|
+
if (start === -1) {
|
|
2150
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2151
|
+
}
|
|
2152
|
+
if (end === -1) end = i;
|
|
2153
|
+
const name = header.slice(start, end);
|
|
2154
|
+
if (code === 44) {
|
|
2155
|
+
push(offers, name, params);
|
|
2156
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2157
|
+
} else {
|
|
2158
|
+
extensionName = name;
|
|
2159
|
+
}
|
|
2160
|
+
start = end = -1;
|
|
2161
|
+
} else {
|
|
2162
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2163
|
+
}
|
|
2164
|
+
} else if (paramName === void 0) {
|
|
2165
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
2166
|
+
if (start === -1) start = i;
|
|
2167
|
+
} else if (code === 32 || code === 9) {
|
|
2168
|
+
if (end === -1 && start !== -1) end = i;
|
|
2169
|
+
} else if (code === 59 || code === 44) {
|
|
2170
|
+
if (start === -1) {
|
|
2171
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2172
|
+
}
|
|
2173
|
+
if (end === -1) end = i;
|
|
2174
|
+
push(params, header.slice(start, end), true);
|
|
2175
|
+
if (code === 44) {
|
|
2176
|
+
push(offers, extensionName, params);
|
|
2177
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2178
|
+
extensionName = void 0;
|
|
2179
|
+
}
|
|
2180
|
+
start = end = -1;
|
|
2181
|
+
} else if (code === 61 && start !== -1 && end === -1) {
|
|
2182
|
+
paramName = header.slice(start, i);
|
|
2183
|
+
start = end = -1;
|
|
2184
|
+
} else {
|
|
2185
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2186
|
+
}
|
|
2187
|
+
} else {
|
|
2188
|
+
if (isEscaping) {
|
|
2189
|
+
if (tokenChars[code] !== 1) {
|
|
2190
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2191
|
+
}
|
|
2192
|
+
if (start === -1) start = i;
|
|
2193
|
+
else if (!mustUnescape) mustUnescape = true;
|
|
2194
|
+
isEscaping = false;
|
|
2195
|
+
} else if (inQuotes) {
|
|
2196
|
+
if (tokenChars[code] === 1) {
|
|
2197
|
+
if (start === -1) start = i;
|
|
2198
|
+
} else if (code === 34 && start !== -1) {
|
|
2199
|
+
inQuotes = false;
|
|
2200
|
+
end = i;
|
|
2201
|
+
} else if (code === 92) {
|
|
2202
|
+
isEscaping = true;
|
|
2203
|
+
} else {
|
|
2204
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2205
|
+
}
|
|
2206
|
+
} else if (code === 34 && header.charCodeAt(i - 1) === 61) {
|
|
2207
|
+
inQuotes = true;
|
|
2208
|
+
} else if (end === -1 && tokenChars[code] === 1) {
|
|
2209
|
+
if (start === -1) start = i;
|
|
2210
|
+
} else if (start !== -1 && (code === 32 || code === 9)) {
|
|
2211
|
+
if (end === -1) end = i;
|
|
2212
|
+
} else if (code === 59 || code === 44) {
|
|
2213
|
+
if (start === -1) {
|
|
2214
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2215
|
+
}
|
|
2216
|
+
if (end === -1) end = i;
|
|
2217
|
+
let value = header.slice(start, end);
|
|
2218
|
+
if (mustUnescape) {
|
|
2219
|
+
value = value.replace(/\\/g, "");
|
|
2220
|
+
mustUnescape = false;
|
|
2221
|
+
}
|
|
2222
|
+
push(params, paramName, value);
|
|
2223
|
+
if (code === 44) {
|
|
2224
|
+
push(offers, extensionName, params);
|
|
2225
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2226
|
+
extensionName = void 0;
|
|
2227
|
+
}
|
|
2228
|
+
paramName = void 0;
|
|
2229
|
+
start = end = -1;
|
|
2230
|
+
} else {
|
|
2231
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2232
|
+
}
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
if (start === -1 || inQuotes || code === 32 || code === 9) {
|
|
2236
|
+
throw new SyntaxError("Unexpected end of input");
|
|
2237
|
+
}
|
|
2238
|
+
if (end === -1) end = i;
|
|
2239
|
+
const token = header.slice(start, end);
|
|
2240
|
+
if (extensionName === void 0) {
|
|
2241
|
+
push(offers, token, params);
|
|
2242
|
+
} else {
|
|
2243
|
+
if (paramName === void 0) {
|
|
2244
|
+
push(params, token, true);
|
|
2245
|
+
} else if (mustUnescape) {
|
|
2246
|
+
push(params, paramName, token.replace(/\\/g, ""));
|
|
2247
|
+
} else {
|
|
2248
|
+
push(params, paramName, token);
|
|
2249
|
+
}
|
|
2250
|
+
push(offers, extensionName, params);
|
|
2251
|
+
}
|
|
2252
|
+
return offers;
|
|
2253
|
+
}
|
|
2254
|
+
function format(extensions) {
|
|
2255
|
+
return Object.keys(extensions).map((extension2) => {
|
|
2256
|
+
let configurations = extensions[extension2];
|
|
2257
|
+
if (!Array.isArray(configurations)) configurations = [configurations];
|
|
2258
|
+
return configurations.map((params) => {
|
|
2259
|
+
return [extension2].concat(
|
|
2260
|
+
Object.keys(params).map((k) => {
|
|
2261
|
+
let values = params[k];
|
|
2262
|
+
if (!Array.isArray(values)) values = [values];
|
|
2263
|
+
return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
|
|
2264
|
+
})
|
|
2265
|
+
).join("; ");
|
|
2266
|
+
}).join(", ");
|
|
2267
|
+
}).join(", ");
|
|
2268
|
+
}
|
|
2269
|
+
module.exports = { format, parse };
|
|
2270
|
+
}
|
|
2271
|
+
});
|
|
2272
|
+
|
|
2273
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket.js
|
|
2274
|
+
var require_websocket = __commonJS({
|
|
2275
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket.js"(exports, module) {
|
|
2276
|
+
"use strict";
|
|
2277
|
+
var EventEmitter = __require("events");
|
|
2278
|
+
var https = __require("https");
|
|
2279
|
+
var http = __require("http");
|
|
2280
|
+
var net = __require("net");
|
|
2281
|
+
var tls = __require("tls");
|
|
2282
|
+
var { randomBytes, createHash } = __require("crypto");
|
|
2283
|
+
var { Duplex, Readable: Readable2 } = __require("stream");
|
|
2284
|
+
var { URL: URL2 } = __require("url");
|
|
2285
|
+
var PerMessageDeflate2 = require_permessage_deflate();
|
|
2286
|
+
var Receiver2 = require_receiver();
|
|
2287
|
+
var Sender2 = require_sender();
|
|
2288
|
+
var { isBlob } = require_validation();
|
|
2289
|
+
var {
|
|
2290
|
+
BINARY_TYPES,
|
|
2291
|
+
CLOSE_TIMEOUT,
|
|
2292
|
+
EMPTY_BUFFER,
|
|
2293
|
+
GUID,
|
|
2294
|
+
kForOnEventAttribute,
|
|
2295
|
+
kListener,
|
|
2296
|
+
kStatusCode,
|
|
2297
|
+
kWebSocket,
|
|
2298
|
+
NOOP
|
|
2299
|
+
} = require_constants();
|
|
2300
|
+
var {
|
|
2301
|
+
EventTarget: { addEventListener, removeEventListener }
|
|
2302
|
+
} = require_event_target();
|
|
2303
|
+
var { format, parse } = require_extension();
|
|
2304
|
+
var { toBuffer } = require_buffer_util();
|
|
2305
|
+
var kAborted = /* @__PURE__ */ Symbol("kAborted");
|
|
2306
|
+
var protocolVersions = [8, 13];
|
|
2307
|
+
var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
|
|
2308
|
+
var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
|
|
2309
|
+
var WebSocket2 = class _WebSocket extends EventEmitter {
|
|
2310
|
+
/**
|
|
2311
|
+
* Create a new `WebSocket`.
|
|
2312
|
+
*
|
|
2313
|
+
* @param {(String|URL)} address The URL to which to connect
|
|
2314
|
+
* @param {(String|String[])} [protocols] The subprotocols
|
|
2315
|
+
* @param {Object} [options] Connection options
|
|
2316
|
+
*/
|
|
2317
|
+
constructor(address, protocols, options) {
|
|
2318
|
+
super();
|
|
2319
|
+
this._binaryType = BINARY_TYPES[0];
|
|
2320
|
+
this._closeCode = 1006;
|
|
2321
|
+
this._closeFrameReceived = false;
|
|
2322
|
+
this._closeFrameSent = false;
|
|
2323
|
+
this._closeMessage = EMPTY_BUFFER;
|
|
2324
|
+
this._closeTimer = null;
|
|
2325
|
+
this._errorEmitted = false;
|
|
2326
|
+
this._extensions = {};
|
|
2327
|
+
this._paused = false;
|
|
2328
|
+
this._protocol = "";
|
|
2329
|
+
this._readyState = _WebSocket.CONNECTING;
|
|
2330
|
+
this._receiver = null;
|
|
2331
|
+
this._sender = null;
|
|
2332
|
+
this._socket = null;
|
|
2333
|
+
if (address !== null) {
|
|
2334
|
+
this._bufferedAmount = 0;
|
|
2335
|
+
this._isServer = false;
|
|
2336
|
+
this._redirects = 0;
|
|
2337
|
+
if (protocols === void 0) {
|
|
2338
|
+
protocols = [];
|
|
2339
|
+
} else if (!Array.isArray(protocols)) {
|
|
2340
|
+
if (typeof protocols === "object" && protocols !== null) {
|
|
2341
|
+
options = protocols;
|
|
2342
|
+
protocols = [];
|
|
2343
|
+
} else {
|
|
2344
|
+
protocols = [protocols];
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
initAsClient(this, address, protocols, options);
|
|
2348
|
+
} else {
|
|
2349
|
+
this._autoPong = options.autoPong;
|
|
2350
|
+
this._closeTimeout = options.closeTimeout;
|
|
2351
|
+
this._isServer = true;
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
/**
|
|
2355
|
+
* For historical reasons, the custom "nodebuffer" type is used by the default
|
|
2356
|
+
* instead of "blob".
|
|
2357
|
+
*
|
|
2358
|
+
* @type {String}
|
|
2359
|
+
*/
|
|
2360
|
+
get binaryType() {
|
|
2361
|
+
return this._binaryType;
|
|
2362
|
+
}
|
|
2363
|
+
set binaryType(type) {
|
|
2364
|
+
if (!BINARY_TYPES.includes(type)) return;
|
|
2365
|
+
this._binaryType = type;
|
|
2366
|
+
if (this._receiver) this._receiver._binaryType = type;
|
|
2367
|
+
}
|
|
2368
|
+
/**
|
|
2369
|
+
* @type {Number}
|
|
2370
|
+
*/
|
|
2371
|
+
get bufferedAmount() {
|
|
2372
|
+
if (!this._socket) return this._bufferedAmount;
|
|
2373
|
+
return this._socket._writableState.length + this._sender._bufferedBytes;
|
|
2374
|
+
}
|
|
2375
|
+
/**
|
|
2376
|
+
* @type {String}
|
|
2377
|
+
*/
|
|
2378
|
+
get extensions() {
|
|
2379
|
+
return Object.keys(this._extensions).join();
|
|
2380
|
+
}
|
|
2381
|
+
/**
|
|
2382
|
+
* @type {Boolean}
|
|
2383
|
+
*/
|
|
2384
|
+
get isPaused() {
|
|
2385
|
+
return this._paused;
|
|
2386
|
+
}
|
|
2387
|
+
/**
|
|
2388
|
+
* @type {Function}
|
|
2389
|
+
*/
|
|
2390
|
+
/* istanbul ignore next */
|
|
2391
|
+
get onclose() {
|
|
2392
|
+
return null;
|
|
2393
|
+
}
|
|
2394
|
+
/**
|
|
2395
|
+
* @type {Function}
|
|
2396
|
+
*/
|
|
2397
|
+
/* istanbul ignore next */
|
|
2398
|
+
get onerror() {
|
|
2399
|
+
return null;
|
|
2400
|
+
}
|
|
2401
|
+
/**
|
|
2402
|
+
* @type {Function}
|
|
2403
|
+
*/
|
|
2404
|
+
/* istanbul ignore next */
|
|
2405
|
+
get onopen() {
|
|
2406
|
+
return null;
|
|
2407
|
+
}
|
|
2408
|
+
/**
|
|
2409
|
+
* @type {Function}
|
|
2410
|
+
*/
|
|
2411
|
+
/* istanbul ignore next */
|
|
2412
|
+
get onmessage() {
|
|
2413
|
+
return null;
|
|
2414
|
+
}
|
|
2415
|
+
/**
|
|
2416
|
+
* @type {String}
|
|
2417
|
+
*/
|
|
2418
|
+
get protocol() {
|
|
2419
|
+
return this._protocol;
|
|
2420
|
+
}
|
|
2421
|
+
/**
|
|
2422
|
+
* @type {Number}
|
|
2423
|
+
*/
|
|
2424
|
+
get readyState() {
|
|
2425
|
+
return this._readyState;
|
|
2426
|
+
}
|
|
2427
|
+
/**
|
|
2428
|
+
* @type {String}
|
|
2429
|
+
*/
|
|
2430
|
+
get url() {
|
|
2431
|
+
return this._url;
|
|
2432
|
+
}
|
|
2433
|
+
/**
|
|
2434
|
+
* Set up the socket and the internal resources.
|
|
2435
|
+
*
|
|
2436
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
2437
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
2438
|
+
* @param {Object} options Options object
|
|
2439
|
+
* @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
|
|
2440
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
2441
|
+
* multiple times in the same tick
|
|
2442
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
2443
|
+
* masking key
|
|
2444
|
+
* @param {Number} [options.maxBufferedChunks=0] The maximum number of
|
|
2445
|
+
* buffered data chunks
|
|
2446
|
+
* @param {Number} [options.maxFragments=0] The maximum number of message
|
|
2447
|
+
* fragments
|
|
2448
|
+
* @param {Number} [options.maxPayload=0] The maximum allowed message size
|
|
2449
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
2450
|
+
* not to skip UTF-8 validation for text and close messages
|
|
2451
|
+
* @private
|
|
2452
|
+
*/
|
|
2453
|
+
setSocket(socket, head, options) {
|
|
2454
|
+
const receiver = new Receiver2({
|
|
2455
|
+
allowSynchronousEvents: options.allowSynchronousEvents,
|
|
2456
|
+
binaryType: this.binaryType,
|
|
2457
|
+
extensions: this._extensions,
|
|
2458
|
+
isServer: this._isServer,
|
|
2459
|
+
maxBufferedChunks: options.maxBufferedChunks,
|
|
2460
|
+
maxFragments: options.maxFragments,
|
|
2461
|
+
maxPayload: options.maxPayload,
|
|
2462
|
+
skipUTF8Validation: options.skipUTF8Validation
|
|
2463
|
+
});
|
|
2464
|
+
const sender = new Sender2(socket, this._extensions, options.generateMask);
|
|
2465
|
+
this._receiver = receiver;
|
|
2466
|
+
this._sender = sender;
|
|
2467
|
+
this._socket = socket;
|
|
2468
|
+
receiver[kWebSocket] = this;
|
|
2469
|
+
sender[kWebSocket] = this;
|
|
2470
|
+
socket[kWebSocket] = this;
|
|
2471
|
+
receiver.on("conclude", receiverOnConclude);
|
|
2472
|
+
receiver.on("drain", receiverOnDrain);
|
|
2473
|
+
receiver.on("error", receiverOnError);
|
|
2474
|
+
receiver.on("message", receiverOnMessage);
|
|
2475
|
+
receiver.on("ping", receiverOnPing);
|
|
2476
|
+
receiver.on("pong", receiverOnPong);
|
|
2477
|
+
sender.onerror = senderOnError;
|
|
2478
|
+
if (socket.setTimeout) socket.setTimeout(0);
|
|
2479
|
+
if (socket.setNoDelay) socket.setNoDelay();
|
|
2480
|
+
if (head.length > 0) socket.unshift(head);
|
|
2481
|
+
socket.on("close", socketOnClose);
|
|
2482
|
+
socket.on("data", socketOnData);
|
|
2483
|
+
socket.on("end", socketOnEnd);
|
|
2484
|
+
socket.on("error", socketOnError);
|
|
2485
|
+
this._readyState = _WebSocket.OPEN;
|
|
2486
|
+
this.emit("open");
|
|
2487
|
+
}
|
|
2488
|
+
/**
|
|
2489
|
+
* Emit the `'close'` event.
|
|
2490
|
+
*
|
|
2491
|
+
* @private
|
|
2492
|
+
*/
|
|
2493
|
+
emitClose() {
|
|
2494
|
+
if (!this._socket) {
|
|
2495
|
+
this._readyState = _WebSocket.CLOSED;
|
|
2496
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
2497
|
+
return;
|
|
2498
|
+
}
|
|
2499
|
+
if (this._extensions[PerMessageDeflate2.extensionName]) {
|
|
2500
|
+
this._extensions[PerMessageDeflate2.extensionName].cleanup();
|
|
2501
|
+
}
|
|
2502
|
+
this._receiver.removeAllListeners();
|
|
2503
|
+
this._readyState = _WebSocket.CLOSED;
|
|
2504
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
2505
|
+
}
|
|
2506
|
+
/**
|
|
2507
|
+
* Start a closing handshake.
|
|
2508
|
+
*
|
|
2509
|
+
* +----------+ +-----------+ +----------+
|
|
2510
|
+
* - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
|
|
2511
|
+
* | +----------+ +-----------+ +----------+ |
|
|
2512
|
+
* +----------+ +-----------+ |
|
|
2513
|
+
* CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
|
|
2514
|
+
* +----------+ +-----------+ |
|
|
2515
|
+
* | | | +---+ |
|
|
2516
|
+
* +------------------------+-->|fin| - - - -
|
|
2517
|
+
* | +---+ | +---+
|
|
2518
|
+
* - - - - -|fin|<---------------------+
|
|
2519
|
+
* +---+
|
|
2520
|
+
*
|
|
2521
|
+
* @param {Number} [code] Status code explaining why the connection is closing
|
|
2522
|
+
* @param {(String|Buffer)} [data] The reason why the connection is
|
|
2523
|
+
* closing
|
|
2524
|
+
* @public
|
|
2525
|
+
*/
|
|
2526
|
+
close(code, data) {
|
|
2527
|
+
if (this.readyState === _WebSocket.CLOSED) return;
|
|
2528
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2529
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
2530
|
+
abortHandshake(this, this._req, msg);
|
|
2531
|
+
return;
|
|
2532
|
+
}
|
|
2533
|
+
if (this.readyState === _WebSocket.CLOSING) {
|
|
2534
|
+
if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
|
|
2535
|
+
this._socket.end();
|
|
2536
|
+
}
|
|
2537
|
+
return;
|
|
2538
|
+
}
|
|
2539
|
+
this._readyState = _WebSocket.CLOSING;
|
|
2540
|
+
this._sender.close(code, data, !this._isServer, (err) => {
|
|
2541
|
+
if (err) return;
|
|
2542
|
+
this._closeFrameSent = true;
|
|
2543
|
+
if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
|
|
2544
|
+
this._socket.end();
|
|
2545
|
+
}
|
|
2546
|
+
});
|
|
2547
|
+
setCloseTimer(this);
|
|
2548
|
+
}
|
|
2549
|
+
/**
|
|
2550
|
+
* Pause the socket.
|
|
2551
|
+
*
|
|
2552
|
+
* @public
|
|
2553
|
+
*/
|
|
2554
|
+
pause() {
|
|
2555
|
+
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
|
|
2556
|
+
return;
|
|
2557
|
+
}
|
|
2558
|
+
this._paused = true;
|
|
2559
|
+
this._socket.pause();
|
|
2560
|
+
}
|
|
2561
|
+
/**
|
|
2562
|
+
* Send a ping.
|
|
2563
|
+
*
|
|
2564
|
+
* @param {*} [data] The data to send
|
|
2565
|
+
* @param {Boolean} [mask] Indicates whether or not to mask `data`
|
|
2566
|
+
* @param {Function} [cb] Callback which is executed when the ping is sent
|
|
2567
|
+
* @public
|
|
2568
|
+
*/
|
|
2569
|
+
ping(data, mask, cb) {
|
|
2570
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2571
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2572
|
+
}
|
|
2573
|
+
if (typeof data === "function") {
|
|
2574
|
+
cb = data;
|
|
2575
|
+
data = mask = void 0;
|
|
2576
|
+
} else if (typeof mask === "function") {
|
|
2577
|
+
cb = mask;
|
|
2578
|
+
mask = void 0;
|
|
2579
|
+
}
|
|
2580
|
+
if (typeof data === "number") data = data.toString();
|
|
2581
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2582
|
+
sendAfterClose(this, data, cb);
|
|
2583
|
+
return;
|
|
2584
|
+
}
|
|
2585
|
+
if (mask === void 0) mask = !this._isServer;
|
|
2586
|
+
this._sender.ping(data || EMPTY_BUFFER, mask, cb);
|
|
2587
|
+
}
|
|
2588
|
+
/**
|
|
2589
|
+
* Send a pong.
|
|
2590
|
+
*
|
|
2591
|
+
* @param {*} [data] The data to send
|
|
2592
|
+
* @param {Boolean} [mask] Indicates whether or not to mask `data`
|
|
2593
|
+
* @param {Function} [cb] Callback which is executed when the pong is sent
|
|
2594
|
+
* @public
|
|
2595
|
+
*/
|
|
2596
|
+
pong(data, mask, cb) {
|
|
2597
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2598
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2599
|
+
}
|
|
2600
|
+
if (typeof data === "function") {
|
|
2601
|
+
cb = data;
|
|
2602
|
+
data = mask = void 0;
|
|
2603
|
+
} else if (typeof mask === "function") {
|
|
2604
|
+
cb = mask;
|
|
2605
|
+
mask = void 0;
|
|
2606
|
+
}
|
|
2607
|
+
if (typeof data === "number") data = data.toString();
|
|
2608
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2609
|
+
sendAfterClose(this, data, cb);
|
|
2610
|
+
return;
|
|
2611
|
+
}
|
|
2612
|
+
if (mask === void 0) mask = !this._isServer;
|
|
2613
|
+
this._sender.pong(data || EMPTY_BUFFER, mask, cb);
|
|
2614
|
+
}
|
|
2615
|
+
/**
|
|
2616
|
+
* Resume the socket.
|
|
2617
|
+
*
|
|
2618
|
+
* @public
|
|
2619
|
+
*/
|
|
2620
|
+
resume() {
|
|
2621
|
+
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
|
|
2622
|
+
return;
|
|
2623
|
+
}
|
|
2624
|
+
this._paused = false;
|
|
2625
|
+
if (!this._receiver._writableState.needDrain) this._socket.resume();
|
|
2626
|
+
}
|
|
2627
|
+
/**
|
|
2628
|
+
* Send a data message.
|
|
2629
|
+
*
|
|
2630
|
+
* @param {*} data The message to send
|
|
2631
|
+
* @param {Object} [options] Options object
|
|
2632
|
+
* @param {Boolean} [options.binary] Specifies whether `data` is binary or
|
|
2633
|
+
* text
|
|
2634
|
+
* @param {Boolean} [options.compress] Specifies whether or not to compress
|
|
2635
|
+
* `data`
|
|
2636
|
+
* @param {Boolean} [options.fin=true] Specifies whether the fragment is the
|
|
2637
|
+
* last one
|
|
2638
|
+
* @param {Boolean} [options.mask] Specifies whether or not to mask `data`
|
|
2639
|
+
* @param {Function} [cb] Callback which is executed when data is written out
|
|
2640
|
+
* @public
|
|
2641
|
+
*/
|
|
2642
|
+
send(data, options, cb) {
|
|
2643
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2644
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2645
|
+
}
|
|
2646
|
+
if (typeof options === "function") {
|
|
2647
|
+
cb = options;
|
|
2648
|
+
options = {};
|
|
2649
|
+
}
|
|
2650
|
+
if (typeof data === "number") data = data.toString();
|
|
2651
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2652
|
+
sendAfterClose(this, data, cb);
|
|
2653
|
+
return;
|
|
2654
|
+
}
|
|
2655
|
+
const opts = {
|
|
2656
|
+
binary: typeof data !== "string",
|
|
2657
|
+
mask: !this._isServer,
|
|
2658
|
+
compress: true,
|
|
2659
|
+
fin: true,
|
|
2660
|
+
...options
|
|
2661
|
+
};
|
|
2662
|
+
if (!this._extensions[PerMessageDeflate2.extensionName]) {
|
|
2663
|
+
opts.compress = false;
|
|
2664
|
+
}
|
|
2665
|
+
this._sender.send(data || EMPTY_BUFFER, opts, cb);
|
|
2666
|
+
}
|
|
2667
|
+
/**
|
|
2668
|
+
* Forcibly close the connection.
|
|
2669
|
+
*
|
|
2670
|
+
* @public
|
|
2671
|
+
*/
|
|
2672
|
+
terminate() {
|
|
2673
|
+
if (this.readyState === _WebSocket.CLOSED) return;
|
|
2674
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2675
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
2676
|
+
abortHandshake(this, this._req, msg);
|
|
2677
|
+
return;
|
|
2678
|
+
}
|
|
2679
|
+
if (this._socket) {
|
|
2680
|
+
this._readyState = _WebSocket.CLOSING;
|
|
2681
|
+
this._socket.destroy();
|
|
2682
|
+
}
|
|
2683
|
+
}
|
|
2684
|
+
};
|
|
2685
|
+
Object.defineProperty(WebSocket2, "CONNECTING", {
|
|
2686
|
+
enumerable: true,
|
|
2687
|
+
value: readyStates.indexOf("CONNECTING")
|
|
2688
|
+
});
|
|
2689
|
+
Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
|
|
2690
|
+
enumerable: true,
|
|
2691
|
+
value: readyStates.indexOf("CONNECTING")
|
|
2692
|
+
});
|
|
2693
|
+
Object.defineProperty(WebSocket2, "OPEN", {
|
|
2694
|
+
enumerable: true,
|
|
2695
|
+
value: readyStates.indexOf("OPEN")
|
|
2696
|
+
});
|
|
2697
|
+
Object.defineProperty(WebSocket2.prototype, "OPEN", {
|
|
2698
|
+
enumerable: true,
|
|
2699
|
+
value: readyStates.indexOf("OPEN")
|
|
2700
|
+
});
|
|
2701
|
+
Object.defineProperty(WebSocket2, "CLOSING", {
|
|
2702
|
+
enumerable: true,
|
|
2703
|
+
value: readyStates.indexOf("CLOSING")
|
|
2704
|
+
});
|
|
2705
|
+
Object.defineProperty(WebSocket2.prototype, "CLOSING", {
|
|
2706
|
+
enumerable: true,
|
|
2707
|
+
value: readyStates.indexOf("CLOSING")
|
|
2708
|
+
});
|
|
2709
|
+
Object.defineProperty(WebSocket2, "CLOSED", {
|
|
2710
|
+
enumerable: true,
|
|
2711
|
+
value: readyStates.indexOf("CLOSED")
|
|
2712
|
+
});
|
|
2713
|
+
Object.defineProperty(WebSocket2.prototype, "CLOSED", {
|
|
2714
|
+
enumerable: true,
|
|
2715
|
+
value: readyStates.indexOf("CLOSED")
|
|
2716
|
+
});
|
|
2717
|
+
[
|
|
2718
|
+
"binaryType",
|
|
2719
|
+
"bufferedAmount",
|
|
2720
|
+
"extensions",
|
|
2721
|
+
"isPaused",
|
|
2722
|
+
"protocol",
|
|
2723
|
+
"readyState",
|
|
2724
|
+
"url"
|
|
2725
|
+
].forEach((property) => {
|
|
2726
|
+
Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
|
|
2727
|
+
});
|
|
2728
|
+
["open", "error", "close", "message"].forEach((method) => {
|
|
2729
|
+
Object.defineProperty(WebSocket2.prototype, `on${method}`, {
|
|
2730
|
+
enumerable: true,
|
|
2731
|
+
get() {
|
|
2732
|
+
for (const listener of this.listeners(method)) {
|
|
2733
|
+
if (listener[kForOnEventAttribute]) return listener[kListener];
|
|
2734
|
+
}
|
|
2735
|
+
return null;
|
|
2736
|
+
},
|
|
2737
|
+
set(handler) {
|
|
2738
|
+
for (const listener of this.listeners(method)) {
|
|
2739
|
+
if (listener[kForOnEventAttribute]) {
|
|
2740
|
+
this.removeListener(method, listener);
|
|
2741
|
+
break;
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
if (typeof handler !== "function") return;
|
|
2745
|
+
this.addEventListener(method, handler, {
|
|
2746
|
+
[kForOnEventAttribute]: true
|
|
2747
|
+
});
|
|
2748
|
+
}
|
|
2749
|
+
});
|
|
2750
|
+
});
|
|
2751
|
+
WebSocket2.prototype.addEventListener = addEventListener;
|
|
2752
|
+
WebSocket2.prototype.removeEventListener = removeEventListener;
|
|
2753
|
+
module.exports = WebSocket2;
|
|
2754
|
+
function initAsClient(websocket, address, protocols, options) {
|
|
2755
|
+
const opts = {
|
|
2756
|
+
allowSynchronousEvents: true,
|
|
2757
|
+
autoPong: true,
|
|
2758
|
+
closeTimeout: CLOSE_TIMEOUT,
|
|
2759
|
+
protocolVersion: protocolVersions[1],
|
|
2760
|
+
maxBufferedChunks: 1024 * 1024,
|
|
2761
|
+
maxFragments: 128 * 1024,
|
|
2762
|
+
maxPayload: 100 * 1024 * 1024,
|
|
2763
|
+
skipUTF8Validation: false,
|
|
2764
|
+
perMessageDeflate: true,
|
|
2765
|
+
followRedirects: false,
|
|
2766
|
+
maxRedirects: 10,
|
|
2767
|
+
...options,
|
|
2768
|
+
socketPath: void 0,
|
|
2769
|
+
hostname: void 0,
|
|
2770
|
+
protocol: void 0,
|
|
2771
|
+
timeout: void 0,
|
|
2772
|
+
method: "GET",
|
|
2773
|
+
host: void 0,
|
|
2774
|
+
path: void 0,
|
|
2775
|
+
port: void 0
|
|
2776
|
+
};
|
|
2777
|
+
websocket._autoPong = opts.autoPong;
|
|
2778
|
+
websocket._closeTimeout = opts.closeTimeout;
|
|
2779
|
+
if (!protocolVersions.includes(opts.protocolVersion)) {
|
|
2780
|
+
throw new RangeError(
|
|
2781
|
+
`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
|
|
2782
|
+
);
|
|
2783
|
+
}
|
|
2784
|
+
let parsedUrl;
|
|
2785
|
+
if (address instanceof URL2) {
|
|
2786
|
+
parsedUrl = address;
|
|
2787
|
+
} else {
|
|
2788
|
+
try {
|
|
2789
|
+
parsedUrl = new URL2(address);
|
|
2790
|
+
} catch {
|
|
2791
|
+
throw new SyntaxError(`Invalid URL: ${address}`);
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
if (parsedUrl.protocol === "http:") {
|
|
2795
|
+
parsedUrl.protocol = "ws:";
|
|
2796
|
+
} else if (parsedUrl.protocol === "https:") {
|
|
2797
|
+
parsedUrl.protocol = "wss:";
|
|
2798
|
+
}
|
|
2799
|
+
websocket._url = parsedUrl.href;
|
|
2800
|
+
const isSecure = parsedUrl.protocol === "wss:";
|
|
2801
|
+
const isIpcUrl = parsedUrl.protocol === "ws+unix:";
|
|
2802
|
+
let invalidUrlMessage;
|
|
2803
|
+
if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
|
|
2804
|
+
invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
|
|
2805
|
+
} else if (isIpcUrl && !parsedUrl.pathname) {
|
|
2806
|
+
invalidUrlMessage = "The URL's pathname is empty";
|
|
2807
|
+
} else if (parsedUrl.hash) {
|
|
2808
|
+
invalidUrlMessage = "The URL contains a fragment identifier";
|
|
2809
|
+
}
|
|
2810
|
+
if (invalidUrlMessage) {
|
|
2811
|
+
const err = new SyntaxError(invalidUrlMessage);
|
|
2812
|
+
if (websocket._redirects === 0) {
|
|
2813
|
+
throw err;
|
|
2814
|
+
} else {
|
|
2815
|
+
emitErrorAndClose(websocket, err);
|
|
2816
|
+
return;
|
|
2817
|
+
}
|
|
2818
|
+
}
|
|
2819
|
+
const defaultPort = isSecure ? 443 : 80;
|
|
2820
|
+
const key = randomBytes(16).toString("base64");
|
|
2821
|
+
const request2 = isSecure ? https.request : http.request;
|
|
2822
|
+
const protocolSet = /* @__PURE__ */ new Set();
|
|
2823
|
+
let perMessageDeflate;
|
|
2824
|
+
opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
|
|
2825
|
+
opts.defaultPort = opts.defaultPort || defaultPort;
|
|
2826
|
+
opts.port = parsedUrl.port || defaultPort;
|
|
2827
|
+
opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
|
|
2828
|
+
opts.headers = {
|
|
2829
|
+
...opts.headers,
|
|
2830
|
+
"Sec-WebSocket-Version": opts.protocolVersion,
|
|
2831
|
+
"Sec-WebSocket-Key": key,
|
|
2832
|
+
Connection: "Upgrade",
|
|
2833
|
+
Upgrade: "websocket"
|
|
2834
|
+
};
|
|
2835
|
+
opts.path = parsedUrl.pathname + parsedUrl.search;
|
|
2836
|
+
opts.timeout = opts.handshakeTimeout;
|
|
2837
|
+
if (opts.perMessageDeflate) {
|
|
2838
|
+
perMessageDeflate = new PerMessageDeflate2({
|
|
2839
|
+
...opts.perMessageDeflate,
|
|
2840
|
+
isServer: false,
|
|
2841
|
+
maxPayload: opts.maxPayload
|
|
2842
|
+
});
|
|
2843
|
+
opts.headers["Sec-WebSocket-Extensions"] = format({
|
|
2844
|
+
[PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
|
|
2845
|
+
});
|
|
2846
|
+
}
|
|
2847
|
+
if (protocols.length) {
|
|
2848
|
+
for (const protocol of protocols) {
|
|
2849
|
+
if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
|
|
2850
|
+
throw new SyntaxError(
|
|
2851
|
+
"An invalid or duplicated subprotocol was specified"
|
|
2852
|
+
);
|
|
2853
|
+
}
|
|
2854
|
+
protocolSet.add(protocol);
|
|
2855
|
+
}
|
|
2856
|
+
opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
|
|
2857
|
+
}
|
|
2858
|
+
if (opts.origin) {
|
|
2859
|
+
if (opts.protocolVersion < 13) {
|
|
2860
|
+
opts.headers["Sec-WebSocket-Origin"] = opts.origin;
|
|
2861
|
+
} else {
|
|
2862
|
+
opts.headers.Origin = opts.origin;
|
|
2863
|
+
}
|
|
2864
|
+
}
|
|
2865
|
+
if (parsedUrl.username || parsedUrl.password) {
|
|
2866
|
+
opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
|
|
2867
|
+
}
|
|
2868
|
+
if (isIpcUrl) {
|
|
2869
|
+
const parts = opts.path.split(":");
|
|
2870
|
+
opts.socketPath = parts[0];
|
|
2871
|
+
opts.path = parts[1];
|
|
2872
|
+
}
|
|
2873
|
+
let req;
|
|
2874
|
+
if (opts.followRedirects) {
|
|
2875
|
+
if (websocket._redirects === 0) {
|
|
2876
|
+
websocket._originalIpc = isIpcUrl;
|
|
2877
|
+
websocket._originalSecure = isSecure;
|
|
2878
|
+
websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
|
|
2879
|
+
const headers = options && options.headers;
|
|
2880
|
+
options = { ...options, headers: {} };
|
|
2881
|
+
if (headers) {
|
|
2882
|
+
for (const [key2, value] of Object.entries(headers)) {
|
|
2883
|
+
options.headers[key2.toLowerCase()] = value;
|
|
2884
|
+
}
|
|
2885
|
+
}
|
|
2886
|
+
} else if (websocket.listenerCount("redirect") === 0) {
|
|
2887
|
+
const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
|
|
2888
|
+
if (!isSameHost || websocket._originalSecure && !isSecure) {
|
|
2889
|
+
delete opts.headers.authorization;
|
|
2890
|
+
delete opts.headers.cookie;
|
|
2891
|
+
if (!isSameHost) delete opts.headers.host;
|
|
2892
|
+
opts.auth = void 0;
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2895
|
+
if (opts.auth && !options.headers.authorization) {
|
|
2896
|
+
options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
|
|
2897
|
+
}
|
|
2898
|
+
req = websocket._req = request2(opts);
|
|
2899
|
+
if (websocket._redirects) {
|
|
2900
|
+
websocket.emit("redirect", websocket.url, req);
|
|
2901
|
+
}
|
|
2902
|
+
} else {
|
|
2903
|
+
req = websocket._req = request2(opts);
|
|
2904
|
+
}
|
|
2905
|
+
if (opts.timeout) {
|
|
2906
|
+
req.on("timeout", () => {
|
|
2907
|
+
abortHandshake(websocket, req, "Opening handshake has timed out");
|
|
2908
|
+
});
|
|
2909
|
+
}
|
|
2910
|
+
req.on("error", (err) => {
|
|
2911
|
+
if (req === null || req[kAborted]) return;
|
|
2912
|
+
req = websocket._req = null;
|
|
2913
|
+
emitErrorAndClose(websocket, err);
|
|
2914
|
+
});
|
|
2915
|
+
req.on("response", (res) => {
|
|
2916
|
+
const location = res.headers.location;
|
|
2917
|
+
const statusCode = res.statusCode;
|
|
2918
|
+
if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
|
|
2919
|
+
if (++websocket._redirects > opts.maxRedirects) {
|
|
2920
|
+
abortHandshake(websocket, req, "Maximum redirects exceeded");
|
|
2921
|
+
return;
|
|
2922
|
+
}
|
|
2923
|
+
req.abort();
|
|
2924
|
+
let addr;
|
|
2925
|
+
try {
|
|
2926
|
+
addr = new URL2(location, address);
|
|
2927
|
+
} catch (e) {
|
|
2928
|
+
const err = new SyntaxError(`Invalid URL: ${location}`);
|
|
2929
|
+
emitErrorAndClose(websocket, err);
|
|
2930
|
+
return;
|
|
2931
|
+
}
|
|
2932
|
+
initAsClient(websocket, addr, protocols, options);
|
|
2933
|
+
} else if (!websocket.emit("unexpected-response", req, res)) {
|
|
2934
|
+
abortHandshake(
|
|
2935
|
+
websocket,
|
|
2936
|
+
req,
|
|
2937
|
+
`Unexpected server response: ${res.statusCode}`
|
|
2938
|
+
);
|
|
2939
|
+
}
|
|
2940
|
+
});
|
|
2941
|
+
req.on("upgrade", (res, socket, head) => {
|
|
2942
|
+
websocket.emit("upgrade", res);
|
|
2943
|
+
if (websocket.readyState !== WebSocket2.CONNECTING) return;
|
|
2944
|
+
req = websocket._req = null;
|
|
2945
|
+
const upgrade = res.headers.upgrade;
|
|
2946
|
+
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
|
|
2947
|
+
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
2948
|
+
return;
|
|
2949
|
+
}
|
|
2950
|
+
const digest = createHash("sha1").update(key + GUID).digest("base64");
|
|
2951
|
+
if (res.headers["sec-websocket-accept"] !== digest) {
|
|
2952
|
+
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
2953
|
+
return;
|
|
2954
|
+
}
|
|
2955
|
+
const serverProt = res.headers["sec-websocket-protocol"];
|
|
2956
|
+
let protError;
|
|
2957
|
+
if (serverProt !== void 0) {
|
|
2958
|
+
if (!protocolSet.size) {
|
|
2959
|
+
protError = "Server sent a subprotocol but none was requested";
|
|
2960
|
+
} else if (!protocolSet.has(serverProt)) {
|
|
2961
|
+
protError = "Server sent an invalid subprotocol";
|
|
2962
|
+
}
|
|
2963
|
+
} else if (protocolSet.size) {
|
|
2964
|
+
protError = "Server sent no subprotocol";
|
|
2965
|
+
}
|
|
2966
|
+
if (protError) {
|
|
2967
|
+
abortHandshake(websocket, socket, protError);
|
|
2968
|
+
return;
|
|
2969
|
+
}
|
|
2970
|
+
if (serverProt) websocket._protocol = serverProt;
|
|
2971
|
+
const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
|
|
2972
|
+
if (secWebSocketExtensions !== void 0) {
|
|
2973
|
+
if (!perMessageDeflate) {
|
|
2974
|
+
const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
|
|
2975
|
+
abortHandshake(websocket, socket, message);
|
|
2976
|
+
return;
|
|
2977
|
+
}
|
|
2978
|
+
let extensions;
|
|
2979
|
+
try {
|
|
2980
|
+
extensions = parse(secWebSocketExtensions);
|
|
2981
|
+
} catch (err) {
|
|
2982
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
2983
|
+
abortHandshake(websocket, socket, message);
|
|
2984
|
+
return;
|
|
2985
|
+
}
|
|
2986
|
+
const extensionNames = Object.keys(extensions);
|
|
2987
|
+
if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
|
|
2988
|
+
const message = "Server indicated an extension that was not requested";
|
|
2989
|
+
abortHandshake(websocket, socket, message);
|
|
2990
|
+
return;
|
|
2991
|
+
}
|
|
2992
|
+
try {
|
|
2993
|
+
perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
|
|
2994
|
+
} catch (err) {
|
|
2995
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
2996
|
+
abortHandshake(websocket, socket, message);
|
|
2997
|
+
return;
|
|
2998
|
+
}
|
|
2999
|
+
websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
|
|
3000
|
+
}
|
|
3001
|
+
websocket.setSocket(socket, head, {
|
|
3002
|
+
allowSynchronousEvents: opts.allowSynchronousEvents,
|
|
3003
|
+
generateMask: opts.generateMask,
|
|
3004
|
+
maxBufferedChunks: opts.maxBufferedChunks,
|
|
3005
|
+
maxFragments: opts.maxFragments,
|
|
3006
|
+
maxPayload: opts.maxPayload,
|
|
3007
|
+
skipUTF8Validation: opts.skipUTF8Validation
|
|
3008
|
+
});
|
|
3009
|
+
});
|
|
3010
|
+
if (opts.finishRequest) {
|
|
3011
|
+
opts.finishRequest(req, websocket);
|
|
3012
|
+
} else {
|
|
3013
|
+
req.end();
|
|
3014
|
+
}
|
|
3015
|
+
}
|
|
3016
|
+
function emitErrorAndClose(websocket, err) {
|
|
3017
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3018
|
+
websocket._errorEmitted = true;
|
|
3019
|
+
websocket.emit("error", err);
|
|
3020
|
+
websocket.emitClose();
|
|
3021
|
+
}
|
|
3022
|
+
function netConnect(options) {
|
|
3023
|
+
options.path = options.socketPath;
|
|
3024
|
+
return net.connect(options);
|
|
3025
|
+
}
|
|
3026
|
+
function tlsConnect(options) {
|
|
3027
|
+
options.path = void 0;
|
|
3028
|
+
if (!options.servername && options.servername !== "") {
|
|
3029
|
+
options.servername = net.isIP(options.host) ? "" : options.host;
|
|
3030
|
+
}
|
|
3031
|
+
return tls.connect(options);
|
|
3032
|
+
}
|
|
3033
|
+
function abortHandshake(websocket, stream, message) {
|
|
3034
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3035
|
+
const err = new Error(message);
|
|
3036
|
+
Error.captureStackTrace(err, abortHandshake);
|
|
3037
|
+
if (stream.setHeader) {
|
|
3038
|
+
stream[kAborted] = true;
|
|
3039
|
+
stream.abort();
|
|
3040
|
+
if (stream.socket && !stream.socket.destroyed) {
|
|
3041
|
+
stream.socket.destroy();
|
|
3042
|
+
}
|
|
3043
|
+
process.nextTick(emitErrorAndClose, websocket, err);
|
|
3044
|
+
} else {
|
|
3045
|
+
stream.destroy(err);
|
|
3046
|
+
stream.once("error", websocket.emit.bind(websocket, "error"));
|
|
3047
|
+
stream.once("close", websocket.emitClose.bind(websocket));
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
function sendAfterClose(websocket, data, cb) {
|
|
3051
|
+
if (data) {
|
|
3052
|
+
const length = isBlob(data) ? data.size : toBuffer(data).length;
|
|
3053
|
+
if (websocket._socket) websocket._sender._bufferedBytes += length;
|
|
3054
|
+
else websocket._bufferedAmount += length;
|
|
3055
|
+
}
|
|
3056
|
+
if (cb) {
|
|
3057
|
+
const err = new Error(
|
|
3058
|
+
`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
|
|
3059
|
+
);
|
|
3060
|
+
process.nextTick(cb, err);
|
|
3061
|
+
}
|
|
3062
|
+
}
|
|
3063
|
+
function receiverOnConclude(code, reason) {
|
|
3064
|
+
const websocket = this[kWebSocket];
|
|
3065
|
+
websocket._closeFrameReceived = true;
|
|
3066
|
+
websocket._closeMessage = reason;
|
|
3067
|
+
websocket._closeCode = code;
|
|
3068
|
+
if (websocket._socket[kWebSocket] === void 0) return;
|
|
3069
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
3070
|
+
process.nextTick(resume, websocket._socket);
|
|
3071
|
+
if (code === 1005) websocket.close();
|
|
3072
|
+
else websocket.close(code, reason);
|
|
3073
|
+
}
|
|
3074
|
+
function receiverOnDrain() {
|
|
3075
|
+
const websocket = this[kWebSocket];
|
|
3076
|
+
if (!websocket.isPaused) websocket._socket.resume();
|
|
3077
|
+
}
|
|
3078
|
+
function receiverOnError(err) {
|
|
3079
|
+
const websocket = this[kWebSocket];
|
|
3080
|
+
if (websocket._socket[kWebSocket] !== void 0) {
|
|
3081
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
3082
|
+
process.nextTick(resume, websocket._socket);
|
|
3083
|
+
websocket.close(err[kStatusCode]);
|
|
3084
|
+
}
|
|
3085
|
+
if (!websocket._errorEmitted) {
|
|
3086
|
+
websocket._errorEmitted = true;
|
|
3087
|
+
websocket.emit("error", err);
|
|
3088
|
+
}
|
|
3089
|
+
}
|
|
3090
|
+
function receiverOnFinish() {
|
|
3091
|
+
this[kWebSocket].emitClose();
|
|
3092
|
+
}
|
|
3093
|
+
function receiverOnMessage(data, isBinary) {
|
|
3094
|
+
this[kWebSocket].emit("message", data, isBinary);
|
|
3095
|
+
}
|
|
3096
|
+
function receiverOnPing(data) {
|
|
3097
|
+
const websocket = this[kWebSocket];
|
|
3098
|
+
if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
|
|
3099
|
+
websocket.emit("ping", data);
|
|
3100
|
+
}
|
|
3101
|
+
function receiverOnPong(data) {
|
|
3102
|
+
this[kWebSocket].emit("pong", data);
|
|
3103
|
+
}
|
|
3104
|
+
function resume(stream) {
|
|
3105
|
+
stream.resume();
|
|
3106
|
+
}
|
|
3107
|
+
function senderOnError(err) {
|
|
3108
|
+
const websocket = this[kWebSocket];
|
|
3109
|
+
if (websocket.readyState === WebSocket2.CLOSED) return;
|
|
3110
|
+
if (websocket.readyState === WebSocket2.OPEN) {
|
|
3111
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3112
|
+
setCloseTimer(websocket);
|
|
3113
|
+
}
|
|
3114
|
+
this._socket.end();
|
|
3115
|
+
if (!websocket._errorEmitted) {
|
|
3116
|
+
websocket._errorEmitted = true;
|
|
3117
|
+
websocket.emit("error", err);
|
|
3118
|
+
}
|
|
3119
|
+
}
|
|
3120
|
+
function setCloseTimer(websocket) {
|
|
3121
|
+
websocket._closeTimer = setTimeout(
|
|
3122
|
+
websocket._socket.destroy.bind(websocket._socket),
|
|
3123
|
+
websocket._closeTimeout
|
|
3124
|
+
);
|
|
3125
|
+
}
|
|
3126
|
+
function socketOnClose() {
|
|
3127
|
+
const websocket = this[kWebSocket];
|
|
3128
|
+
this.removeListener("close", socketOnClose);
|
|
3129
|
+
this.removeListener("data", socketOnData);
|
|
3130
|
+
this.removeListener("end", socketOnEnd);
|
|
3131
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3132
|
+
if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
|
|
3133
|
+
const chunk = this.read(this._readableState.length);
|
|
3134
|
+
websocket._receiver.write(chunk);
|
|
3135
|
+
}
|
|
3136
|
+
websocket._receiver.end();
|
|
3137
|
+
this[kWebSocket] = void 0;
|
|
3138
|
+
clearTimeout(websocket._closeTimer);
|
|
3139
|
+
if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
|
|
3140
|
+
websocket.emitClose();
|
|
3141
|
+
} else {
|
|
3142
|
+
websocket._receiver.on("error", receiverOnFinish);
|
|
3143
|
+
websocket._receiver.on("finish", receiverOnFinish);
|
|
3144
|
+
}
|
|
3145
|
+
}
|
|
3146
|
+
function socketOnData(chunk) {
|
|
3147
|
+
if (!this[kWebSocket]._receiver.write(chunk)) {
|
|
3148
|
+
this.pause();
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
function socketOnEnd() {
|
|
3152
|
+
const websocket = this[kWebSocket];
|
|
3153
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3154
|
+
websocket._receiver.end();
|
|
3155
|
+
this.end();
|
|
3156
|
+
}
|
|
3157
|
+
function socketOnError() {
|
|
3158
|
+
const websocket = this[kWebSocket];
|
|
3159
|
+
this.removeListener("error", socketOnError);
|
|
3160
|
+
this.on("error", NOOP);
|
|
3161
|
+
if (websocket) {
|
|
3162
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3163
|
+
this.destroy();
|
|
3164
|
+
}
|
|
3165
|
+
}
|
|
3166
|
+
}
|
|
3167
|
+
});
|
|
3168
|
+
|
|
3169
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/stream.js
|
|
3170
|
+
var require_stream = __commonJS({
|
|
3171
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/stream.js"(exports, module) {
|
|
3172
|
+
"use strict";
|
|
3173
|
+
var WebSocket2 = require_websocket();
|
|
3174
|
+
var { Duplex } = __require("stream");
|
|
3175
|
+
function emitClose(stream) {
|
|
3176
|
+
stream.emit("close");
|
|
3177
|
+
}
|
|
3178
|
+
function duplexOnEnd() {
|
|
3179
|
+
if (!this.destroyed && this._writableState.finished) {
|
|
3180
|
+
this.destroy();
|
|
3181
|
+
}
|
|
3182
|
+
}
|
|
3183
|
+
function duplexOnError(err) {
|
|
3184
|
+
this.removeListener("error", duplexOnError);
|
|
3185
|
+
this.destroy();
|
|
3186
|
+
if (this.listenerCount("error") === 0) {
|
|
3187
|
+
this.emit("error", err);
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
function createWebSocketStream2(ws, options) {
|
|
3191
|
+
let terminateOnDestroy = true;
|
|
3192
|
+
const duplex = new Duplex({
|
|
3193
|
+
...options,
|
|
3194
|
+
autoDestroy: false,
|
|
3195
|
+
emitClose: false,
|
|
3196
|
+
objectMode: false,
|
|
3197
|
+
writableObjectMode: false
|
|
3198
|
+
});
|
|
3199
|
+
ws.on("message", function message(msg, isBinary) {
|
|
3200
|
+
const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
|
|
3201
|
+
if (!duplex.push(data)) ws.pause();
|
|
3202
|
+
});
|
|
3203
|
+
ws.once("error", function error(err) {
|
|
3204
|
+
if (duplex.destroyed) return;
|
|
3205
|
+
terminateOnDestroy = false;
|
|
3206
|
+
duplex.destroy(err);
|
|
3207
|
+
});
|
|
3208
|
+
ws.once("close", function close() {
|
|
3209
|
+
if (duplex.destroyed) return;
|
|
3210
|
+
duplex.push(null);
|
|
3211
|
+
});
|
|
3212
|
+
duplex._destroy = function(err, callback) {
|
|
3213
|
+
if (ws.readyState === ws.CLOSED) {
|
|
3214
|
+
callback(err);
|
|
3215
|
+
process.nextTick(emitClose, duplex);
|
|
3216
|
+
return;
|
|
3217
|
+
}
|
|
3218
|
+
let called = false;
|
|
3219
|
+
ws.once("error", function error(err2) {
|
|
3220
|
+
called = true;
|
|
3221
|
+
callback(err2);
|
|
3222
|
+
});
|
|
3223
|
+
ws.once("close", function close() {
|
|
3224
|
+
if (!called) callback(err);
|
|
3225
|
+
process.nextTick(emitClose, duplex);
|
|
3226
|
+
});
|
|
3227
|
+
if (terminateOnDestroy) ws.terminate();
|
|
3228
|
+
};
|
|
3229
|
+
duplex._final = function(callback) {
|
|
3230
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
3231
|
+
ws.once("open", function open() {
|
|
3232
|
+
duplex._final(callback);
|
|
3233
|
+
});
|
|
3234
|
+
return;
|
|
3235
|
+
}
|
|
3236
|
+
if (ws._socket === null) return;
|
|
3237
|
+
if (ws._socket._writableState.finished) {
|
|
3238
|
+
callback();
|
|
3239
|
+
if (duplex._readableState.endEmitted) duplex.destroy();
|
|
3240
|
+
} else {
|
|
3241
|
+
ws._socket.once("finish", function finish() {
|
|
3242
|
+
callback();
|
|
3243
|
+
});
|
|
3244
|
+
ws.close();
|
|
3245
|
+
}
|
|
3246
|
+
};
|
|
3247
|
+
duplex._read = function() {
|
|
3248
|
+
if (ws.isPaused) ws.resume();
|
|
3249
|
+
};
|
|
3250
|
+
duplex._write = function(chunk, encoding, callback) {
|
|
3251
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
3252
|
+
ws.once("open", function open() {
|
|
3253
|
+
duplex._write(chunk, encoding, callback);
|
|
3254
|
+
});
|
|
3255
|
+
return;
|
|
3256
|
+
}
|
|
3257
|
+
ws.send(chunk, callback);
|
|
3258
|
+
};
|
|
3259
|
+
duplex.on("end", duplexOnEnd);
|
|
3260
|
+
duplex.on("error", duplexOnError);
|
|
3261
|
+
return duplex;
|
|
3262
|
+
}
|
|
3263
|
+
module.exports = createWebSocketStream2;
|
|
3264
|
+
}
|
|
3265
|
+
});
|
|
3266
|
+
|
|
3267
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/subprotocol.js
|
|
3268
|
+
var require_subprotocol = __commonJS({
|
|
3269
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/subprotocol.js"(exports, module) {
|
|
3270
|
+
"use strict";
|
|
3271
|
+
var { tokenChars } = require_validation();
|
|
3272
|
+
function parse(header) {
|
|
3273
|
+
const protocols = /* @__PURE__ */ new Set();
|
|
3274
|
+
let start = -1;
|
|
3275
|
+
let end = -1;
|
|
3276
|
+
let i = 0;
|
|
3277
|
+
for (i; i < header.length; i++) {
|
|
3278
|
+
const code = header.charCodeAt(i);
|
|
3279
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
3280
|
+
if (start === -1) start = i;
|
|
3281
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
3282
|
+
if (end === -1 && start !== -1) end = i;
|
|
3283
|
+
} else if (code === 44) {
|
|
3284
|
+
if (start === -1) {
|
|
3285
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
3286
|
+
}
|
|
3287
|
+
if (end === -1) end = i;
|
|
3288
|
+
const protocol2 = header.slice(start, end);
|
|
3289
|
+
if (protocols.has(protocol2)) {
|
|
3290
|
+
throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
|
|
3291
|
+
}
|
|
3292
|
+
protocols.add(protocol2);
|
|
3293
|
+
start = end = -1;
|
|
3294
|
+
} else {
|
|
3295
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
3296
|
+
}
|
|
3297
|
+
}
|
|
3298
|
+
if (start === -1 || end !== -1) {
|
|
3299
|
+
throw new SyntaxError("Unexpected end of input");
|
|
3300
|
+
}
|
|
3301
|
+
const protocol = header.slice(start, i);
|
|
3302
|
+
if (protocols.has(protocol)) {
|
|
3303
|
+
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
|
|
3304
|
+
}
|
|
3305
|
+
protocols.add(protocol);
|
|
3306
|
+
return protocols;
|
|
3307
|
+
}
|
|
3308
|
+
module.exports = { parse };
|
|
3309
|
+
}
|
|
3310
|
+
});
|
|
3311
|
+
|
|
3312
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js
|
|
3313
|
+
var require_websocket_server = __commonJS({
|
|
3314
|
+
"../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js"(exports, module) {
|
|
3315
|
+
"use strict";
|
|
3316
|
+
var EventEmitter = __require("events");
|
|
3317
|
+
var http = __require("http");
|
|
3318
|
+
var { Duplex } = __require("stream");
|
|
3319
|
+
var { createHash } = __require("crypto");
|
|
3320
|
+
var extension2 = require_extension();
|
|
3321
|
+
var PerMessageDeflate2 = require_permessage_deflate();
|
|
3322
|
+
var subprotocol2 = require_subprotocol();
|
|
3323
|
+
var WebSocket2 = require_websocket();
|
|
3324
|
+
var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
|
|
3325
|
+
var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
|
|
3326
|
+
var RUNNING = 0;
|
|
3327
|
+
var CLOSING = 1;
|
|
3328
|
+
var CLOSED = 2;
|
|
3329
|
+
var WebSocketServer2 = class extends EventEmitter {
|
|
3330
|
+
/**
|
|
3331
|
+
* Create a `WebSocketServer` instance.
|
|
3332
|
+
*
|
|
3333
|
+
* @param {Object} options Configuration options
|
|
3334
|
+
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
|
|
3335
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
3336
|
+
* multiple times in the same tick
|
|
3337
|
+
* @param {Boolean} [options.autoPong=true] Specifies whether or not to
|
|
3338
|
+
* automatically send a pong in response to a ping
|
|
3339
|
+
* @param {Number} [options.backlog=511] The maximum length of the queue of
|
|
3340
|
+
* pending connections
|
|
3341
|
+
* @param {Boolean} [options.clientTracking=true] Specifies whether or not to
|
|
3342
|
+
* track clients
|
|
3343
|
+
* @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
|
|
3344
|
+
* wait for the closing handshake to finish after `websocket.close()` is
|
|
3345
|
+
* called
|
|
3346
|
+
* @param {Function} [options.handleProtocols] A hook to handle protocols
|
|
3347
|
+
* @param {String} [options.host] The hostname where to bind the server
|
|
3348
|
+
* @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
|
|
3349
|
+
* buffered data chunks
|
|
3350
|
+
* @param {Number} [options.maxFragments=131072] The maximum number of message
|
|
3351
|
+
* fragments
|
|
3352
|
+
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
|
|
3353
|
+
* size
|
|
3354
|
+
* @param {Boolean} [options.noServer=false] Enable no server mode
|
|
3355
|
+
* @param {String} [options.path] Accept only connections matching this path
|
|
3356
|
+
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
|
|
3357
|
+
* permessage-deflate
|
|
3358
|
+
* @param {Number} [options.port] The port where to bind the server
|
|
3359
|
+
* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
|
|
3360
|
+
* server to use
|
|
3361
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
3362
|
+
* not to skip UTF-8 validation for text and close messages
|
|
3363
|
+
* @param {Function} [options.verifyClient] A hook to reject connections
|
|
3364
|
+
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
|
|
3365
|
+
* class to use. It must be the `WebSocket` class or class that extends it
|
|
3366
|
+
* @param {Function} [callback] A listener for the `listening` event
|
|
3367
|
+
*/
|
|
3368
|
+
constructor(options, callback) {
|
|
3369
|
+
super();
|
|
3370
|
+
options = {
|
|
3371
|
+
allowSynchronousEvents: true,
|
|
3372
|
+
autoPong: true,
|
|
3373
|
+
maxBufferedChunks: 1024 * 1024,
|
|
3374
|
+
maxFragments: 128 * 1024,
|
|
3375
|
+
maxPayload: 100 * 1024 * 1024,
|
|
3376
|
+
skipUTF8Validation: false,
|
|
3377
|
+
perMessageDeflate: false,
|
|
3378
|
+
handleProtocols: null,
|
|
3379
|
+
clientTracking: true,
|
|
3380
|
+
closeTimeout: CLOSE_TIMEOUT,
|
|
3381
|
+
verifyClient: null,
|
|
3382
|
+
noServer: false,
|
|
3383
|
+
backlog: null,
|
|
3384
|
+
// use default (511 as implemented in net.js)
|
|
3385
|
+
server: null,
|
|
3386
|
+
host: null,
|
|
3387
|
+
path: null,
|
|
3388
|
+
port: null,
|
|
3389
|
+
WebSocket: WebSocket2,
|
|
3390
|
+
...options
|
|
3391
|
+
};
|
|
3392
|
+
if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
|
|
3393
|
+
throw new TypeError(
|
|
3394
|
+
'One and only one of the "port", "server", or "noServer" options must be specified'
|
|
3395
|
+
);
|
|
3396
|
+
}
|
|
3397
|
+
if (options.port != null) {
|
|
3398
|
+
this._server = http.createServer((req, res) => {
|
|
3399
|
+
const body = http.STATUS_CODES[426];
|
|
3400
|
+
res.writeHead(426, {
|
|
3401
|
+
"Content-Length": body.length,
|
|
3402
|
+
"Content-Type": "text/plain"
|
|
3403
|
+
});
|
|
3404
|
+
res.end(body);
|
|
3405
|
+
});
|
|
3406
|
+
this._server.listen(
|
|
3407
|
+
options.port,
|
|
3408
|
+
options.host,
|
|
3409
|
+
options.backlog,
|
|
3410
|
+
callback
|
|
3411
|
+
);
|
|
3412
|
+
} else if (options.server) {
|
|
3413
|
+
this._server = options.server;
|
|
3414
|
+
}
|
|
3415
|
+
if (this._server) {
|
|
3416
|
+
const emitConnection = this.emit.bind(this, "connection");
|
|
3417
|
+
this._removeListeners = addListeners(this._server, {
|
|
3418
|
+
listening: this.emit.bind(this, "listening"),
|
|
3419
|
+
error: this.emit.bind(this, "error"),
|
|
3420
|
+
upgrade: (req, socket, head) => {
|
|
3421
|
+
this.handleUpgrade(req, socket, head, emitConnection);
|
|
3422
|
+
}
|
|
3423
|
+
});
|
|
3424
|
+
}
|
|
3425
|
+
if (options.perMessageDeflate === true) options.perMessageDeflate = {};
|
|
3426
|
+
if (options.clientTracking) {
|
|
3427
|
+
this.clients = /* @__PURE__ */ new Set();
|
|
3428
|
+
this._shouldEmitClose = false;
|
|
3429
|
+
}
|
|
3430
|
+
this.options = options;
|
|
3431
|
+
this._state = RUNNING;
|
|
3432
|
+
}
|
|
3433
|
+
/**
|
|
3434
|
+
* Returns the bound address, the address family name, and port of the server
|
|
3435
|
+
* as reported by the operating system if listening on an IP socket.
|
|
3436
|
+
* If the server is listening on a pipe or UNIX domain socket, the name is
|
|
3437
|
+
* returned as a string.
|
|
3438
|
+
*
|
|
3439
|
+
* @return {(Object|String|null)} The address of the server
|
|
3440
|
+
* @public
|
|
3441
|
+
*/
|
|
3442
|
+
address() {
|
|
3443
|
+
if (this.options.noServer) {
|
|
3444
|
+
throw new Error('The server is operating in "noServer" mode');
|
|
3445
|
+
}
|
|
3446
|
+
if (!this._server) return null;
|
|
3447
|
+
return this._server.address();
|
|
3448
|
+
}
|
|
3449
|
+
/**
|
|
3450
|
+
* Stop the server from accepting new connections and emit the `'close'` event
|
|
3451
|
+
* when all existing connections are closed.
|
|
3452
|
+
*
|
|
3453
|
+
* @param {Function} [cb] A one-time listener for the `'close'` event
|
|
3454
|
+
* @public
|
|
3455
|
+
*/
|
|
3456
|
+
close(cb) {
|
|
3457
|
+
if (this._state === CLOSED) {
|
|
3458
|
+
if (cb) {
|
|
3459
|
+
this.once("close", () => {
|
|
3460
|
+
cb(new Error("The server is not running"));
|
|
3461
|
+
});
|
|
3462
|
+
}
|
|
3463
|
+
process.nextTick(emitClose, this);
|
|
3464
|
+
return;
|
|
3465
|
+
}
|
|
3466
|
+
if (cb) this.once("close", cb);
|
|
3467
|
+
if (this._state === CLOSING) return;
|
|
3468
|
+
this._state = CLOSING;
|
|
3469
|
+
if (this.options.noServer || this.options.server) {
|
|
3470
|
+
if (this._server) {
|
|
3471
|
+
this._removeListeners();
|
|
3472
|
+
this._removeListeners = this._server = null;
|
|
3473
|
+
}
|
|
3474
|
+
if (this.clients) {
|
|
3475
|
+
if (!this.clients.size) {
|
|
3476
|
+
process.nextTick(emitClose, this);
|
|
3477
|
+
} else {
|
|
3478
|
+
this._shouldEmitClose = true;
|
|
3479
|
+
}
|
|
3480
|
+
} else {
|
|
3481
|
+
process.nextTick(emitClose, this);
|
|
3482
|
+
}
|
|
3483
|
+
} else {
|
|
3484
|
+
const server = this._server;
|
|
3485
|
+
this._removeListeners();
|
|
3486
|
+
this._removeListeners = this._server = null;
|
|
3487
|
+
server.close(() => {
|
|
3488
|
+
emitClose(this);
|
|
3489
|
+
});
|
|
3490
|
+
}
|
|
3491
|
+
}
|
|
3492
|
+
/**
|
|
3493
|
+
* See if a given request should be handled by this server instance.
|
|
3494
|
+
*
|
|
3495
|
+
* @param {http.IncomingMessage} req Request object to inspect
|
|
3496
|
+
* @return {Boolean} `true` if the request is valid, else `false`
|
|
3497
|
+
* @public
|
|
3498
|
+
*/
|
|
3499
|
+
shouldHandle(req) {
|
|
3500
|
+
if (this.options.path) {
|
|
3501
|
+
const index = req.url.indexOf("?");
|
|
3502
|
+
const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
|
|
3503
|
+
if (pathname !== this.options.path) return false;
|
|
3504
|
+
}
|
|
3505
|
+
return true;
|
|
3506
|
+
}
|
|
3507
|
+
/**
|
|
3508
|
+
* Handle a HTTP Upgrade request.
|
|
3509
|
+
*
|
|
3510
|
+
* @param {http.IncomingMessage} req The request object
|
|
3511
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
3512
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
3513
|
+
* @param {Function} cb Callback
|
|
3514
|
+
* @public
|
|
3515
|
+
*/
|
|
3516
|
+
handleUpgrade(req, socket, head, cb) {
|
|
3517
|
+
socket.on("error", socketOnError);
|
|
3518
|
+
const key = req.headers["sec-websocket-key"];
|
|
3519
|
+
const upgrade = req.headers.upgrade;
|
|
3520
|
+
const version = +req.headers["sec-websocket-version"];
|
|
3521
|
+
if (req.method !== "GET") {
|
|
3522
|
+
const message = "Invalid HTTP method";
|
|
3523
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
|
|
3524
|
+
return;
|
|
3525
|
+
}
|
|
3526
|
+
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
|
|
3527
|
+
const message = "Invalid Upgrade header";
|
|
3528
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3529
|
+
return;
|
|
3530
|
+
}
|
|
3531
|
+
if (key === void 0 || !keyRegex.test(key)) {
|
|
3532
|
+
const message = "Missing or invalid Sec-WebSocket-Key header";
|
|
3533
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3534
|
+
return;
|
|
3535
|
+
}
|
|
3536
|
+
if (version !== 13 && version !== 8) {
|
|
3537
|
+
const message = "Missing or invalid Sec-WebSocket-Version header";
|
|
3538
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
|
|
3539
|
+
"Sec-WebSocket-Version": "13, 8"
|
|
3540
|
+
});
|
|
3541
|
+
return;
|
|
3542
|
+
}
|
|
3543
|
+
if (!this.shouldHandle(req)) {
|
|
3544
|
+
abortHandshake(socket, 400);
|
|
3545
|
+
return;
|
|
3546
|
+
}
|
|
3547
|
+
const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
|
|
3548
|
+
let protocols = /* @__PURE__ */ new Set();
|
|
3549
|
+
if (secWebSocketProtocol !== void 0) {
|
|
3550
|
+
try {
|
|
3551
|
+
protocols = subprotocol2.parse(secWebSocketProtocol);
|
|
3552
|
+
} catch (err) {
|
|
3553
|
+
const message = "Invalid Sec-WebSocket-Protocol header";
|
|
3554
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3555
|
+
return;
|
|
3556
|
+
}
|
|
3557
|
+
}
|
|
3558
|
+
const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
|
|
3559
|
+
const extensions = {};
|
|
3560
|
+
if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
|
|
3561
|
+
const perMessageDeflate = new PerMessageDeflate2({
|
|
3562
|
+
...this.options.perMessageDeflate,
|
|
3563
|
+
isServer: true,
|
|
3564
|
+
maxPayload: this.options.maxPayload
|
|
3565
|
+
});
|
|
3566
|
+
try {
|
|
3567
|
+
const offers = extension2.parse(secWebSocketExtensions);
|
|
3568
|
+
if (offers[PerMessageDeflate2.extensionName]) {
|
|
3569
|
+
perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
|
|
3570
|
+
extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
|
|
3571
|
+
}
|
|
3572
|
+
} catch (err) {
|
|
3573
|
+
const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
|
|
3574
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3575
|
+
return;
|
|
3576
|
+
}
|
|
3577
|
+
}
|
|
3578
|
+
if (this.options.verifyClient) {
|
|
3579
|
+
const info = {
|
|
3580
|
+
origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
|
|
3581
|
+
secure: !!(req.socket.authorized || req.socket.encrypted),
|
|
3582
|
+
req
|
|
3583
|
+
};
|
|
3584
|
+
if (this.options.verifyClient.length === 2) {
|
|
3585
|
+
this.options.verifyClient(info, (verified, code, message, headers) => {
|
|
3586
|
+
if (!verified) {
|
|
3587
|
+
return abortHandshake(socket, code || 401, message, headers);
|
|
3588
|
+
}
|
|
3589
|
+
this.completeUpgrade(
|
|
3590
|
+
extensions,
|
|
3591
|
+
key,
|
|
3592
|
+
protocols,
|
|
3593
|
+
req,
|
|
3594
|
+
socket,
|
|
3595
|
+
head,
|
|
3596
|
+
cb
|
|
3597
|
+
);
|
|
3598
|
+
});
|
|
3599
|
+
return;
|
|
3600
|
+
}
|
|
3601
|
+
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
|
|
3602
|
+
}
|
|
3603
|
+
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
|
|
3604
|
+
}
|
|
3605
|
+
/**
|
|
3606
|
+
* Upgrade the connection to WebSocket.
|
|
3607
|
+
*
|
|
3608
|
+
* @param {Object} extensions The accepted extensions
|
|
3609
|
+
* @param {String} key The value of the `Sec-WebSocket-Key` header
|
|
3610
|
+
* @param {Set} protocols The subprotocols
|
|
3611
|
+
* @param {http.IncomingMessage} req The request object
|
|
3612
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
3613
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
3614
|
+
* @param {Function} cb Callback
|
|
3615
|
+
* @throws {Error} If called more than once with the same socket
|
|
3616
|
+
* @private
|
|
3617
|
+
*/
|
|
3618
|
+
completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
|
|
3619
|
+
if (!socket.readable || !socket.writable) return socket.destroy();
|
|
3620
|
+
if (socket[kWebSocket]) {
|
|
3621
|
+
throw new Error(
|
|
3622
|
+
"server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
|
|
3623
|
+
);
|
|
3624
|
+
}
|
|
3625
|
+
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
3626
|
+
const digest = createHash("sha1").update(key + GUID).digest("base64");
|
|
3627
|
+
const headers = [
|
|
3628
|
+
"HTTP/1.1 101 Switching Protocols",
|
|
3629
|
+
"Upgrade: websocket",
|
|
3630
|
+
"Connection: Upgrade",
|
|
3631
|
+
`Sec-WebSocket-Accept: ${digest}`
|
|
3632
|
+
];
|
|
3633
|
+
const ws = new this.options.WebSocket(null, void 0, this.options);
|
|
3634
|
+
if (protocols.size) {
|
|
3635
|
+
const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
|
|
3636
|
+
if (protocol) {
|
|
3637
|
+
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
|
|
3638
|
+
ws._protocol = protocol;
|
|
3639
|
+
}
|
|
3640
|
+
}
|
|
3641
|
+
if (extensions[PerMessageDeflate2.extensionName]) {
|
|
3642
|
+
const params = extensions[PerMessageDeflate2.extensionName].params;
|
|
3643
|
+
const value = extension2.format({
|
|
3644
|
+
[PerMessageDeflate2.extensionName]: [params]
|
|
3645
|
+
});
|
|
3646
|
+
headers.push(`Sec-WebSocket-Extensions: ${value}`);
|
|
3647
|
+
ws._extensions = extensions;
|
|
3648
|
+
}
|
|
3649
|
+
this.emit("headers", headers, req);
|
|
3650
|
+
socket.write(headers.concat("\r\n").join("\r\n"));
|
|
3651
|
+
socket.removeListener("error", socketOnError);
|
|
3652
|
+
ws.setSocket(socket, head, {
|
|
3653
|
+
allowSynchronousEvents: this.options.allowSynchronousEvents,
|
|
3654
|
+
maxBufferedChunks: this.options.maxBufferedChunks,
|
|
3655
|
+
maxFragments: this.options.maxFragments,
|
|
3656
|
+
maxPayload: this.options.maxPayload,
|
|
3657
|
+
skipUTF8Validation: this.options.skipUTF8Validation
|
|
3658
|
+
});
|
|
3659
|
+
if (this.clients) {
|
|
3660
|
+
this.clients.add(ws);
|
|
3661
|
+
ws.on("close", () => {
|
|
3662
|
+
this.clients.delete(ws);
|
|
3663
|
+
if (this._shouldEmitClose && !this.clients.size) {
|
|
3664
|
+
process.nextTick(emitClose, this);
|
|
3665
|
+
}
|
|
3666
|
+
});
|
|
3667
|
+
}
|
|
3668
|
+
cb(ws, req);
|
|
3669
|
+
}
|
|
3670
|
+
};
|
|
3671
|
+
module.exports = WebSocketServer2;
|
|
3672
|
+
function addListeners(server, map) {
|
|
3673
|
+
for (const event of Object.keys(map)) server.on(event, map[event]);
|
|
3674
|
+
return function removeListeners() {
|
|
3675
|
+
for (const event of Object.keys(map)) {
|
|
3676
|
+
server.removeListener(event, map[event]);
|
|
3677
|
+
}
|
|
3678
|
+
};
|
|
3679
|
+
}
|
|
3680
|
+
function emitClose(server) {
|
|
3681
|
+
server._state = CLOSED;
|
|
3682
|
+
server.emit("close");
|
|
3683
|
+
}
|
|
3684
|
+
function socketOnError() {
|
|
3685
|
+
this.destroy();
|
|
3686
|
+
}
|
|
3687
|
+
function abortHandshake(socket, code, message, headers) {
|
|
3688
|
+
message = message || http.STATUS_CODES[code];
|
|
3689
|
+
headers = {
|
|
3690
|
+
Connection: "close",
|
|
3691
|
+
"Content-Type": "text/html",
|
|
3692
|
+
"Content-Length": Buffer.byteLength(message),
|
|
3693
|
+
...headers
|
|
3694
|
+
};
|
|
3695
|
+
socket.once("finish", socket.destroy);
|
|
3696
|
+
socket.end(
|
|
3697
|
+
`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
|
|
3698
|
+
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
|
|
3699
|
+
);
|
|
3700
|
+
}
|
|
3701
|
+
function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
|
|
3702
|
+
if (server.listenerCount("wsClientError")) {
|
|
3703
|
+
const err = new Error(message);
|
|
3704
|
+
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
|
|
3705
|
+
server.emit("wsClientError", err, socket, req);
|
|
3706
|
+
} else {
|
|
3707
|
+
abortHandshake(socket, code, message, headers);
|
|
3708
|
+
}
|
|
3709
|
+
}
|
|
3710
|
+
}
|
|
3711
|
+
});
|
|
2
3712
|
|
|
3
3713
|
// ../../node_modules/.pnpm/citty@0.2.2/node_modules/citty/dist/_chunks/libs/scule.mjs
|
|
4
3714
|
var NUMBER_CHAR_RE = /\d/;
|
|
@@ -1137,6 +4847,17 @@ var fmtWorker = (w) => {
|
|
|
1137
4847
|
const offline = w.connected === false ? " [offline]" : "";
|
|
1138
4848
|
return `W-${w.id} ${w.name} ${w.hostname}${offline}`;
|
|
1139
4849
|
};
|
|
4850
|
+
var fmtInterval = (sec) => {
|
|
4851
|
+
if (sec % 86400 === 0) return `${sec / 86400}d`;
|
|
4852
|
+
if (sec % 3600 === 0) return `${sec / 3600}h`;
|
|
4853
|
+
if (sec % 60 === 0) return `${sec / 60}m`;
|
|
4854
|
+
return `${sec}s`;
|
|
4855
|
+
};
|
|
4856
|
+
var fmtLoop = (l) => {
|
|
4857
|
+
const label = l.name ? `${l.name} ` : "";
|
|
4858
|
+
const last = l.lastStatus ? ` last:${l.lastStatus}` : "";
|
|
4859
|
+
return `${l.id} [${l.enabled ? "on" : "off"}] ${label}every ${fmtInterval(l.intervalSec)}${last} "${l.message}"`;
|
|
4860
|
+
};
|
|
1140
4861
|
var renderOne = (item, fmt, json) => json ? toJson(item) : fmt(item);
|
|
1141
4862
|
var renderList = (items, fmt, json) => {
|
|
1142
4863
|
if (json) return toJson(items);
|
|
@@ -1193,6 +4914,20 @@ var primeLogin = (baseUrl) => {
|
|
|
1193
4914
|
);
|
|
1194
4915
|
};
|
|
1195
4916
|
|
|
4917
|
+
// src/client/loops.ts
|
|
4918
|
+
var loopsClient = (baseUrl) => {
|
|
4919
|
+
const u = (p) => `${baseUrl}${p}`;
|
|
4920
|
+
return {
|
|
4921
|
+
create: (sessionId, input) => request(u(`/sessions/${sessionId}/loops`), { method: "POST", body: input }),
|
|
4922
|
+
listBySession: (sessionId) => request(u(`/sessions/${sessionId}/loops`), { method: "GET" }),
|
|
4923
|
+
get: (id) => request(u(`/loops/${id}`), { method: "GET" }),
|
|
4924
|
+
update: (id, input) => request(u(`/loops/${id}`), { method: "PATCH", body: input }),
|
|
4925
|
+
remove: async (id) => {
|
|
4926
|
+
await request(u(`/loops/${id}`), { method: "DELETE" });
|
|
4927
|
+
}
|
|
4928
|
+
};
|
|
4929
|
+
};
|
|
4930
|
+
|
|
1196
4931
|
// src/client/projects.ts
|
|
1197
4932
|
var projectClient = (baseUrl) => {
|
|
1198
4933
|
const u = (p) => `${baseUrl}${p}`;
|
|
@@ -1270,6 +5005,8 @@ var sessionsClient = (baseUrl) => {
|
|
|
1270
5005
|
}),
|
|
1271
5006
|
resume: (id) => request(u(`/sessions/${id}/resume`), { method: "POST" }),
|
|
1272
5007
|
stop: (id) => request(u(`/sessions/${id}/stop`), { method: "POST" }),
|
|
5008
|
+
openTerminal: (id) => request(u(`/sessions/${id}/terminal`), { method: "POST", body: { action: "open" } }),
|
|
5009
|
+
closeTerminal: (id) => request(u(`/sessions/${id}/terminal`), { method: "POST", body: { action: "close" } }),
|
|
1273
5010
|
clear: (id) => request(u(`/sessions/${id}/clear`), { method: "POST" }),
|
|
1274
5011
|
abort: (id) => request(u(`/sessions/${id}/abort`), { method: "POST" }),
|
|
1275
5012
|
rename: (id, name) => request(u(`/sessions/${id}/rename`), { method: "POST", body: { name } }),
|
|
@@ -1368,6 +5105,7 @@ var clientFromBase = (baseUrl) => ({
|
|
|
1368
5105
|
requirements: requirementClient(baseUrl),
|
|
1369
5106
|
tasks: taskClient(baseUrl),
|
|
1370
5107
|
sessions: sessionsClient(baseUrl),
|
|
5108
|
+
loops: loopsClient(baseUrl),
|
|
1371
5109
|
workers: workersClient(baseUrl)
|
|
1372
5110
|
});
|
|
1373
5111
|
var BOUNDARY_EVENTS = /* @__PURE__ */ new Set([
|
|
@@ -1441,6 +5179,13 @@ var parseWorkerHandle = (handle) => {
|
|
|
1441
5179
|
return m ? Number(m[1]) : null;
|
|
1442
5180
|
};
|
|
1443
5181
|
var splitCsv = (s) => s ? s.split(",").map((x) => x.trim()).filter(Boolean) : void 0;
|
|
5182
|
+
var parseDuration = (s) => {
|
|
5183
|
+
const m = s.trim().match(/^(\d+)\s*([smhd]?)$/);
|
|
5184
|
+
if (!m) throw new Error(`bad interval "${s}" \u2014 use e.g. 90s, 30m, 2h, 1d`);
|
|
5185
|
+
const n = Number(m[1]);
|
|
5186
|
+
const mult = m[2] === "d" ? 86400 : m[2] === "h" ? 3600 : m[2] === "m" ? 60 : 1;
|
|
5187
|
+
return n * mult;
|
|
5188
|
+
};
|
|
1444
5189
|
|
|
1445
5190
|
// src/commands/channel/close.ts
|
|
1446
5191
|
var closeCommand = defineCommand({
|
|
@@ -1962,6 +5707,163 @@ var init = defineCommand({
|
|
|
1962
5707
|
}
|
|
1963
5708
|
});
|
|
1964
5709
|
|
|
5710
|
+
// src/commands/session/shared.ts
|
|
5711
|
+
import { homedir } from "node:os";
|
|
5712
|
+
import { join as join3 } from "node:path";
|
|
5713
|
+
var defaultWorktreeDir = (env = process.env) => env.BATON_WORKTREE_DIR ?? join3(env.XDG_DATA_HOME ?? join3(env.HOME ?? homedir(), ".local/share"), "baton", "worktrees");
|
|
5714
|
+
var slug = (s) => s.toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
|
|
5715
|
+
var resolveSession = async (client, projectId, handle) => {
|
|
5716
|
+
const asInt = Number(handle);
|
|
5717
|
+
if (Number.isInteger(asInt) && asInt > 0) {
|
|
5718
|
+
const byId = await client.sessions.get(asInt).catch(() => null);
|
|
5719
|
+
if (byId) return { id: byId.id, name: byId.name };
|
|
5720
|
+
}
|
|
5721
|
+
const byName = await client.sessions.findByName(projectId, handle);
|
|
5722
|
+
if (byName) return { id: byName.id, name: byName.name };
|
|
5723
|
+
throw new Error(`session "${handle}" not found in project ${projectId}`);
|
|
5724
|
+
};
|
|
5725
|
+
|
|
5726
|
+
// src/commands/loop/create.ts
|
|
5727
|
+
var loopCreateCommand = defineCommand({
|
|
5728
|
+
meta: { name: "create", description: "create a recurring scheduled message on a session" },
|
|
5729
|
+
args: {
|
|
5730
|
+
session: { type: "positional", required: true, description: "session int id or name" },
|
|
5731
|
+
message: {
|
|
5732
|
+
type: "string",
|
|
5733
|
+
required: true,
|
|
5734
|
+
description: "message sent to the session each beat"
|
|
5735
|
+
},
|
|
5736
|
+
every: {
|
|
5737
|
+
type: "string",
|
|
5738
|
+
required: true,
|
|
5739
|
+
description: "interval: 90s / 30m / 2h / 1d (min 30s)"
|
|
5740
|
+
},
|
|
5741
|
+
name: { type: "string", description: "optional label" },
|
|
5742
|
+
off: { type: "boolean", description: "create paused (disabled)" },
|
|
5743
|
+
project: { type: "string", description: "project id (overrides .baton.json)" },
|
|
5744
|
+
...common
|
|
5745
|
+
},
|
|
5746
|
+
run: async ({ args }) => {
|
|
5747
|
+
const c = clientFor(args);
|
|
5748
|
+
const session2 = await resolveSession(c, resolveProjectId(args), args.session);
|
|
5749
|
+
const loop2 = await c.loops.create(session2.id, {
|
|
5750
|
+
message: args.message,
|
|
5751
|
+
intervalSec: parseDuration(args.every),
|
|
5752
|
+
name: args.name,
|
|
5753
|
+
enabled: !args.off
|
|
5754
|
+
});
|
|
5755
|
+
console.log(renderOne(loop2, fmtLoop, Boolean(args.json)));
|
|
5756
|
+
}
|
|
5757
|
+
});
|
|
5758
|
+
|
|
5759
|
+
// src/commands/loop/disable.ts
|
|
5760
|
+
var loopDisableCommand = defineCommand({
|
|
5761
|
+
meta: { name: "disable", description: "disable (pause) a loop" },
|
|
5762
|
+
args: {
|
|
5763
|
+
loop: { type: "positional", required: true, description: "loop int id" },
|
|
5764
|
+
...common
|
|
5765
|
+
},
|
|
5766
|
+
run: async ({ args }) => {
|
|
5767
|
+
const c = clientFor(args);
|
|
5768
|
+
const loop2 = await c.loops.update(Number(args.loop), { enabled: false });
|
|
5769
|
+
console.log(renderOne(loop2, fmtLoop, Boolean(args.json)));
|
|
5770
|
+
}
|
|
5771
|
+
});
|
|
5772
|
+
|
|
5773
|
+
// src/commands/loop/enable.ts
|
|
5774
|
+
var loopEnableCommand = defineCommand({
|
|
5775
|
+
meta: { name: "enable", description: "enable (resume) a loop" },
|
|
5776
|
+
args: {
|
|
5777
|
+
loop: { type: "positional", required: true, description: "loop int id" },
|
|
5778
|
+
...common
|
|
5779
|
+
},
|
|
5780
|
+
run: async ({ args }) => {
|
|
5781
|
+
const c = clientFor(args);
|
|
5782
|
+
const loop2 = await c.loops.update(Number(args.loop), { enabled: true });
|
|
5783
|
+
console.log(renderOne(loop2, fmtLoop, Boolean(args.json)));
|
|
5784
|
+
}
|
|
5785
|
+
});
|
|
5786
|
+
|
|
5787
|
+
// src/commands/loop/get.ts
|
|
5788
|
+
var loopGetCommand = defineCommand({
|
|
5789
|
+
meta: { name: "get", description: "show one loop" },
|
|
5790
|
+
args: {
|
|
5791
|
+
loop: { type: "positional", required: true, description: "loop int id" },
|
|
5792
|
+
...common
|
|
5793
|
+
},
|
|
5794
|
+
run: async ({ args }) => {
|
|
5795
|
+
const c = clientFor(args);
|
|
5796
|
+
const loop2 = await c.loops.get(Number(args.loop));
|
|
5797
|
+
console.log(renderOne(loop2, fmtLoop, Boolean(args.json)));
|
|
5798
|
+
}
|
|
5799
|
+
});
|
|
5800
|
+
|
|
5801
|
+
// src/commands/loop/ls.ts
|
|
5802
|
+
var loopLsCommand = defineCommand({
|
|
5803
|
+
meta: { name: "ls", description: "list a session's loops" },
|
|
5804
|
+
args: {
|
|
5805
|
+
session: { type: "positional", required: true, description: "session int id or name" },
|
|
5806
|
+
project: { type: "string", description: "project id (overrides .baton.json)" },
|
|
5807
|
+
...common
|
|
5808
|
+
},
|
|
5809
|
+
run: async ({ args }) => {
|
|
5810
|
+
const c = clientFor(args);
|
|
5811
|
+
const session2 = await resolveSession(c, resolveProjectId(args), args.session);
|
|
5812
|
+
const loops = await c.loops.listBySession(session2.id);
|
|
5813
|
+
console.log(renderList(loops, fmtLoop, Boolean(args.json)));
|
|
5814
|
+
}
|
|
5815
|
+
});
|
|
5816
|
+
|
|
5817
|
+
// src/commands/loop/rm.ts
|
|
5818
|
+
var loopRmCommand = defineCommand({
|
|
5819
|
+
meta: { name: "rm", description: "delete a loop" },
|
|
5820
|
+
args: {
|
|
5821
|
+
loop: { type: "positional", required: true, description: "loop int id" },
|
|
5822
|
+
...common
|
|
5823
|
+
},
|
|
5824
|
+
run: async ({ args }) => {
|
|
5825
|
+
const c = clientFor(args);
|
|
5826
|
+
const id = Number(args.loop);
|
|
5827
|
+
await c.loops.remove(id);
|
|
5828
|
+
console.log(removed("loop", id, Boolean(args.json)));
|
|
5829
|
+
}
|
|
5830
|
+
});
|
|
5831
|
+
|
|
5832
|
+
// src/commands/loop/set.ts
|
|
5833
|
+
var loopSetCommand = defineCommand({
|
|
5834
|
+
meta: { name: "set", description: "update a loop (message / interval / name)" },
|
|
5835
|
+
args: {
|
|
5836
|
+
loop: { type: "positional", required: true, description: "loop int id" },
|
|
5837
|
+
message: { type: "string", description: "new message" },
|
|
5838
|
+
every: { type: "string", description: "new interval: 90s / 30m / 2h / 1d" },
|
|
5839
|
+
name: { type: "string", description: "new label" },
|
|
5840
|
+
...common
|
|
5841
|
+
},
|
|
5842
|
+
run: async ({ args }) => {
|
|
5843
|
+
const c = clientFor(args);
|
|
5844
|
+
const patch2 = {};
|
|
5845
|
+
if (args.message !== void 0) patch2.message = args.message;
|
|
5846
|
+
if (args.every !== void 0 && args.every !== "") patch2.intervalSec = parseDuration(args.every);
|
|
5847
|
+
if (args.name !== void 0) patch2.name = args.name;
|
|
5848
|
+
const loop2 = await c.loops.update(Number(args.loop), patch2);
|
|
5849
|
+
console.log(renderOne(loop2, fmtLoop, Boolean(args.json)));
|
|
5850
|
+
}
|
|
5851
|
+
});
|
|
5852
|
+
|
|
5853
|
+
// src/commands/loop.ts
|
|
5854
|
+
var loop = defineCommand({
|
|
5855
|
+
meta: { name: "loop", description: "recurring scheduled messages that wake a session" },
|
|
5856
|
+
subCommands: {
|
|
5857
|
+
create: loopCreateCommand,
|
|
5858
|
+
ls: loopLsCommand,
|
|
5859
|
+
get: loopGetCommand,
|
|
5860
|
+
set: loopSetCommand,
|
|
5861
|
+
enable: loopEnableCommand,
|
|
5862
|
+
disable: loopDisableCommand,
|
|
5863
|
+
rm: loopRmCommand
|
|
5864
|
+
}
|
|
5865
|
+
});
|
|
5866
|
+
|
|
1965
5867
|
// src/commands/project.ts
|
|
1966
5868
|
var createProject = (c, input, json) => c.projects.create(input).then((p) => renderOne(p, fmtProject, json));
|
|
1967
5869
|
var listProjects = (c, workspaceId, json) => c.projects.listByWorkspace(workspaceId).then((ps) => renderList(ps, fmtProject, json));
|
|
@@ -2039,7 +5941,7 @@ var project = defineCommand({
|
|
|
2039
5941
|
// src/commands/relay.ts
|
|
2040
5942
|
import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "node:fs";
|
|
2041
5943
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
2042
|
-
import { join as
|
|
5944
|
+
import { join as join4 } from "node:path";
|
|
2043
5945
|
|
|
2044
5946
|
// src/client/relay.ts
|
|
2045
5947
|
var relayClient = (baseUrl) => {
|
|
@@ -2167,11 +6069,11 @@ var listenCommand2 = defineCommand({
|
|
|
2167
6069
|
process.stdout.write(`${JSON.stringify(o)}
|
|
2168
6070
|
`);
|
|
2169
6071
|
};
|
|
2170
|
-
const spillDir =
|
|
6072
|
+
const spillDir = join4(tmpdir2(), "hotline", args.channel);
|
|
2171
6073
|
mkdirSync2(spillDir, { recursive: true });
|
|
2172
6074
|
const surface = (m) => {
|
|
2173
6075
|
const text = typeof m.text === "string" ? m.text : "";
|
|
2174
|
-
const file =
|
|
6076
|
+
const file = join4(spillDir, `${m.seq}.txt`);
|
|
2175
6077
|
writeFileSync4(file, text);
|
|
2176
6078
|
const truncated = text.length > PREVIEW2;
|
|
2177
6079
|
emit({
|
|
@@ -2325,22 +6227,6 @@ var requirement = defineCommand({
|
|
|
2325
6227
|
}
|
|
2326
6228
|
});
|
|
2327
6229
|
|
|
2328
|
-
// src/commands/session/shared.ts
|
|
2329
|
-
import { homedir } from "node:os";
|
|
2330
|
-
import { join as join4 } from "node:path";
|
|
2331
|
-
var defaultWorktreeDir = (env = process.env) => env.BATON_WORKTREE_DIR ?? join4(env.XDG_DATA_HOME ?? join4(env.HOME ?? homedir(), ".local/share"), "baton", "worktrees");
|
|
2332
|
-
var slug = (s) => s.toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
|
|
2333
|
-
var resolveSession = async (client, projectId, handle) => {
|
|
2334
|
-
const asInt = Number(handle);
|
|
2335
|
-
if (Number.isInteger(asInt) && asInt > 0) {
|
|
2336
|
-
const byId = await client.sessions.get(asInt).catch(() => null);
|
|
2337
|
-
if (byId) return { id: byId.id, name: byId.name };
|
|
2338
|
-
}
|
|
2339
|
-
const byName = await client.sessions.findByName(projectId, handle);
|
|
2340
|
-
if (byName) return { id: byName.id, name: byName.name };
|
|
2341
|
-
throw new Error(`session "${handle}" not found in project ${projectId}`);
|
|
2342
|
-
};
|
|
2343
|
-
|
|
2344
6230
|
// src/commands/session/abort.ts
|
|
2345
6231
|
var sessionAbortCommand = defineCommand({
|
|
2346
6232
|
meta: {
|
|
@@ -3045,6 +6931,42 @@ var sessionStopCommand = defineCommand({
|
|
|
3045
6931
|
}
|
|
3046
6932
|
});
|
|
3047
6933
|
|
|
6934
|
+
// src/commands/session/terminal.ts
|
|
6935
|
+
var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
6936
|
+
var sessionTerminalCommand = defineCommand({
|
|
6937
|
+
meta: { name: "terminal", description: "open an interactive terminal for a session" },
|
|
6938
|
+
args: {
|
|
6939
|
+
session: { type: "positional", required: true, description: "session int id or name" },
|
|
6940
|
+
project: { type: "string", description: "project id (overrides .baton.json)" },
|
|
6941
|
+
close: { type: "boolean", description: "close the terminal instead of opening one" },
|
|
6942
|
+
...common
|
|
6943
|
+
},
|
|
6944
|
+
run: async ({ args }) => {
|
|
6945
|
+
const c = clientFor(args);
|
|
6946
|
+
const handle = await resolveSession(c, resolveProjectId(args), args.session);
|
|
6947
|
+
if (args.close) {
|
|
6948
|
+
const s = await c.sessions.closeTerminal(handle.id);
|
|
6949
|
+
console.log(renderOne(s, fmtSession, Boolean(args.json)));
|
|
6950
|
+
return;
|
|
6951
|
+
}
|
|
6952
|
+
let view;
|
|
6953
|
+
try {
|
|
6954
|
+
view = await c.sessions.openTerminal(handle.id);
|
|
6955
|
+
} catch (e) {
|
|
6956
|
+
console.log(e instanceof Error ? e.message : String(e));
|
|
6957
|
+
return;
|
|
6958
|
+
}
|
|
6959
|
+
for (let i = 0; i < 10 && !view.terminalOpen; i++) {
|
|
6960
|
+
await sleep2(500);
|
|
6961
|
+
view = await c.sessions.get(handle.id);
|
|
6962
|
+
}
|
|
6963
|
+
if (args.json) console.log(renderOne(view, fmtSession, true));
|
|
6964
|
+
else if (view.terminalOpen)
|
|
6965
|
+
console.log(`terminal open \u2014 view session #${handle.id} in the web UI`);
|
|
6966
|
+
else console.log("terminal did not start (worker offline, or pty unavailable)");
|
|
6967
|
+
}
|
|
6968
|
+
});
|
|
6969
|
+
|
|
3048
6970
|
// src/commands/session.ts
|
|
3049
6971
|
var session = defineCommand({
|
|
3050
6972
|
meta: { name: "session", description: "create / resume / stop / send to agent sessions" },
|
|
@@ -3059,7 +6981,8 @@ var session = defineCommand({
|
|
|
3059
6981
|
send: sessionSendCommand,
|
|
3060
6982
|
ls: sessionLsCommand,
|
|
3061
6983
|
get: sessionGetCommand,
|
|
3062
|
-
run: sessionRunCommand
|
|
6984
|
+
run: sessionRunCommand,
|
|
6985
|
+
terminal: sessionTerminalCommand
|
|
3063
6986
|
}
|
|
3064
6987
|
});
|
|
3065
6988
|
|
|
@@ -3225,7 +7148,58 @@ var task = defineCommand({
|
|
|
3225
7148
|
// src/commands/worker.ts
|
|
3226
7149
|
import { hostname as osHostname } from "node:os";
|
|
3227
7150
|
|
|
3228
|
-
// src/worker/
|
|
7151
|
+
// src/worker/watchdog.ts
|
|
7152
|
+
var stale = (okAt, now, thresholdMs) => now - okAt > thresholdMs;
|
|
7153
|
+
var streamWedged = (isOpen, okAt, now, thresholdMs) => !isOpen && stale(okAt, now, thresholdMs);
|
|
7154
|
+
|
|
7155
|
+
// src/worker/liveness.ts
|
|
7156
|
+
var HEARTBEAT_MS = 3e4;
|
|
7157
|
+
var HEARTBEAT_TIMEOUT_MS = 15e3;
|
|
7158
|
+
var HEARTBEAT_DEAD_MS = 15e4;
|
|
7159
|
+
var STREAM_STALE_MS = 9e4;
|
|
7160
|
+
var createLiveness = (deps) => {
|
|
7161
|
+
const { client, cfg, log, isStreamOpen, onTrip } = deps;
|
|
7162
|
+
let heartbeatOkAt = Date.now();
|
|
7163
|
+
let streamOkAt = Date.now();
|
|
7164
|
+
let timer = null;
|
|
7165
|
+
const ping = async () => {
|
|
7166
|
+
try {
|
|
7167
|
+
await Promise.race([
|
|
7168
|
+
client.workers.heartbeat(cfg.machineId),
|
|
7169
|
+
new Promise(
|
|
7170
|
+
(_, reject) => setTimeout(() => reject(new Error("heartbeat timeout")), HEARTBEAT_TIMEOUT_MS)
|
|
7171
|
+
)
|
|
7172
|
+
]);
|
|
7173
|
+
heartbeatOkAt = Date.now();
|
|
7174
|
+
} catch (e) {
|
|
7175
|
+
log(`heartbeat failed: ${String(e)}`);
|
|
7176
|
+
}
|
|
7177
|
+
};
|
|
7178
|
+
const tick = () => {
|
|
7179
|
+
const now = Date.now();
|
|
7180
|
+
if (stale(heartbeatOkAt, now, HEARTBEAT_DEAD_MS))
|
|
7181
|
+
onTrip(`heartbeat down ~${HEARTBEAT_DEAD_MS / 1e3}s`);
|
|
7182
|
+
else if (streamWedged(isStreamOpen(), streamOkAt, now, STREAM_STALE_MS))
|
|
7183
|
+
onTrip(`command stream wedged ~${STREAM_STALE_MS / 1e3}s`);
|
|
7184
|
+
};
|
|
7185
|
+
return {
|
|
7186
|
+
markStreamOk: () => {
|
|
7187
|
+
streamOkAt = Date.now();
|
|
7188
|
+
},
|
|
7189
|
+
start: () => {
|
|
7190
|
+
void ping();
|
|
7191
|
+
timer = setInterval(() => {
|
|
7192
|
+
void ping();
|
|
7193
|
+
tick();
|
|
7194
|
+
}, HEARTBEAT_MS);
|
|
7195
|
+
},
|
|
7196
|
+
stop: () => {
|
|
7197
|
+
if (timer) clearInterval(timer);
|
|
7198
|
+
}
|
|
7199
|
+
};
|
|
7200
|
+
};
|
|
7201
|
+
|
|
7202
|
+
// src/worker/session-supervisor.ts
|
|
3229
7203
|
import { spawn } from "node:child_process";
|
|
3230
7204
|
import { randomUUID } from "node:crypto";
|
|
3231
7205
|
import { existsSync as existsSync5 } from "node:fs";
|
|
@@ -3390,67 +7364,31 @@ var restoreWorktree = (repo, worktreePath, sessionCode) => {
|
|
|
3390
7364
|
createWorktree({ repo, worktreePath, sessionCode, base: repoHeadBranch(repo) });
|
|
3391
7365
|
};
|
|
3392
7366
|
|
|
3393
|
-
// src/worker/
|
|
3394
|
-
var
|
|
3395
|
-
|
|
7367
|
+
// src/worker/proc.ts
|
|
7368
|
+
var killProcessGroup = (proc) => {
|
|
7369
|
+
if (proc.pid === void 0) return;
|
|
7370
|
+
try {
|
|
7371
|
+
process.kill(-proc.pid, "SIGTERM");
|
|
7372
|
+
} catch {
|
|
7373
|
+
}
|
|
7374
|
+
};
|
|
3396
7375
|
|
|
3397
|
-
// src/worker/
|
|
7376
|
+
// src/worker/session-supervisor.ts
|
|
3398
7377
|
var binPath = () => {
|
|
3399
7378
|
const here = dirname2(fileURLToPath(import.meta.url));
|
|
3400
7379
|
const devShim = join7(here, "..", "..", "bin", "baton.mjs");
|
|
3401
7380
|
return existsSync5(devShim) ? devShim : fileURLToPath(import.meta.url);
|
|
3402
7381
|
};
|
|
3403
|
-
var
|
|
3404
|
-
const repo =
|
|
7382
|
+
var createSessionSupervisor = (deps) => {
|
|
7383
|
+
const { client, cfg, repo, log, hasTerminal, closeTerminal } = deps;
|
|
3405
7384
|
const worktreeDir = defaultWorktreeDir();
|
|
3406
7385
|
const children = /* @__PURE__ */ new Map();
|
|
3407
|
-
const log = (m) => console.log(`[worker #${cfg.workerId} ${cfg.name}] ${m}`);
|
|
3408
|
-
const HEARTBEAT_MS = 3e4;
|
|
3409
|
-
const HEARTBEAT_TIMEOUT_MS = 15e3;
|
|
3410
|
-
const HEARTBEAT_DEAD_MS = 15e4;
|
|
3411
|
-
const STREAM_STALE_MS = 9e4;
|
|
3412
|
-
const ES_OPEN = 1;
|
|
3413
|
-
let heartbeatOkAt = Date.now();
|
|
3414
|
-
let streamOkAt = Date.now();
|
|
3415
|
-
let fatal = false;
|
|
3416
|
-
let stop = () => {
|
|
3417
|
-
};
|
|
3418
|
-
const trip = (reason) => {
|
|
3419
|
-
if (fatal) return;
|
|
3420
|
-
log(`${reason} \u2014 exiting so the supervisor restarts a clean worker`);
|
|
3421
|
-
fatal = true;
|
|
3422
|
-
stop();
|
|
3423
|
-
};
|
|
3424
|
-
const ping = async () => {
|
|
3425
|
-
try {
|
|
3426
|
-
await Promise.race([
|
|
3427
|
-
client.workers.heartbeat(cfg.machineId),
|
|
3428
|
-
new Promise(
|
|
3429
|
-
(_, reject) => setTimeout(() => reject(new Error("heartbeat timeout")), HEARTBEAT_TIMEOUT_MS)
|
|
3430
|
-
)
|
|
3431
|
-
]);
|
|
3432
|
-
heartbeatOkAt = Date.now();
|
|
3433
|
-
} catch (e) {
|
|
3434
|
-
log(`heartbeat failed: ${String(e)}`);
|
|
3435
|
-
}
|
|
3436
|
-
};
|
|
3437
|
-
const killChild = (child) => {
|
|
3438
|
-
if (child.pid === void 0) return;
|
|
3439
|
-
try {
|
|
3440
|
-
process.kill(-child.pid, "SIGTERM");
|
|
3441
|
-
} catch {
|
|
3442
|
-
}
|
|
3443
|
-
};
|
|
3444
7386
|
const spawnChild = (sessionId, worktreePath) => {
|
|
3445
7387
|
if (children.has(sessionId)) return;
|
|
3446
7388
|
const child = spawn(process.execPath, [binPath(), "session", "run", String(sessionId)], {
|
|
3447
7389
|
detached: true,
|
|
3448
7390
|
stdio: "inherit",
|
|
3449
|
-
env: {
|
|
3450
|
-
...process.env,
|
|
3451
|
-
BATON_SERVER: cfg.server,
|
|
3452
|
-
BATON_WORKER_TOKEN: cfg.apiToken
|
|
3453
|
-
}
|
|
7391
|
+
env: { ...process.env, BATON_SERVER: cfg.server, BATON_WORKER_TOKEN: cfg.apiToken }
|
|
3454
7392
|
});
|
|
3455
7393
|
children.set(sessionId, { child, worktreePath });
|
|
3456
7394
|
log(`spawned session #${sessionId} (${worktreePath})`);
|
|
@@ -3461,7 +7399,9 @@ var runWorkerDaemon = async (cfg, client, signal) => {
|
|
|
3461
7399
|
});
|
|
3462
7400
|
});
|
|
3463
7401
|
};
|
|
3464
|
-
const
|
|
7402
|
+
const start = async (sessionId, name) => {
|
|
7403
|
+
if (hasTerminal(sessionId))
|
|
7404
|
+
return log(`session #${sessionId} has an open terminal \u2014 skipping headless start`);
|
|
3465
7405
|
if (children.has(sessionId)) return log(`session #${sessionId} already running`);
|
|
3466
7406
|
const session2 = await client.sessions.get(sessionId);
|
|
3467
7407
|
let worktreePath = session2.worktreePath;
|
|
@@ -3482,26 +7422,30 @@ var runWorkerDaemon = async (cfg, client, signal) => {
|
|
|
3482
7422
|
}
|
|
3483
7423
|
ensureExcluded(repo, PROJECT_CONFIG_NAME);
|
|
3484
7424
|
saveProjectConfig(join7(worktreePath, PROJECT_CONFIG_NAME), worktreeConfig(cfg));
|
|
7425
|
+
if (hasTerminal(sessionId))
|
|
7426
|
+
return log(`session #${sessionId} terminal opened mid-start \u2014 skipping headless start`);
|
|
3485
7427
|
spawnChild(sessionId, worktreePath);
|
|
3486
7428
|
};
|
|
3487
|
-
const
|
|
7429
|
+
const stop = (sessionId) => {
|
|
7430
|
+
closeTerminal(sessionId);
|
|
3488
7431
|
const entry = children.get(sessionId);
|
|
3489
7432
|
if (!entry) return;
|
|
3490
|
-
|
|
7433
|
+
killProcessGroup(entry.child);
|
|
3491
7434
|
children.delete(sessionId);
|
|
3492
7435
|
log(`stopped session #${sessionId}`);
|
|
3493
7436
|
};
|
|
3494
|
-
const
|
|
7437
|
+
const remove = (sessionId, worktreePath) => {
|
|
7438
|
+
closeTerminal(sessionId);
|
|
3495
7439
|
const entry = children.get(sessionId);
|
|
3496
7440
|
if (entry) {
|
|
3497
|
-
|
|
7441
|
+
killProcessGroup(entry.child);
|
|
3498
7442
|
children.delete(sessionId);
|
|
3499
7443
|
}
|
|
3500
7444
|
const wt = entry?.worktreePath ?? worktreePath;
|
|
3501
7445
|
if (wt) removeWorktree(repo, wt);
|
|
3502
7446
|
log(`deleted session #${sessionId} (removed worktree)`);
|
|
3503
7447
|
};
|
|
3504
|
-
const
|
|
7448
|
+
const title = async (sessionId, agentSessionId, worktreePath) => {
|
|
3505
7449
|
const exchange = readFirstExchange(agentSessionId);
|
|
3506
7450
|
if (!exchange) return log(`title #${sessionId}: no transcript yet, skipping`);
|
|
3507
7451
|
const outcome = await generateTitle({
|
|
@@ -3523,12 +7467,167 @@ var runWorkerDaemon = async (cfg, client, signal) => {
|
|
|
3523
7467
|
const live = new Set(owned.map((s) => s.id));
|
|
3524
7468
|
for (const [sid, entry] of children) {
|
|
3525
7469
|
if (!live.has(sid)) {
|
|
3526
|
-
|
|
7470
|
+
killProcessGroup(entry.child);
|
|
3527
7471
|
children.delete(sid);
|
|
3528
7472
|
log(`reconcile: stopped orphan session #${sid}`);
|
|
3529
7473
|
}
|
|
3530
7474
|
}
|
|
3531
7475
|
};
|
|
7476
|
+
return {
|
|
7477
|
+
start,
|
|
7478
|
+
stop,
|
|
7479
|
+
remove,
|
|
7480
|
+
title,
|
|
7481
|
+
reconcile,
|
|
7482
|
+
has: (sessionId) => children.has(sessionId),
|
|
7483
|
+
killAll: () => {
|
|
7484
|
+
for (const { child } of children.values()) killProcessGroup(child);
|
|
7485
|
+
}
|
|
7486
|
+
};
|
|
7487
|
+
};
|
|
7488
|
+
|
|
7489
|
+
// src/worker/terminal-manager.ts
|
|
7490
|
+
import { existsSync as existsSync7 } from "node:fs";
|
|
7491
|
+
import { spawn as spawn2 } from "node-pty";
|
|
7492
|
+
|
|
7493
|
+
// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/wrapper.mjs
|
|
7494
|
+
var import_stream2 = __toESM(require_stream(), 1);
|
|
7495
|
+
var import_extension = __toESM(require_extension(), 1);
|
|
7496
|
+
var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
|
|
7497
|
+
var import_receiver = __toESM(require_receiver(), 1);
|
|
7498
|
+
var import_sender = __toESM(require_sender(), 1);
|
|
7499
|
+
var import_subprotocol = __toESM(require_subprotocol(), 1);
|
|
7500
|
+
var import_websocket = __toESM(require_websocket(), 1);
|
|
7501
|
+
var import_websocket_server = __toESM(require_websocket_server(), 1);
|
|
7502
|
+
|
|
7503
|
+
// src/worker/pty.ts
|
|
7504
|
+
import { existsSync as existsSync6, readdirSync as readdirSync2 } from "node:fs";
|
|
7505
|
+
import { homedir as homedir3 } from "node:os";
|
|
7506
|
+
import { join as join8 } from "node:path";
|
|
7507
|
+
var MAX_TERMINALS = 10;
|
|
7508
|
+
var ptyArgs = (agentSessionId, hasJsonl) => hasJsonl ? ["--resume", agentSessionId] : ["--session-id", agentSessionId];
|
|
7509
|
+
var hasSessionJsonl = (agentSessionId) => {
|
|
7510
|
+
const root = join8(homedir3(), ".claude", "projects");
|
|
7511
|
+
if (!existsSync6(root)) return false;
|
|
7512
|
+
for (const dir of readdirSync2(root))
|
|
7513
|
+
if (existsSync6(join8(root, dir, `${agentSessionId}.jsonl`))) return true;
|
|
7514
|
+
return false;
|
|
7515
|
+
};
|
|
7516
|
+
var serverTerminalWsUrl = (server, sessionId) => `${server.replace(/^http/, "ws")}/workers/me/terminal/ws?sessionId=${sessionId}`;
|
|
7517
|
+
var isPositiveDim = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
7518
|
+
|
|
7519
|
+
// src/worker/terminal-manager.ts
|
|
7520
|
+
var createTerminalManager = (deps) => {
|
|
7521
|
+
const { cfg, log, hasChild } = deps;
|
|
7522
|
+
const terminals = /* @__PURE__ */ new Map();
|
|
7523
|
+
const open = (sessionId, agentSessionId, worktreePath) => {
|
|
7524
|
+
const why = terminals.has(sessionId) ? "already open" : hasChild(sessionId) ? "headless child running" : !existsSync7(worktreePath) ? `worktree missing (${worktreePath})` : terminals.size >= MAX_TERMINALS ? `cap ${MAX_TERMINALS} reached` : null;
|
|
7525
|
+
if (why) {
|
|
7526
|
+
log(`terminal #${sessionId}: ${why} \u2014 refusing`);
|
|
7527
|
+
return;
|
|
7528
|
+
}
|
|
7529
|
+
const claudeBin = process.env.BATON_CLAUDE_BIN ?? "claude";
|
|
7530
|
+
const term = spawn2(claudeBin, ptyArgs(agentSessionId, hasSessionJsonl(agentSessionId)), {
|
|
7531
|
+
name: "xterm-color",
|
|
7532
|
+
cols: 80,
|
|
7533
|
+
rows: 24,
|
|
7534
|
+
cwd: worktreePath,
|
|
7535
|
+
env: process.env
|
|
7536
|
+
});
|
|
7537
|
+
const ws = new import_websocket.default(serverTerminalWsUrl(cfg.server, sessionId), {
|
|
7538
|
+
headers: { authorization: `Bearer ${cfg.apiToken}` }
|
|
7539
|
+
});
|
|
7540
|
+
terminals.set(sessionId, { pty: term, ws });
|
|
7541
|
+
const teardown = (why2) => {
|
|
7542
|
+
if (terminals.get(sessionId)?.pty !== term) return;
|
|
7543
|
+
terminals.delete(sessionId);
|
|
7544
|
+
log(`terminal #${sessionId} gone (${why2})`);
|
|
7545
|
+
try {
|
|
7546
|
+
term.kill();
|
|
7547
|
+
} catch {
|
|
7548
|
+
}
|
|
7549
|
+
try {
|
|
7550
|
+
ws.close();
|
|
7551
|
+
} catch {
|
|
7552
|
+
}
|
|
7553
|
+
};
|
|
7554
|
+
term.onData((d) => {
|
|
7555
|
+
if (ws.readyState === import_websocket.default.OPEN) ws.send(d);
|
|
7556
|
+
});
|
|
7557
|
+
term.onExit(() => teardown("pty exit"));
|
|
7558
|
+
ws.on("open", () => log(`terminal #${sessionId} bridged \u2192 ${cfg.server}`));
|
|
7559
|
+
ws.on("message", (raw) => {
|
|
7560
|
+
try {
|
|
7561
|
+
const m = JSON.parse(raw.toString());
|
|
7562
|
+
if (m.t === "i" && typeof m.d === "string") term.write(m.d);
|
|
7563
|
+
else if (m.t === "r" && isPositiveDim(m.c) && isPositiveDim(m.r)) term.resize(m.c, m.r);
|
|
7564
|
+
} catch (e) {
|
|
7565
|
+
log(`terminal #${sessionId}: bad control frame: ${String(e)}`);
|
|
7566
|
+
}
|
|
7567
|
+
});
|
|
7568
|
+
ws.on("close", () => teardown("server ws closed"));
|
|
7569
|
+
ws.on("error", (e) => teardown(`ws error: ${String(e)}`));
|
|
7570
|
+
};
|
|
7571
|
+
const close = (sessionId) => {
|
|
7572
|
+
const t = terminals.get(sessionId);
|
|
7573
|
+
if (!t) return;
|
|
7574
|
+
log(`closing terminal #${sessionId}`);
|
|
7575
|
+
try {
|
|
7576
|
+
t.ws.close();
|
|
7577
|
+
} catch {
|
|
7578
|
+
}
|
|
7579
|
+
};
|
|
7580
|
+
return {
|
|
7581
|
+
open,
|
|
7582
|
+
close,
|
|
7583
|
+
has: (sessionId) => terminals.has(sessionId),
|
|
7584
|
+
killAll: () => {
|
|
7585
|
+
for (const { pty, ws } of terminals.values()) {
|
|
7586
|
+
try {
|
|
7587
|
+
pty.kill();
|
|
7588
|
+
} catch {
|
|
7589
|
+
}
|
|
7590
|
+
try {
|
|
7591
|
+
ws.close();
|
|
7592
|
+
} catch {
|
|
7593
|
+
}
|
|
7594
|
+
}
|
|
7595
|
+
}
|
|
7596
|
+
};
|
|
7597
|
+
};
|
|
7598
|
+
|
|
7599
|
+
// src/worker/daemon.ts
|
|
7600
|
+
var ES_OPEN = 1;
|
|
7601
|
+
var runWorkerDaemon = async (cfg, client, signal) => {
|
|
7602
|
+
const log = (m) => console.log(`[worker #${cfg.workerId} ${cfg.name}] ${m}`);
|
|
7603
|
+
const supervisor = createSessionSupervisor({
|
|
7604
|
+
client,
|
|
7605
|
+
cfg,
|
|
7606
|
+
repo: process.cwd(),
|
|
7607
|
+
log,
|
|
7608
|
+
hasTerminal: (id) => terminals.has(id),
|
|
7609
|
+
closeTerminal: (id) => terminals.close(id)
|
|
7610
|
+
});
|
|
7611
|
+
const terminals = createTerminalManager({
|
|
7612
|
+
cfg,
|
|
7613
|
+
log,
|
|
7614
|
+
hasChild: (id) => supervisor.has(id)
|
|
7615
|
+
});
|
|
7616
|
+
let fatal = false;
|
|
7617
|
+
let stop = () => {
|
|
7618
|
+
};
|
|
7619
|
+
const liveness = createLiveness({
|
|
7620
|
+
client,
|
|
7621
|
+
cfg,
|
|
7622
|
+
log,
|
|
7623
|
+
isStreamOpen: () => es.readyState === ES_OPEN,
|
|
7624
|
+
onTrip: (reason) => {
|
|
7625
|
+
if (fatal) return;
|
|
7626
|
+
log(`${reason} \u2014 exiting so the supervisor restarts a clean worker`);
|
|
7627
|
+
fatal = true;
|
|
7628
|
+
stop();
|
|
7629
|
+
}
|
|
7630
|
+
});
|
|
3532
7631
|
const es = new EventSource(`${cfg.server}/workers/me/stream`, {
|
|
3533
7632
|
fetch: (url, init2) => fetch(url, {
|
|
3534
7633
|
...init2,
|
|
@@ -3539,57 +7638,50 @@ var runWorkerDaemon = async (cfg, client, signal) => {
|
|
|
3539
7638
|
})
|
|
3540
7639
|
});
|
|
3541
7640
|
es.onopen = () => {
|
|
3542
|
-
|
|
3543
|
-
void reconcile().catch((err) => log(`reconcile failed: ${String(err)}`));
|
|
7641
|
+
liveness.markStreamOk();
|
|
7642
|
+
void supervisor.reconcile().catch((err) => log(`reconcile failed: ${String(err)}`));
|
|
3544
7643
|
};
|
|
3545
7644
|
es.onmessage = (e) => {
|
|
3546
|
-
|
|
7645
|
+
liveness.markStreamOk();
|
|
3547
7646
|
try {
|
|
3548
7647
|
const cmd = JSON.parse(e.data);
|
|
3549
7648
|
if (cmd.cmd === "session.start")
|
|
3550
|
-
void
|
|
3551
|
-
else if (cmd.cmd === "session.stop")
|
|
3552
|
-
else if (cmd.cmd === "session.delete")
|
|
7649
|
+
void supervisor.start(cmd.sessionId, cmd.name).catch((err) => log(`start failed: ${String(err)}`));
|
|
7650
|
+
else if (cmd.cmd === "session.stop") supervisor.stop(cmd.sessionId);
|
|
7651
|
+
else if (cmd.cmd === "session.delete") supervisor.remove(cmd.sessionId, cmd.worktreePath);
|
|
3553
7652
|
else if (cmd.cmd === "session.title")
|
|
3554
|
-
void
|
|
3555
|
-
|
|
3556
|
-
)
|
|
7653
|
+
void supervisor.title(cmd.sessionId, cmd.agentSessionId, cmd.worktreePath).catch((err) => log(`title failed: ${String(err)}`));
|
|
7654
|
+
else if (cmd.cmd === "session.terminal") {
|
|
7655
|
+
if (cmd.action === "open")
|
|
7656
|
+
terminals.open(cmd.sessionId, cmd.agentSessionId, cmd.worktreePath);
|
|
7657
|
+
else terminals.close(cmd.sessionId);
|
|
7658
|
+
}
|
|
3557
7659
|
} catch {
|
|
3558
7660
|
}
|
|
3559
7661
|
};
|
|
3560
7662
|
es.onerror = () => log("command stream error (eventsource will retry)");
|
|
3561
|
-
log(`listening for commands (server ${cfg.server}, repo ${
|
|
3562
|
-
|
|
3563
|
-
const now = Date.now();
|
|
3564
|
-
if (stale(heartbeatOkAt, now, HEARTBEAT_DEAD_MS))
|
|
3565
|
-
trip(`heartbeat down ~${HEARTBEAT_DEAD_MS / 1e3}s`);
|
|
3566
|
-
else if (streamWedged(es.readyState === ES_OPEN, streamOkAt, now, STREAM_STALE_MS))
|
|
3567
|
-
trip(`command stream wedged ~${STREAM_STALE_MS / 1e3}s`);
|
|
3568
|
-
};
|
|
3569
|
-
void ping();
|
|
3570
|
-
const hb = setInterval(() => {
|
|
3571
|
-
void ping();
|
|
3572
|
-
watchdog();
|
|
3573
|
-
}, HEARTBEAT_MS);
|
|
7663
|
+
log(`listening for commands (server ${cfg.server}, repo ${process.cwd()})`);
|
|
7664
|
+
liveness.start();
|
|
3574
7665
|
await new Promise((resolve2) => {
|
|
3575
7666
|
stop = resolve2;
|
|
3576
7667
|
if (signal.aborted) return resolve2();
|
|
3577
7668
|
signal.addEventListener("abort", () => resolve2(), { once: true });
|
|
3578
7669
|
});
|
|
3579
7670
|
es.close();
|
|
3580
|
-
|
|
3581
|
-
|
|
7671
|
+
liveness.stop();
|
|
7672
|
+
supervisor.killAll();
|
|
7673
|
+
terminals.killAll();
|
|
3582
7674
|
if (fatal) process.exit(1);
|
|
3583
7675
|
};
|
|
3584
7676
|
|
|
3585
7677
|
// src/worker/machine-id.ts
|
|
3586
7678
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
3587
|
-
import { existsSync as
|
|
3588
|
-
import { homedir as
|
|
3589
|
-
import { dirname as dirname3, join as
|
|
3590
|
-
var machineIdPath = (env = process.env) =>
|
|
7679
|
+
import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "node:fs";
|
|
7680
|
+
import { homedir as homedir4 } from "node:os";
|
|
7681
|
+
import { dirname as dirname3, join as join9 } from "node:path";
|
|
7682
|
+
var machineIdPath = (env = process.env) => join9(env.XDG_DATA_HOME ?? join9(env.HOME ?? homedir4(), ".local/share"), "baton", "machine-id");
|
|
3591
7683
|
var readOrCreateMachineId = (path = machineIdPath()) => {
|
|
3592
|
-
if (
|
|
7684
|
+
if (existsSync8(path)) {
|
|
3593
7685
|
const s = readFileSync6(path, "utf8").trim();
|
|
3594
7686
|
if (s) return s;
|
|
3595
7687
|
}
|
|
@@ -3866,6 +7958,7 @@ var main = defineCommand({
|
|
|
3866
7958
|
init,
|
|
3867
7959
|
worker,
|
|
3868
7960
|
session,
|
|
7961
|
+
loop,
|
|
3869
7962
|
relay,
|
|
3870
7963
|
channel,
|
|
3871
7964
|
workspace,
|