@a-company/paradigm 3.1.5 → 3.5.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/{accept-orchestration-CWZNCGZX.js → accept-orchestration-DIGPJVUR.js} +6 -5
- package/dist/{aggregate-W7Q6VIM2.js → aggregate-V4KPR3RW.js} +2 -2
- package/dist/{beacon-B47XSTL7.js → beacon-XRXL5KZB.js} +2 -2
- package/dist/{chunk-4LGLU2LO.js → chunk-2E2RTBSM.js} +533 -182
- package/dist/{chunk-YCLN7WXV.js → chunk-2QNZ6PVD.js} +219 -35
- package/dist/{chunk-UM54F7G5.js → chunk-4N6AYEEA.js} +1 -1
- package/dist/{chunk-MVXJVRFI.js → chunk-5TUAVVIG.js} +65 -1
- package/dist/{chunk-5C4SGQKH.js → chunk-6P4IFIK2.js} +4 -2
- package/dist/{chunk-WS5KM7OL.js → chunk-6RNYVBSG.js} +1 -1
- package/dist/{chunk-N6PJAPDE.js → chunk-AK5M6KJB.js} +18 -0
- package/dist/{chunk-VZ7CXFRZ.js → chunk-CRICL4FQ.js} +1004 -17
- package/dist/{chunk-MC7XC7XQ.js → chunk-GZDFVP2N.js} +20 -13
- package/dist/chunk-HPC3JAUP.js +42 -0
- package/dist/chunk-IRVA7NKV.js +657 -0
- package/dist/{chunk-ZPN7MXRA.js → chunk-KFHK6EBI.js} +184 -1
- package/dist/{chunk-UUZ2DMG5.js → chunk-KWDTBXP2.js} +1 -1
- package/dist/{chunk-DRUDZKIT.js → chunk-M2XMTJHQ.js} +693 -70
- package/dist/{chunk-PW2EXJQT.js → chunk-MRENOFTR.js} +24 -1
- package/dist/{chunk-QS36NGWV.js → chunk-QHJGB5TV.js} +1 -1
- package/dist/chunk-UI3XXVJ6.js +449 -0
- package/dist/{chunk-AD2LSCHB.js → chunk-Y4XZWCHK.js} +40 -74
- package/dist/{constellation-K3CIQCHI.js → constellation-GNK5DIMH.js} +2 -2
- package/dist/{cost-AEK6R7HK.js → cost-AGO5N7DD.js} +1 -1
- package/dist/{cursorrules-KI5QWHIX.js → cursorrules-LQFA7M62.js} +2 -2
- package/dist/{delete-W67IVTLJ.js → delete-3YXAJ5AA.js} +12 -1
- package/dist/{diff-AJJ5H6HV.js → diff-J6C5IHPV.js} +6 -5
- package/dist/{dist-2F7NO4H4-KSL6SJIO.js → dist-AG5JNIZU-XSEZ2LLK.js} +28 -3
- package/dist/dist-JOHRYQUA.js +7294 -0
- package/dist/{dist-NHJQVVUW.js → dist-Q6SAZI7X.js} +2 -2
- package/dist/{dist-GPQ4LAY3.js → dist-YP2CO4TG.js} +24 -6
- package/dist/{doctor-JBIV5PMN.js → doctor-TQYRF7KK.js} +2 -2
- package/dist/{edit-Y7XPYSMK.js → edit-EOMPXOG5.js} +1 -1
- package/dist/flow-7JUH6D4H.js +185 -0
- package/dist/global-AXILUM5X.js +136 -0
- package/dist/{habits-FA65W77Y.js → habits-CHP4EW5H.js} +234 -5
- package/dist/{hooks-JKWO44WH.js → hooks-DLZEYHI3.js} +1 -1
- package/dist/index.js +125 -100
- package/dist/{lint-HXKTWRNO.js → lint-N4LMMEXH.js} +141 -1
- package/dist/{list-R3QWW4SC.js → list-JKBJ7ESH.js} +1 -1
- package/dist/mcp.js +9273 -6515
- package/dist/{orchestrate-4ZH5GUQH.js → orchestrate-FAV64G2R.js} +6 -5
- package/dist/{probe-OYCP4JYG.js → probe-X3J2JX62.js} +18 -3
- package/dist/{promote-E6NBZ3BK.js → promote-HZH5E5CO.js} +1 -1
- package/dist/{providers-4PGPZEWP.js → providers-NQ67LO2Z.js} +1 -1
- package/dist/{record-OHQNWOUP.js → record-EECZ3E4I.js} +1 -1
- package/dist/{remember-6VZ74B7E.js → remember-3KJZGDUG.js} +1 -1
- package/dist/{review-RUHX25A5.js → review-BF26ILZB.js} +1 -1
- package/dist/{ripple-SBQOSTZD.js → ripple-JIUAMBLA.js} +2 -2
- package/dist/sentinel-ZTL224IG.js +63 -0
- package/dist/{server-MV4HNFVF.js → server-MZBYDXJY.js} +4193 -9
- package/dist/{setup-DF4F3ICN.js → setup-363IB6MO.js} +1 -1
- package/dist/{setup-JHBPZAG7.js → setup-UKJ3VGHI.js} +4 -4
- package/dist/{shift-2LQFQP4P.js → shift-KDVYB6CR.js} +16 -13
- package/dist/{show-WTOJXUTN.js → show-SAMTXEHG.js} +1 -1
- package/dist/{snapshot-GTVPRYZG.js → snapshot-KCMONZAO.js} +2 -2
- package/dist/{spawn-BJRQA2NR.js → spawn-EO7B2UM3.js} +2 -2
- package/dist/{summary-5SBFO7QK.js → summary-E2PU4UN2.js} +3 -3
- package/dist/{switch-6EANJ7O6.js → switch-CC2KACXO.js} +1 -1
- package/dist/{sync-5KSTPJ4B.js → sync-5VJPZQNX.js} +2 -2
- package/dist/sync-llms-7QDA3ZWC.js +166 -0
- package/dist/{team-NWP2KJAB.js → team-6CCNANKE.js} +7 -6
- package/dist/{test-MA5TWJQV.js → test-DK2RWLTK.js} +91 -8
- package/dist/{thread-JCJVRUQR.js → thread-RNSLADXN.js} +18 -2
- package/dist/{timeline-P7BARFLI.js → timeline-TJDVVVA3.js} +1 -1
- package/dist/{triage-TBIWJA6R.js → triage-PXMU3RWV.js} +2 -2
- package/dist/university-content/courses/para-101.json +2 -1
- package/dist/university-content/courses/para-201.json +102 -3
- package/dist/university-content/courses/para-301.json +14 -11
- package/dist/university-content/courses/para-401.json +57 -3
- package/dist/university-content/courses/para-501.json +204 -6
- package/dist/university-content/plsat/v3.0.json +808 -3
- package/dist/university-content/reference.json +270 -0
- package/dist/{upgrade-TIYFQYPO.js → upgrade-RBSE4M6I.js} +1 -1
- package/dist/{validate-QEEY6KFS.js → validate-2LTHHORX.js} +1 -1
- package/dist/{watch-4LT4O6K7.js → watch-NBPOMOEX.js} +76 -0
- package/dist/{watch-2XEYUH43.js → watch-PAEH6MOG.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-GWM2WRXL.js +0 -1095
- package/dist/sentinel-WB7GIK4V.js +0 -43
- /package/dist/{chunk-TAP5N3HH.js → chunk-CCG6KYBT.js} +0 -0
|
@@ -1,13 +1,3631 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
|
-
SentinelStorage
|
|
4
|
-
|
|
3
|
+
SentinelStorage,
|
|
4
|
+
loadServerConfig,
|
|
5
|
+
v4_default
|
|
6
|
+
} from "./chunk-CRICL4FQ.js";
|
|
5
7
|
import {
|
|
6
8
|
__commonJS,
|
|
7
9
|
__require,
|
|
8
10
|
__toESM
|
|
9
11
|
} from "./chunk-MO4EEYFW.js";
|
|
10
12
|
|
|
13
|
+
// ../../node_modules/ws/lib/constants.js
|
|
14
|
+
var require_constants = __commonJS({
|
|
15
|
+
"../../node_modules/ws/lib/constants.js"(exports, module) {
|
|
16
|
+
"use strict";
|
|
17
|
+
var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
|
|
18
|
+
var hasBlob = typeof Blob !== "undefined";
|
|
19
|
+
if (hasBlob) BINARY_TYPES.push("blob");
|
|
20
|
+
module.exports = {
|
|
21
|
+
BINARY_TYPES,
|
|
22
|
+
CLOSE_TIMEOUT: 3e4,
|
|
23
|
+
EMPTY_BUFFER: Buffer.alloc(0),
|
|
24
|
+
GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
|
|
25
|
+
hasBlob,
|
|
26
|
+
kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
|
|
27
|
+
kListener: /* @__PURE__ */ Symbol("kListener"),
|
|
28
|
+
kStatusCode: /* @__PURE__ */ Symbol("status-code"),
|
|
29
|
+
kWebSocket: /* @__PURE__ */ Symbol("websocket"),
|
|
30
|
+
NOOP: () => {
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
// ../../node_modules/ws/lib/buffer-util.js
|
|
37
|
+
var require_buffer_util = __commonJS({
|
|
38
|
+
"../../node_modules/ws/lib/buffer-util.js"(exports, module) {
|
|
39
|
+
"use strict";
|
|
40
|
+
var { EMPTY_BUFFER } = require_constants();
|
|
41
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
42
|
+
function concat(list, totalLength) {
|
|
43
|
+
if (list.length === 0) return EMPTY_BUFFER;
|
|
44
|
+
if (list.length === 1) return list[0];
|
|
45
|
+
const target = Buffer.allocUnsafe(totalLength);
|
|
46
|
+
let offset = 0;
|
|
47
|
+
for (let i = 0; i < list.length; i++) {
|
|
48
|
+
const buf = list[i];
|
|
49
|
+
target.set(buf, offset);
|
|
50
|
+
offset += buf.length;
|
|
51
|
+
}
|
|
52
|
+
if (offset < totalLength) {
|
|
53
|
+
return new FastBuffer(target.buffer, target.byteOffset, offset);
|
|
54
|
+
}
|
|
55
|
+
return target;
|
|
56
|
+
}
|
|
57
|
+
function _mask(source, mask, output, offset, length) {
|
|
58
|
+
for (let i = 0; i < length; i++) {
|
|
59
|
+
output[offset + i] = source[i] ^ mask[i & 3];
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function _unmask(buffer, mask) {
|
|
63
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
64
|
+
buffer[i] ^= mask[i & 3];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function toArrayBuffer(buf) {
|
|
68
|
+
if (buf.length === buf.buffer.byteLength) {
|
|
69
|
+
return buf.buffer;
|
|
70
|
+
}
|
|
71
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
|
|
72
|
+
}
|
|
73
|
+
function toBuffer(data) {
|
|
74
|
+
toBuffer.readOnly = true;
|
|
75
|
+
if (Buffer.isBuffer(data)) return data;
|
|
76
|
+
let buf;
|
|
77
|
+
if (data instanceof ArrayBuffer) {
|
|
78
|
+
buf = new FastBuffer(data);
|
|
79
|
+
} else if (ArrayBuffer.isView(data)) {
|
|
80
|
+
buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
|
|
81
|
+
} else {
|
|
82
|
+
buf = Buffer.from(data);
|
|
83
|
+
toBuffer.readOnly = false;
|
|
84
|
+
}
|
|
85
|
+
return buf;
|
|
86
|
+
}
|
|
87
|
+
module.exports = {
|
|
88
|
+
concat,
|
|
89
|
+
mask: _mask,
|
|
90
|
+
toArrayBuffer,
|
|
91
|
+
toBuffer,
|
|
92
|
+
unmask: _unmask
|
|
93
|
+
};
|
|
94
|
+
if (!process.env.WS_NO_BUFFER_UTIL) {
|
|
95
|
+
try {
|
|
96
|
+
const bufferUtil = __require("bufferutil");
|
|
97
|
+
module.exports.mask = function(source, mask, output, offset, length) {
|
|
98
|
+
if (length < 48) _mask(source, mask, output, offset, length);
|
|
99
|
+
else bufferUtil.mask(source, mask, output, offset, length);
|
|
100
|
+
};
|
|
101
|
+
module.exports.unmask = function(buffer, mask) {
|
|
102
|
+
if (buffer.length < 32) _unmask(buffer, mask);
|
|
103
|
+
else bufferUtil.unmask(buffer, mask);
|
|
104
|
+
};
|
|
105
|
+
} catch (e) {
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
// ../../node_modules/ws/lib/limiter.js
|
|
112
|
+
var require_limiter = __commonJS({
|
|
113
|
+
"../../node_modules/ws/lib/limiter.js"(exports, module) {
|
|
114
|
+
"use strict";
|
|
115
|
+
var kDone = /* @__PURE__ */ Symbol("kDone");
|
|
116
|
+
var kRun = /* @__PURE__ */ Symbol("kRun");
|
|
117
|
+
var Limiter = class {
|
|
118
|
+
/**
|
|
119
|
+
* Creates a new `Limiter`.
|
|
120
|
+
*
|
|
121
|
+
* @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
|
|
122
|
+
* to run concurrently
|
|
123
|
+
*/
|
|
124
|
+
constructor(concurrency) {
|
|
125
|
+
this[kDone] = () => {
|
|
126
|
+
this.pending--;
|
|
127
|
+
this[kRun]();
|
|
128
|
+
};
|
|
129
|
+
this.concurrency = concurrency || Infinity;
|
|
130
|
+
this.jobs = [];
|
|
131
|
+
this.pending = 0;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Adds a job to the queue.
|
|
135
|
+
*
|
|
136
|
+
* @param {Function} job The job to run
|
|
137
|
+
* @public
|
|
138
|
+
*/
|
|
139
|
+
add(job) {
|
|
140
|
+
this.jobs.push(job);
|
|
141
|
+
this[kRun]();
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Removes a job from the queue and runs it if possible.
|
|
145
|
+
*
|
|
146
|
+
* @private
|
|
147
|
+
*/
|
|
148
|
+
[kRun]() {
|
|
149
|
+
if (this.pending === this.concurrency) return;
|
|
150
|
+
if (this.jobs.length) {
|
|
151
|
+
const job = this.jobs.shift();
|
|
152
|
+
this.pending++;
|
|
153
|
+
job(this[kDone]);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
module.exports = Limiter;
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// ../../node_modules/ws/lib/permessage-deflate.js
|
|
162
|
+
var require_permessage_deflate = __commonJS({
|
|
163
|
+
"../../node_modules/ws/lib/permessage-deflate.js"(exports, module) {
|
|
164
|
+
"use strict";
|
|
165
|
+
var zlib = __require("zlib");
|
|
166
|
+
var bufferUtil = require_buffer_util();
|
|
167
|
+
var Limiter = require_limiter();
|
|
168
|
+
var { kStatusCode } = require_constants();
|
|
169
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
170
|
+
var TRAILER = Buffer.from([0, 0, 255, 255]);
|
|
171
|
+
var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
|
|
172
|
+
var kTotalLength = /* @__PURE__ */ Symbol("total-length");
|
|
173
|
+
var kCallback = /* @__PURE__ */ Symbol("callback");
|
|
174
|
+
var kBuffers = /* @__PURE__ */ Symbol("buffers");
|
|
175
|
+
var kError = /* @__PURE__ */ Symbol("error");
|
|
176
|
+
var zlibLimiter;
|
|
177
|
+
var PerMessageDeflate = class {
|
|
178
|
+
/**
|
|
179
|
+
* Creates a PerMessageDeflate instance.
|
|
180
|
+
*
|
|
181
|
+
* @param {Object} [options] Configuration options
|
|
182
|
+
* @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
|
|
183
|
+
* for, or request, a custom client window size
|
|
184
|
+
* @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
|
|
185
|
+
* acknowledge disabling of client context takeover
|
|
186
|
+
* @param {Number} [options.concurrencyLimit=10] The number of concurrent
|
|
187
|
+
* calls to zlib
|
|
188
|
+
* @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
|
|
189
|
+
* use of a custom server window size
|
|
190
|
+
* @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
|
|
191
|
+
* disabling of server context takeover
|
|
192
|
+
* @param {Number} [options.threshold=1024] Size (in bytes) below which
|
|
193
|
+
* messages should not be compressed if context takeover is disabled
|
|
194
|
+
* @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
|
|
195
|
+
* deflate
|
|
196
|
+
* @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
|
|
197
|
+
* inflate
|
|
198
|
+
* @param {Boolean} [isServer=false] Create the instance in either server or
|
|
199
|
+
* client mode
|
|
200
|
+
* @param {Number} [maxPayload=0] The maximum allowed message length
|
|
201
|
+
*/
|
|
202
|
+
constructor(options, isServer, maxPayload) {
|
|
203
|
+
this._maxPayload = maxPayload | 0;
|
|
204
|
+
this._options = options || {};
|
|
205
|
+
this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
|
|
206
|
+
this._isServer = !!isServer;
|
|
207
|
+
this._deflate = null;
|
|
208
|
+
this._inflate = null;
|
|
209
|
+
this.params = null;
|
|
210
|
+
if (!zlibLimiter) {
|
|
211
|
+
const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
|
|
212
|
+
zlibLimiter = new Limiter(concurrency);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* @type {String}
|
|
217
|
+
*/
|
|
218
|
+
static get extensionName() {
|
|
219
|
+
return "permessage-deflate";
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Create an extension negotiation offer.
|
|
223
|
+
*
|
|
224
|
+
* @return {Object} Extension parameters
|
|
225
|
+
* @public
|
|
226
|
+
*/
|
|
227
|
+
offer() {
|
|
228
|
+
const params = {};
|
|
229
|
+
if (this._options.serverNoContextTakeover) {
|
|
230
|
+
params.server_no_context_takeover = true;
|
|
231
|
+
}
|
|
232
|
+
if (this._options.clientNoContextTakeover) {
|
|
233
|
+
params.client_no_context_takeover = true;
|
|
234
|
+
}
|
|
235
|
+
if (this._options.serverMaxWindowBits) {
|
|
236
|
+
params.server_max_window_bits = this._options.serverMaxWindowBits;
|
|
237
|
+
}
|
|
238
|
+
if (this._options.clientMaxWindowBits) {
|
|
239
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
240
|
+
} else if (this._options.clientMaxWindowBits == null) {
|
|
241
|
+
params.client_max_window_bits = true;
|
|
242
|
+
}
|
|
243
|
+
return params;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Accept an extension negotiation offer/response.
|
|
247
|
+
*
|
|
248
|
+
* @param {Array} configurations The extension negotiation offers/reponse
|
|
249
|
+
* @return {Object} Accepted configuration
|
|
250
|
+
* @public
|
|
251
|
+
*/
|
|
252
|
+
accept(configurations) {
|
|
253
|
+
configurations = this.normalizeParams(configurations);
|
|
254
|
+
this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
|
|
255
|
+
return this.params;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Releases all resources used by the extension.
|
|
259
|
+
*
|
|
260
|
+
* @public
|
|
261
|
+
*/
|
|
262
|
+
cleanup() {
|
|
263
|
+
if (this._inflate) {
|
|
264
|
+
this._inflate.close();
|
|
265
|
+
this._inflate = null;
|
|
266
|
+
}
|
|
267
|
+
if (this._deflate) {
|
|
268
|
+
const callback = this._deflate[kCallback];
|
|
269
|
+
this._deflate.close();
|
|
270
|
+
this._deflate = null;
|
|
271
|
+
if (callback) {
|
|
272
|
+
callback(
|
|
273
|
+
new Error(
|
|
274
|
+
"The deflate stream was closed while data was being processed"
|
|
275
|
+
)
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Accept an extension negotiation offer.
|
|
282
|
+
*
|
|
283
|
+
* @param {Array} offers The extension negotiation offers
|
|
284
|
+
* @return {Object} Accepted configuration
|
|
285
|
+
* @private
|
|
286
|
+
*/
|
|
287
|
+
acceptAsServer(offers) {
|
|
288
|
+
const opts = this._options;
|
|
289
|
+
const accepted = offers.find((params) => {
|
|
290
|
+
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) {
|
|
291
|
+
return false;
|
|
292
|
+
}
|
|
293
|
+
return true;
|
|
294
|
+
});
|
|
295
|
+
if (!accepted) {
|
|
296
|
+
throw new Error("None of the extension offers can be accepted");
|
|
297
|
+
}
|
|
298
|
+
if (opts.serverNoContextTakeover) {
|
|
299
|
+
accepted.server_no_context_takeover = true;
|
|
300
|
+
}
|
|
301
|
+
if (opts.clientNoContextTakeover) {
|
|
302
|
+
accepted.client_no_context_takeover = true;
|
|
303
|
+
}
|
|
304
|
+
if (typeof opts.serverMaxWindowBits === "number") {
|
|
305
|
+
accepted.server_max_window_bits = opts.serverMaxWindowBits;
|
|
306
|
+
}
|
|
307
|
+
if (typeof opts.clientMaxWindowBits === "number") {
|
|
308
|
+
accepted.client_max_window_bits = opts.clientMaxWindowBits;
|
|
309
|
+
} else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
|
|
310
|
+
delete accepted.client_max_window_bits;
|
|
311
|
+
}
|
|
312
|
+
return accepted;
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Accept the extension negotiation response.
|
|
316
|
+
*
|
|
317
|
+
* @param {Array} response The extension negotiation response
|
|
318
|
+
* @return {Object} Accepted configuration
|
|
319
|
+
* @private
|
|
320
|
+
*/
|
|
321
|
+
acceptAsClient(response) {
|
|
322
|
+
const params = response[0];
|
|
323
|
+
if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
|
|
324
|
+
throw new Error('Unexpected parameter "client_no_context_takeover"');
|
|
325
|
+
}
|
|
326
|
+
if (!params.client_max_window_bits) {
|
|
327
|
+
if (typeof this._options.clientMaxWindowBits === "number") {
|
|
328
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
329
|
+
}
|
|
330
|
+
} else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
|
|
331
|
+
throw new Error(
|
|
332
|
+
'Unexpected or invalid parameter "client_max_window_bits"'
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
return params;
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Normalize parameters.
|
|
339
|
+
*
|
|
340
|
+
* @param {Array} configurations The extension negotiation offers/reponse
|
|
341
|
+
* @return {Array} The offers/response with normalized parameters
|
|
342
|
+
* @private
|
|
343
|
+
*/
|
|
344
|
+
normalizeParams(configurations) {
|
|
345
|
+
configurations.forEach((params) => {
|
|
346
|
+
Object.keys(params).forEach((key) => {
|
|
347
|
+
let value = params[key];
|
|
348
|
+
if (value.length > 1) {
|
|
349
|
+
throw new Error(`Parameter "${key}" must have only a single value`);
|
|
350
|
+
}
|
|
351
|
+
value = value[0];
|
|
352
|
+
if (key === "client_max_window_bits") {
|
|
353
|
+
if (value !== true) {
|
|
354
|
+
const num = +value;
|
|
355
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
356
|
+
throw new TypeError(
|
|
357
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
value = num;
|
|
361
|
+
} else if (!this._isServer) {
|
|
362
|
+
throw new TypeError(
|
|
363
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
} else if (key === "server_max_window_bits") {
|
|
367
|
+
const num = +value;
|
|
368
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
369
|
+
throw new TypeError(
|
|
370
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
value = num;
|
|
374
|
+
} else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
|
|
375
|
+
if (value !== true) {
|
|
376
|
+
throw new TypeError(
|
|
377
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
} else {
|
|
381
|
+
throw new Error(`Unknown parameter "${key}"`);
|
|
382
|
+
}
|
|
383
|
+
params[key] = value;
|
|
384
|
+
});
|
|
385
|
+
});
|
|
386
|
+
return configurations;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Decompress data. Concurrency limited.
|
|
390
|
+
*
|
|
391
|
+
* @param {Buffer} data Compressed data
|
|
392
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
393
|
+
* @param {Function} callback Callback
|
|
394
|
+
* @public
|
|
395
|
+
*/
|
|
396
|
+
decompress(data, fin, callback) {
|
|
397
|
+
zlibLimiter.add((done) => {
|
|
398
|
+
this._decompress(data, fin, (err, result) => {
|
|
399
|
+
done();
|
|
400
|
+
callback(err, result);
|
|
401
|
+
});
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Compress data. Concurrency limited.
|
|
406
|
+
*
|
|
407
|
+
* @param {(Buffer|String)} data Data to compress
|
|
408
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
409
|
+
* @param {Function} callback Callback
|
|
410
|
+
* @public
|
|
411
|
+
*/
|
|
412
|
+
compress(data, fin, callback) {
|
|
413
|
+
zlibLimiter.add((done) => {
|
|
414
|
+
this._compress(data, fin, (err, result) => {
|
|
415
|
+
done();
|
|
416
|
+
callback(err, result);
|
|
417
|
+
});
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Decompress data.
|
|
422
|
+
*
|
|
423
|
+
* @param {Buffer} data Compressed data
|
|
424
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
425
|
+
* @param {Function} callback Callback
|
|
426
|
+
* @private
|
|
427
|
+
*/
|
|
428
|
+
_decompress(data, fin, callback) {
|
|
429
|
+
const endpoint = this._isServer ? "client" : "server";
|
|
430
|
+
if (!this._inflate) {
|
|
431
|
+
const key = `${endpoint}_max_window_bits`;
|
|
432
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
433
|
+
this._inflate = zlib.createInflateRaw({
|
|
434
|
+
...this._options.zlibInflateOptions,
|
|
435
|
+
windowBits
|
|
436
|
+
});
|
|
437
|
+
this._inflate[kPerMessageDeflate] = this;
|
|
438
|
+
this._inflate[kTotalLength] = 0;
|
|
439
|
+
this._inflate[kBuffers] = [];
|
|
440
|
+
this._inflate.on("error", inflateOnError);
|
|
441
|
+
this._inflate.on("data", inflateOnData);
|
|
442
|
+
}
|
|
443
|
+
this._inflate[kCallback] = callback;
|
|
444
|
+
this._inflate.write(data);
|
|
445
|
+
if (fin) this._inflate.write(TRAILER);
|
|
446
|
+
this._inflate.flush(() => {
|
|
447
|
+
const err = this._inflate[kError];
|
|
448
|
+
if (err) {
|
|
449
|
+
this._inflate.close();
|
|
450
|
+
this._inflate = null;
|
|
451
|
+
callback(err);
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
const data2 = bufferUtil.concat(
|
|
455
|
+
this._inflate[kBuffers],
|
|
456
|
+
this._inflate[kTotalLength]
|
|
457
|
+
);
|
|
458
|
+
if (this._inflate._readableState.endEmitted) {
|
|
459
|
+
this._inflate.close();
|
|
460
|
+
this._inflate = null;
|
|
461
|
+
} else {
|
|
462
|
+
this._inflate[kTotalLength] = 0;
|
|
463
|
+
this._inflate[kBuffers] = [];
|
|
464
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
465
|
+
this._inflate.reset();
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
callback(null, data2);
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Compress data.
|
|
473
|
+
*
|
|
474
|
+
* @param {(Buffer|String)} data Data to compress
|
|
475
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
476
|
+
* @param {Function} callback Callback
|
|
477
|
+
* @private
|
|
478
|
+
*/
|
|
479
|
+
_compress(data, fin, callback) {
|
|
480
|
+
const endpoint = this._isServer ? "server" : "client";
|
|
481
|
+
if (!this._deflate) {
|
|
482
|
+
const key = `${endpoint}_max_window_bits`;
|
|
483
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
484
|
+
this._deflate = zlib.createDeflateRaw({
|
|
485
|
+
...this._options.zlibDeflateOptions,
|
|
486
|
+
windowBits
|
|
487
|
+
});
|
|
488
|
+
this._deflate[kTotalLength] = 0;
|
|
489
|
+
this._deflate[kBuffers] = [];
|
|
490
|
+
this._deflate.on("data", deflateOnData);
|
|
491
|
+
}
|
|
492
|
+
this._deflate[kCallback] = callback;
|
|
493
|
+
this._deflate.write(data);
|
|
494
|
+
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
|
|
495
|
+
if (!this._deflate) {
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
let data2 = bufferUtil.concat(
|
|
499
|
+
this._deflate[kBuffers],
|
|
500
|
+
this._deflate[kTotalLength]
|
|
501
|
+
);
|
|
502
|
+
if (fin) {
|
|
503
|
+
data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
|
|
504
|
+
}
|
|
505
|
+
this._deflate[kCallback] = null;
|
|
506
|
+
this._deflate[kTotalLength] = 0;
|
|
507
|
+
this._deflate[kBuffers] = [];
|
|
508
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
509
|
+
this._deflate.reset();
|
|
510
|
+
}
|
|
511
|
+
callback(null, data2);
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
module.exports = PerMessageDeflate;
|
|
516
|
+
function deflateOnData(chunk) {
|
|
517
|
+
this[kBuffers].push(chunk);
|
|
518
|
+
this[kTotalLength] += chunk.length;
|
|
519
|
+
}
|
|
520
|
+
function inflateOnData(chunk) {
|
|
521
|
+
this[kTotalLength] += chunk.length;
|
|
522
|
+
if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
|
|
523
|
+
this[kBuffers].push(chunk);
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
this[kError] = new RangeError("Max payload size exceeded");
|
|
527
|
+
this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
|
|
528
|
+
this[kError][kStatusCode] = 1009;
|
|
529
|
+
this.removeListener("data", inflateOnData);
|
|
530
|
+
this.reset();
|
|
531
|
+
}
|
|
532
|
+
function inflateOnError(err) {
|
|
533
|
+
this[kPerMessageDeflate]._inflate = null;
|
|
534
|
+
if (this[kError]) {
|
|
535
|
+
this[kCallback](this[kError]);
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
err[kStatusCode] = 1007;
|
|
539
|
+
this[kCallback](err);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
});
|
|
543
|
+
|
|
544
|
+
// ../../node_modules/ws/lib/validation.js
|
|
545
|
+
var require_validation = __commonJS({
|
|
546
|
+
"../../node_modules/ws/lib/validation.js"(exports, module) {
|
|
547
|
+
"use strict";
|
|
548
|
+
var { isUtf8 } = __require("buffer");
|
|
549
|
+
var { hasBlob } = require_constants();
|
|
550
|
+
var tokenChars = [
|
|
551
|
+
0,
|
|
552
|
+
0,
|
|
553
|
+
0,
|
|
554
|
+
0,
|
|
555
|
+
0,
|
|
556
|
+
0,
|
|
557
|
+
0,
|
|
558
|
+
0,
|
|
559
|
+
0,
|
|
560
|
+
0,
|
|
561
|
+
0,
|
|
562
|
+
0,
|
|
563
|
+
0,
|
|
564
|
+
0,
|
|
565
|
+
0,
|
|
566
|
+
0,
|
|
567
|
+
// 0 - 15
|
|
568
|
+
0,
|
|
569
|
+
0,
|
|
570
|
+
0,
|
|
571
|
+
0,
|
|
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
|
+
// 16 - 31
|
|
585
|
+
0,
|
|
586
|
+
1,
|
|
587
|
+
0,
|
|
588
|
+
1,
|
|
589
|
+
1,
|
|
590
|
+
1,
|
|
591
|
+
1,
|
|
592
|
+
1,
|
|
593
|
+
0,
|
|
594
|
+
0,
|
|
595
|
+
1,
|
|
596
|
+
1,
|
|
597
|
+
0,
|
|
598
|
+
1,
|
|
599
|
+
1,
|
|
600
|
+
0,
|
|
601
|
+
// 32 - 47
|
|
602
|
+
1,
|
|
603
|
+
1,
|
|
604
|
+
1,
|
|
605
|
+
1,
|
|
606
|
+
1,
|
|
607
|
+
1,
|
|
608
|
+
1,
|
|
609
|
+
1,
|
|
610
|
+
1,
|
|
611
|
+
1,
|
|
612
|
+
0,
|
|
613
|
+
0,
|
|
614
|
+
0,
|
|
615
|
+
0,
|
|
616
|
+
0,
|
|
617
|
+
0,
|
|
618
|
+
// 48 - 63
|
|
619
|
+
0,
|
|
620
|
+
1,
|
|
621
|
+
1,
|
|
622
|
+
1,
|
|
623
|
+
1,
|
|
624
|
+
1,
|
|
625
|
+
1,
|
|
626
|
+
1,
|
|
627
|
+
1,
|
|
628
|
+
1,
|
|
629
|
+
1,
|
|
630
|
+
1,
|
|
631
|
+
1,
|
|
632
|
+
1,
|
|
633
|
+
1,
|
|
634
|
+
1,
|
|
635
|
+
// 64 - 79
|
|
636
|
+
1,
|
|
637
|
+
1,
|
|
638
|
+
1,
|
|
639
|
+
1,
|
|
640
|
+
1,
|
|
641
|
+
1,
|
|
642
|
+
1,
|
|
643
|
+
1,
|
|
644
|
+
1,
|
|
645
|
+
1,
|
|
646
|
+
1,
|
|
647
|
+
0,
|
|
648
|
+
0,
|
|
649
|
+
0,
|
|
650
|
+
1,
|
|
651
|
+
1,
|
|
652
|
+
// 80 - 95
|
|
653
|
+
1,
|
|
654
|
+
1,
|
|
655
|
+
1,
|
|
656
|
+
1,
|
|
657
|
+
1,
|
|
658
|
+
1,
|
|
659
|
+
1,
|
|
660
|
+
1,
|
|
661
|
+
1,
|
|
662
|
+
1,
|
|
663
|
+
1,
|
|
664
|
+
1,
|
|
665
|
+
1,
|
|
666
|
+
1,
|
|
667
|
+
1,
|
|
668
|
+
1,
|
|
669
|
+
// 96 - 111
|
|
670
|
+
1,
|
|
671
|
+
1,
|
|
672
|
+
1,
|
|
673
|
+
1,
|
|
674
|
+
1,
|
|
675
|
+
1,
|
|
676
|
+
1,
|
|
677
|
+
1,
|
|
678
|
+
1,
|
|
679
|
+
1,
|
|
680
|
+
1,
|
|
681
|
+
0,
|
|
682
|
+
1,
|
|
683
|
+
0,
|
|
684
|
+
1,
|
|
685
|
+
0
|
|
686
|
+
// 112 - 127
|
|
687
|
+
];
|
|
688
|
+
function isValidStatusCode(code) {
|
|
689
|
+
return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
|
|
690
|
+
}
|
|
691
|
+
function _isValidUTF8(buf) {
|
|
692
|
+
const len = buf.length;
|
|
693
|
+
let i = 0;
|
|
694
|
+
while (i < len) {
|
|
695
|
+
if ((buf[i] & 128) === 0) {
|
|
696
|
+
i++;
|
|
697
|
+
} else if ((buf[i] & 224) === 192) {
|
|
698
|
+
if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
|
|
699
|
+
return false;
|
|
700
|
+
}
|
|
701
|
+
i += 2;
|
|
702
|
+
} else if ((buf[i] & 240) === 224) {
|
|
703
|
+
if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
|
|
704
|
+
buf[i] === 237 && (buf[i + 1] & 224) === 160) {
|
|
705
|
+
return false;
|
|
706
|
+
}
|
|
707
|
+
i += 3;
|
|
708
|
+
} else if ((buf[i] & 248) === 240) {
|
|
709
|
+
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
|
|
710
|
+
buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
|
|
711
|
+
return false;
|
|
712
|
+
}
|
|
713
|
+
i += 4;
|
|
714
|
+
} else {
|
|
715
|
+
return false;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
return true;
|
|
719
|
+
}
|
|
720
|
+
function isBlob(value) {
|
|
721
|
+
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");
|
|
722
|
+
}
|
|
723
|
+
module.exports = {
|
|
724
|
+
isBlob,
|
|
725
|
+
isValidStatusCode,
|
|
726
|
+
isValidUTF8: _isValidUTF8,
|
|
727
|
+
tokenChars
|
|
728
|
+
};
|
|
729
|
+
if (isUtf8) {
|
|
730
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
731
|
+
return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
|
|
732
|
+
};
|
|
733
|
+
} else if (!process.env.WS_NO_UTF_8_VALIDATE) {
|
|
734
|
+
try {
|
|
735
|
+
const isValidUTF8 = __require("utf-8-validate");
|
|
736
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
737
|
+
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
|
|
738
|
+
};
|
|
739
|
+
} catch (e) {
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
// ../../node_modules/ws/lib/receiver.js
|
|
746
|
+
var require_receiver = __commonJS({
|
|
747
|
+
"../../node_modules/ws/lib/receiver.js"(exports, module) {
|
|
748
|
+
"use strict";
|
|
749
|
+
var { Writable } = __require("stream");
|
|
750
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
751
|
+
var {
|
|
752
|
+
BINARY_TYPES,
|
|
753
|
+
EMPTY_BUFFER,
|
|
754
|
+
kStatusCode,
|
|
755
|
+
kWebSocket
|
|
756
|
+
} = require_constants();
|
|
757
|
+
var { concat, toArrayBuffer, unmask } = require_buffer_util();
|
|
758
|
+
var { isValidStatusCode, isValidUTF8 } = require_validation();
|
|
759
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
760
|
+
var GET_INFO = 0;
|
|
761
|
+
var GET_PAYLOAD_LENGTH_16 = 1;
|
|
762
|
+
var GET_PAYLOAD_LENGTH_64 = 2;
|
|
763
|
+
var GET_MASK = 3;
|
|
764
|
+
var GET_DATA = 4;
|
|
765
|
+
var INFLATING = 5;
|
|
766
|
+
var DEFER_EVENT = 6;
|
|
767
|
+
var Receiver2 = class extends Writable {
|
|
768
|
+
/**
|
|
769
|
+
* Creates a Receiver instance.
|
|
770
|
+
*
|
|
771
|
+
* @param {Object} [options] Options object
|
|
772
|
+
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
|
|
773
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
774
|
+
* multiple times in the same tick
|
|
775
|
+
* @param {String} [options.binaryType=nodebuffer] The type for binary data
|
|
776
|
+
* @param {Object} [options.extensions] An object containing the negotiated
|
|
777
|
+
* extensions
|
|
778
|
+
* @param {Boolean} [options.isServer=false] Specifies whether to operate in
|
|
779
|
+
* client or server mode
|
|
780
|
+
* @param {Number} [options.maxPayload=0] The maximum allowed message length
|
|
781
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
782
|
+
* not to skip UTF-8 validation for text and close messages
|
|
783
|
+
*/
|
|
784
|
+
constructor(options = {}) {
|
|
785
|
+
super();
|
|
786
|
+
this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
|
|
787
|
+
this._binaryType = options.binaryType || BINARY_TYPES[0];
|
|
788
|
+
this._extensions = options.extensions || {};
|
|
789
|
+
this._isServer = !!options.isServer;
|
|
790
|
+
this._maxPayload = options.maxPayload | 0;
|
|
791
|
+
this._skipUTF8Validation = !!options.skipUTF8Validation;
|
|
792
|
+
this[kWebSocket] = void 0;
|
|
793
|
+
this._bufferedBytes = 0;
|
|
794
|
+
this._buffers = [];
|
|
795
|
+
this._compressed = false;
|
|
796
|
+
this._payloadLength = 0;
|
|
797
|
+
this._mask = void 0;
|
|
798
|
+
this._fragmented = 0;
|
|
799
|
+
this._masked = false;
|
|
800
|
+
this._fin = false;
|
|
801
|
+
this._opcode = 0;
|
|
802
|
+
this._totalPayloadLength = 0;
|
|
803
|
+
this._messageLength = 0;
|
|
804
|
+
this._fragments = [];
|
|
805
|
+
this._errored = false;
|
|
806
|
+
this._loop = false;
|
|
807
|
+
this._state = GET_INFO;
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Implements `Writable.prototype._write()`.
|
|
811
|
+
*
|
|
812
|
+
* @param {Buffer} chunk The chunk of data to write
|
|
813
|
+
* @param {String} encoding The character encoding of `chunk`
|
|
814
|
+
* @param {Function} cb Callback
|
|
815
|
+
* @private
|
|
816
|
+
*/
|
|
817
|
+
_write(chunk, encoding, cb) {
|
|
818
|
+
if (this._opcode === 8 && this._state == GET_INFO) return cb();
|
|
819
|
+
this._bufferedBytes += chunk.length;
|
|
820
|
+
this._buffers.push(chunk);
|
|
821
|
+
this.startLoop(cb);
|
|
822
|
+
}
|
|
823
|
+
/**
|
|
824
|
+
* Consumes `n` bytes from the buffered data.
|
|
825
|
+
*
|
|
826
|
+
* @param {Number} n The number of bytes to consume
|
|
827
|
+
* @return {Buffer} The consumed bytes
|
|
828
|
+
* @private
|
|
829
|
+
*/
|
|
830
|
+
consume(n) {
|
|
831
|
+
this._bufferedBytes -= n;
|
|
832
|
+
if (n === this._buffers[0].length) return this._buffers.shift();
|
|
833
|
+
if (n < this._buffers[0].length) {
|
|
834
|
+
const buf = this._buffers[0];
|
|
835
|
+
this._buffers[0] = new FastBuffer(
|
|
836
|
+
buf.buffer,
|
|
837
|
+
buf.byteOffset + n,
|
|
838
|
+
buf.length - n
|
|
839
|
+
);
|
|
840
|
+
return new FastBuffer(buf.buffer, buf.byteOffset, n);
|
|
841
|
+
}
|
|
842
|
+
const dst = Buffer.allocUnsafe(n);
|
|
843
|
+
do {
|
|
844
|
+
const buf = this._buffers[0];
|
|
845
|
+
const offset = dst.length - n;
|
|
846
|
+
if (n >= buf.length) {
|
|
847
|
+
dst.set(this._buffers.shift(), offset);
|
|
848
|
+
} else {
|
|
849
|
+
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
|
|
850
|
+
this._buffers[0] = new FastBuffer(
|
|
851
|
+
buf.buffer,
|
|
852
|
+
buf.byteOffset + n,
|
|
853
|
+
buf.length - n
|
|
854
|
+
);
|
|
855
|
+
}
|
|
856
|
+
n -= buf.length;
|
|
857
|
+
} while (n > 0);
|
|
858
|
+
return dst;
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Starts the parsing loop.
|
|
862
|
+
*
|
|
863
|
+
* @param {Function} cb Callback
|
|
864
|
+
* @private
|
|
865
|
+
*/
|
|
866
|
+
startLoop(cb) {
|
|
867
|
+
this._loop = true;
|
|
868
|
+
do {
|
|
869
|
+
switch (this._state) {
|
|
870
|
+
case GET_INFO:
|
|
871
|
+
this.getInfo(cb);
|
|
872
|
+
break;
|
|
873
|
+
case GET_PAYLOAD_LENGTH_16:
|
|
874
|
+
this.getPayloadLength16(cb);
|
|
875
|
+
break;
|
|
876
|
+
case GET_PAYLOAD_LENGTH_64:
|
|
877
|
+
this.getPayloadLength64(cb);
|
|
878
|
+
break;
|
|
879
|
+
case GET_MASK:
|
|
880
|
+
this.getMask();
|
|
881
|
+
break;
|
|
882
|
+
case GET_DATA:
|
|
883
|
+
this.getData(cb);
|
|
884
|
+
break;
|
|
885
|
+
case INFLATING:
|
|
886
|
+
case DEFER_EVENT:
|
|
887
|
+
this._loop = false;
|
|
888
|
+
return;
|
|
889
|
+
}
|
|
890
|
+
} while (this._loop);
|
|
891
|
+
if (!this._errored) cb();
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Reads the first two bytes of a frame.
|
|
895
|
+
*
|
|
896
|
+
* @param {Function} cb Callback
|
|
897
|
+
* @private
|
|
898
|
+
*/
|
|
899
|
+
getInfo(cb) {
|
|
900
|
+
if (this._bufferedBytes < 2) {
|
|
901
|
+
this._loop = false;
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
const buf = this.consume(2);
|
|
905
|
+
if ((buf[0] & 48) !== 0) {
|
|
906
|
+
const error = this.createError(
|
|
907
|
+
RangeError,
|
|
908
|
+
"RSV2 and RSV3 must be clear",
|
|
909
|
+
true,
|
|
910
|
+
1002,
|
|
911
|
+
"WS_ERR_UNEXPECTED_RSV_2_3"
|
|
912
|
+
);
|
|
913
|
+
cb(error);
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
const compressed = (buf[0] & 64) === 64;
|
|
917
|
+
if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
|
|
918
|
+
const error = this.createError(
|
|
919
|
+
RangeError,
|
|
920
|
+
"RSV1 must be clear",
|
|
921
|
+
true,
|
|
922
|
+
1002,
|
|
923
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
924
|
+
);
|
|
925
|
+
cb(error);
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
this._fin = (buf[0] & 128) === 128;
|
|
929
|
+
this._opcode = buf[0] & 15;
|
|
930
|
+
this._payloadLength = buf[1] & 127;
|
|
931
|
+
if (this._opcode === 0) {
|
|
932
|
+
if (compressed) {
|
|
933
|
+
const error = this.createError(
|
|
934
|
+
RangeError,
|
|
935
|
+
"RSV1 must be clear",
|
|
936
|
+
true,
|
|
937
|
+
1002,
|
|
938
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
939
|
+
);
|
|
940
|
+
cb(error);
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
if (!this._fragmented) {
|
|
944
|
+
const error = this.createError(
|
|
945
|
+
RangeError,
|
|
946
|
+
"invalid opcode 0",
|
|
947
|
+
true,
|
|
948
|
+
1002,
|
|
949
|
+
"WS_ERR_INVALID_OPCODE"
|
|
950
|
+
);
|
|
951
|
+
cb(error);
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
this._opcode = this._fragmented;
|
|
955
|
+
} else if (this._opcode === 1 || this._opcode === 2) {
|
|
956
|
+
if (this._fragmented) {
|
|
957
|
+
const error = this.createError(
|
|
958
|
+
RangeError,
|
|
959
|
+
`invalid opcode ${this._opcode}`,
|
|
960
|
+
true,
|
|
961
|
+
1002,
|
|
962
|
+
"WS_ERR_INVALID_OPCODE"
|
|
963
|
+
);
|
|
964
|
+
cb(error);
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
this._compressed = compressed;
|
|
968
|
+
} else if (this._opcode > 7 && this._opcode < 11) {
|
|
969
|
+
if (!this._fin) {
|
|
970
|
+
const error = this.createError(
|
|
971
|
+
RangeError,
|
|
972
|
+
"FIN must be set",
|
|
973
|
+
true,
|
|
974
|
+
1002,
|
|
975
|
+
"WS_ERR_EXPECTED_FIN"
|
|
976
|
+
);
|
|
977
|
+
cb(error);
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
if (compressed) {
|
|
981
|
+
const error = this.createError(
|
|
982
|
+
RangeError,
|
|
983
|
+
"RSV1 must be clear",
|
|
984
|
+
true,
|
|
985
|
+
1002,
|
|
986
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
987
|
+
);
|
|
988
|
+
cb(error);
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
|
|
992
|
+
const error = this.createError(
|
|
993
|
+
RangeError,
|
|
994
|
+
`invalid payload length ${this._payloadLength}`,
|
|
995
|
+
true,
|
|
996
|
+
1002,
|
|
997
|
+
"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
|
|
998
|
+
);
|
|
999
|
+
cb(error);
|
|
1000
|
+
return;
|
|
1001
|
+
}
|
|
1002
|
+
} else {
|
|
1003
|
+
const error = this.createError(
|
|
1004
|
+
RangeError,
|
|
1005
|
+
`invalid opcode ${this._opcode}`,
|
|
1006
|
+
true,
|
|
1007
|
+
1002,
|
|
1008
|
+
"WS_ERR_INVALID_OPCODE"
|
|
1009
|
+
);
|
|
1010
|
+
cb(error);
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
|
|
1014
|
+
this._masked = (buf[1] & 128) === 128;
|
|
1015
|
+
if (this._isServer) {
|
|
1016
|
+
if (!this._masked) {
|
|
1017
|
+
const error = this.createError(
|
|
1018
|
+
RangeError,
|
|
1019
|
+
"MASK must be set",
|
|
1020
|
+
true,
|
|
1021
|
+
1002,
|
|
1022
|
+
"WS_ERR_EXPECTED_MASK"
|
|
1023
|
+
);
|
|
1024
|
+
cb(error);
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
} else if (this._masked) {
|
|
1028
|
+
const error = this.createError(
|
|
1029
|
+
RangeError,
|
|
1030
|
+
"MASK must be clear",
|
|
1031
|
+
true,
|
|
1032
|
+
1002,
|
|
1033
|
+
"WS_ERR_UNEXPECTED_MASK"
|
|
1034
|
+
);
|
|
1035
|
+
cb(error);
|
|
1036
|
+
return;
|
|
1037
|
+
}
|
|
1038
|
+
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
|
|
1039
|
+
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
|
|
1040
|
+
else this.haveLength(cb);
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Gets extended payload length (7+16).
|
|
1044
|
+
*
|
|
1045
|
+
* @param {Function} cb Callback
|
|
1046
|
+
* @private
|
|
1047
|
+
*/
|
|
1048
|
+
getPayloadLength16(cb) {
|
|
1049
|
+
if (this._bufferedBytes < 2) {
|
|
1050
|
+
this._loop = false;
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
this._payloadLength = this.consume(2).readUInt16BE(0);
|
|
1054
|
+
this.haveLength(cb);
|
|
1055
|
+
}
|
|
1056
|
+
/**
|
|
1057
|
+
* Gets extended payload length (7+64).
|
|
1058
|
+
*
|
|
1059
|
+
* @param {Function} cb Callback
|
|
1060
|
+
* @private
|
|
1061
|
+
*/
|
|
1062
|
+
getPayloadLength64(cb) {
|
|
1063
|
+
if (this._bufferedBytes < 8) {
|
|
1064
|
+
this._loop = false;
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
const buf = this.consume(8);
|
|
1068
|
+
const num = buf.readUInt32BE(0);
|
|
1069
|
+
if (num > Math.pow(2, 53 - 32) - 1) {
|
|
1070
|
+
const error = this.createError(
|
|
1071
|
+
RangeError,
|
|
1072
|
+
"Unsupported WebSocket frame: payload length > 2^53 - 1",
|
|
1073
|
+
false,
|
|
1074
|
+
1009,
|
|
1075
|
+
"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
|
|
1076
|
+
);
|
|
1077
|
+
cb(error);
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
|
|
1081
|
+
this.haveLength(cb);
|
|
1082
|
+
}
|
|
1083
|
+
/**
|
|
1084
|
+
* Payload length has been read.
|
|
1085
|
+
*
|
|
1086
|
+
* @param {Function} cb Callback
|
|
1087
|
+
* @private
|
|
1088
|
+
*/
|
|
1089
|
+
haveLength(cb) {
|
|
1090
|
+
if (this._payloadLength && this._opcode < 8) {
|
|
1091
|
+
this._totalPayloadLength += this._payloadLength;
|
|
1092
|
+
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
|
|
1093
|
+
const error = this.createError(
|
|
1094
|
+
RangeError,
|
|
1095
|
+
"Max payload size exceeded",
|
|
1096
|
+
false,
|
|
1097
|
+
1009,
|
|
1098
|
+
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
|
|
1099
|
+
);
|
|
1100
|
+
cb(error);
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
if (this._masked) this._state = GET_MASK;
|
|
1105
|
+
else this._state = GET_DATA;
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* Reads mask bytes.
|
|
1109
|
+
*
|
|
1110
|
+
* @private
|
|
1111
|
+
*/
|
|
1112
|
+
getMask() {
|
|
1113
|
+
if (this._bufferedBytes < 4) {
|
|
1114
|
+
this._loop = false;
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
this._mask = this.consume(4);
|
|
1118
|
+
this._state = GET_DATA;
|
|
1119
|
+
}
|
|
1120
|
+
/**
|
|
1121
|
+
* Reads data bytes.
|
|
1122
|
+
*
|
|
1123
|
+
* @param {Function} cb Callback
|
|
1124
|
+
* @private
|
|
1125
|
+
*/
|
|
1126
|
+
getData(cb) {
|
|
1127
|
+
let data = EMPTY_BUFFER;
|
|
1128
|
+
if (this._payloadLength) {
|
|
1129
|
+
if (this._bufferedBytes < this._payloadLength) {
|
|
1130
|
+
this._loop = false;
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
data = this.consume(this._payloadLength);
|
|
1134
|
+
if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
|
|
1135
|
+
unmask(data, this._mask);
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
if (this._opcode > 7) {
|
|
1139
|
+
this.controlMessage(data, cb);
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
if (this._compressed) {
|
|
1143
|
+
this._state = INFLATING;
|
|
1144
|
+
this.decompress(data, cb);
|
|
1145
|
+
return;
|
|
1146
|
+
}
|
|
1147
|
+
if (data.length) {
|
|
1148
|
+
this._messageLength = this._totalPayloadLength;
|
|
1149
|
+
this._fragments.push(data);
|
|
1150
|
+
}
|
|
1151
|
+
this.dataMessage(cb);
|
|
1152
|
+
}
|
|
1153
|
+
/**
|
|
1154
|
+
* Decompresses data.
|
|
1155
|
+
*
|
|
1156
|
+
* @param {Buffer} data Compressed data
|
|
1157
|
+
* @param {Function} cb Callback
|
|
1158
|
+
* @private
|
|
1159
|
+
*/
|
|
1160
|
+
decompress(data, cb) {
|
|
1161
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
1162
|
+
perMessageDeflate.decompress(data, this._fin, (err, buf) => {
|
|
1163
|
+
if (err) return cb(err);
|
|
1164
|
+
if (buf.length) {
|
|
1165
|
+
this._messageLength += buf.length;
|
|
1166
|
+
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
|
|
1167
|
+
const error = this.createError(
|
|
1168
|
+
RangeError,
|
|
1169
|
+
"Max payload size exceeded",
|
|
1170
|
+
false,
|
|
1171
|
+
1009,
|
|
1172
|
+
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
|
|
1173
|
+
);
|
|
1174
|
+
cb(error);
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
this._fragments.push(buf);
|
|
1178
|
+
}
|
|
1179
|
+
this.dataMessage(cb);
|
|
1180
|
+
if (this._state === GET_INFO) this.startLoop(cb);
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
/**
|
|
1184
|
+
* Handles a data message.
|
|
1185
|
+
*
|
|
1186
|
+
* @param {Function} cb Callback
|
|
1187
|
+
* @private
|
|
1188
|
+
*/
|
|
1189
|
+
dataMessage(cb) {
|
|
1190
|
+
if (!this._fin) {
|
|
1191
|
+
this._state = GET_INFO;
|
|
1192
|
+
return;
|
|
1193
|
+
}
|
|
1194
|
+
const messageLength = this._messageLength;
|
|
1195
|
+
const fragments = this._fragments;
|
|
1196
|
+
this._totalPayloadLength = 0;
|
|
1197
|
+
this._messageLength = 0;
|
|
1198
|
+
this._fragmented = 0;
|
|
1199
|
+
this._fragments = [];
|
|
1200
|
+
if (this._opcode === 2) {
|
|
1201
|
+
let data;
|
|
1202
|
+
if (this._binaryType === "nodebuffer") {
|
|
1203
|
+
data = concat(fragments, messageLength);
|
|
1204
|
+
} else if (this._binaryType === "arraybuffer") {
|
|
1205
|
+
data = toArrayBuffer(concat(fragments, messageLength));
|
|
1206
|
+
} else if (this._binaryType === "blob") {
|
|
1207
|
+
data = new Blob(fragments);
|
|
1208
|
+
} else {
|
|
1209
|
+
data = fragments;
|
|
1210
|
+
}
|
|
1211
|
+
if (this._allowSynchronousEvents) {
|
|
1212
|
+
this.emit("message", data, true);
|
|
1213
|
+
this._state = GET_INFO;
|
|
1214
|
+
} else {
|
|
1215
|
+
this._state = DEFER_EVENT;
|
|
1216
|
+
setImmediate(() => {
|
|
1217
|
+
this.emit("message", data, true);
|
|
1218
|
+
this._state = GET_INFO;
|
|
1219
|
+
this.startLoop(cb);
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
} else {
|
|
1223
|
+
const buf = concat(fragments, messageLength);
|
|
1224
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
1225
|
+
const error = this.createError(
|
|
1226
|
+
Error,
|
|
1227
|
+
"invalid UTF-8 sequence",
|
|
1228
|
+
true,
|
|
1229
|
+
1007,
|
|
1230
|
+
"WS_ERR_INVALID_UTF8"
|
|
1231
|
+
);
|
|
1232
|
+
cb(error);
|
|
1233
|
+
return;
|
|
1234
|
+
}
|
|
1235
|
+
if (this._state === INFLATING || this._allowSynchronousEvents) {
|
|
1236
|
+
this.emit("message", buf, false);
|
|
1237
|
+
this._state = GET_INFO;
|
|
1238
|
+
} else {
|
|
1239
|
+
this._state = DEFER_EVENT;
|
|
1240
|
+
setImmediate(() => {
|
|
1241
|
+
this.emit("message", buf, false);
|
|
1242
|
+
this._state = GET_INFO;
|
|
1243
|
+
this.startLoop(cb);
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Handles a control message.
|
|
1250
|
+
*
|
|
1251
|
+
* @param {Buffer} data Data to handle
|
|
1252
|
+
* @return {(Error|RangeError|undefined)} A possible error
|
|
1253
|
+
* @private
|
|
1254
|
+
*/
|
|
1255
|
+
controlMessage(data, cb) {
|
|
1256
|
+
if (this._opcode === 8) {
|
|
1257
|
+
if (data.length === 0) {
|
|
1258
|
+
this._loop = false;
|
|
1259
|
+
this.emit("conclude", 1005, EMPTY_BUFFER);
|
|
1260
|
+
this.end();
|
|
1261
|
+
} else {
|
|
1262
|
+
const code = data.readUInt16BE(0);
|
|
1263
|
+
if (!isValidStatusCode(code)) {
|
|
1264
|
+
const error = this.createError(
|
|
1265
|
+
RangeError,
|
|
1266
|
+
`invalid status code ${code}`,
|
|
1267
|
+
true,
|
|
1268
|
+
1002,
|
|
1269
|
+
"WS_ERR_INVALID_CLOSE_CODE"
|
|
1270
|
+
);
|
|
1271
|
+
cb(error);
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
const buf = new FastBuffer(
|
|
1275
|
+
data.buffer,
|
|
1276
|
+
data.byteOffset + 2,
|
|
1277
|
+
data.length - 2
|
|
1278
|
+
);
|
|
1279
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
1280
|
+
const error = this.createError(
|
|
1281
|
+
Error,
|
|
1282
|
+
"invalid UTF-8 sequence",
|
|
1283
|
+
true,
|
|
1284
|
+
1007,
|
|
1285
|
+
"WS_ERR_INVALID_UTF8"
|
|
1286
|
+
);
|
|
1287
|
+
cb(error);
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
this._loop = false;
|
|
1291
|
+
this.emit("conclude", code, buf);
|
|
1292
|
+
this.end();
|
|
1293
|
+
}
|
|
1294
|
+
this._state = GET_INFO;
|
|
1295
|
+
return;
|
|
1296
|
+
}
|
|
1297
|
+
if (this._allowSynchronousEvents) {
|
|
1298
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
1299
|
+
this._state = GET_INFO;
|
|
1300
|
+
} else {
|
|
1301
|
+
this._state = DEFER_EVENT;
|
|
1302
|
+
setImmediate(() => {
|
|
1303
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
1304
|
+
this._state = GET_INFO;
|
|
1305
|
+
this.startLoop(cb);
|
|
1306
|
+
});
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* Builds an error object.
|
|
1311
|
+
*
|
|
1312
|
+
* @param {function(new:Error|RangeError)} ErrorCtor The error constructor
|
|
1313
|
+
* @param {String} message The error message
|
|
1314
|
+
* @param {Boolean} prefix Specifies whether or not to add a default prefix to
|
|
1315
|
+
* `message`
|
|
1316
|
+
* @param {Number} statusCode The status code
|
|
1317
|
+
* @param {String} errorCode The exposed error code
|
|
1318
|
+
* @return {(Error|RangeError)} The error
|
|
1319
|
+
* @private
|
|
1320
|
+
*/
|
|
1321
|
+
createError(ErrorCtor, message, prefix, statusCode, errorCode) {
|
|
1322
|
+
this._loop = false;
|
|
1323
|
+
this._errored = true;
|
|
1324
|
+
const err = new ErrorCtor(
|
|
1325
|
+
prefix ? `Invalid WebSocket frame: ${message}` : message
|
|
1326
|
+
);
|
|
1327
|
+
Error.captureStackTrace(err, this.createError);
|
|
1328
|
+
err.code = errorCode;
|
|
1329
|
+
err[kStatusCode] = statusCode;
|
|
1330
|
+
return err;
|
|
1331
|
+
}
|
|
1332
|
+
};
|
|
1333
|
+
module.exports = Receiver2;
|
|
1334
|
+
}
|
|
1335
|
+
});
|
|
1336
|
+
|
|
1337
|
+
// ../../node_modules/ws/lib/sender.js
|
|
1338
|
+
var require_sender = __commonJS({
|
|
1339
|
+
"../../node_modules/ws/lib/sender.js"(exports, module) {
|
|
1340
|
+
"use strict";
|
|
1341
|
+
var { Duplex } = __require("stream");
|
|
1342
|
+
var { randomFillSync } = __require("crypto");
|
|
1343
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
1344
|
+
var { EMPTY_BUFFER, kWebSocket, NOOP: NOOP2 } = require_constants();
|
|
1345
|
+
var { isBlob, isValidStatusCode } = require_validation();
|
|
1346
|
+
var { mask: applyMask, toBuffer } = require_buffer_util();
|
|
1347
|
+
var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
|
|
1348
|
+
var maskBuffer = Buffer.alloc(4);
|
|
1349
|
+
var RANDOM_POOL_SIZE = 8 * 1024;
|
|
1350
|
+
var randomPool;
|
|
1351
|
+
var randomPoolPointer = RANDOM_POOL_SIZE;
|
|
1352
|
+
var DEFAULT = 0;
|
|
1353
|
+
var DEFLATING = 1;
|
|
1354
|
+
var GET_BLOB_DATA = 2;
|
|
1355
|
+
var Sender2 = class _Sender {
|
|
1356
|
+
/**
|
|
1357
|
+
* Creates a Sender instance.
|
|
1358
|
+
*
|
|
1359
|
+
* @param {Duplex} socket The connection socket
|
|
1360
|
+
* @param {Object} [extensions] An object containing the negotiated extensions
|
|
1361
|
+
* @param {Function} [generateMask] The function used to generate the masking
|
|
1362
|
+
* key
|
|
1363
|
+
*/
|
|
1364
|
+
constructor(socket, extensions, generateMask) {
|
|
1365
|
+
this._extensions = extensions || {};
|
|
1366
|
+
if (generateMask) {
|
|
1367
|
+
this._generateMask = generateMask;
|
|
1368
|
+
this._maskBuffer = Buffer.alloc(4);
|
|
1369
|
+
}
|
|
1370
|
+
this._socket = socket;
|
|
1371
|
+
this._firstFragment = true;
|
|
1372
|
+
this._compress = false;
|
|
1373
|
+
this._bufferedBytes = 0;
|
|
1374
|
+
this._queue = [];
|
|
1375
|
+
this._state = DEFAULT;
|
|
1376
|
+
this.onerror = NOOP2;
|
|
1377
|
+
this[kWebSocket] = void 0;
|
|
1378
|
+
}
|
|
1379
|
+
/**
|
|
1380
|
+
* Frames a piece of data according to the HyBi WebSocket protocol.
|
|
1381
|
+
*
|
|
1382
|
+
* @param {(Buffer|String)} data The data to frame
|
|
1383
|
+
* @param {Object} options Options object
|
|
1384
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
1385
|
+
* FIN bit
|
|
1386
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
1387
|
+
* masking key
|
|
1388
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1389
|
+
* `data`
|
|
1390
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
1391
|
+
* key
|
|
1392
|
+
* @param {Number} options.opcode The opcode
|
|
1393
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
1394
|
+
* modified
|
|
1395
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
1396
|
+
* RSV1 bit
|
|
1397
|
+
* @return {(Buffer|String)[]} The framed data
|
|
1398
|
+
* @public
|
|
1399
|
+
*/
|
|
1400
|
+
static frame(data, options) {
|
|
1401
|
+
let mask;
|
|
1402
|
+
let merge = false;
|
|
1403
|
+
let offset = 2;
|
|
1404
|
+
let skipMasking = false;
|
|
1405
|
+
if (options.mask) {
|
|
1406
|
+
mask = options.maskBuffer || maskBuffer;
|
|
1407
|
+
if (options.generateMask) {
|
|
1408
|
+
options.generateMask(mask);
|
|
1409
|
+
} else {
|
|
1410
|
+
if (randomPoolPointer === RANDOM_POOL_SIZE) {
|
|
1411
|
+
if (randomPool === void 0) {
|
|
1412
|
+
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
|
|
1413
|
+
}
|
|
1414
|
+
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
|
|
1415
|
+
randomPoolPointer = 0;
|
|
1416
|
+
}
|
|
1417
|
+
mask[0] = randomPool[randomPoolPointer++];
|
|
1418
|
+
mask[1] = randomPool[randomPoolPointer++];
|
|
1419
|
+
mask[2] = randomPool[randomPoolPointer++];
|
|
1420
|
+
mask[3] = randomPool[randomPoolPointer++];
|
|
1421
|
+
}
|
|
1422
|
+
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
|
|
1423
|
+
offset = 6;
|
|
1424
|
+
}
|
|
1425
|
+
let dataLength;
|
|
1426
|
+
if (typeof data === "string") {
|
|
1427
|
+
if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
|
|
1428
|
+
dataLength = options[kByteLength];
|
|
1429
|
+
} else {
|
|
1430
|
+
data = Buffer.from(data);
|
|
1431
|
+
dataLength = data.length;
|
|
1432
|
+
}
|
|
1433
|
+
} else {
|
|
1434
|
+
dataLength = data.length;
|
|
1435
|
+
merge = options.mask && options.readOnly && !skipMasking;
|
|
1436
|
+
}
|
|
1437
|
+
let payloadLength = dataLength;
|
|
1438
|
+
if (dataLength >= 65536) {
|
|
1439
|
+
offset += 8;
|
|
1440
|
+
payloadLength = 127;
|
|
1441
|
+
} else if (dataLength > 125) {
|
|
1442
|
+
offset += 2;
|
|
1443
|
+
payloadLength = 126;
|
|
1444
|
+
}
|
|
1445
|
+
const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
|
|
1446
|
+
target[0] = options.fin ? options.opcode | 128 : options.opcode;
|
|
1447
|
+
if (options.rsv1) target[0] |= 64;
|
|
1448
|
+
target[1] = payloadLength;
|
|
1449
|
+
if (payloadLength === 126) {
|
|
1450
|
+
target.writeUInt16BE(dataLength, 2);
|
|
1451
|
+
} else if (payloadLength === 127) {
|
|
1452
|
+
target[2] = target[3] = 0;
|
|
1453
|
+
target.writeUIntBE(dataLength, 4, 6);
|
|
1454
|
+
}
|
|
1455
|
+
if (!options.mask) return [target, data];
|
|
1456
|
+
target[1] |= 128;
|
|
1457
|
+
target[offset - 4] = mask[0];
|
|
1458
|
+
target[offset - 3] = mask[1];
|
|
1459
|
+
target[offset - 2] = mask[2];
|
|
1460
|
+
target[offset - 1] = mask[3];
|
|
1461
|
+
if (skipMasking) return [target, data];
|
|
1462
|
+
if (merge) {
|
|
1463
|
+
applyMask(data, mask, target, offset, dataLength);
|
|
1464
|
+
return [target];
|
|
1465
|
+
}
|
|
1466
|
+
applyMask(data, mask, data, 0, dataLength);
|
|
1467
|
+
return [target, data];
|
|
1468
|
+
}
|
|
1469
|
+
/**
|
|
1470
|
+
* Sends a close message to the other peer.
|
|
1471
|
+
*
|
|
1472
|
+
* @param {Number} [code] The status code component of the body
|
|
1473
|
+
* @param {(String|Buffer)} [data] The message component of the body
|
|
1474
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask the message
|
|
1475
|
+
* @param {Function} [cb] Callback
|
|
1476
|
+
* @public
|
|
1477
|
+
*/
|
|
1478
|
+
close(code, data, mask, cb) {
|
|
1479
|
+
let buf;
|
|
1480
|
+
if (code === void 0) {
|
|
1481
|
+
buf = EMPTY_BUFFER;
|
|
1482
|
+
} else if (typeof code !== "number" || !isValidStatusCode(code)) {
|
|
1483
|
+
throw new TypeError("First argument must be a valid error code number");
|
|
1484
|
+
} else if (data === void 0 || !data.length) {
|
|
1485
|
+
buf = Buffer.allocUnsafe(2);
|
|
1486
|
+
buf.writeUInt16BE(code, 0);
|
|
1487
|
+
} else {
|
|
1488
|
+
const length = Buffer.byteLength(data);
|
|
1489
|
+
if (length > 123) {
|
|
1490
|
+
throw new RangeError("The message must not be greater than 123 bytes");
|
|
1491
|
+
}
|
|
1492
|
+
buf = Buffer.allocUnsafe(2 + length);
|
|
1493
|
+
buf.writeUInt16BE(code, 0);
|
|
1494
|
+
if (typeof data === "string") {
|
|
1495
|
+
buf.write(data, 2);
|
|
1496
|
+
} else {
|
|
1497
|
+
buf.set(data, 2);
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
const options = {
|
|
1501
|
+
[kByteLength]: buf.length,
|
|
1502
|
+
fin: true,
|
|
1503
|
+
generateMask: this._generateMask,
|
|
1504
|
+
mask,
|
|
1505
|
+
maskBuffer: this._maskBuffer,
|
|
1506
|
+
opcode: 8,
|
|
1507
|
+
readOnly: false,
|
|
1508
|
+
rsv1: false
|
|
1509
|
+
};
|
|
1510
|
+
if (this._state !== DEFAULT) {
|
|
1511
|
+
this.enqueue([this.dispatch, buf, false, options, cb]);
|
|
1512
|
+
} else {
|
|
1513
|
+
this.sendFrame(_Sender.frame(buf, options), cb);
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
/**
|
|
1517
|
+
* Sends a ping message to the other peer.
|
|
1518
|
+
*
|
|
1519
|
+
* @param {*} data The message to send
|
|
1520
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
|
|
1521
|
+
* @param {Function} [cb] Callback
|
|
1522
|
+
* @public
|
|
1523
|
+
*/
|
|
1524
|
+
ping(data, mask, cb) {
|
|
1525
|
+
let byteLength;
|
|
1526
|
+
let readOnly;
|
|
1527
|
+
if (typeof data === "string") {
|
|
1528
|
+
byteLength = Buffer.byteLength(data);
|
|
1529
|
+
readOnly = false;
|
|
1530
|
+
} else if (isBlob(data)) {
|
|
1531
|
+
byteLength = data.size;
|
|
1532
|
+
readOnly = false;
|
|
1533
|
+
} else {
|
|
1534
|
+
data = toBuffer(data);
|
|
1535
|
+
byteLength = data.length;
|
|
1536
|
+
readOnly = toBuffer.readOnly;
|
|
1537
|
+
}
|
|
1538
|
+
if (byteLength > 125) {
|
|
1539
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1540
|
+
}
|
|
1541
|
+
const options = {
|
|
1542
|
+
[kByteLength]: byteLength,
|
|
1543
|
+
fin: true,
|
|
1544
|
+
generateMask: this._generateMask,
|
|
1545
|
+
mask,
|
|
1546
|
+
maskBuffer: this._maskBuffer,
|
|
1547
|
+
opcode: 9,
|
|
1548
|
+
readOnly,
|
|
1549
|
+
rsv1: false
|
|
1550
|
+
};
|
|
1551
|
+
if (isBlob(data)) {
|
|
1552
|
+
if (this._state !== DEFAULT) {
|
|
1553
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1554
|
+
} else {
|
|
1555
|
+
this.getBlobData(data, false, options, cb);
|
|
1556
|
+
}
|
|
1557
|
+
} else if (this._state !== DEFAULT) {
|
|
1558
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1559
|
+
} else {
|
|
1560
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
/**
|
|
1564
|
+
* Sends a pong message to the other peer.
|
|
1565
|
+
*
|
|
1566
|
+
* @param {*} data The message to send
|
|
1567
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
|
|
1568
|
+
* @param {Function} [cb] Callback
|
|
1569
|
+
* @public
|
|
1570
|
+
*/
|
|
1571
|
+
pong(data, mask, cb) {
|
|
1572
|
+
let byteLength;
|
|
1573
|
+
let readOnly;
|
|
1574
|
+
if (typeof data === "string") {
|
|
1575
|
+
byteLength = Buffer.byteLength(data);
|
|
1576
|
+
readOnly = false;
|
|
1577
|
+
} else if (isBlob(data)) {
|
|
1578
|
+
byteLength = data.size;
|
|
1579
|
+
readOnly = false;
|
|
1580
|
+
} else {
|
|
1581
|
+
data = toBuffer(data);
|
|
1582
|
+
byteLength = data.length;
|
|
1583
|
+
readOnly = toBuffer.readOnly;
|
|
1584
|
+
}
|
|
1585
|
+
if (byteLength > 125) {
|
|
1586
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1587
|
+
}
|
|
1588
|
+
const options = {
|
|
1589
|
+
[kByteLength]: byteLength,
|
|
1590
|
+
fin: true,
|
|
1591
|
+
generateMask: this._generateMask,
|
|
1592
|
+
mask,
|
|
1593
|
+
maskBuffer: this._maskBuffer,
|
|
1594
|
+
opcode: 10,
|
|
1595
|
+
readOnly,
|
|
1596
|
+
rsv1: false
|
|
1597
|
+
};
|
|
1598
|
+
if (isBlob(data)) {
|
|
1599
|
+
if (this._state !== DEFAULT) {
|
|
1600
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1601
|
+
} else {
|
|
1602
|
+
this.getBlobData(data, false, options, cb);
|
|
1603
|
+
}
|
|
1604
|
+
} else if (this._state !== DEFAULT) {
|
|
1605
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1606
|
+
} else {
|
|
1607
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
/**
|
|
1611
|
+
* Sends a data message to the other peer.
|
|
1612
|
+
*
|
|
1613
|
+
* @param {*} data The message to send
|
|
1614
|
+
* @param {Object} options Options object
|
|
1615
|
+
* @param {Boolean} [options.binary=false] Specifies whether `data` is binary
|
|
1616
|
+
* or text
|
|
1617
|
+
* @param {Boolean} [options.compress=false] Specifies whether or not to
|
|
1618
|
+
* compress `data`
|
|
1619
|
+
* @param {Boolean} [options.fin=false] Specifies whether the fragment is the
|
|
1620
|
+
* last one
|
|
1621
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1622
|
+
* `data`
|
|
1623
|
+
* @param {Function} [cb] Callback
|
|
1624
|
+
* @public
|
|
1625
|
+
*/
|
|
1626
|
+
send(data, options, cb) {
|
|
1627
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
1628
|
+
let opcode = options.binary ? 2 : 1;
|
|
1629
|
+
let rsv1 = options.compress;
|
|
1630
|
+
let byteLength;
|
|
1631
|
+
let readOnly;
|
|
1632
|
+
if (typeof data === "string") {
|
|
1633
|
+
byteLength = Buffer.byteLength(data);
|
|
1634
|
+
readOnly = false;
|
|
1635
|
+
} else if (isBlob(data)) {
|
|
1636
|
+
byteLength = data.size;
|
|
1637
|
+
readOnly = false;
|
|
1638
|
+
} else {
|
|
1639
|
+
data = toBuffer(data);
|
|
1640
|
+
byteLength = data.length;
|
|
1641
|
+
readOnly = toBuffer.readOnly;
|
|
1642
|
+
}
|
|
1643
|
+
if (this._firstFragment) {
|
|
1644
|
+
this._firstFragment = false;
|
|
1645
|
+
if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
|
|
1646
|
+
rsv1 = byteLength >= perMessageDeflate._threshold;
|
|
1647
|
+
}
|
|
1648
|
+
this._compress = rsv1;
|
|
1649
|
+
} else {
|
|
1650
|
+
rsv1 = false;
|
|
1651
|
+
opcode = 0;
|
|
1652
|
+
}
|
|
1653
|
+
if (options.fin) this._firstFragment = true;
|
|
1654
|
+
const opts = {
|
|
1655
|
+
[kByteLength]: byteLength,
|
|
1656
|
+
fin: options.fin,
|
|
1657
|
+
generateMask: this._generateMask,
|
|
1658
|
+
mask: options.mask,
|
|
1659
|
+
maskBuffer: this._maskBuffer,
|
|
1660
|
+
opcode,
|
|
1661
|
+
readOnly,
|
|
1662
|
+
rsv1
|
|
1663
|
+
};
|
|
1664
|
+
if (isBlob(data)) {
|
|
1665
|
+
if (this._state !== DEFAULT) {
|
|
1666
|
+
this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
|
|
1667
|
+
} else {
|
|
1668
|
+
this.getBlobData(data, this._compress, opts, cb);
|
|
1669
|
+
}
|
|
1670
|
+
} else if (this._state !== DEFAULT) {
|
|
1671
|
+
this.enqueue([this.dispatch, data, this._compress, opts, cb]);
|
|
1672
|
+
} else {
|
|
1673
|
+
this.dispatch(data, this._compress, opts, cb);
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
/**
|
|
1677
|
+
* Gets the contents of a blob as binary data.
|
|
1678
|
+
*
|
|
1679
|
+
* @param {Blob} blob The blob
|
|
1680
|
+
* @param {Boolean} [compress=false] Specifies whether or not to compress
|
|
1681
|
+
* the data
|
|
1682
|
+
* @param {Object} options Options object
|
|
1683
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
1684
|
+
* FIN bit
|
|
1685
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
1686
|
+
* masking key
|
|
1687
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1688
|
+
* `data`
|
|
1689
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
1690
|
+
* key
|
|
1691
|
+
* @param {Number} options.opcode The opcode
|
|
1692
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
1693
|
+
* modified
|
|
1694
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
1695
|
+
* RSV1 bit
|
|
1696
|
+
* @param {Function} [cb] Callback
|
|
1697
|
+
* @private
|
|
1698
|
+
*/
|
|
1699
|
+
getBlobData(blob, compress, options, cb) {
|
|
1700
|
+
this._bufferedBytes += options[kByteLength];
|
|
1701
|
+
this._state = GET_BLOB_DATA;
|
|
1702
|
+
blob.arrayBuffer().then((arrayBuffer) => {
|
|
1703
|
+
if (this._socket.destroyed) {
|
|
1704
|
+
const err = new Error(
|
|
1705
|
+
"The socket was closed while the blob was being read"
|
|
1706
|
+
);
|
|
1707
|
+
process.nextTick(callCallbacks, this, err, cb);
|
|
1708
|
+
return;
|
|
1709
|
+
}
|
|
1710
|
+
this._bufferedBytes -= options[kByteLength];
|
|
1711
|
+
const data = toBuffer(arrayBuffer);
|
|
1712
|
+
if (!compress) {
|
|
1713
|
+
this._state = DEFAULT;
|
|
1714
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1715
|
+
this.dequeue();
|
|
1716
|
+
} else {
|
|
1717
|
+
this.dispatch(data, compress, options, cb);
|
|
1718
|
+
}
|
|
1719
|
+
}).catch((err) => {
|
|
1720
|
+
process.nextTick(onError2, this, err, cb);
|
|
1721
|
+
});
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* Dispatches a message.
|
|
1725
|
+
*
|
|
1726
|
+
* @param {(Buffer|String)} data The message to send
|
|
1727
|
+
* @param {Boolean} [compress=false] Specifies whether or not to compress
|
|
1728
|
+
* `data`
|
|
1729
|
+
* @param {Object} options Options object
|
|
1730
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
1731
|
+
* FIN bit
|
|
1732
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
1733
|
+
* masking key
|
|
1734
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1735
|
+
* `data`
|
|
1736
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
1737
|
+
* key
|
|
1738
|
+
* @param {Number} options.opcode The opcode
|
|
1739
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
1740
|
+
* modified
|
|
1741
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
1742
|
+
* RSV1 bit
|
|
1743
|
+
* @param {Function} [cb] Callback
|
|
1744
|
+
* @private
|
|
1745
|
+
*/
|
|
1746
|
+
dispatch(data, compress, options, cb) {
|
|
1747
|
+
if (!compress) {
|
|
1748
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1749
|
+
return;
|
|
1750
|
+
}
|
|
1751
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
1752
|
+
this._bufferedBytes += options[kByteLength];
|
|
1753
|
+
this._state = DEFLATING;
|
|
1754
|
+
perMessageDeflate.compress(data, options.fin, (_, buf) => {
|
|
1755
|
+
if (this._socket.destroyed) {
|
|
1756
|
+
const err = new Error(
|
|
1757
|
+
"The socket was closed while data was being compressed"
|
|
1758
|
+
);
|
|
1759
|
+
callCallbacks(this, err, cb);
|
|
1760
|
+
return;
|
|
1761
|
+
}
|
|
1762
|
+
this._bufferedBytes -= options[kByteLength];
|
|
1763
|
+
this._state = DEFAULT;
|
|
1764
|
+
options.readOnly = false;
|
|
1765
|
+
this.sendFrame(_Sender.frame(buf, options), cb);
|
|
1766
|
+
this.dequeue();
|
|
1767
|
+
});
|
|
1768
|
+
}
|
|
1769
|
+
/**
|
|
1770
|
+
* Executes queued send operations.
|
|
1771
|
+
*
|
|
1772
|
+
* @private
|
|
1773
|
+
*/
|
|
1774
|
+
dequeue() {
|
|
1775
|
+
while (this._state === DEFAULT && this._queue.length) {
|
|
1776
|
+
const params = this._queue.shift();
|
|
1777
|
+
this._bufferedBytes -= params[3][kByteLength];
|
|
1778
|
+
Reflect.apply(params[0], this, params.slice(1));
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
/**
|
|
1782
|
+
* Enqueues a send operation.
|
|
1783
|
+
*
|
|
1784
|
+
* @param {Array} params Send operation parameters.
|
|
1785
|
+
* @private
|
|
1786
|
+
*/
|
|
1787
|
+
enqueue(params) {
|
|
1788
|
+
this._bufferedBytes += params[3][kByteLength];
|
|
1789
|
+
this._queue.push(params);
|
|
1790
|
+
}
|
|
1791
|
+
/**
|
|
1792
|
+
* Sends a frame.
|
|
1793
|
+
*
|
|
1794
|
+
* @param {(Buffer | String)[]} list The frame to send
|
|
1795
|
+
* @param {Function} [cb] Callback
|
|
1796
|
+
* @private
|
|
1797
|
+
*/
|
|
1798
|
+
sendFrame(list, cb) {
|
|
1799
|
+
if (list.length === 2) {
|
|
1800
|
+
this._socket.cork();
|
|
1801
|
+
this._socket.write(list[0]);
|
|
1802
|
+
this._socket.write(list[1], cb);
|
|
1803
|
+
this._socket.uncork();
|
|
1804
|
+
} else {
|
|
1805
|
+
this._socket.write(list[0], cb);
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
};
|
|
1809
|
+
module.exports = Sender2;
|
|
1810
|
+
function callCallbacks(sender, err, cb) {
|
|
1811
|
+
if (typeof cb === "function") cb(err);
|
|
1812
|
+
for (let i = 0; i < sender._queue.length; i++) {
|
|
1813
|
+
const params = sender._queue[i];
|
|
1814
|
+
const callback = params[params.length - 1];
|
|
1815
|
+
if (typeof callback === "function") callback(err);
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
function onError2(sender, err, cb) {
|
|
1819
|
+
callCallbacks(sender, err, cb);
|
|
1820
|
+
sender.onerror(err);
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
});
|
|
1824
|
+
|
|
1825
|
+
// ../../node_modules/ws/lib/event-target.js
|
|
1826
|
+
var require_event_target = __commonJS({
|
|
1827
|
+
"../../node_modules/ws/lib/event-target.js"(exports, module) {
|
|
1828
|
+
"use strict";
|
|
1829
|
+
var { kForOnEventAttribute, kListener } = require_constants();
|
|
1830
|
+
var kCode = /* @__PURE__ */ Symbol("kCode");
|
|
1831
|
+
var kData = /* @__PURE__ */ Symbol("kData");
|
|
1832
|
+
var kError = /* @__PURE__ */ Symbol("kError");
|
|
1833
|
+
var kMessage = /* @__PURE__ */ Symbol("kMessage");
|
|
1834
|
+
var kReason = /* @__PURE__ */ Symbol("kReason");
|
|
1835
|
+
var kTarget = /* @__PURE__ */ Symbol("kTarget");
|
|
1836
|
+
var kType = /* @__PURE__ */ Symbol("kType");
|
|
1837
|
+
var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
|
|
1838
|
+
var Event = class {
|
|
1839
|
+
/**
|
|
1840
|
+
* Create a new `Event`.
|
|
1841
|
+
*
|
|
1842
|
+
* @param {String} type The name of the event
|
|
1843
|
+
* @throws {TypeError} If the `type` argument is not specified
|
|
1844
|
+
*/
|
|
1845
|
+
constructor(type) {
|
|
1846
|
+
this[kTarget] = null;
|
|
1847
|
+
this[kType] = type;
|
|
1848
|
+
}
|
|
1849
|
+
/**
|
|
1850
|
+
* @type {*}
|
|
1851
|
+
*/
|
|
1852
|
+
get target() {
|
|
1853
|
+
return this[kTarget];
|
|
1854
|
+
}
|
|
1855
|
+
/**
|
|
1856
|
+
* @type {String}
|
|
1857
|
+
*/
|
|
1858
|
+
get type() {
|
|
1859
|
+
return this[kType];
|
|
1860
|
+
}
|
|
1861
|
+
};
|
|
1862
|
+
Object.defineProperty(Event.prototype, "target", { enumerable: true });
|
|
1863
|
+
Object.defineProperty(Event.prototype, "type", { enumerable: true });
|
|
1864
|
+
var CloseEvent = class extends Event {
|
|
1865
|
+
/**
|
|
1866
|
+
* Create a new `CloseEvent`.
|
|
1867
|
+
*
|
|
1868
|
+
* @param {String} type The name of the event
|
|
1869
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
1870
|
+
* attributes via object members of the same name
|
|
1871
|
+
* @param {Number} [options.code=0] The status code explaining why the
|
|
1872
|
+
* connection was closed
|
|
1873
|
+
* @param {String} [options.reason=''] A human-readable string explaining why
|
|
1874
|
+
* the connection was closed
|
|
1875
|
+
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
|
|
1876
|
+
* connection was cleanly closed
|
|
1877
|
+
*/
|
|
1878
|
+
constructor(type, options = {}) {
|
|
1879
|
+
super(type);
|
|
1880
|
+
this[kCode] = options.code === void 0 ? 0 : options.code;
|
|
1881
|
+
this[kReason] = options.reason === void 0 ? "" : options.reason;
|
|
1882
|
+
this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
|
|
1883
|
+
}
|
|
1884
|
+
/**
|
|
1885
|
+
* @type {Number}
|
|
1886
|
+
*/
|
|
1887
|
+
get code() {
|
|
1888
|
+
return this[kCode];
|
|
1889
|
+
}
|
|
1890
|
+
/**
|
|
1891
|
+
* @type {String}
|
|
1892
|
+
*/
|
|
1893
|
+
get reason() {
|
|
1894
|
+
return this[kReason];
|
|
1895
|
+
}
|
|
1896
|
+
/**
|
|
1897
|
+
* @type {Boolean}
|
|
1898
|
+
*/
|
|
1899
|
+
get wasClean() {
|
|
1900
|
+
return this[kWasClean];
|
|
1901
|
+
}
|
|
1902
|
+
};
|
|
1903
|
+
Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
|
|
1904
|
+
Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
|
|
1905
|
+
Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
|
|
1906
|
+
var ErrorEvent = class extends Event {
|
|
1907
|
+
/**
|
|
1908
|
+
* Create a new `ErrorEvent`.
|
|
1909
|
+
*
|
|
1910
|
+
* @param {String} type The name of the event
|
|
1911
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
1912
|
+
* attributes via object members of the same name
|
|
1913
|
+
* @param {*} [options.error=null] The error that generated this event
|
|
1914
|
+
* @param {String} [options.message=''] The error message
|
|
1915
|
+
*/
|
|
1916
|
+
constructor(type, options = {}) {
|
|
1917
|
+
super(type);
|
|
1918
|
+
this[kError] = options.error === void 0 ? null : options.error;
|
|
1919
|
+
this[kMessage] = options.message === void 0 ? "" : options.message;
|
|
1920
|
+
}
|
|
1921
|
+
/**
|
|
1922
|
+
* @type {*}
|
|
1923
|
+
*/
|
|
1924
|
+
get error() {
|
|
1925
|
+
return this[kError];
|
|
1926
|
+
}
|
|
1927
|
+
/**
|
|
1928
|
+
* @type {String}
|
|
1929
|
+
*/
|
|
1930
|
+
get message() {
|
|
1931
|
+
return this[kMessage];
|
|
1932
|
+
}
|
|
1933
|
+
};
|
|
1934
|
+
Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
|
|
1935
|
+
Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
|
|
1936
|
+
var MessageEvent = class extends Event {
|
|
1937
|
+
/**
|
|
1938
|
+
* Create a new `MessageEvent`.
|
|
1939
|
+
*
|
|
1940
|
+
* @param {String} type The name of the event
|
|
1941
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
1942
|
+
* attributes via object members of the same name
|
|
1943
|
+
* @param {*} [options.data=null] The message content
|
|
1944
|
+
*/
|
|
1945
|
+
constructor(type, options = {}) {
|
|
1946
|
+
super(type);
|
|
1947
|
+
this[kData] = options.data === void 0 ? null : options.data;
|
|
1948
|
+
}
|
|
1949
|
+
/**
|
|
1950
|
+
* @type {*}
|
|
1951
|
+
*/
|
|
1952
|
+
get data() {
|
|
1953
|
+
return this[kData];
|
|
1954
|
+
}
|
|
1955
|
+
};
|
|
1956
|
+
Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
|
|
1957
|
+
var EventTarget = {
|
|
1958
|
+
/**
|
|
1959
|
+
* Register an event listener.
|
|
1960
|
+
*
|
|
1961
|
+
* @param {String} type A string representing the event type to listen for
|
|
1962
|
+
* @param {(Function|Object)} handler The listener to add
|
|
1963
|
+
* @param {Object} [options] An options object specifies characteristics about
|
|
1964
|
+
* the event listener
|
|
1965
|
+
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
|
|
1966
|
+
* listener should be invoked at most once after being added. If `true`,
|
|
1967
|
+
* the listener would be automatically removed when invoked.
|
|
1968
|
+
* @public
|
|
1969
|
+
*/
|
|
1970
|
+
addEventListener(type, handler, options = {}) {
|
|
1971
|
+
for (const listener of this.listeners(type)) {
|
|
1972
|
+
if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
1973
|
+
return;
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
let wrapper;
|
|
1977
|
+
if (type === "message") {
|
|
1978
|
+
wrapper = function onMessage(data, isBinary) {
|
|
1979
|
+
const event = new MessageEvent("message", {
|
|
1980
|
+
data: isBinary ? data : data.toString()
|
|
1981
|
+
});
|
|
1982
|
+
event[kTarget] = this;
|
|
1983
|
+
callListener(handler, this, event);
|
|
1984
|
+
};
|
|
1985
|
+
} else if (type === "close") {
|
|
1986
|
+
wrapper = function onClose(code, message) {
|
|
1987
|
+
const event = new CloseEvent("close", {
|
|
1988
|
+
code,
|
|
1989
|
+
reason: message.toString(),
|
|
1990
|
+
wasClean: this._closeFrameReceived && this._closeFrameSent
|
|
1991
|
+
});
|
|
1992
|
+
event[kTarget] = this;
|
|
1993
|
+
callListener(handler, this, event);
|
|
1994
|
+
};
|
|
1995
|
+
} else if (type === "error") {
|
|
1996
|
+
wrapper = function onError2(error) {
|
|
1997
|
+
const event = new ErrorEvent("error", {
|
|
1998
|
+
error,
|
|
1999
|
+
message: error.message
|
|
2000
|
+
});
|
|
2001
|
+
event[kTarget] = this;
|
|
2002
|
+
callListener(handler, this, event);
|
|
2003
|
+
};
|
|
2004
|
+
} else if (type === "open") {
|
|
2005
|
+
wrapper = function onOpen() {
|
|
2006
|
+
const event = new Event("open");
|
|
2007
|
+
event[kTarget] = this;
|
|
2008
|
+
callListener(handler, this, event);
|
|
2009
|
+
};
|
|
2010
|
+
} else {
|
|
2011
|
+
return;
|
|
2012
|
+
}
|
|
2013
|
+
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
|
|
2014
|
+
wrapper[kListener] = handler;
|
|
2015
|
+
if (options.once) {
|
|
2016
|
+
this.once(type, wrapper);
|
|
2017
|
+
} else {
|
|
2018
|
+
this.on(type, wrapper);
|
|
2019
|
+
}
|
|
2020
|
+
},
|
|
2021
|
+
/**
|
|
2022
|
+
* Remove an event listener.
|
|
2023
|
+
*
|
|
2024
|
+
* @param {String} type A string representing the event type to remove
|
|
2025
|
+
* @param {(Function|Object)} handler The listener to remove
|
|
2026
|
+
* @public
|
|
2027
|
+
*/
|
|
2028
|
+
removeEventListener(type, handler) {
|
|
2029
|
+
for (const listener of this.listeners(type)) {
|
|
2030
|
+
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
2031
|
+
this.removeListener(type, listener);
|
|
2032
|
+
break;
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
};
|
|
2037
|
+
module.exports = {
|
|
2038
|
+
CloseEvent,
|
|
2039
|
+
ErrorEvent,
|
|
2040
|
+
Event,
|
|
2041
|
+
EventTarget,
|
|
2042
|
+
MessageEvent
|
|
2043
|
+
};
|
|
2044
|
+
function callListener(listener, thisArg, event) {
|
|
2045
|
+
if (typeof listener === "object" && listener.handleEvent) {
|
|
2046
|
+
listener.handleEvent.call(listener, event);
|
|
2047
|
+
} else {
|
|
2048
|
+
listener.call(thisArg, event);
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
}
|
|
2052
|
+
});
|
|
2053
|
+
|
|
2054
|
+
// ../../node_modules/ws/lib/extension.js
|
|
2055
|
+
var require_extension = __commonJS({
|
|
2056
|
+
"../../node_modules/ws/lib/extension.js"(exports, module) {
|
|
2057
|
+
"use strict";
|
|
2058
|
+
var { tokenChars } = require_validation();
|
|
2059
|
+
function push(dest, name, elem) {
|
|
2060
|
+
if (dest[name] === void 0) dest[name] = [elem];
|
|
2061
|
+
else dest[name].push(elem);
|
|
2062
|
+
}
|
|
2063
|
+
function parse(header) {
|
|
2064
|
+
const offers = /* @__PURE__ */ Object.create(null);
|
|
2065
|
+
let params = /* @__PURE__ */ Object.create(null);
|
|
2066
|
+
let mustUnescape = false;
|
|
2067
|
+
let isEscaping = false;
|
|
2068
|
+
let inQuotes = false;
|
|
2069
|
+
let extensionName;
|
|
2070
|
+
let paramName;
|
|
2071
|
+
let start = -1;
|
|
2072
|
+
let code = -1;
|
|
2073
|
+
let end = -1;
|
|
2074
|
+
let i = 0;
|
|
2075
|
+
for (; i < header.length; i++) {
|
|
2076
|
+
code = header.charCodeAt(i);
|
|
2077
|
+
if (extensionName === void 0) {
|
|
2078
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
2079
|
+
if (start === -1) start = i;
|
|
2080
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
2081
|
+
if (end === -1 && start !== -1) end = i;
|
|
2082
|
+
} else if (code === 59 || code === 44) {
|
|
2083
|
+
if (start === -1) {
|
|
2084
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2085
|
+
}
|
|
2086
|
+
if (end === -1) end = i;
|
|
2087
|
+
const name = header.slice(start, end);
|
|
2088
|
+
if (code === 44) {
|
|
2089
|
+
push(offers, name, params);
|
|
2090
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2091
|
+
} else {
|
|
2092
|
+
extensionName = name;
|
|
2093
|
+
}
|
|
2094
|
+
start = end = -1;
|
|
2095
|
+
} else {
|
|
2096
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2097
|
+
}
|
|
2098
|
+
} else if (paramName === void 0) {
|
|
2099
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
2100
|
+
if (start === -1) start = i;
|
|
2101
|
+
} else if (code === 32 || code === 9) {
|
|
2102
|
+
if (end === -1 && start !== -1) end = i;
|
|
2103
|
+
} else if (code === 59 || code === 44) {
|
|
2104
|
+
if (start === -1) {
|
|
2105
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2106
|
+
}
|
|
2107
|
+
if (end === -1) end = i;
|
|
2108
|
+
push(params, header.slice(start, end), true);
|
|
2109
|
+
if (code === 44) {
|
|
2110
|
+
push(offers, extensionName, params);
|
|
2111
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2112
|
+
extensionName = void 0;
|
|
2113
|
+
}
|
|
2114
|
+
start = end = -1;
|
|
2115
|
+
} else if (code === 61 && start !== -1 && end === -1) {
|
|
2116
|
+
paramName = header.slice(start, i);
|
|
2117
|
+
start = end = -1;
|
|
2118
|
+
} else {
|
|
2119
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2120
|
+
}
|
|
2121
|
+
} else {
|
|
2122
|
+
if (isEscaping) {
|
|
2123
|
+
if (tokenChars[code] !== 1) {
|
|
2124
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2125
|
+
}
|
|
2126
|
+
if (start === -1) start = i;
|
|
2127
|
+
else if (!mustUnescape) mustUnescape = true;
|
|
2128
|
+
isEscaping = false;
|
|
2129
|
+
} else if (inQuotes) {
|
|
2130
|
+
if (tokenChars[code] === 1) {
|
|
2131
|
+
if (start === -1) start = i;
|
|
2132
|
+
} else if (code === 34 && start !== -1) {
|
|
2133
|
+
inQuotes = false;
|
|
2134
|
+
end = i;
|
|
2135
|
+
} else if (code === 92) {
|
|
2136
|
+
isEscaping = true;
|
|
2137
|
+
} else {
|
|
2138
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2139
|
+
}
|
|
2140
|
+
} else if (code === 34 && header.charCodeAt(i - 1) === 61) {
|
|
2141
|
+
inQuotes = true;
|
|
2142
|
+
} else if (end === -1 && tokenChars[code] === 1) {
|
|
2143
|
+
if (start === -1) start = i;
|
|
2144
|
+
} else if (start !== -1 && (code === 32 || code === 9)) {
|
|
2145
|
+
if (end === -1) end = i;
|
|
2146
|
+
} else if (code === 59 || code === 44) {
|
|
2147
|
+
if (start === -1) {
|
|
2148
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2149
|
+
}
|
|
2150
|
+
if (end === -1) end = i;
|
|
2151
|
+
let value = header.slice(start, end);
|
|
2152
|
+
if (mustUnescape) {
|
|
2153
|
+
value = value.replace(/\\/g, "");
|
|
2154
|
+
mustUnescape = false;
|
|
2155
|
+
}
|
|
2156
|
+
push(params, paramName, value);
|
|
2157
|
+
if (code === 44) {
|
|
2158
|
+
push(offers, extensionName, params);
|
|
2159
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2160
|
+
extensionName = void 0;
|
|
2161
|
+
}
|
|
2162
|
+
paramName = void 0;
|
|
2163
|
+
start = end = -1;
|
|
2164
|
+
} else {
|
|
2165
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
if (start === -1 || inQuotes || code === 32 || code === 9) {
|
|
2170
|
+
throw new SyntaxError("Unexpected end of input");
|
|
2171
|
+
}
|
|
2172
|
+
if (end === -1) end = i;
|
|
2173
|
+
const token = header.slice(start, end);
|
|
2174
|
+
if (extensionName === void 0) {
|
|
2175
|
+
push(offers, token, params);
|
|
2176
|
+
} else {
|
|
2177
|
+
if (paramName === void 0) {
|
|
2178
|
+
push(params, token, true);
|
|
2179
|
+
} else if (mustUnescape) {
|
|
2180
|
+
push(params, paramName, token.replace(/\\/g, ""));
|
|
2181
|
+
} else {
|
|
2182
|
+
push(params, paramName, token);
|
|
2183
|
+
}
|
|
2184
|
+
push(offers, extensionName, params);
|
|
2185
|
+
}
|
|
2186
|
+
return offers;
|
|
2187
|
+
}
|
|
2188
|
+
function format(extensions) {
|
|
2189
|
+
return Object.keys(extensions).map((extension) => {
|
|
2190
|
+
let configurations = extensions[extension];
|
|
2191
|
+
if (!Array.isArray(configurations)) configurations = [configurations];
|
|
2192
|
+
return configurations.map((params) => {
|
|
2193
|
+
return [extension].concat(
|
|
2194
|
+
Object.keys(params).map((k) => {
|
|
2195
|
+
let values = params[k];
|
|
2196
|
+
if (!Array.isArray(values)) values = [values];
|
|
2197
|
+
return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
|
|
2198
|
+
})
|
|
2199
|
+
).join("; ");
|
|
2200
|
+
}).join(", ");
|
|
2201
|
+
}).join(", ");
|
|
2202
|
+
}
|
|
2203
|
+
module.exports = { format, parse };
|
|
2204
|
+
}
|
|
2205
|
+
});
|
|
2206
|
+
|
|
2207
|
+
// ../../node_modules/ws/lib/websocket.js
|
|
2208
|
+
var require_websocket = __commonJS({
|
|
2209
|
+
"../../node_modules/ws/lib/websocket.js"(exports, module) {
|
|
2210
|
+
"use strict";
|
|
2211
|
+
var EventEmitter2 = __require("events");
|
|
2212
|
+
var https = __require("https");
|
|
2213
|
+
var http2 = __require("http");
|
|
2214
|
+
var net = __require("net");
|
|
2215
|
+
var tls = __require("tls");
|
|
2216
|
+
var { randomBytes, createHash } = __require("crypto");
|
|
2217
|
+
var { Duplex, Readable } = __require("stream");
|
|
2218
|
+
var { URL } = __require("url");
|
|
2219
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
2220
|
+
var Receiver2 = require_receiver();
|
|
2221
|
+
var Sender2 = require_sender();
|
|
2222
|
+
var { isBlob } = require_validation();
|
|
2223
|
+
var {
|
|
2224
|
+
BINARY_TYPES,
|
|
2225
|
+
CLOSE_TIMEOUT,
|
|
2226
|
+
EMPTY_BUFFER,
|
|
2227
|
+
GUID,
|
|
2228
|
+
kForOnEventAttribute,
|
|
2229
|
+
kListener,
|
|
2230
|
+
kStatusCode,
|
|
2231
|
+
kWebSocket,
|
|
2232
|
+
NOOP: NOOP2
|
|
2233
|
+
} = require_constants();
|
|
2234
|
+
var {
|
|
2235
|
+
EventTarget: { addEventListener, removeEventListener }
|
|
2236
|
+
} = require_event_target();
|
|
2237
|
+
var { format, parse } = require_extension();
|
|
2238
|
+
var { toBuffer } = require_buffer_util();
|
|
2239
|
+
var kAborted = /* @__PURE__ */ Symbol("kAborted");
|
|
2240
|
+
var protocolVersions = [8, 13];
|
|
2241
|
+
var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
|
|
2242
|
+
var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
|
|
2243
|
+
var WebSocket2 = class _WebSocket extends EventEmitter2 {
|
|
2244
|
+
/**
|
|
2245
|
+
* Create a new `WebSocket`.
|
|
2246
|
+
*
|
|
2247
|
+
* @param {(String|URL)} address The URL to which to connect
|
|
2248
|
+
* @param {(String|String[])} [protocols] The subprotocols
|
|
2249
|
+
* @param {Object} [options] Connection options
|
|
2250
|
+
*/
|
|
2251
|
+
constructor(address, protocols, options) {
|
|
2252
|
+
super();
|
|
2253
|
+
this._binaryType = BINARY_TYPES[0];
|
|
2254
|
+
this._closeCode = 1006;
|
|
2255
|
+
this._closeFrameReceived = false;
|
|
2256
|
+
this._closeFrameSent = false;
|
|
2257
|
+
this._closeMessage = EMPTY_BUFFER;
|
|
2258
|
+
this._closeTimer = null;
|
|
2259
|
+
this._errorEmitted = false;
|
|
2260
|
+
this._extensions = {};
|
|
2261
|
+
this._paused = false;
|
|
2262
|
+
this._protocol = "";
|
|
2263
|
+
this._readyState = _WebSocket.CONNECTING;
|
|
2264
|
+
this._receiver = null;
|
|
2265
|
+
this._sender = null;
|
|
2266
|
+
this._socket = null;
|
|
2267
|
+
if (address !== null) {
|
|
2268
|
+
this._bufferedAmount = 0;
|
|
2269
|
+
this._isServer = false;
|
|
2270
|
+
this._redirects = 0;
|
|
2271
|
+
if (protocols === void 0) {
|
|
2272
|
+
protocols = [];
|
|
2273
|
+
} else if (!Array.isArray(protocols)) {
|
|
2274
|
+
if (typeof protocols === "object" && protocols !== null) {
|
|
2275
|
+
options = protocols;
|
|
2276
|
+
protocols = [];
|
|
2277
|
+
} else {
|
|
2278
|
+
protocols = [protocols];
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
initAsClient(this, address, protocols, options);
|
|
2282
|
+
} else {
|
|
2283
|
+
this._autoPong = options.autoPong;
|
|
2284
|
+
this._closeTimeout = options.closeTimeout;
|
|
2285
|
+
this._isServer = true;
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
/**
|
|
2289
|
+
* For historical reasons, the custom "nodebuffer" type is used by the default
|
|
2290
|
+
* instead of "blob".
|
|
2291
|
+
*
|
|
2292
|
+
* @type {String}
|
|
2293
|
+
*/
|
|
2294
|
+
get binaryType() {
|
|
2295
|
+
return this._binaryType;
|
|
2296
|
+
}
|
|
2297
|
+
set binaryType(type) {
|
|
2298
|
+
if (!BINARY_TYPES.includes(type)) return;
|
|
2299
|
+
this._binaryType = type;
|
|
2300
|
+
if (this._receiver) this._receiver._binaryType = type;
|
|
2301
|
+
}
|
|
2302
|
+
/**
|
|
2303
|
+
* @type {Number}
|
|
2304
|
+
*/
|
|
2305
|
+
get bufferedAmount() {
|
|
2306
|
+
if (!this._socket) return this._bufferedAmount;
|
|
2307
|
+
return this._socket._writableState.length + this._sender._bufferedBytes;
|
|
2308
|
+
}
|
|
2309
|
+
/**
|
|
2310
|
+
* @type {String}
|
|
2311
|
+
*/
|
|
2312
|
+
get extensions() {
|
|
2313
|
+
return Object.keys(this._extensions).join();
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* @type {Boolean}
|
|
2317
|
+
*/
|
|
2318
|
+
get isPaused() {
|
|
2319
|
+
return this._paused;
|
|
2320
|
+
}
|
|
2321
|
+
/**
|
|
2322
|
+
* @type {Function}
|
|
2323
|
+
*/
|
|
2324
|
+
/* istanbul ignore next */
|
|
2325
|
+
get onclose() {
|
|
2326
|
+
return null;
|
|
2327
|
+
}
|
|
2328
|
+
/**
|
|
2329
|
+
* @type {Function}
|
|
2330
|
+
*/
|
|
2331
|
+
/* istanbul ignore next */
|
|
2332
|
+
get onerror() {
|
|
2333
|
+
return null;
|
|
2334
|
+
}
|
|
2335
|
+
/**
|
|
2336
|
+
* @type {Function}
|
|
2337
|
+
*/
|
|
2338
|
+
/* istanbul ignore next */
|
|
2339
|
+
get onopen() {
|
|
2340
|
+
return null;
|
|
2341
|
+
}
|
|
2342
|
+
/**
|
|
2343
|
+
* @type {Function}
|
|
2344
|
+
*/
|
|
2345
|
+
/* istanbul ignore next */
|
|
2346
|
+
get onmessage() {
|
|
2347
|
+
return null;
|
|
2348
|
+
}
|
|
2349
|
+
/**
|
|
2350
|
+
* @type {String}
|
|
2351
|
+
*/
|
|
2352
|
+
get protocol() {
|
|
2353
|
+
return this._protocol;
|
|
2354
|
+
}
|
|
2355
|
+
/**
|
|
2356
|
+
* @type {Number}
|
|
2357
|
+
*/
|
|
2358
|
+
get readyState() {
|
|
2359
|
+
return this._readyState;
|
|
2360
|
+
}
|
|
2361
|
+
/**
|
|
2362
|
+
* @type {String}
|
|
2363
|
+
*/
|
|
2364
|
+
get url() {
|
|
2365
|
+
return this._url;
|
|
2366
|
+
}
|
|
2367
|
+
/**
|
|
2368
|
+
* Set up the socket and the internal resources.
|
|
2369
|
+
*
|
|
2370
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
2371
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
2372
|
+
* @param {Object} options Options object
|
|
2373
|
+
* @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
|
|
2374
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
2375
|
+
* multiple times in the same tick
|
|
2376
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
2377
|
+
* masking key
|
|
2378
|
+
* @param {Number} [options.maxPayload=0] The maximum allowed message size
|
|
2379
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
2380
|
+
* not to skip UTF-8 validation for text and close messages
|
|
2381
|
+
* @private
|
|
2382
|
+
*/
|
|
2383
|
+
setSocket(socket, head, options) {
|
|
2384
|
+
const receiver = new Receiver2({
|
|
2385
|
+
allowSynchronousEvents: options.allowSynchronousEvents,
|
|
2386
|
+
binaryType: this.binaryType,
|
|
2387
|
+
extensions: this._extensions,
|
|
2388
|
+
isServer: this._isServer,
|
|
2389
|
+
maxPayload: options.maxPayload,
|
|
2390
|
+
skipUTF8Validation: options.skipUTF8Validation
|
|
2391
|
+
});
|
|
2392
|
+
const sender = new Sender2(socket, this._extensions, options.generateMask);
|
|
2393
|
+
this._receiver = receiver;
|
|
2394
|
+
this._sender = sender;
|
|
2395
|
+
this._socket = socket;
|
|
2396
|
+
receiver[kWebSocket] = this;
|
|
2397
|
+
sender[kWebSocket] = this;
|
|
2398
|
+
socket[kWebSocket] = this;
|
|
2399
|
+
receiver.on("conclude", receiverOnConclude);
|
|
2400
|
+
receiver.on("drain", receiverOnDrain);
|
|
2401
|
+
receiver.on("error", receiverOnError);
|
|
2402
|
+
receiver.on("message", receiverOnMessage);
|
|
2403
|
+
receiver.on("ping", receiverOnPing);
|
|
2404
|
+
receiver.on("pong", receiverOnPong);
|
|
2405
|
+
sender.onerror = senderOnError;
|
|
2406
|
+
if (socket.setTimeout) socket.setTimeout(0);
|
|
2407
|
+
if (socket.setNoDelay) socket.setNoDelay();
|
|
2408
|
+
if (head.length > 0) socket.unshift(head);
|
|
2409
|
+
socket.on("close", socketOnClose);
|
|
2410
|
+
socket.on("data", socketOnData);
|
|
2411
|
+
socket.on("end", socketOnEnd);
|
|
2412
|
+
socket.on("error", socketOnError);
|
|
2413
|
+
this._readyState = _WebSocket.OPEN;
|
|
2414
|
+
this.emit("open");
|
|
2415
|
+
}
|
|
2416
|
+
/**
|
|
2417
|
+
* Emit the `'close'` event.
|
|
2418
|
+
*
|
|
2419
|
+
* @private
|
|
2420
|
+
*/
|
|
2421
|
+
emitClose() {
|
|
2422
|
+
if (!this._socket) {
|
|
2423
|
+
this._readyState = _WebSocket.CLOSED;
|
|
2424
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
2425
|
+
return;
|
|
2426
|
+
}
|
|
2427
|
+
if (this._extensions[PerMessageDeflate.extensionName]) {
|
|
2428
|
+
this._extensions[PerMessageDeflate.extensionName].cleanup();
|
|
2429
|
+
}
|
|
2430
|
+
this._receiver.removeAllListeners();
|
|
2431
|
+
this._readyState = _WebSocket.CLOSED;
|
|
2432
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
2433
|
+
}
|
|
2434
|
+
/**
|
|
2435
|
+
* Start a closing handshake.
|
|
2436
|
+
*
|
|
2437
|
+
* +----------+ +-----------+ +----------+
|
|
2438
|
+
* - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
|
|
2439
|
+
* | +----------+ +-----------+ +----------+ |
|
|
2440
|
+
* +----------+ +-----------+ |
|
|
2441
|
+
* CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
|
|
2442
|
+
* +----------+ +-----------+ |
|
|
2443
|
+
* | | | +---+ |
|
|
2444
|
+
* +------------------------+-->|fin| - - - -
|
|
2445
|
+
* | +---+ | +---+
|
|
2446
|
+
* - - - - -|fin|<---------------------+
|
|
2447
|
+
* +---+
|
|
2448
|
+
*
|
|
2449
|
+
* @param {Number} [code] Status code explaining why the connection is closing
|
|
2450
|
+
* @param {(String|Buffer)} [data] The reason why the connection is
|
|
2451
|
+
* closing
|
|
2452
|
+
* @public
|
|
2453
|
+
*/
|
|
2454
|
+
close(code, data) {
|
|
2455
|
+
if (this.readyState === _WebSocket.CLOSED) return;
|
|
2456
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2457
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
2458
|
+
abortHandshake(this, this._req, msg);
|
|
2459
|
+
return;
|
|
2460
|
+
}
|
|
2461
|
+
if (this.readyState === _WebSocket.CLOSING) {
|
|
2462
|
+
if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
|
|
2463
|
+
this._socket.end();
|
|
2464
|
+
}
|
|
2465
|
+
return;
|
|
2466
|
+
}
|
|
2467
|
+
this._readyState = _WebSocket.CLOSING;
|
|
2468
|
+
this._sender.close(code, data, !this._isServer, (err) => {
|
|
2469
|
+
if (err) return;
|
|
2470
|
+
this._closeFrameSent = true;
|
|
2471
|
+
if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
|
|
2472
|
+
this._socket.end();
|
|
2473
|
+
}
|
|
2474
|
+
});
|
|
2475
|
+
setCloseTimer(this);
|
|
2476
|
+
}
|
|
2477
|
+
/**
|
|
2478
|
+
* Pause the socket.
|
|
2479
|
+
*
|
|
2480
|
+
* @public
|
|
2481
|
+
*/
|
|
2482
|
+
pause() {
|
|
2483
|
+
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
|
|
2484
|
+
return;
|
|
2485
|
+
}
|
|
2486
|
+
this._paused = true;
|
|
2487
|
+
this._socket.pause();
|
|
2488
|
+
}
|
|
2489
|
+
/**
|
|
2490
|
+
* Send a ping.
|
|
2491
|
+
*
|
|
2492
|
+
* @param {*} [data] The data to send
|
|
2493
|
+
* @param {Boolean} [mask] Indicates whether or not to mask `data`
|
|
2494
|
+
* @param {Function} [cb] Callback which is executed when the ping is sent
|
|
2495
|
+
* @public
|
|
2496
|
+
*/
|
|
2497
|
+
ping(data, mask, cb) {
|
|
2498
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2499
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2500
|
+
}
|
|
2501
|
+
if (typeof data === "function") {
|
|
2502
|
+
cb = data;
|
|
2503
|
+
data = mask = void 0;
|
|
2504
|
+
} else if (typeof mask === "function") {
|
|
2505
|
+
cb = mask;
|
|
2506
|
+
mask = void 0;
|
|
2507
|
+
}
|
|
2508
|
+
if (typeof data === "number") data = data.toString();
|
|
2509
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2510
|
+
sendAfterClose(this, data, cb);
|
|
2511
|
+
return;
|
|
2512
|
+
}
|
|
2513
|
+
if (mask === void 0) mask = !this._isServer;
|
|
2514
|
+
this._sender.ping(data || EMPTY_BUFFER, mask, cb);
|
|
2515
|
+
}
|
|
2516
|
+
/**
|
|
2517
|
+
* Send a pong.
|
|
2518
|
+
*
|
|
2519
|
+
* @param {*} [data] The data to send
|
|
2520
|
+
* @param {Boolean} [mask] Indicates whether or not to mask `data`
|
|
2521
|
+
* @param {Function} [cb] Callback which is executed when the pong is sent
|
|
2522
|
+
* @public
|
|
2523
|
+
*/
|
|
2524
|
+
pong(data, mask, cb) {
|
|
2525
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2526
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2527
|
+
}
|
|
2528
|
+
if (typeof data === "function") {
|
|
2529
|
+
cb = data;
|
|
2530
|
+
data = mask = void 0;
|
|
2531
|
+
} else if (typeof mask === "function") {
|
|
2532
|
+
cb = mask;
|
|
2533
|
+
mask = void 0;
|
|
2534
|
+
}
|
|
2535
|
+
if (typeof data === "number") data = data.toString();
|
|
2536
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2537
|
+
sendAfterClose(this, data, cb);
|
|
2538
|
+
return;
|
|
2539
|
+
}
|
|
2540
|
+
if (mask === void 0) mask = !this._isServer;
|
|
2541
|
+
this._sender.pong(data || EMPTY_BUFFER, mask, cb);
|
|
2542
|
+
}
|
|
2543
|
+
/**
|
|
2544
|
+
* Resume the socket.
|
|
2545
|
+
*
|
|
2546
|
+
* @public
|
|
2547
|
+
*/
|
|
2548
|
+
resume() {
|
|
2549
|
+
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
|
|
2550
|
+
return;
|
|
2551
|
+
}
|
|
2552
|
+
this._paused = false;
|
|
2553
|
+
if (!this._receiver._writableState.needDrain) this._socket.resume();
|
|
2554
|
+
}
|
|
2555
|
+
/**
|
|
2556
|
+
* Send a data message.
|
|
2557
|
+
*
|
|
2558
|
+
* @param {*} data The message to send
|
|
2559
|
+
* @param {Object} [options] Options object
|
|
2560
|
+
* @param {Boolean} [options.binary] Specifies whether `data` is binary or
|
|
2561
|
+
* text
|
|
2562
|
+
* @param {Boolean} [options.compress] Specifies whether or not to compress
|
|
2563
|
+
* `data`
|
|
2564
|
+
* @param {Boolean} [options.fin=true] Specifies whether the fragment is the
|
|
2565
|
+
* last one
|
|
2566
|
+
* @param {Boolean} [options.mask] Specifies whether or not to mask `data`
|
|
2567
|
+
* @param {Function} [cb] Callback which is executed when data is written out
|
|
2568
|
+
* @public
|
|
2569
|
+
*/
|
|
2570
|
+
send(data, options, cb) {
|
|
2571
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2572
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2573
|
+
}
|
|
2574
|
+
if (typeof options === "function") {
|
|
2575
|
+
cb = options;
|
|
2576
|
+
options = {};
|
|
2577
|
+
}
|
|
2578
|
+
if (typeof data === "number") data = data.toString();
|
|
2579
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2580
|
+
sendAfterClose(this, data, cb);
|
|
2581
|
+
return;
|
|
2582
|
+
}
|
|
2583
|
+
const opts = {
|
|
2584
|
+
binary: typeof data !== "string",
|
|
2585
|
+
mask: !this._isServer,
|
|
2586
|
+
compress: true,
|
|
2587
|
+
fin: true,
|
|
2588
|
+
...options
|
|
2589
|
+
};
|
|
2590
|
+
if (!this._extensions[PerMessageDeflate.extensionName]) {
|
|
2591
|
+
opts.compress = false;
|
|
2592
|
+
}
|
|
2593
|
+
this._sender.send(data || EMPTY_BUFFER, opts, cb);
|
|
2594
|
+
}
|
|
2595
|
+
/**
|
|
2596
|
+
* Forcibly close the connection.
|
|
2597
|
+
*
|
|
2598
|
+
* @public
|
|
2599
|
+
*/
|
|
2600
|
+
terminate() {
|
|
2601
|
+
if (this.readyState === _WebSocket.CLOSED) return;
|
|
2602
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2603
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
2604
|
+
abortHandshake(this, this._req, msg);
|
|
2605
|
+
return;
|
|
2606
|
+
}
|
|
2607
|
+
if (this._socket) {
|
|
2608
|
+
this._readyState = _WebSocket.CLOSING;
|
|
2609
|
+
this._socket.destroy();
|
|
2610
|
+
}
|
|
2611
|
+
}
|
|
2612
|
+
};
|
|
2613
|
+
Object.defineProperty(WebSocket2, "CONNECTING", {
|
|
2614
|
+
enumerable: true,
|
|
2615
|
+
value: readyStates.indexOf("CONNECTING")
|
|
2616
|
+
});
|
|
2617
|
+
Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
|
|
2618
|
+
enumerable: true,
|
|
2619
|
+
value: readyStates.indexOf("CONNECTING")
|
|
2620
|
+
});
|
|
2621
|
+
Object.defineProperty(WebSocket2, "OPEN", {
|
|
2622
|
+
enumerable: true,
|
|
2623
|
+
value: readyStates.indexOf("OPEN")
|
|
2624
|
+
});
|
|
2625
|
+
Object.defineProperty(WebSocket2.prototype, "OPEN", {
|
|
2626
|
+
enumerable: true,
|
|
2627
|
+
value: readyStates.indexOf("OPEN")
|
|
2628
|
+
});
|
|
2629
|
+
Object.defineProperty(WebSocket2, "CLOSING", {
|
|
2630
|
+
enumerable: true,
|
|
2631
|
+
value: readyStates.indexOf("CLOSING")
|
|
2632
|
+
});
|
|
2633
|
+
Object.defineProperty(WebSocket2.prototype, "CLOSING", {
|
|
2634
|
+
enumerable: true,
|
|
2635
|
+
value: readyStates.indexOf("CLOSING")
|
|
2636
|
+
});
|
|
2637
|
+
Object.defineProperty(WebSocket2, "CLOSED", {
|
|
2638
|
+
enumerable: true,
|
|
2639
|
+
value: readyStates.indexOf("CLOSED")
|
|
2640
|
+
});
|
|
2641
|
+
Object.defineProperty(WebSocket2.prototype, "CLOSED", {
|
|
2642
|
+
enumerable: true,
|
|
2643
|
+
value: readyStates.indexOf("CLOSED")
|
|
2644
|
+
});
|
|
2645
|
+
[
|
|
2646
|
+
"binaryType",
|
|
2647
|
+
"bufferedAmount",
|
|
2648
|
+
"extensions",
|
|
2649
|
+
"isPaused",
|
|
2650
|
+
"protocol",
|
|
2651
|
+
"readyState",
|
|
2652
|
+
"url"
|
|
2653
|
+
].forEach((property) => {
|
|
2654
|
+
Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
|
|
2655
|
+
});
|
|
2656
|
+
["open", "error", "close", "message"].forEach((method) => {
|
|
2657
|
+
Object.defineProperty(WebSocket2.prototype, `on${method}`, {
|
|
2658
|
+
enumerable: true,
|
|
2659
|
+
get() {
|
|
2660
|
+
for (const listener of this.listeners(method)) {
|
|
2661
|
+
if (listener[kForOnEventAttribute]) return listener[kListener];
|
|
2662
|
+
}
|
|
2663
|
+
return null;
|
|
2664
|
+
},
|
|
2665
|
+
set(handler) {
|
|
2666
|
+
for (const listener of this.listeners(method)) {
|
|
2667
|
+
if (listener[kForOnEventAttribute]) {
|
|
2668
|
+
this.removeListener(method, listener);
|
|
2669
|
+
break;
|
|
2670
|
+
}
|
|
2671
|
+
}
|
|
2672
|
+
if (typeof handler !== "function") return;
|
|
2673
|
+
this.addEventListener(method, handler, {
|
|
2674
|
+
[kForOnEventAttribute]: true
|
|
2675
|
+
});
|
|
2676
|
+
}
|
|
2677
|
+
});
|
|
2678
|
+
});
|
|
2679
|
+
WebSocket2.prototype.addEventListener = addEventListener;
|
|
2680
|
+
WebSocket2.prototype.removeEventListener = removeEventListener;
|
|
2681
|
+
module.exports = WebSocket2;
|
|
2682
|
+
function initAsClient(websocket, address, protocols, options) {
|
|
2683
|
+
const opts = {
|
|
2684
|
+
allowSynchronousEvents: true,
|
|
2685
|
+
autoPong: true,
|
|
2686
|
+
closeTimeout: CLOSE_TIMEOUT,
|
|
2687
|
+
protocolVersion: protocolVersions[1],
|
|
2688
|
+
maxPayload: 100 * 1024 * 1024,
|
|
2689
|
+
skipUTF8Validation: false,
|
|
2690
|
+
perMessageDeflate: true,
|
|
2691
|
+
followRedirects: false,
|
|
2692
|
+
maxRedirects: 10,
|
|
2693
|
+
...options,
|
|
2694
|
+
socketPath: void 0,
|
|
2695
|
+
hostname: void 0,
|
|
2696
|
+
protocol: void 0,
|
|
2697
|
+
timeout: void 0,
|
|
2698
|
+
method: "GET",
|
|
2699
|
+
host: void 0,
|
|
2700
|
+
path: void 0,
|
|
2701
|
+
port: void 0
|
|
2702
|
+
};
|
|
2703
|
+
websocket._autoPong = opts.autoPong;
|
|
2704
|
+
websocket._closeTimeout = opts.closeTimeout;
|
|
2705
|
+
if (!protocolVersions.includes(opts.protocolVersion)) {
|
|
2706
|
+
throw new RangeError(
|
|
2707
|
+
`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
|
|
2708
|
+
);
|
|
2709
|
+
}
|
|
2710
|
+
let parsedUrl;
|
|
2711
|
+
if (address instanceof URL) {
|
|
2712
|
+
parsedUrl = address;
|
|
2713
|
+
} else {
|
|
2714
|
+
try {
|
|
2715
|
+
parsedUrl = new URL(address);
|
|
2716
|
+
} catch (e) {
|
|
2717
|
+
throw new SyntaxError(`Invalid URL: ${address}`);
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
if (parsedUrl.protocol === "http:") {
|
|
2721
|
+
parsedUrl.protocol = "ws:";
|
|
2722
|
+
} else if (parsedUrl.protocol === "https:") {
|
|
2723
|
+
parsedUrl.protocol = "wss:";
|
|
2724
|
+
}
|
|
2725
|
+
websocket._url = parsedUrl.href;
|
|
2726
|
+
const isSecure = parsedUrl.protocol === "wss:";
|
|
2727
|
+
const isIpcUrl = parsedUrl.protocol === "ws+unix:";
|
|
2728
|
+
let invalidUrlMessage;
|
|
2729
|
+
if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
|
|
2730
|
+
invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
|
|
2731
|
+
} else if (isIpcUrl && !parsedUrl.pathname) {
|
|
2732
|
+
invalidUrlMessage = "The URL's pathname is empty";
|
|
2733
|
+
} else if (parsedUrl.hash) {
|
|
2734
|
+
invalidUrlMessage = "The URL contains a fragment identifier";
|
|
2735
|
+
}
|
|
2736
|
+
if (invalidUrlMessage) {
|
|
2737
|
+
const err = new SyntaxError(invalidUrlMessage);
|
|
2738
|
+
if (websocket._redirects === 0) {
|
|
2739
|
+
throw err;
|
|
2740
|
+
} else {
|
|
2741
|
+
emitErrorAndClose(websocket, err);
|
|
2742
|
+
return;
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
const defaultPort = isSecure ? 443 : 80;
|
|
2746
|
+
const key = randomBytes(16).toString("base64");
|
|
2747
|
+
const request = isSecure ? https.request : http2.request;
|
|
2748
|
+
const protocolSet = /* @__PURE__ */ new Set();
|
|
2749
|
+
let perMessageDeflate;
|
|
2750
|
+
opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
|
|
2751
|
+
opts.defaultPort = opts.defaultPort || defaultPort;
|
|
2752
|
+
opts.port = parsedUrl.port || defaultPort;
|
|
2753
|
+
opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
|
|
2754
|
+
opts.headers = {
|
|
2755
|
+
...opts.headers,
|
|
2756
|
+
"Sec-WebSocket-Version": opts.protocolVersion,
|
|
2757
|
+
"Sec-WebSocket-Key": key,
|
|
2758
|
+
Connection: "Upgrade",
|
|
2759
|
+
Upgrade: "websocket"
|
|
2760
|
+
};
|
|
2761
|
+
opts.path = parsedUrl.pathname + parsedUrl.search;
|
|
2762
|
+
opts.timeout = opts.handshakeTimeout;
|
|
2763
|
+
if (opts.perMessageDeflate) {
|
|
2764
|
+
perMessageDeflate = new PerMessageDeflate(
|
|
2765
|
+
opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
|
|
2766
|
+
false,
|
|
2767
|
+
opts.maxPayload
|
|
2768
|
+
);
|
|
2769
|
+
opts.headers["Sec-WebSocket-Extensions"] = format({
|
|
2770
|
+
[PerMessageDeflate.extensionName]: perMessageDeflate.offer()
|
|
2771
|
+
});
|
|
2772
|
+
}
|
|
2773
|
+
if (protocols.length) {
|
|
2774
|
+
for (const protocol of protocols) {
|
|
2775
|
+
if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
|
|
2776
|
+
throw new SyntaxError(
|
|
2777
|
+
"An invalid or duplicated subprotocol was specified"
|
|
2778
|
+
);
|
|
2779
|
+
}
|
|
2780
|
+
protocolSet.add(protocol);
|
|
2781
|
+
}
|
|
2782
|
+
opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
|
|
2783
|
+
}
|
|
2784
|
+
if (opts.origin) {
|
|
2785
|
+
if (opts.protocolVersion < 13) {
|
|
2786
|
+
opts.headers["Sec-WebSocket-Origin"] = opts.origin;
|
|
2787
|
+
} else {
|
|
2788
|
+
opts.headers.Origin = opts.origin;
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
if (parsedUrl.username || parsedUrl.password) {
|
|
2792
|
+
opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
|
|
2793
|
+
}
|
|
2794
|
+
if (isIpcUrl) {
|
|
2795
|
+
const parts = opts.path.split(":");
|
|
2796
|
+
opts.socketPath = parts[0];
|
|
2797
|
+
opts.path = parts[1];
|
|
2798
|
+
}
|
|
2799
|
+
let req;
|
|
2800
|
+
if (opts.followRedirects) {
|
|
2801
|
+
if (websocket._redirects === 0) {
|
|
2802
|
+
websocket._originalIpc = isIpcUrl;
|
|
2803
|
+
websocket._originalSecure = isSecure;
|
|
2804
|
+
websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
|
|
2805
|
+
const headers = options && options.headers;
|
|
2806
|
+
options = { ...options, headers: {} };
|
|
2807
|
+
if (headers) {
|
|
2808
|
+
for (const [key2, value] of Object.entries(headers)) {
|
|
2809
|
+
options.headers[key2.toLowerCase()] = value;
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
} else if (websocket.listenerCount("redirect") === 0) {
|
|
2813
|
+
const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
|
|
2814
|
+
if (!isSameHost || websocket._originalSecure && !isSecure) {
|
|
2815
|
+
delete opts.headers.authorization;
|
|
2816
|
+
delete opts.headers.cookie;
|
|
2817
|
+
if (!isSameHost) delete opts.headers.host;
|
|
2818
|
+
opts.auth = void 0;
|
|
2819
|
+
}
|
|
2820
|
+
}
|
|
2821
|
+
if (opts.auth && !options.headers.authorization) {
|
|
2822
|
+
options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
|
|
2823
|
+
}
|
|
2824
|
+
req = websocket._req = request(opts);
|
|
2825
|
+
if (websocket._redirects) {
|
|
2826
|
+
websocket.emit("redirect", websocket.url, req);
|
|
2827
|
+
}
|
|
2828
|
+
} else {
|
|
2829
|
+
req = websocket._req = request(opts);
|
|
2830
|
+
}
|
|
2831
|
+
if (opts.timeout) {
|
|
2832
|
+
req.on("timeout", () => {
|
|
2833
|
+
abortHandshake(websocket, req, "Opening handshake has timed out");
|
|
2834
|
+
});
|
|
2835
|
+
}
|
|
2836
|
+
req.on("error", (err) => {
|
|
2837
|
+
if (req === null || req[kAborted]) return;
|
|
2838
|
+
req = websocket._req = null;
|
|
2839
|
+
emitErrorAndClose(websocket, err);
|
|
2840
|
+
});
|
|
2841
|
+
req.on("response", (res) => {
|
|
2842
|
+
const location = res.headers.location;
|
|
2843
|
+
const statusCode = res.statusCode;
|
|
2844
|
+
if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
|
|
2845
|
+
if (++websocket._redirects > opts.maxRedirects) {
|
|
2846
|
+
abortHandshake(websocket, req, "Maximum redirects exceeded");
|
|
2847
|
+
return;
|
|
2848
|
+
}
|
|
2849
|
+
req.abort();
|
|
2850
|
+
let addr;
|
|
2851
|
+
try {
|
|
2852
|
+
addr = new URL(location, address);
|
|
2853
|
+
} catch (e) {
|
|
2854
|
+
const err = new SyntaxError(`Invalid URL: ${location}`);
|
|
2855
|
+
emitErrorAndClose(websocket, err);
|
|
2856
|
+
return;
|
|
2857
|
+
}
|
|
2858
|
+
initAsClient(websocket, addr, protocols, options);
|
|
2859
|
+
} else if (!websocket.emit("unexpected-response", req, res)) {
|
|
2860
|
+
abortHandshake(
|
|
2861
|
+
websocket,
|
|
2862
|
+
req,
|
|
2863
|
+
`Unexpected server response: ${res.statusCode}`
|
|
2864
|
+
);
|
|
2865
|
+
}
|
|
2866
|
+
});
|
|
2867
|
+
req.on("upgrade", (res, socket, head) => {
|
|
2868
|
+
websocket.emit("upgrade", res);
|
|
2869
|
+
if (websocket.readyState !== WebSocket2.CONNECTING) return;
|
|
2870
|
+
req = websocket._req = null;
|
|
2871
|
+
const upgrade = res.headers.upgrade;
|
|
2872
|
+
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
|
|
2873
|
+
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
2874
|
+
return;
|
|
2875
|
+
}
|
|
2876
|
+
const digest = createHash("sha1").update(key + GUID).digest("base64");
|
|
2877
|
+
if (res.headers["sec-websocket-accept"] !== digest) {
|
|
2878
|
+
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
2879
|
+
return;
|
|
2880
|
+
}
|
|
2881
|
+
const serverProt = res.headers["sec-websocket-protocol"];
|
|
2882
|
+
let protError;
|
|
2883
|
+
if (serverProt !== void 0) {
|
|
2884
|
+
if (!protocolSet.size) {
|
|
2885
|
+
protError = "Server sent a subprotocol but none was requested";
|
|
2886
|
+
} else if (!protocolSet.has(serverProt)) {
|
|
2887
|
+
protError = "Server sent an invalid subprotocol";
|
|
2888
|
+
}
|
|
2889
|
+
} else if (protocolSet.size) {
|
|
2890
|
+
protError = "Server sent no subprotocol";
|
|
2891
|
+
}
|
|
2892
|
+
if (protError) {
|
|
2893
|
+
abortHandshake(websocket, socket, protError);
|
|
2894
|
+
return;
|
|
2895
|
+
}
|
|
2896
|
+
if (serverProt) websocket._protocol = serverProt;
|
|
2897
|
+
const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
|
|
2898
|
+
if (secWebSocketExtensions !== void 0) {
|
|
2899
|
+
if (!perMessageDeflate) {
|
|
2900
|
+
const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
|
|
2901
|
+
abortHandshake(websocket, socket, message);
|
|
2902
|
+
return;
|
|
2903
|
+
}
|
|
2904
|
+
let extensions;
|
|
2905
|
+
try {
|
|
2906
|
+
extensions = parse(secWebSocketExtensions);
|
|
2907
|
+
} catch (err) {
|
|
2908
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
2909
|
+
abortHandshake(websocket, socket, message);
|
|
2910
|
+
return;
|
|
2911
|
+
}
|
|
2912
|
+
const extensionNames = Object.keys(extensions);
|
|
2913
|
+
if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
|
|
2914
|
+
const message = "Server indicated an extension that was not requested";
|
|
2915
|
+
abortHandshake(websocket, socket, message);
|
|
2916
|
+
return;
|
|
2917
|
+
}
|
|
2918
|
+
try {
|
|
2919
|
+
perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
|
|
2920
|
+
} catch (err) {
|
|
2921
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
2922
|
+
abortHandshake(websocket, socket, message);
|
|
2923
|
+
return;
|
|
2924
|
+
}
|
|
2925
|
+
websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
|
|
2926
|
+
}
|
|
2927
|
+
websocket.setSocket(socket, head, {
|
|
2928
|
+
allowSynchronousEvents: opts.allowSynchronousEvents,
|
|
2929
|
+
generateMask: opts.generateMask,
|
|
2930
|
+
maxPayload: opts.maxPayload,
|
|
2931
|
+
skipUTF8Validation: opts.skipUTF8Validation
|
|
2932
|
+
});
|
|
2933
|
+
});
|
|
2934
|
+
if (opts.finishRequest) {
|
|
2935
|
+
opts.finishRequest(req, websocket);
|
|
2936
|
+
} else {
|
|
2937
|
+
req.end();
|
|
2938
|
+
}
|
|
2939
|
+
}
|
|
2940
|
+
function emitErrorAndClose(websocket, err) {
|
|
2941
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
2942
|
+
websocket._errorEmitted = true;
|
|
2943
|
+
websocket.emit("error", err);
|
|
2944
|
+
websocket.emitClose();
|
|
2945
|
+
}
|
|
2946
|
+
function netConnect(options) {
|
|
2947
|
+
options.path = options.socketPath;
|
|
2948
|
+
return net.connect(options);
|
|
2949
|
+
}
|
|
2950
|
+
function tlsConnect(options) {
|
|
2951
|
+
options.path = void 0;
|
|
2952
|
+
if (!options.servername && options.servername !== "") {
|
|
2953
|
+
options.servername = net.isIP(options.host) ? "" : options.host;
|
|
2954
|
+
}
|
|
2955
|
+
return tls.connect(options);
|
|
2956
|
+
}
|
|
2957
|
+
function abortHandshake(websocket, stream, message) {
|
|
2958
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
2959
|
+
const err = new Error(message);
|
|
2960
|
+
Error.captureStackTrace(err, abortHandshake);
|
|
2961
|
+
if (stream.setHeader) {
|
|
2962
|
+
stream[kAborted] = true;
|
|
2963
|
+
stream.abort();
|
|
2964
|
+
if (stream.socket && !stream.socket.destroyed) {
|
|
2965
|
+
stream.socket.destroy();
|
|
2966
|
+
}
|
|
2967
|
+
process.nextTick(emitErrorAndClose, websocket, err);
|
|
2968
|
+
} else {
|
|
2969
|
+
stream.destroy(err);
|
|
2970
|
+
stream.once("error", websocket.emit.bind(websocket, "error"));
|
|
2971
|
+
stream.once("close", websocket.emitClose.bind(websocket));
|
|
2972
|
+
}
|
|
2973
|
+
}
|
|
2974
|
+
function sendAfterClose(websocket, data, cb) {
|
|
2975
|
+
if (data) {
|
|
2976
|
+
const length = isBlob(data) ? data.size : toBuffer(data).length;
|
|
2977
|
+
if (websocket._socket) websocket._sender._bufferedBytes += length;
|
|
2978
|
+
else websocket._bufferedAmount += length;
|
|
2979
|
+
}
|
|
2980
|
+
if (cb) {
|
|
2981
|
+
const err = new Error(
|
|
2982
|
+
`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
|
|
2983
|
+
);
|
|
2984
|
+
process.nextTick(cb, err);
|
|
2985
|
+
}
|
|
2986
|
+
}
|
|
2987
|
+
function receiverOnConclude(code, reason) {
|
|
2988
|
+
const websocket = this[kWebSocket];
|
|
2989
|
+
websocket._closeFrameReceived = true;
|
|
2990
|
+
websocket._closeMessage = reason;
|
|
2991
|
+
websocket._closeCode = code;
|
|
2992
|
+
if (websocket._socket[kWebSocket] === void 0) return;
|
|
2993
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
2994
|
+
process.nextTick(resume, websocket._socket);
|
|
2995
|
+
if (code === 1005) websocket.close();
|
|
2996
|
+
else websocket.close(code, reason);
|
|
2997
|
+
}
|
|
2998
|
+
function receiverOnDrain() {
|
|
2999
|
+
const websocket = this[kWebSocket];
|
|
3000
|
+
if (!websocket.isPaused) websocket._socket.resume();
|
|
3001
|
+
}
|
|
3002
|
+
function receiverOnError(err) {
|
|
3003
|
+
const websocket = this[kWebSocket];
|
|
3004
|
+
if (websocket._socket[kWebSocket] !== void 0) {
|
|
3005
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
3006
|
+
process.nextTick(resume, websocket._socket);
|
|
3007
|
+
websocket.close(err[kStatusCode]);
|
|
3008
|
+
}
|
|
3009
|
+
if (!websocket._errorEmitted) {
|
|
3010
|
+
websocket._errorEmitted = true;
|
|
3011
|
+
websocket.emit("error", err);
|
|
3012
|
+
}
|
|
3013
|
+
}
|
|
3014
|
+
function receiverOnFinish() {
|
|
3015
|
+
this[kWebSocket].emitClose();
|
|
3016
|
+
}
|
|
3017
|
+
function receiverOnMessage(data, isBinary) {
|
|
3018
|
+
this[kWebSocket].emit("message", data, isBinary);
|
|
3019
|
+
}
|
|
3020
|
+
function receiverOnPing(data) {
|
|
3021
|
+
const websocket = this[kWebSocket];
|
|
3022
|
+
if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP2);
|
|
3023
|
+
websocket.emit("ping", data);
|
|
3024
|
+
}
|
|
3025
|
+
function receiverOnPong(data) {
|
|
3026
|
+
this[kWebSocket].emit("pong", data);
|
|
3027
|
+
}
|
|
3028
|
+
function resume(stream) {
|
|
3029
|
+
stream.resume();
|
|
3030
|
+
}
|
|
3031
|
+
function senderOnError(err) {
|
|
3032
|
+
const websocket = this[kWebSocket];
|
|
3033
|
+
if (websocket.readyState === WebSocket2.CLOSED) return;
|
|
3034
|
+
if (websocket.readyState === WebSocket2.OPEN) {
|
|
3035
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3036
|
+
setCloseTimer(websocket);
|
|
3037
|
+
}
|
|
3038
|
+
this._socket.end();
|
|
3039
|
+
if (!websocket._errorEmitted) {
|
|
3040
|
+
websocket._errorEmitted = true;
|
|
3041
|
+
websocket.emit("error", err);
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
function setCloseTimer(websocket) {
|
|
3045
|
+
websocket._closeTimer = setTimeout(
|
|
3046
|
+
websocket._socket.destroy.bind(websocket._socket),
|
|
3047
|
+
websocket._closeTimeout
|
|
3048
|
+
);
|
|
3049
|
+
}
|
|
3050
|
+
function socketOnClose() {
|
|
3051
|
+
const websocket = this[kWebSocket];
|
|
3052
|
+
this.removeListener("close", socketOnClose);
|
|
3053
|
+
this.removeListener("data", socketOnData);
|
|
3054
|
+
this.removeListener("end", socketOnEnd);
|
|
3055
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3056
|
+
if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
|
|
3057
|
+
const chunk = this.read(this._readableState.length);
|
|
3058
|
+
websocket._receiver.write(chunk);
|
|
3059
|
+
}
|
|
3060
|
+
websocket._receiver.end();
|
|
3061
|
+
this[kWebSocket] = void 0;
|
|
3062
|
+
clearTimeout(websocket._closeTimer);
|
|
3063
|
+
if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
|
|
3064
|
+
websocket.emitClose();
|
|
3065
|
+
} else {
|
|
3066
|
+
websocket._receiver.on("error", receiverOnFinish);
|
|
3067
|
+
websocket._receiver.on("finish", receiverOnFinish);
|
|
3068
|
+
}
|
|
3069
|
+
}
|
|
3070
|
+
function socketOnData(chunk) {
|
|
3071
|
+
if (!this[kWebSocket]._receiver.write(chunk)) {
|
|
3072
|
+
this.pause();
|
|
3073
|
+
}
|
|
3074
|
+
}
|
|
3075
|
+
function socketOnEnd() {
|
|
3076
|
+
const websocket = this[kWebSocket];
|
|
3077
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3078
|
+
websocket._receiver.end();
|
|
3079
|
+
this.end();
|
|
3080
|
+
}
|
|
3081
|
+
function socketOnError() {
|
|
3082
|
+
const websocket = this[kWebSocket];
|
|
3083
|
+
this.removeListener("error", socketOnError);
|
|
3084
|
+
this.on("error", NOOP2);
|
|
3085
|
+
if (websocket) {
|
|
3086
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3087
|
+
this.destroy();
|
|
3088
|
+
}
|
|
3089
|
+
}
|
|
3090
|
+
}
|
|
3091
|
+
});
|
|
3092
|
+
|
|
3093
|
+
// ../../node_modules/ws/lib/stream.js
|
|
3094
|
+
var require_stream = __commonJS({
|
|
3095
|
+
"../../node_modules/ws/lib/stream.js"(exports, module) {
|
|
3096
|
+
"use strict";
|
|
3097
|
+
var WebSocket2 = require_websocket();
|
|
3098
|
+
var { Duplex } = __require("stream");
|
|
3099
|
+
function emitClose(stream) {
|
|
3100
|
+
stream.emit("close");
|
|
3101
|
+
}
|
|
3102
|
+
function duplexOnEnd() {
|
|
3103
|
+
if (!this.destroyed && this._writableState.finished) {
|
|
3104
|
+
this.destroy();
|
|
3105
|
+
}
|
|
3106
|
+
}
|
|
3107
|
+
function duplexOnError(err) {
|
|
3108
|
+
this.removeListener("error", duplexOnError);
|
|
3109
|
+
this.destroy();
|
|
3110
|
+
if (this.listenerCount("error") === 0) {
|
|
3111
|
+
this.emit("error", err);
|
|
3112
|
+
}
|
|
3113
|
+
}
|
|
3114
|
+
function createWebSocketStream2(ws, options) {
|
|
3115
|
+
let terminateOnDestroy = true;
|
|
3116
|
+
const duplex = new Duplex({
|
|
3117
|
+
...options,
|
|
3118
|
+
autoDestroy: false,
|
|
3119
|
+
emitClose: false,
|
|
3120
|
+
objectMode: false,
|
|
3121
|
+
writableObjectMode: false
|
|
3122
|
+
});
|
|
3123
|
+
ws.on("message", function message(msg, isBinary) {
|
|
3124
|
+
const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
|
|
3125
|
+
if (!duplex.push(data)) ws.pause();
|
|
3126
|
+
});
|
|
3127
|
+
ws.once("error", function error(err) {
|
|
3128
|
+
if (duplex.destroyed) return;
|
|
3129
|
+
terminateOnDestroy = false;
|
|
3130
|
+
duplex.destroy(err);
|
|
3131
|
+
});
|
|
3132
|
+
ws.once("close", function close() {
|
|
3133
|
+
if (duplex.destroyed) return;
|
|
3134
|
+
duplex.push(null);
|
|
3135
|
+
});
|
|
3136
|
+
duplex._destroy = function(err, callback) {
|
|
3137
|
+
if (ws.readyState === ws.CLOSED) {
|
|
3138
|
+
callback(err);
|
|
3139
|
+
process.nextTick(emitClose, duplex);
|
|
3140
|
+
return;
|
|
3141
|
+
}
|
|
3142
|
+
let called = false;
|
|
3143
|
+
ws.once("error", function error(err2) {
|
|
3144
|
+
called = true;
|
|
3145
|
+
callback(err2);
|
|
3146
|
+
});
|
|
3147
|
+
ws.once("close", function close() {
|
|
3148
|
+
if (!called) callback(err);
|
|
3149
|
+
process.nextTick(emitClose, duplex);
|
|
3150
|
+
});
|
|
3151
|
+
if (terminateOnDestroy) ws.terminate();
|
|
3152
|
+
};
|
|
3153
|
+
duplex._final = function(callback) {
|
|
3154
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
3155
|
+
ws.once("open", function open() {
|
|
3156
|
+
duplex._final(callback);
|
|
3157
|
+
});
|
|
3158
|
+
return;
|
|
3159
|
+
}
|
|
3160
|
+
if (ws._socket === null) return;
|
|
3161
|
+
if (ws._socket._writableState.finished) {
|
|
3162
|
+
callback();
|
|
3163
|
+
if (duplex._readableState.endEmitted) duplex.destroy();
|
|
3164
|
+
} else {
|
|
3165
|
+
ws._socket.once("finish", function finish() {
|
|
3166
|
+
callback();
|
|
3167
|
+
});
|
|
3168
|
+
ws.close();
|
|
3169
|
+
}
|
|
3170
|
+
};
|
|
3171
|
+
duplex._read = function() {
|
|
3172
|
+
if (ws.isPaused) ws.resume();
|
|
3173
|
+
};
|
|
3174
|
+
duplex._write = function(chunk, encoding, callback) {
|
|
3175
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
3176
|
+
ws.once("open", function open() {
|
|
3177
|
+
duplex._write(chunk, encoding, callback);
|
|
3178
|
+
});
|
|
3179
|
+
return;
|
|
3180
|
+
}
|
|
3181
|
+
ws.send(chunk, callback);
|
|
3182
|
+
};
|
|
3183
|
+
duplex.on("end", duplexOnEnd);
|
|
3184
|
+
duplex.on("error", duplexOnError);
|
|
3185
|
+
return duplex;
|
|
3186
|
+
}
|
|
3187
|
+
module.exports = createWebSocketStream2;
|
|
3188
|
+
}
|
|
3189
|
+
});
|
|
3190
|
+
|
|
3191
|
+
// ../../node_modules/ws/lib/subprotocol.js
|
|
3192
|
+
var require_subprotocol = __commonJS({
|
|
3193
|
+
"../../node_modules/ws/lib/subprotocol.js"(exports, module) {
|
|
3194
|
+
"use strict";
|
|
3195
|
+
var { tokenChars } = require_validation();
|
|
3196
|
+
function parse(header) {
|
|
3197
|
+
const protocols = /* @__PURE__ */ new Set();
|
|
3198
|
+
let start = -1;
|
|
3199
|
+
let end = -1;
|
|
3200
|
+
let i = 0;
|
|
3201
|
+
for (i; i < header.length; i++) {
|
|
3202
|
+
const code = header.charCodeAt(i);
|
|
3203
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
3204
|
+
if (start === -1) start = i;
|
|
3205
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
3206
|
+
if (end === -1 && start !== -1) end = i;
|
|
3207
|
+
} else if (code === 44) {
|
|
3208
|
+
if (start === -1) {
|
|
3209
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
3210
|
+
}
|
|
3211
|
+
if (end === -1) end = i;
|
|
3212
|
+
const protocol2 = header.slice(start, end);
|
|
3213
|
+
if (protocols.has(protocol2)) {
|
|
3214
|
+
throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
|
|
3215
|
+
}
|
|
3216
|
+
protocols.add(protocol2);
|
|
3217
|
+
start = end = -1;
|
|
3218
|
+
} else {
|
|
3219
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
3220
|
+
}
|
|
3221
|
+
}
|
|
3222
|
+
if (start === -1 || end !== -1) {
|
|
3223
|
+
throw new SyntaxError("Unexpected end of input");
|
|
3224
|
+
}
|
|
3225
|
+
const protocol = header.slice(start, i);
|
|
3226
|
+
if (protocols.has(protocol)) {
|
|
3227
|
+
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
|
|
3228
|
+
}
|
|
3229
|
+
protocols.add(protocol);
|
|
3230
|
+
return protocols;
|
|
3231
|
+
}
|
|
3232
|
+
module.exports = { parse };
|
|
3233
|
+
}
|
|
3234
|
+
});
|
|
3235
|
+
|
|
3236
|
+
// ../../node_modules/ws/lib/websocket-server.js
|
|
3237
|
+
var require_websocket_server = __commonJS({
|
|
3238
|
+
"../../node_modules/ws/lib/websocket-server.js"(exports, module) {
|
|
3239
|
+
"use strict";
|
|
3240
|
+
var EventEmitter2 = __require("events");
|
|
3241
|
+
var http2 = __require("http");
|
|
3242
|
+
var { Duplex } = __require("stream");
|
|
3243
|
+
var { createHash } = __require("crypto");
|
|
3244
|
+
var extension = require_extension();
|
|
3245
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
3246
|
+
var subprotocol = require_subprotocol();
|
|
3247
|
+
var WebSocket2 = require_websocket();
|
|
3248
|
+
var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
|
|
3249
|
+
var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
|
|
3250
|
+
var RUNNING = 0;
|
|
3251
|
+
var CLOSING = 1;
|
|
3252
|
+
var CLOSED = 2;
|
|
3253
|
+
var WebSocketServer2 = class extends EventEmitter2 {
|
|
3254
|
+
/**
|
|
3255
|
+
* Create a `WebSocketServer` instance.
|
|
3256
|
+
*
|
|
3257
|
+
* @param {Object} options Configuration options
|
|
3258
|
+
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
|
|
3259
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
3260
|
+
* multiple times in the same tick
|
|
3261
|
+
* @param {Boolean} [options.autoPong=true] Specifies whether or not to
|
|
3262
|
+
* automatically send a pong in response to a ping
|
|
3263
|
+
* @param {Number} [options.backlog=511] The maximum length of the queue of
|
|
3264
|
+
* pending connections
|
|
3265
|
+
* @param {Boolean} [options.clientTracking=true] Specifies whether or not to
|
|
3266
|
+
* track clients
|
|
3267
|
+
* @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
|
|
3268
|
+
* wait for the closing handshake to finish after `websocket.close()` is
|
|
3269
|
+
* called
|
|
3270
|
+
* @param {Function} [options.handleProtocols] A hook to handle protocols
|
|
3271
|
+
* @param {String} [options.host] The hostname where to bind the server
|
|
3272
|
+
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
|
|
3273
|
+
* size
|
|
3274
|
+
* @param {Boolean} [options.noServer=false] Enable no server mode
|
|
3275
|
+
* @param {String} [options.path] Accept only connections matching this path
|
|
3276
|
+
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
|
|
3277
|
+
* permessage-deflate
|
|
3278
|
+
* @param {Number} [options.port] The port where to bind the server
|
|
3279
|
+
* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
|
|
3280
|
+
* server to use
|
|
3281
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
3282
|
+
* not to skip UTF-8 validation for text and close messages
|
|
3283
|
+
* @param {Function} [options.verifyClient] A hook to reject connections
|
|
3284
|
+
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
|
|
3285
|
+
* class to use. It must be the `WebSocket` class or class that extends it
|
|
3286
|
+
* @param {Function} [callback] A listener for the `listening` event
|
|
3287
|
+
*/
|
|
3288
|
+
constructor(options, callback) {
|
|
3289
|
+
super();
|
|
3290
|
+
options = {
|
|
3291
|
+
allowSynchronousEvents: true,
|
|
3292
|
+
autoPong: true,
|
|
3293
|
+
maxPayload: 100 * 1024 * 1024,
|
|
3294
|
+
skipUTF8Validation: false,
|
|
3295
|
+
perMessageDeflate: false,
|
|
3296
|
+
handleProtocols: null,
|
|
3297
|
+
clientTracking: true,
|
|
3298
|
+
closeTimeout: CLOSE_TIMEOUT,
|
|
3299
|
+
verifyClient: null,
|
|
3300
|
+
noServer: false,
|
|
3301
|
+
backlog: null,
|
|
3302
|
+
// use default (511 as implemented in net.js)
|
|
3303
|
+
server: null,
|
|
3304
|
+
host: null,
|
|
3305
|
+
path: null,
|
|
3306
|
+
port: null,
|
|
3307
|
+
WebSocket: WebSocket2,
|
|
3308
|
+
...options
|
|
3309
|
+
};
|
|
3310
|
+
if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
|
|
3311
|
+
throw new TypeError(
|
|
3312
|
+
'One and only one of the "port", "server", or "noServer" options must be specified'
|
|
3313
|
+
);
|
|
3314
|
+
}
|
|
3315
|
+
if (options.port != null) {
|
|
3316
|
+
this._server = http2.createServer((req, res) => {
|
|
3317
|
+
const body = http2.STATUS_CODES[426];
|
|
3318
|
+
res.writeHead(426, {
|
|
3319
|
+
"Content-Length": body.length,
|
|
3320
|
+
"Content-Type": "text/plain"
|
|
3321
|
+
});
|
|
3322
|
+
res.end(body);
|
|
3323
|
+
});
|
|
3324
|
+
this._server.listen(
|
|
3325
|
+
options.port,
|
|
3326
|
+
options.host,
|
|
3327
|
+
options.backlog,
|
|
3328
|
+
callback
|
|
3329
|
+
);
|
|
3330
|
+
} else if (options.server) {
|
|
3331
|
+
this._server = options.server;
|
|
3332
|
+
}
|
|
3333
|
+
if (this._server) {
|
|
3334
|
+
const emitConnection = this.emit.bind(this, "connection");
|
|
3335
|
+
this._removeListeners = addListeners(this._server, {
|
|
3336
|
+
listening: this.emit.bind(this, "listening"),
|
|
3337
|
+
error: this.emit.bind(this, "error"),
|
|
3338
|
+
upgrade: (req, socket, head) => {
|
|
3339
|
+
this.handleUpgrade(req, socket, head, emitConnection);
|
|
3340
|
+
}
|
|
3341
|
+
});
|
|
3342
|
+
}
|
|
3343
|
+
if (options.perMessageDeflate === true) options.perMessageDeflate = {};
|
|
3344
|
+
if (options.clientTracking) {
|
|
3345
|
+
this.clients = /* @__PURE__ */ new Set();
|
|
3346
|
+
this._shouldEmitClose = false;
|
|
3347
|
+
}
|
|
3348
|
+
this.options = options;
|
|
3349
|
+
this._state = RUNNING;
|
|
3350
|
+
}
|
|
3351
|
+
/**
|
|
3352
|
+
* Returns the bound address, the address family name, and port of the server
|
|
3353
|
+
* as reported by the operating system if listening on an IP socket.
|
|
3354
|
+
* If the server is listening on a pipe or UNIX domain socket, the name is
|
|
3355
|
+
* returned as a string.
|
|
3356
|
+
*
|
|
3357
|
+
* @return {(Object|String|null)} The address of the server
|
|
3358
|
+
* @public
|
|
3359
|
+
*/
|
|
3360
|
+
address() {
|
|
3361
|
+
if (this.options.noServer) {
|
|
3362
|
+
throw new Error('The server is operating in "noServer" mode');
|
|
3363
|
+
}
|
|
3364
|
+
if (!this._server) return null;
|
|
3365
|
+
return this._server.address();
|
|
3366
|
+
}
|
|
3367
|
+
/**
|
|
3368
|
+
* Stop the server from accepting new connections and emit the `'close'` event
|
|
3369
|
+
* when all existing connections are closed.
|
|
3370
|
+
*
|
|
3371
|
+
* @param {Function} [cb] A one-time listener for the `'close'` event
|
|
3372
|
+
* @public
|
|
3373
|
+
*/
|
|
3374
|
+
close(cb) {
|
|
3375
|
+
if (this._state === CLOSED) {
|
|
3376
|
+
if (cb) {
|
|
3377
|
+
this.once("close", () => {
|
|
3378
|
+
cb(new Error("The server is not running"));
|
|
3379
|
+
});
|
|
3380
|
+
}
|
|
3381
|
+
process.nextTick(emitClose, this);
|
|
3382
|
+
return;
|
|
3383
|
+
}
|
|
3384
|
+
if (cb) this.once("close", cb);
|
|
3385
|
+
if (this._state === CLOSING) return;
|
|
3386
|
+
this._state = CLOSING;
|
|
3387
|
+
if (this.options.noServer || this.options.server) {
|
|
3388
|
+
if (this._server) {
|
|
3389
|
+
this._removeListeners();
|
|
3390
|
+
this._removeListeners = this._server = null;
|
|
3391
|
+
}
|
|
3392
|
+
if (this.clients) {
|
|
3393
|
+
if (!this.clients.size) {
|
|
3394
|
+
process.nextTick(emitClose, this);
|
|
3395
|
+
} else {
|
|
3396
|
+
this._shouldEmitClose = true;
|
|
3397
|
+
}
|
|
3398
|
+
} else {
|
|
3399
|
+
process.nextTick(emitClose, this);
|
|
3400
|
+
}
|
|
3401
|
+
} else {
|
|
3402
|
+
const server = this._server;
|
|
3403
|
+
this._removeListeners();
|
|
3404
|
+
this._removeListeners = this._server = null;
|
|
3405
|
+
server.close(() => {
|
|
3406
|
+
emitClose(this);
|
|
3407
|
+
});
|
|
3408
|
+
}
|
|
3409
|
+
}
|
|
3410
|
+
/**
|
|
3411
|
+
* See if a given request should be handled by this server instance.
|
|
3412
|
+
*
|
|
3413
|
+
* @param {http.IncomingMessage} req Request object to inspect
|
|
3414
|
+
* @return {Boolean} `true` if the request is valid, else `false`
|
|
3415
|
+
* @public
|
|
3416
|
+
*/
|
|
3417
|
+
shouldHandle(req) {
|
|
3418
|
+
if (this.options.path) {
|
|
3419
|
+
const index = req.url.indexOf("?");
|
|
3420
|
+
const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
|
|
3421
|
+
if (pathname !== this.options.path) return false;
|
|
3422
|
+
}
|
|
3423
|
+
return true;
|
|
3424
|
+
}
|
|
3425
|
+
/**
|
|
3426
|
+
* Handle a HTTP Upgrade request.
|
|
3427
|
+
*
|
|
3428
|
+
* @param {http.IncomingMessage} req The request object
|
|
3429
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
3430
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
3431
|
+
* @param {Function} cb Callback
|
|
3432
|
+
* @public
|
|
3433
|
+
*/
|
|
3434
|
+
handleUpgrade(req, socket, head, cb) {
|
|
3435
|
+
socket.on("error", socketOnError);
|
|
3436
|
+
const key = req.headers["sec-websocket-key"];
|
|
3437
|
+
const upgrade = req.headers.upgrade;
|
|
3438
|
+
const version = +req.headers["sec-websocket-version"];
|
|
3439
|
+
if (req.method !== "GET") {
|
|
3440
|
+
const message = "Invalid HTTP method";
|
|
3441
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
|
|
3442
|
+
return;
|
|
3443
|
+
}
|
|
3444
|
+
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
|
|
3445
|
+
const message = "Invalid Upgrade header";
|
|
3446
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3447
|
+
return;
|
|
3448
|
+
}
|
|
3449
|
+
if (key === void 0 || !keyRegex.test(key)) {
|
|
3450
|
+
const message = "Missing or invalid Sec-WebSocket-Key header";
|
|
3451
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3452
|
+
return;
|
|
3453
|
+
}
|
|
3454
|
+
if (version !== 13 && version !== 8) {
|
|
3455
|
+
const message = "Missing or invalid Sec-WebSocket-Version header";
|
|
3456
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
|
|
3457
|
+
"Sec-WebSocket-Version": "13, 8"
|
|
3458
|
+
});
|
|
3459
|
+
return;
|
|
3460
|
+
}
|
|
3461
|
+
if (!this.shouldHandle(req)) {
|
|
3462
|
+
abortHandshake(socket, 400);
|
|
3463
|
+
return;
|
|
3464
|
+
}
|
|
3465
|
+
const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
|
|
3466
|
+
let protocols = /* @__PURE__ */ new Set();
|
|
3467
|
+
if (secWebSocketProtocol !== void 0) {
|
|
3468
|
+
try {
|
|
3469
|
+
protocols = subprotocol.parse(secWebSocketProtocol);
|
|
3470
|
+
} catch (err) {
|
|
3471
|
+
const message = "Invalid Sec-WebSocket-Protocol header";
|
|
3472
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3473
|
+
return;
|
|
3474
|
+
}
|
|
3475
|
+
}
|
|
3476
|
+
const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
|
|
3477
|
+
const extensions = {};
|
|
3478
|
+
if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
|
|
3479
|
+
const perMessageDeflate = new PerMessageDeflate(
|
|
3480
|
+
this.options.perMessageDeflate,
|
|
3481
|
+
true,
|
|
3482
|
+
this.options.maxPayload
|
|
3483
|
+
);
|
|
3484
|
+
try {
|
|
3485
|
+
const offers = extension.parse(secWebSocketExtensions);
|
|
3486
|
+
if (offers[PerMessageDeflate.extensionName]) {
|
|
3487
|
+
perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
|
|
3488
|
+
extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
|
|
3489
|
+
}
|
|
3490
|
+
} catch (err) {
|
|
3491
|
+
const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
|
|
3492
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3493
|
+
return;
|
|
3494
|
+
}
|
|
3495
|
+
}
|
|
3496
|
+
if (this.options.verifyClient) {
|
|
3497
|
+
const info = {
|
|
3498
|
+
origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
|
|
3499
|
+
secure: !!(req.socket.authorized || req.socket.encrypted),
|
|
3500
|
+
req
|
|
3501
|
+
};
|
|
3502
|
+
if (this.options.verifyClient.length === 2) {
|
|
3503
|
+
this.options.verifyClient(info, (verified, code, message, headers) => {
|
|
3504
|
+
if (!verified) {
|
|
3505
|
+
return abortHandshake(socket, code || 401, message, headers);
|
|
3506
|
+
}
|
|
3507
|
+
this.completeUpgrade(
|
|
3508
|
+
extensions,
|
|
3509
|
+
key,
|
|
3510
|
+
protocols,
|
|
3511
|
+
req,
|
|
3512
|
+
socket,
|
|
3513
|
+
head,
|
|
3514
|
+
cb
|
|
3515
|
+
);
|
|
3516
|
+
});
|
|
3517
|
+
return;
|
|
3518
|
+
}
|
|
3519
|
+
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
|
|
3520
|
+
}
|
|
3521
|
+
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
|
|
3522
|
+
}
|
|
3523
|
+
/**
|
|
3524
|
+
* Upgrade the connection to WebSocket.
|
|
3525
|
+
*
|
|
3526
|
+
* @param {Object} extensions The accepted extensions
|
|
3527
|
+
* @param {String} key The value of the `Sec-WebSocket-Key` header
|
|
3528
|
+
* @param {Set} protocols The subprotocols
|
|
3529
|
+
* @param {http.IncomingMessage} req The request object
|
|
3530
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
3531
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
3532
|
+
* @param {Function} cb Callback
|
|
3533
|
+
* @throws {Error} If called more than once with the same socket
|
|
3534
|
+
* @private
|
|
3535
|
+
*/
|
|
3536
|
+
completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
|
|
3537
|
+
if (!socket.readable || !socket.writable) return socket.destroy();
|
|
3538
|
+
if (socket[kWebSocket]) {
|
|
3539
|
+
throw new Error(
|
|
3540
|
+
"server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
|
|
3541
|
+
);
|
|
3542
|
+
}
|
|
3543
|
+
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
3544
|
+
const digest = createHash("sha1").update(key + GUID).digest("base64");
|
|
3545
|
+
const headers = [
|
|
3546
|
+
"HTTP/1.1 101 Switching Protocols",
|
|
3547
|
+
"Upgrade: websocket",
|
|
3548
|
+
"Connection: Upgrade",
|
|
3549
|
+
`Sec-WebSocket-Accept: ${digest}`
|
|
3550
|
+
];
|
|
3551
|
+
const ws = new this.options.WebSocket(null, void 0, this.options);
|
|
3552
|
+
if (protocols.size) {
|
|
3553
|
+
const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
|
|
3554
|
+
if (protocol) {
|
|
3555
|
+
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
|
|
3556
|
+
ws._protocol = protocol;
|
|
3557
|
+
}
|
|
3558
|
+
}
|
|
3559
|
+
if (extensions[PerMessageDeflate.extensionName]) {
|
|
3560
|
+
const params = extensions[PerMessageDeflate.extensionName].params;
|
|
3561
|
+
const value = extension.format({
|
|
3562
|
+
[PerMessageDeflate.extensionName]: [params]
|
|
3563
|
+
});
|
|
3564
|
+
headers.push(`Sec-WebSocket-Extensions: ${value}`);
|
|
3565
|
+
ws._extensions = extensions;
|
|
3566
|
+
}
|
|
3567
|
+
this.emit("headers", headers, req);
|
|
3568
|
+
socket.write(headers.concat("\r\n").join("\r\n"));
|
|
3569
|
+
socket.removeListener("error", socketOnError);
|
|
3570
|
+
ws.setSocket(socket, head, {
|
|
3571
|
+
allowSynchronousEvents: this.options.allowSynchronousEvents,
|
|
3572
|
+
maxPayload: this.options.maxPayload,
|
|
3573
|
+
skipUTF8Validation: this.options.skipUTF8Validation
|
|
3574
|
+
});
|
|
3575
|
+
if (this.clients) {
|
|
3576
|
+
this.clients.add(ws);
|
|
3577
|
+
ws.on("close", () => {
|
|
3578
|
+
this.clients.delete(ws);
|
|
3579
|
+
if (this._shouldEmitClose && !this.clients.size) {
|
|
3580
|
+
process.nextTick(emitClose, this);
|
|
3581
|
+
}
|
|
3582
|
+
});
|
|
3583
|
+
}
|
|
3584
|
+
cb(ws, req);
|
|
3585
|
+
}
|
|
3586
|
+
};
|
|
3587
|
+
module.exports = WebSocketServer2;
|
|
3588
|
+
function addListeners(server, map) {
|
|
3589
|
+
for (const event of Object.keys(map)) server.on(event, map[event]);
|
|
3590
|
+
return function removeListeners() {
|
|
3591
|
+
for (const event of Object.keys(map)) {
|
|
3592
|
+
server.removeListener(event, map[event]);
|
|
3593
|
+
}
|
|
3594
|
+
};
|
|
3595
|
+
}
|
|
3596
|
+
function emitClose(server) {
|
|
3597
|
+
server._state = CLOSED;
|
|
3598
|
+
server.emit("close");
|
|
3599
|
+
}
|
|
3600
|
+
function socketOnError() {
|
|
3601
|
+
this.destroy();
|
|
3602
|
+
}
|
|
3603
|
+
function abortHandshake(socket, code, message, headers) {
|
|
3604
|
+
message = message || http2.STATUS_CODES[code];
|
|
3605
|
+
headers = {
|
|
3606
|
+
Connection: "close",
|
|
3607
|
+
"Content-Type": "text/html",
|
|
3608
|
+
"Content-Length": Buffer.byteLength(message),
|
|
3609
|
+
...headers
|
|
3610
|
+
};
|
|
3611
|
+
socket.once("finish", socket.destroy);
|
|
3612
|
+
socket.end(
|
|
3613
|
+
`HTTP/1.1 ${code} ${http2.STATUS_CODES[code]}\r
|
|
3614
|
+
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
|
|
3615
|
+
);
|
|
3616
|
+
}
|
|
3617
|
+
function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
|
|
3618
|
+
if (server.listenerCount("wsClientError")) {
|
|
3619
|
+
const err = new Error(message);
|
|
3620
|
+
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
|
|
3621
|
+
server.emit("wsClientError", err, socket, req);
|
|
3622
|
+
} else {
|
|
3623
|
+
abortHandshake(socket, code, message, headers);
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
}
|
|
3627
|
+
});
|
|
3628
|
+
|
|
11
3629
|
// ../../node_modules/ms/index.js
|
|
12
3630
|
var require_ms = __commonJS({
|
|
13
3631
|
"../../node_modules/ms/index.js"(exports, module) {
|
|
@@ -761,10 +4379,20 @@ var require_dist2 = __commonJS({
|
|
|
761
4379
|
|
|
762
4380
|
// ../sentinel/dist/server/index.js
|
|
763
4381
|
import express from "express";
|
|
4382
|
+
import * as http from "http";
|
|
764
4383
|
import * as path3 from "path";
|
|
765
4384
|
import * as fs2 from "fs";
|
|
766
4385
|
import { fileURLToPath } from "url";
|
|
767
4386
|
import chalk3 from "chalk";
|
|
4387
|
+
|
|
4388
|
+
// ../../node_modules/ws/wrapper.mjs
|
|
4389
|
+
var import_stream = __toESM(require_stream(), 1);
|
|
4390
|
+
var import_receiver = __toESM(require_receiver(), 1);
|
|
4391
|
+
var import_sender = __toESM(require_sender(), 1);
|
|
4392
|
+
var import_websocket = __toESM(require_websocket(), 1);
|
|
4393
|
+
var import_websocket_server = __toESM(require_websocket_server(), 1);
|
|
4394
|
+
|
|
4395
|
+
// ../sentinel/dist/server/index.js
|
|
768
4396
|
import { Router } from "express";
|
|
769
4397
|
import chalk2 from "chalk";
|
|
770
4398
|
import * as fs from "fs";
|
|
@@ -5320,6 +8948,10 @@ var esm_default = gitInstanceFactory;
|
|
|
5320
8948
|
import * as path2 from "path";
|
|
5321
8949
|
import { Router as Router4 } from "express";
|
|
5322
8950
|
import { Router as Router5 } from "express";
|
|
8951
|
+
import { Router as Router6 } from "express";
|
|
8952
|
+
import { Router as Router7 } from "express";
|
|
8953
|
+
import { Router as Router8 } from "express";
|
|
8954
|
+
import { Router as Router9 } from "express";
|
|
5323
8955
|
var LOG_LEVEL = process.env.SENTINEL_LOG_LEVEL || process.env.LOG_LEVEL || "info";
|
|
5324
8956
|
var LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
5325
8957
|
function shouldLog(level) {
|
|
@@ -5407,7 +9039,7 @@ async function loadParadigmConfig(projectDir) {
|
|
|
5407
9039
|
}
|
|
5408
9040
|
async function loadWithPremiseCore(projectDir) {
|
|
5409
9041
|
try {
|
|
5410
|
-
const { aggregateFromDirectory } = await import("./dist-
|
|
9042
|
+
const { aggregateFromDirectory } = await import("./dist-AG5JNIZU-XSEZ2LLK.js");
|
|
5411
9043
|
log.flow("load-symbols").info("Using premise-core aggregator", { path: projectDir });
|
|
5412
9044
|
const result = await aggregateFromDirectory(projectDir);
|
|
5413
9045
|
const counts = {};
|
|
@@ -6044,6 +9676,441 @@ function createPatternsRouter(_projectDir) {
|
|
|
6044
9676
|
});
|
|
6045
9677
|
return router;
|
|
6046
9678
|
}
|
|
9679
|
+
function inferSymbolType(symbol) {
|
|
9680
|
+
if (symbol.startsWith("#")) return "component";
|
|
9681
|
+
if (symbol.startsWith("^")) return "gate";
|
|
9682
|
+
if (symbol.startsWith("!")) return "signal";
|
|
9683
|
+
if (symbol.startsWith("$")) return "flow";
|
|
9684
|
+
if (symbol.startsWith("~")) return "aspect";
|
|
9685
|
+
return "raw";
|
|
9686
|
+
}
|
|
9687
|
+
function validateSymbol(symbol, index) {
|
|
9688
|
+
const entry = index.find((e) => e.symbol === symbol);
|
|
9689
|
+
if (entry) return { known: true };
|
|
9690
|
+
const symbolName = symbol.replace(/^[#^!$~]/, "");
|
|
9691
|
+
let bestMatch;
|
|
9692
|
+
let bestScore = 0;
|
|
9693
|
+
for (const e of index) {
|
|
9694
|
+
const eName = e.symbol.replace(/^[#^!$~]/, "");
|
|
9695
|
+
let shared = 0;
|
|
9696
|
+
for (let i = 0; i < Math.min(symbolName.length, eName.length); i++) {
|
|
9697
|
+
if (symbolName[i] === eName[i]) shared++;
|
|
9698
|
+
else break;
|
|
9699
|
+
}
|
|
9700
|
+
const score = shared / Math.max(symbolName.length, eName.length);
|
|
9701
|
+
if (score > bestScore && score > 0.5) {
|
|
9702
|
+
bestScore = score;
|
|
9703
|
+
bestMatch = e.symbol;
|
|
9704
|
+
}
|
|
9705
|
+
}
|
|
9706
|
+
return { known: false, suggestion: bestMatch };
|
|
9707
|
+
}
|
|
9708
|
+
function autoPromoteToIncident(entry, storage) {
|
|
9709
|
+
try {
|
|
9710
|
+
const symbolType = inferSymbolType(entry.symbol);
|
|
9711
|
+
const symbols = {};
|
|
9712
|
+
if (symbolType === "component") symbols.component = entry.symbol;
|
|
9713
|
+
else if (symbolType === "gate") symbols.gate = entry.symbol;
|
|
9714
|
+
else if (symbolType === "signal") symbols.signal = entry.symbol;
|
|
9715
|
+
else if (symbolType === "flow") symbols.flow = entry.symbol;
|
|
9716
|
+
else symbols.component = entry.symbol;
|
|
9717
|
+
storage.recordIncident({
|
|
9718
|
+
error: {
|
|
9719
|
+
message: entry.message,
|
|
9720
|
+
type: "LogError"
|
|
9721
|
+
},
|
|
9722
|
+
symbols,
|
|
9723
|
+
environment: entry.environment || "unknown",
|
|
9724
|
+
service: entry.service
|
|
9725
|
+
});
|
|
9726
|
+
} catch {
|
|
9727
|
+
}
|
|
9728
|
+
}
|
|
9729
|
+
var insertsSincePrune = 0;
|
|
9730
|
+
function createLogsRouter(options) {
|
|
9731
|
+
const router = Router6();
|
|
9732
|
+
const { storage, serverConfig, onLogReceived, symbolIndex } = options;
|
|
9733
|
+
router.post("/", async (req, res) => {
|
|
9734
|
+
try {
|
|
9735
|
+
const body = req.body;
|
|
9736
|
+
let entries;
|
|
9737
|
+
if (Array.isArray(body.entries)) {
|
|
9738
|
+
entries = body.entries;
|
|
9739
|
+
} else if (body.level && body.symbol && body.message && body.service) {
|
|
9740
|
+
entries = [body];
|
|
9741
|
+
} else {
|
|
9742
|
+
res.status(400).json({ error: "Expected {entries: [...]} or a single log entry with level, symbol, message, service" });
|
|
9743
|
+
return;
|
|
9744
|
+
}
|
|
9745
|
+
if (entries.length > serverConfig.maxBatchSize) {
|
|
9746
|
+
res.status(413).json({
|
|
9747
|
+
error: `Batch too large: ${entries.length} entries, max ${serverConfig.maxBatchSize}`
|
|
9748
|
+
});
|
|
9749
|
+
return;
|
|
9750
|
+
}
|
|
9751
|
+
for (let i = 0; i < entries.length; i++) {
|
|
9752
|
+
const e = entries[i];
|
|
9753
|
+
if (!e.level || !e.symbol || !e.message || !e.service) {
|
|
9754
|
+
res.status(400).json({
|
|
9755
|
+
error: `Entry ${i}: missing required fields (level, symbol, message, service)`
|
|
9756
|
+
});
|
|
9757
|
+
return;
|
|
9758
|
+
}
|
|
9759
|
+
if (!["debug", "info", "warn", "error"].includes(e.level)) {
|
|
9760
|
+
res.status(400).json({
|
|
9761
|
+
error: `Entry ${i}: invalid level "${e.level}", must be debug|info|warn|error`
|
|
9762
|
+
});
|
|
9763
|
+
return;
|
|
9764
|
+
}
|
|
9765
|
+
}
|
|
9766
|
+
const result = storage.insertLogBatch(entries);
|
|
9767
|
+
for (const input of entries) {
|
|
9768
|
+
const entry = {
|
|
9769
|
+
id: input.id || v4_default(),
|
|
9770
|
+
timestamp: input.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
|
|
9771
|
+
level: input.level,
|
|
9772
|
+
symbol: input.symbol,
|
|
9773
|
+
symbolType: input.symbolType || inferSymbolType(input.symbol),
|
|
9774
|
+
message: input.message,
|
|
9775
|
+
data: input.data,
|
|
9776
|
+
service: input.service,
|
|
9777
|
+
sessionId: input.sessionId,
|
|
9778
|
+
correlationId: input.correlationId,
|
|
9779
|
+
durationMs: input.durationMs,
|
|
9780
|
+
environment: input.environment
|
|
9781
|
+
};
|
|
9782
|
+
let validation;
|
|
9783
|
+
if (symbolIndex) {
|
|
9784
|
+
validation = validateSymbol(entry.symbol, symbolIndex);
|
|
9785
|
+
}
|
|
9786
|
+
if (entry.level === "error") {
|
|
9787
|
+
autoPromoteToIncident(entry, storage);
|
|
9788
|
+
}
|
|
9789
|
+
if (onLogReceived) {
|
|
9790
|
+
onLogReceived(entry, validation);
|
|
9791
|
+
}
|
|
9792
|
+
}
|
|
9793
|
+
insertsSincePrune += result.accepted;
|
|
9794
|
+
if (serverConfig.maxLogs > 0 && insertsSincePrune >= serverConfig.pruneIntervalInserts) {
|
|
9795
|
+
insertsSincePrune = 0;
|
|
9796
|
+
storage.pruneLogs(serverConfig.maxLogs);
|
|
9797
|
+
}
|
|
9798
|
+
res.json({ accepted: result.accepted, errors: result.errors.length > 0 ? result.errors : void 0 });
|
|
9799
|
+
} catch (error) {
|
|
9800
|
+
res.status(500).json({ error: "Failed to insert logs" });
|
|
9801
|
+
}
|
|
9802
|
+
});
|
|
9803
|
+
router.get("/", async (req, res) => {
|
|
9804
|
+
try {
|
|
9805
|
+
const options2 = {
|
|
9806
|
+
level: req.query.level,
|
|
9807
|
+
symbol: req.query.symbol,
|
|
9808
|
+
service: req.query.service,
|
|
9809
|
+
sessionId: req.query.sessionId,
|
|
9810
|
+
correlationId: req.query.correlationId,
|
|
9811
|
+
search: req.query.search,
|
|
9812
|
+
since: req.query.since,
|
|
9813
|
+
until: req.query.until,
|
|
9814
|
+
limit: req.query.limit ? parseInt(req.query.limit) : 100,
|
|
9815
|
+
offset: req.query.offset ? parseInt(req.query.offset) : 0
|
|
9816
|
+
};
|
|
9817
|
+
const logs = storage.queryLogs(options2);
|
|
9818
|
+
const total = storage.getLogCount(options2);
|
|
9819
|
+
res.json({ count: logs.length, total, logs });
|
|
9820
|
+
} catch (error) {
|
|
9821
|
+
res.status(500).json({ error: "Failed to query logs" });
|
|
9822
|
+
}
|
|
9823
|
+
});
|
|
9824
|
+
return router;
|
|
9825
|
+
}
|
|
9826
|
+
function createServicesRouter(options) {
|
|
9827
|
+
const router = Router7();
|
|
9828
|
+
const { storage } = options;
|
|
9829
|
+
router.post("/", async (req, res) => {
|
|
9830
|
+
try {
|
|
9831
|
+
const { name, version, pid, environment, metadata } = req.body;
|
|
9832
|
+
if (!name) {
|
|
9833
|
+
res.status(400).json({ error: "Missing required field: name" });
|
|
9834
|
+
return;
|
|
9835
|
+
}
|
|
9836
|
+
storage.registerService({ name, version, pid, environment, metadata });
|
|
9837
|
+
res.json({ success: true, service: name });
|
|
9838
|
+
} catch (error) {
|
|
9839
|
+
res.status(500).json({ error: "Failed to register service" });
|
|
9840
|
+
}
|
|
9841
|
+
});
|
|
9842
|
+
router.get("/", async (_req, res) => {
|
|
9843
|
+
try {
|
|
9844
|
+
const services = storage.getServices();
|
|
9845
|
+
res.json({ count: services.length, services });
|
|
9846
|
+
} catch (error) {
|
|
9847
|
+
res.status(500).json({ error: "Failed to list services" });
|
|
9848
|
+
}
|
|
9849
|
+
});
|
|
9850
|
+
return router;
|
|
9851
|
+
}
|
|
9852
|
+
function createStateRouter(options) {
|
|
9853
|
+
const router = Router7();
|
|
9854
|
+
const { storage } = options;
|
|
9855
|
+
router.post("/", async (req, res) => {
|
|
9856
|
+
try {
|
|
9857
|
+
const { service, sessionId, state, activeFlows, activeGates } = req.body;
|
|
9858
|
+
if (!service || !sessionId || !state) {
|
|
9859
|
+
res.status(400).json({ error: "Missing required fields: service, sessionId, state" });
|
|
9860
|
+
return;
|
|
9861
|
+
}
|
|
9862
|
+
storage.upsertAppState({
|
|
9863
|
+
service,
|
|
9864
|
+
sessionId,
|
|
9865
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
9866
|
+
state,
|
|
9867
|
+
activeFlows,
|
|
9868
|
+
activeGates
|
|
9869
|
+
});
|
|
9870
|
+
storage.updateServiceLastSeen(service);
|
|
9871
|
+
res.json({ success: true });
|
|
9872
|
+
} catch (error) {
|
|
9873
|
+
res.status(500).json({ error: "Failed to update state" });
|
|
9874
|
+
}
|
|
9875
|
+
});
|
|
9876
|
+
router.get("/", async (_req, res) => {
|
|
9877
|
+
try {
|
|
9878
|
+
const states = storage.getAllAppStates();
|
|
9879
|
+
res.json({ count: states.length, states });
|
|
9880
|
+
} catch (error) {
|
|
9881
|
+
res.status(500).json({ error: "Failed to get states" });
|
|
9882
|
+
}
|
|
9883
|
+
});
|
|
9884
|
+
router.get("/:service", async (req, res) => {
|
|
9885
|
+
try {
|
|
9886
|
+
const states = storage.getAppState(req.params.service);
|
|
9887
|
+
res.json({ count: states.length, states });
|
|
9888
|
+
} catch (error) {
|
|
9889
|
+
res.status(500).json({ error: "Failed to get service state" });
|
|
9890
|
+
}
|
|
9891
|
+
});
|
|
9892
|
+
return router;
|
|
9893
|
+
}
|
|
9894
|
+
var VALID_METRIC_TYPES = ["counter", "gauge", "histogram"];
|
|
9895
|
+
function createMetricsRouter(options) {
|
|
9896
|
+
const router = Router8();
|
|
9897
|
+
const { storage, serverConfig } = options;
|
|
9898
|
+
router.post("/", (req, res) => {
|
|
9899
|
+
try {
|
|
9900
|
+
const body = req.body;
|
|
9901
|
+
let entries;
|
|
9902
|
+
if (Array.isArray(body.entries)) {
|
|
9903
|
+
entries = body.entries;
|
|
9904
|
+
} else if (body.name && body.type && body.value !== void 0 && body.service) {
|
|
9905
|
+
entries = [body];
|
|
9906
|
+
} else {
|
|
9907
|
+
res.status(400).json({
|
|
9908
|
+
error: "Expected {entries: [...]} or a single metric with name, type, value, service"
|
|
9909
|
+
});
|
|
9910
|
+
return;
|
|
9911
|
+
}
|
|
9912
|
+
if (entries.length > serverConfig.maxBatchSize) {
|
|
9913
|
+
res.status(413).json({
|
|
9914
|
+
error: `Batch too large: ${entries.length} entries, max ${serverConfig.maxBatchSize}`
|
|
9915
|
+
});
|
|
9916
|
+
return;
|
|
9917
|
+
}
|
|
9918
|
+
for (let i = 0; i < entries.length; i++) {
|
|
9919
|
+
const e = entries[i];
|
|
9920
|
+
if (!e.name || !e.type || e.value === void 0 || !e.service) {
|
|
9921
|
+
res.status(400).json({
|
|
9922
|
+
error: `Entry ${i}: missing required fields (name, type, value, service)`
|
|
9923
|
+
});
|
|
9924
|
+
return;
|
|
9925
|
+
}
|
|
9926
|
+
if (!VALID_METRIC_TYPES.includes(e.type)) {
|
|
9927
|
+
res.status(400).json({
|
|
9928
|
+
error: `Entry ${i}: invalid type "${e.type}", must be counter|gauge|histogram`
|
|
9929
|
+
});
|
|
9930
|
+
return;
|
|
9931
|
+
}
|
|
9932
|
+
}
|
|
9933
|
+
const result = storage.insertMetricBatch(entries);
|
|
9934
|
+
res.json({
|
|
9935
|
+
accepted: result.accepted,
|
|
9936
|
+
errors: result.errors.length > 0 ? result.errors : void 0
|
|
9937
|
+
});
|
|
9938
|
+
} catch {
|
|
9939
|
+
res.status(500).json({ error: "Failed to insert metrics" });
|
|
9940
|
+
}
|
|
9941
|
+
});
|
|
9942
|
+
router.get("/", (req, res) => {
|
|
9943
|
+
try {
|
|
9944
|
+
const options2 = {
|
|
9945
|
+
name: req.query.name,
|
|
9946
|
+
type: req.query.type,
|
|
9947
|
+
service: req.query.service,
|
|
9948
|
+
tag: req.query.tag,
|
|
9949
|
+
since: req.query.since,
|
|
9950
|
+
until: req.query.until,
|
|
9951
|
+
limit: req.query.limit ? parseInt(req.query.limit) : 100,
|
|
9952
|
+
offset: req.query.offset ? parseInt(req.query.offset) : 0
|
|
9953
|
+
};
|
|
9954
|
+
const metrics = storage.queryMetrics(options2);
|
|
9955
|
+
const total = storage.getMetricCount(options2);
|
|
9956
|
+
res.json({ count: metrics.length, total, metrics });
|
|
9957
|
+
} catch {
|
|
9958
|
+
res.status(500).json({ error: "Failed to query metrics" });
|
|
9959
|
+
}
|
|
9960
|
+
});
|
|
9961
|
+
router.get("/aggregate/:name", (req, res) => {
|
|
9962
|
+
try {
|
|
9963
|
+
const aggregation = storage.aggregateMetric(req.params.name, {
|
|
9964
|
+
service: req.query.service,
|
|
9965
|
+
since: req.query.since,
|
|
9966
|
+
until: req.query.until
|
|
9967
|
+
});
|
|
9968
|
+
res.json(aggregation);
|
|
9969
|
+
} catch {
|
|
9970
|
+
res.status(500).json({ error: "Failed to aggregate metric" });
|
|
9971
|
+
}
|
|
9972
|
+
});
|
|
9973
|
+
return router;
|
|
9974
|
+
}
|
|
9975
|
+
function createTracesRouter(options) {
|
|
9976
|
+
const router = Router9();
|
|
9977
|
+
const { storage } = options;
|
|
9978
|
+
router.post("/", (req, res) => {
|
|
9979
|
+
try {
|
|
9980
|
+
const body = req.body;
|
|
9981
|
+
if (!body.traceId || !body.service || !body.symbol || !body.operation) {
|
|
9982
|
+
res.status(400).json({
|
|
9983
|
+
error: "Missing required fields: traceId, service, symbol, operation"
|
|
9984
|
+
});
|
|
9985
|
+
return;
|
|
9986
|
+
}
|
|
9987
|
+
const spanId = storage.insertSpan(body);
|
|
9988
|
+
res.json({ spanId, traceId: body.traceId });
|
|
9989
|
+
} catch {
|
|
9990
|
+
res.status(500).json({ error: "Failed to insert trace span" });
|
|
9991
|
+
}
|
|
9992
|
+
});
|
|
9993
|
+
router.get("/", (req, res) => {
|
|
9994
|
+
try {
|
|
9995
|
+
const traces = storage.queryTraces({
|
|
9996
|
+
service: req.query.service,
|
|
9997
|
+
symbol: req.query.symbol,
|
|
9998
|
+
since: req.query.since,
|
|
9999
|
+
limit: req.query.limit ? parseInt(req.query.limit) : 20
|
|
10000
|
+
});
|
|
10001
|
+
res.json({ count: traces.length, traces });
|
|
10002
|
+
} catch {
|
|
10003
|
+
res.status(500).json({ error: "Failed to query traces" });
|
|
10004
|
+
}
|
|
10005
|
+
});
|
|
10006
|
+
router.get("/:traceId", (req, res) => {
|
|
10007
|
+
try {
|
|
10008
|
+
const trace = storage.getTrace(req.params.traceId);
|
|
10009
|
+
if (!trace) {
|
|
10010
|
+
res.status(404).json({ error: "Trace not found" });
|
|
10011
|
+
return;
|
|
10012
|
+
}
|
|
10013
|
+
res.json(trace);
|
|
10014
|
+
} catch {
|
|
10015
|
+
res.status(500).json({ error: "Failed to get trace" });
|
|
10016
|
+
}
|
|
10017
|
+
});
|
|
10018
|
+
return router;
|
|
10019
|
+
}
|
|
10020
|
+
function createAuthMiddleware(config) {
|
|
10021
|
+
return function authMiddleware(requiredPermission) {
|
|
10022
|
+
return (req, res, next) => {
|
|
10023
|
+
if (!config.enabled) {
|
|
10024
|
+
next();
|
|
10025
|
+
return;
|
|
10026
|
+
}
|
|
10027
|
+
const authHeader = req.headers.authorization;
|
|
10028
|
+
if (!authHeader) {
|
|
10029
|
+
res.status(401).json({ error: "Authentication required. Provide Authorization: Bearer <token>" });
|
|
10030
|
+
return;
|
|
10031
|
+
}
|
|
10032
|
+
const match = authHeader.match(/^Bearer\s+(.+)$/i);
|
|
10033
|
+
if (!match) {
|
|
10034
|
+
res.status(401).json({ error: "Invalid authorization format. Use: Bearer <token>" });
|
|
10035
|
+
return;
|
|
10036
|
+
}
|
|
10037
|
+
const tokenValue = match[1];
|
|
10038
|
+
const tokenEntry = config.tokens.find((t) => t.token === tokenValue);
|
|
10039
|
+
if (!tokenEntry) {
|
|
10040
|
+
res.status(401).json({ error: "Invalid token" });
|
|
10041
|
+
return;
|
|
10042
|
+
}
|
|
10043
|
+
if (tokenEntry.expiresAt && new Date(tokenEntry.expiresAt) < /* @__PURE__ */ new Date()) {
|
|
10044
|
+
res.status(401).json({ error: "Token expired" });
|
|
10045
|
+
return;
|
|
10046
|
+
}
|
|
10047
|
+
const permissionLevel = { read: 1, write: 2, admin: 3 };
|
|
10048
|
+
const hasPermission = tokenEntry.permissions.some(
|
|
10049
|
+
(p) => permissionLevel[p] >= permissionLevel[requiredPermission]
|
|
10050
|
+
);
|
|
10051
|
+
if (!hasPermission) {
|
|
10052
|
+
res.status(403).json({ error: `Insufficient permissions. Required: ${requiredPermission}` });
|
|
10053
|
+
return;
|
|
10054
|
+
}
|
|
10055
|
+
req.authToken = tokenEntry;
|
|
10056
|
+
next();
|
|
10057
|
+
};
|
|
10058
|
+
};
|
|
10059
|
+
}
|
|
10060
|
+
var serviceWindows = /* @__PURE__ */ new Map();
|
|
10061
|
+
var globalWindow = { count: 0, windowStart: Date.now() };
|
|
10062
|
+
var WINDOW_MS = 6e4;
|
|
10063
|
+
function getOrResetWindow(entry) {
|
|
10064
|
+
const now = Date.now();
|
|
10065
|
+
if (now - entry.windowStart > WINDOW_MS) {
|
|
10066
|
+
entry.count = 0;
|
|
10067
|
+
entry.windowStart = now;
|
|
10068
|
+
}
|
|
10069
|
+
return entry;
|
|
10070
|
+
}
|
|
10071
|
+
function createRateLimiter(config) {
|
|
10072
|
+
return (req, res, next) => {
|
|
10073
|
+
if (!config.enabled) {
|
|
10074
|
+
next();
|
|
10075
|
+
return;
|
|
10076
|
+
}
|
|
10077
|
+
const service = req.body?.service || req.body?.entries?.[0]?.service || req.query.service || "_unknown";
|
|
10078
|
+
const rule = config.perService[service] || config.global;
|
|
10079
|
+
if (rule.samplingRate < 1 && Math.random() > rule.samplingRate) {
|
|
10080
|
+
res.status(200).json({ accepted: 0, sampled: true, message: "Request dropped by sampling" });
|
|
10081
|
+
return;
|
|
10082
|
+
}
|
|
10083
|
+
const gw = getOrResetWindow(globalWindow);
|
|
10084
|
+
if (gw.count >= config.global.maxRequestsPerMinute) {
|
|
10085
|
+
res.status(429).json({
|
|
10086
|
+
error: "Global rate limit exceeded",
|
|
10087
|
+
retryAfterMs: WINDOW_MS - (Date.now() - gw.windowStart)
|
|
10088
|
+
});
|
|
10089
|
+
return;
|
|
10090
|
+
}
|
|
10091
|
+
if (!serviceWindows.has(service)) {
|
|
10092
|
+
serviceWindows.set(service, { count: 0, windowStart: Date.now() });
|
|
10093
|
+
}
|
|
10094
|
+
const sw = getOrResetWindow(serviceWindows.get(service));
|
|
10095
|
+
if (sw.count >= rule.maxRequestsPerMinute) {
|
|
10096
|
+
res.status(429).json({
|
|
10097
|
+
error: `Rate limit exceeded for service: ${service}`,
|
|
10098
|
+
retryAfterMs: WINDOW_MS - (Date.now() - sw.windowStart)
|
|
10099
|
+
});
|
|
10100
|
+
return;
|
|
10101
|
+
}
|
|
10102
|
+
const batchSize = req.body?.entries?.length || 1;
|
|
10103
|
+
if (batchSize > rule.maxEntriesPerBatch) {
|
|
10104
|
+
res.status(413).json({
|
|
10105
|
+
error: `Batch too large: ${batchSize} entries, max ${rule.maxEntriesPerBatch} for service ${service}`
|
|
10106
|
+
});
|
|
10107
|
+
return;
|
|
10108
|
+
}
|
|
10109
|
+
gw.count++;
|
|
10110
|
+
sw.count++;
|
|
10111
|
+
next();
|
|
10112
|
+
};
|
|
10113
|
+
}
|
|
6047
10114
|
var __filename = fileURLToPath(import.meta.url);
|
|
6048
10115
|
var __dirname = path3.dirname(__filename);
|
|
6049
10116
|
var log3 = {
|
|
@@ -6071,11 +10138,20 @@ var log3 = {
|
|
|
6071
10138
|
};
|
|
6072
10139
|
function createApp(options) {
|
|
6073
10140
|
const app = express();
|
|
6074
|
-
app.use(express.json());
|
|
10141
|
+
app.use(express.json({ limit: "5mb" }));
|
|
6075
10142
|
app.use((_req, res, next) => {
|
|
6076
|
-
|
|
10143
|
+
const corsOrigin = options.serverConfig?.cors?.origin;
|
|
10144
|
+
const origin = Array.isArray(corsOrigin) ? corsOrigin.join(", ") : corsOrigin ?? "*";
|
|
10145
|
+
res.header("Access-Control-Allow-Origin", origin);
|
|
6077
10146
|
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
|
|
6078
|
-
res.header("Access-Control-Allow-Headers", "Content-Type");
|
|
10147
|
+
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
|
10148
|
+
if (options.serverConfig?.cors?.credentials) {
|
|
10149
|
+
res.header("Access-Control-Allow-Credentials", "true");
|
|
10150
|
+
}
|
|
10151
|
+
if (_req.method === "OPTIONS") {
|
|
10152
|
+
res.sendStatus(204);
|
|
10153
|
+
return;
|
|
10154
|
+
}
|
|
6079
10155
|
next();
|
|
6080
10156
|
});
|
|
6081
10157
|
app.use("/api/symbols", createSymbolsRouter(options.projectDir));
|
|
@@ -6083,6 +10159,26 @@ function createApp(options) {
|
|
|
6083
10159
|
app.use("/api/commits", createCommitsRouter(options.projectDir));
|
|
6084
10160
|
app.use("/api/incidents", createIncidentsRouter(options.projectDir));
|
|
6085
10161
|
app.use("/api/patterns", createPatternsRouter(options.projectDir));
|
|
10162
|
+
if (options.storage && options.serverConfig) {
|
|
10163
|
+
const config = options.serverConfig;
|
|
10164
|
+
const auth = createAuthMiddleware(config.auth);
|
|
10165
|
+
const rateLimiter = createRateLimiter(config.rateLimit);
|
|
10166
|
+
app.use("/api/logs", rateLimiter, auth("write"), createLogsRouter({
|
|
10167
|
+
storage: options.storage,
|
|
10168
|
+
serverConfig: config,
|
|
10169
|
+
onLogReceived: options.onLogReceived,
|
|
10170
|
+
symbolIndex: options.symbolIndex
|
|
10171
|
+
}));
|
|
10172
|
+
app.use("/api/services", rateLimiter, auth("write"), createServicesRouter({ storage: options.storage }));
|
|
10173
|
+
app.use("/api/state", rateLimiter, auth("write"), createStateRouter({ storage: options.storage }));
|
|
10174
|
+
app.use("/api/metrics", rateLimiter, auth("write"), createMetricsRouter({
|
|
10175
|
+
storage: options.storage,
|
|
10176
|
+
serverConfig: config
|
|
10177
|
+
}));
|
|
10178
|
+
app.use("/api/traces", rateLimiter, auth("write"), createTracesRouter({
|
|
10179
|
+
storage: options.storage
|
|
10180
|
+
}));
|
|
10181
|
+
}
|
|
6086
10182
|
app.get("/api/health", (_req, res) => {
|
|
6087
10183
|
res.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
6088
10184
|
});
|
|
@@ -6098,12 +10194,100 @@ function createApp(options) {
|
|
|
6098
10194
|
return app;
|
|
6099
10195
|
}
|
|
6100
10196
|
async function startServer(options) {
|
|
6101
|
-
const
|
|
10197
|
+
const serverConfig = loadServerConfig(options.projectDir);
|
|
10198
|
+
if (options.logPruneLimit !== void 0) {
|
|
10199
|
+
serverConfig.maxLogs = options.logPruneLimit;
|
|
10200
|
+
}
|
|
10201
|
+
const storage = new SentinelStorage(options.dbPath);
|
|
10202
|
+
await storage.ensureReady();
|
|
10203
|
+
let symbolIndex = [];
|
|
10204
|
+
try {
|
|
10205
|
+
symbolIndex = await loadSymbolIndex(options.projectDir);
|
|
10206
|
+
} catch {
|
|
10207
|
+
log3.component("sentinel-server").warn("Could not load symbol index for validation");
|
|
10208
|
+
}
|
|
10209
|
+
const wsClients = /* @__PURE__ */ new Set();
|
|
10210
|
+
function broadcast(message) {
|
|
10211
|
+
const data = JSON.stringify(message);
|
|
10212
|
+
for (const client of wsClients) {
|
|
10213
|
+
if (client.readyState === import_websocket.default.OPEN) {
|
|
10214
|
+
client.send(data);
|
|
10215
|
+
}
|
|
10216
|
+
}
|
|
10217
|
+
}
|
|
10218
|
+
function onLogReceived(entry, validation) {
|
|
10219
|
+
const message = { type: "log", entry };
|
|
10220
|
+
if (validation && !validation.known) {
|
|
10221
|
+
message.validation = validation;
|
|
10222
|
+
}
|
|
10223
|
+
broadcast(message);
|
|
10224
|
+
if (entry.symbolType === "signal" || entry.symbolType === "gate" || entry.symbolType === "flow") {
|
|
10225
|
+
broadcast({
|
|
10226
|
+
type: "flow_event",
|
|
10227
|
+
flowId: entry.symbolType === "flow" ? entry.symbol : void 0,
|
|
10228
|
+
nodeSymbol: entry.symbol,
|
|
10229
|
+
event: entry.symbolType,
|
|
10230
|
+
timestamp: entry.timestamp,
|
|
10231
|
+
service: entry.service
|
|
10232
|
+
});
|
|
10233
|
+
}
|
|
10234
|
+
}
|
|
10235
|
+
const app = createApp({
|
|
10236
|
+
...options,
|
|
10237
|
+
storage,
|
|
10238
|
+
serverConfig,
|
|
10239
|
+
symbolIndex,
|
|
10240
|
+
onLogReceived
|
|
10241
|
+
});
|
|
6102
10242
|
log3.component("sentinel-server").info("Starting server", { port: options.port });
|
|
6103
10243
|
log3.component("sentinel-server").info("Project directory", { path: options.projectDir });
|
|
6104
10244
|
return new Promise((resolve, reject) => {
|
|
6105
|
-
const
|
|
10245
|
+
const httpServer = http.createServer(app);
|
|
10246
|
+
const wss = new import_websocket_server.default({ server: httpServer });
|
|
10247
|
+
wss.on("connection", (ws) => {
|
|
10248
|
+
if (wsClients.size >= serverConfig.wsMaxSubscribers) {
|
|
10249
|
+
ws.close(1013, "Max subscribers reached");
|
|
10250
|
+
return;
|
|
10251
|
+
}
|
|
10252
|
+
wsClients.add(ws);
|
|
10253
|
+
log3.component("sentinel-ws").info("Client connected", { total: wsClients.size });
|
|
10254
|
+
ws.on("message", (raw) => {
|
|
10255
|
+
try {
|
|
10256
|
+
const msg = JSON.parse(raw.toString());
|
|
10257
|
+
if (msg.method === "ping") {
|
|
10258
|
+
ws.send(JSON.stringify({
|
|
10259
|
+
jsonrpc: "2.0",
|
|
10260
|
+
result: { pong: true, timestamp: (/* @__PURE__ */ new Date()).toISOString() },
|
|
10261
|
+
id: msg.id
|
|
10262
|
+
}));
|
|
10263
|
+
} else if (msg.method === "subscribe") {
|
|
10264
|
+
ws.send(JSON.stringify({
|
|
10265
|
+
jsonrpc: "2.0",
|
|
10266
|
+
result: { subscribed: true },
|
|
10267
|
+
id: msg.id
|
|
10268
|
+
}));
|
|
10269
|
+
} else if (msg.method === "query_logs") {
|
|
10270
|
+
const logs = storage.queryLogs(msg.params || {});
|
|
10271
|
+
ws.send(JSON.stringify({
|
|
10272
|
+
jsonrpc: "2.0",
|
|
10273
|
+
result: { logs },
|
|
10274
|
+
id: msg.id
|
|
10275
|
+
}));
|
|
10276
|
+
}
|
|
10277
|
+
} catch {
|
|
10278
|
+
}
|
|
10279
|
+
});
|
|
10280
|
+
ws.on("close", () => {
|
|
10281
|
+
wsClients.delete(ws);
|
|
10282
|
+
log3.component("sentinel-ws").info("Client disconnected", { total: wsClients.size });
|
|
10283
|
+
});
|
|
10284
|
+
ws.on("error", () => {
|
|
10285
|
+
wsClients.delete(ws);
|
|
10286
|
+
});
|
|
10287
|
+
});
|
|
10288
|
+
httpServer.listen(options.port, () => {
|
|
6106
10289
|
log3.component("sentinel-server").success("Server running", { url: `http://localhost:${options.port}` });
|
|
10290
|
+
log3.component("sentinel-ws").success("WebSocket ready", { url: `ws://localhost:${options.port}` });
|
|
6107
10291
|
if (options.open) {
|
|
6108
10292
|
import("open").then((openModule) => {
|
|
6109
10293
|
openModule.default(`http://localhost:${options.port}`);
|
|
@@ -6114,7 +10298,7 @@ async function startServer(options) {
|
|
|
6114
10298
|
}
|
|
6115
10299
|
resolve();
|
|
6116
10300
|
});
|
|
6117
|
-
|
|
10301
|
+
httpServer.on("error", (err) => {
|
|
6118
10302
|
if (err.code === "EADDRINUSE") {
|
|
6119
10303
|
log3.component("sentinel-server").error("Port already in use", { port: options.port });
|
|
6120
10304
|
} else {
|