@granular-software/sdk 0.2.0 → 0.3.1
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/adapters/anthropic.d.mts +1 -1
- package/dist/adapters/anthropic.d.ts +1 -1
- package/dist/adapters/langchain.d.mts +1 -1
- package/dist/adapters/langchain.d.ts +1 -1
- package/dist/adapters/mastra.d.mts +1 -1
- package/dist/adapters/mastra.d.ts +1 -1
- package/dist/adapters/openai.d.mts +1 -1
- package/dist/adapters/openai.d.ts +1 -1
- package/dist/cli/index.js +231 -13
- package/dist/index.d.mts +200 -20
- package/dist/index.d.ts +200 -20
- package/dist/index.js +4433 -65
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4428 -57
- package/dist/index.mjs.map +1 -1
- package/dist/{types-D46q5WTh.d.mts → types-CnX4jXYQ.d.mts} +47 -3
- package/dist/{types-D46q5WTh.d.ts → types-CnX4jXYQ.d.ts} +47 -3
- package/package.json +2 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,3922 @@
|
|
|
1
|
-
import WebSocket from 'ws';
|
|
2
1
|
import * as Automerge from '@automerge/automerge';
|
|
3
2
|
|
|
4
|
-
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
10
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
11
|
+
}) : x)(function(x) {
|
|
12
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
13
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
14
|
+
});
|
|
15
|
+
var __esm = (fn, res) => function __init() {
|
|
16
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
17
|
+
};
|
|
18
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
19
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
20
|
+
};
|
|
21
|
+
var __export = (target, all) => {
|
|
22
|
+
for (var name in all)
|
|
23
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
24
|
+
};
|
|
25
|
+
var __copyProps = (to, from, except, desc) => {
|
|
26
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
27
|
+
for (let key of __getOwnPropNames(from))
|
|
28
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
29
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
30
|
+
}
|
|
31
|
+
return to;
|
|
32
|
+
};
|
|
33
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
34
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
35
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
36
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
37
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
38
|
+
__defProp(target, "default", { value: mod, enumerable: true }) ,
|
|
39
|
+
mod
|
|
40
|
+
));
|
|
41
|
+
|
|
42
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/constants.js
|
|
43
|
+
var require_constants = __commonJS({
|
|
44
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/constants.js"(exports, module) {
|
|
45
|
+
var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
|
|
46
|
+
var hasBlob = typeof Blob !== "undefined";
|
|
47
|
+
if (hasBlob) BINARY_TYPES.push("blob");
|
|
48
|
+
module.exports = {
|
|
49
|
+
BINARY_TYPES,
|
|
50
|
+
EMPTY_BUFFER: Buffer.alloc(0),
|
|
51
|
+
GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
|
|
52
|
+
hasBlob,
|
|
53
|
+
kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
|
|
54
|
+
kListener: Symbol("kListener"),
|
|
55
|
+
kStatusCode: Symbol("status-code"),
|
|
56
|
+
kWebSocket: Symbol("websocket"),
|
|
57
|
+
NOOP: () => {
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// ../../node_modules/.bun/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js
|
|
64
|
+
var require_node_gyp_build = __commonJS({
|
|
65
|
+
"../../node_modules/.bun/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(exports, module) {
|
|
66
|
+
var fs = __require("fs");
|
|
67
|
+
var path = __require("path");
|
|
68
|
+
var os = __require("os");
|
|
69
|
+
var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
|
|
70
|
+
var vars = process.config && process.config.variables || {};
|
|
71
|
+
var prebuildsOnly = !!process.env.PREBUILDS_ONLY;
|
|
72
|
+
var abi = process.versions.modules;
|
|
73
|
+
var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node";
|
|
74
|
+
var arch = process.env.npm_config_arch || os.arch();
|
|
75
|
+
var platform = process.env.npm_config_platform || os.platform();
|
|
76
|
+
var libc = process.env.LIBC || (isAlpine(platform) ? "musl" : "glibc");
|
|
77
|
+
var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || "";
|
|
78
|
+
var uv = (process.versions.uv || "").split(".")[0];
|
|
79
|
+
module.exports = load2;
|
|
80
|
+
function load2(dir) {
|
|
81
|
+
return runtimeRequire(load2.resolve(dir));
|
|
82
|
+
}
|
|
83
|
+
load2.resolve = load2.path = function(dir) {
|
|
84
|
+
dir = path.resolve(dir || ".");
|
|
85
|
+
try {
|
|
86
|
+
var name = runtimeRequire(path.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
|
|
87
|
+
if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"];
|
|
88
|
+
} catch (err) {
|
|
89
|
+
}
|
|
90
|
+
if (!prebuildsOnly) {
|
|
91
|
+
var release = getFirst(path.join(dir, "build/Release"), matchBuild);
|
|
92
|
+
if (release) return release;
|
|
93
|
+
var debug = getFirst(path.join(dir, "build/Debug"), matchBuild);
|
|
94
|
+
if (debug) return debug;
|
|
95
|
+
}
|
|
96
|
+
var prebuild = resolve(dir);
|
|
97
|
+
if (prebuild) return prebuild;
|
|
98
|
+
var nearby = resolve(path.dirname(process.execPath));
|
|
99
|
+
if (nearby) return nearby;
|
|
100
|
+
var target = [
|
|
101
|
+
"platform=" + platform,
|
|
102
|
+
"arch=" + arch,
|
|
103
|
+
"runtime=" + runtime,
|
|
104
|
+
"abi=" + abi,
|
|
105
|
+
"uv=" + uv,
|
|
106
|
+
armv ? "armv=" + armv : "",
|
|
107
|
+
"libc=" + libc,
|
|
108
|
+
"node=" + process.versions.node,
|
|
109
|
+
process.versions.electron ? "electron=" + process.versions.electron : "",
|
|
110
|
+
typeof __webpack_require__ === "function" ? "webpack=true" : ""
|
|
111
|
+
// eslint-disable-line
|
|
112
|
+
].filter(Boolean).join(" ");
|
|
113
|
+
throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n");
|
|
114
|
+
function resolve(dir2) {
|
|
115
|
+
var tuples = readdirSync(path.join(dir2, "prebuilds")).map(parseTuple);
|
|
116
|
+
var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0];
|
|
117
|
+
if (!tuple) return;
|
|
118
|
+
var prebuilds = path.join(dir2, "prebuilds", tuple.name);
|
|
119
|
+
var parsed = readdirSync(prebuilds).map(parseTags);
|
|
120
|
+
var candidates = parsed.filter(matchTags(runtime, abi));
|
|
121
|
+
var winner = candidates.sort(compareTags(runtime))[0];
|
|
122
|
+
if (winner) return path.join(prebuilds, winner.file);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
function readdirSync(dir) {
|
|
126
|
+
try {
|
|
127
|
+
return fs.readdirSync(dir);
|
|
128
|
+
} catch (err) {
|
|
129
|
+
return [];
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function getFirst(dir, filter) {
|
|
133
|
+
var files = readdirSync(dir).filter(filter);
|
|
134
|
+
return files[0] && path.join(dir, files[0]);
|
|
135
|
+
}
|
|
136
|
+
function matchBuild(name) {
|
|
137
|
+
return /\.node$/.test(name);
|
|
138
|
+
}
|
|
139
|
+
function parseTuple(name) {
|
|
140
|
+
var arr = name.split("-");
|
|
141
|
+
if (arr.length !== 2) return;
|
|
142
|
+
var platform2 = arr[0];
|
|
143
|
+
var architectures = arr[1].split("+");
|
|
144
|
+
if (!platform2) return;
|
|
145
|
+
if (!architectures.length) return;
|
|
146
|
+
if (!architectures.every(Boolean)) return;
|
|
147
|
+
return { name, platform: platform2, architectures };
|
|
148
|
+
}
|
|
149
|
+
function matchTuple(platform2, arch2) {
|
|
150
|
+
return function(tuple) {
|
|
151
|
+
if (tuple == null) return false;
|
|
152
|
+
if (tuple.platform !== platform2) return false;
|
|
153
|
+
return tuple.architectures.includes(arch2);
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function compareTuples(a, b) {
|
|
157
|
+
return a.architectures.length - b.architectures.length;
|
|
158
|
+
}
|
|
159
|
+
function parseTags(file) {
|
|
160
|
+
var arr = file.split(".");
|
|
161
|
+
var extension = arr.pop();
|
|
162
|
+
var tags = { file, specificity: 0 };
|
|
163
|
+
if (extension !== "node") return;
|
|
164
|
+
for (var i = 0; i < arr.length; i++) {
|
|
165
|
+
var tag = arr[i];
|
|
166
|
+
if (tag === "node" || tag === "electron" || tag === "node-webkit") {
|
|
167
|
+
tags.runtime = tag;
|
|
168
|
+
} else if (tag === "napi") {
|
|
169
|
+
tags.napi = true;
|
|
170
|
+
} else if (tag.slice(0, 3) === "abi") {
|
|
171
|
+
tags.abi = tag.slice(3);
|
|
172
|
+
} else if (tag.slice(0, 2) === "uv") {
|
|
173
|
+
tags.uv = tag.slice(2);
|
|
174
|
+
} else if (tag.slice(0, 4) === "armv") {
|
|
175
|
+
tags.armv = tag.slice(4);
|
|
176
|
+
} else if (tag === "glibc" || tag === "musl") {
|
|
177
|
+
tags.libc = tag;
|
|
178
|
+
} else {
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
tags.specificity++;
|
|
182
|
+
}
|
|
183
|
+
return tags;
|
|
184
|
+
}
|
|
185
|
+
function matchTags(runtime2, abi2) {
|
|
186
|
+
return function(tags) {
|
|
187
|
+
if (tags == null) return false;
|
|
188
|
+
if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false;
|
|
189
|
+
if (tags.abi && tags.abi !== abi2 && !tags.napi) return false;
|
|
190
|
+
if (tags.uv && tags.uv !== uv) return false;
|
|
191
|
+
if (tags.armv && tags.armv !== armv) return false;
|
|
192
|
+
if (tags.libc && tags.libc !== libc) return false;
|
|
193
|
+
return true;
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
function runtimeAgnostic(tags) {
|
|
197
|
+
return tags.runtime === "node" && tags.napi;
|
|
198
|
+
}
|
|
199
|
+
function compareTags(runtime2) {
|
|
200
|
+
return function(a, b) {
|
|
201
|
+
if (a.runtime !== b.runtime) {
|
|
202
|
+
return a.runtime === runtime2 ? -1 : 1;
|
|
203
|
+
} else if (a.abi !== b.abi) {
|
|
204
|
+
return a.abi ? -1 : 1;
|
|
205
|
+
} else if (a.specificity !== b.specificity) {
|
|
206
|
+
return a.specificity > b.specificity ? -1 : 1;
|
|
207
|
+
} else {
|
|
208
|
+
return 0;
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function isNwjs() {
|
|
213
|
+
return !!(process.versions && process.versions.nw);
|
|
214
|
+
}
|
|
215
|
+
function isElectron() {
|
|
216
|
+
if (process.versions && process.versions.electron) return true;
|
|
217
|
+
if (process.env.ELECTRON_RUN_AS_NODE) return true;
|
|
218
|
+
return typeof window !== "undefined" && window.process && window.process.type === "renderer";
|
|
219
|
+
}
|
|
220
|
+
function isAlpine(platform2) {
|
|
221
|
+
return platform2 === "linux" && fs.existsSync("/etc/alpine-release");
|
|
222
|
+
}
|
|
223
|
+
load2.parseTags = parseTags;
|
|
224
|
+
load2.matchTags = matchTags;
|
|
225
|
+
load2.compareTags = compareTags;
|
|
226
|
+
load2.parseTuple = parseTuple;
|
|
227
|
+
load2.matchTuple = matchTuple;
|
|
228
|
+
load2.compareTuples = compareTuples;
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
// ../../node_modules/.bun/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js
|
|
233
|
+
var require_node_gyp_build2 = __commonJS({
|
|
234
|
+
"../../node_modules/.bun/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(exports, module) {
|
|
235
|
+
var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
|
|
236
|
+
if (typeof runtimeRequire.addon === "function") {
|
|
237
|
+
module.exports = runtimeRequire.addon.bind(runtimeRequire);
|
|
238
|
+
} else {
|
|
239
|
+
module.exports = require_node_gyp_build();
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
// ../../node_modules/.bun/bufferutil@4.0.9/node_modules/bufferutil/fallback.js
|
|
245
|
+
var require_fallback = __commonJS({
|
|
246
|
+
"../../node_modules/.bun/bufferutil@4.0.9/node_modules/bufferutil/fallback.js"(exports, module) {
|
|
247
|
+
var mask = (source, mask2, output, offset, length) => {
|
|
248
|
+
for (var i = 0; i < length; i++) {
|
|
249
|
+
output[offset + i] = source[i] ^ mask2[i & 3];
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
var unmask = (buffer, mask2) => {
|
|
253
|
+
const length = buffer.length;
|
|
254
|
+
for (var i = 0; i < length; i++) {
|
|
255
|
+
buffer[i] ^= mask2[i & 3];
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
module.exports = { mask, unmask };
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
// ../../node_modules/.bun/bufferutil@4.0.9/node_modules/bufferutil/index.js
|
|
263
|
+
var require_bufferutil = __commonJS({
|
|
264
|
+
"../../node_modules/.bun/bufferutil@4.0.9/node_modules/bufferutil/index.js"(exports, module) {
|
|
265
|
+
try {
|
|
266
|
+
module.exports = require_node_gyp_build2()(__dirname);
|
|
267
|
+
} catch (e) {
|
|
268
|
+
module.exports = require_fallback();
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/buffer-util.js
|
|
274
|
+
var require_buffer_util = __commonJS({
|
|
275
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/buffer-util.js"(exports, module) {
|
|
276
|
+
var { EMPTY_BUFFER } = require_constants();
|
|
277
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
278
|
+
function concat(list, totalLength) {
|
|
279
|
+
if (list.length === 0) return EMPTY_BUFFER;
|
|
280
|
+
if (list.length === 1) return list[0];
|
|
281
|
+
const target = Buffer.allocUnsafe(totalLength);
|
|
282
|
+
let offset = 0;
|
|
283
|
+
for (let i = 0; i < list.length; i++) {
|
|
284
|
+
const buf = list[i];
|
|
285
|
+
target.set(buf, offset);
|
|
286
|
+
offset += buf.length;
|
|
287
|
+
}
|
|
288
|
+
if (offset < totalLength) {
|
|
289
|
+
return new FastBuffer(target.buffer, target.byteOffset, offset);
|
|
290
|
+
}
|
|
291
|
+
return target;
|
|
292
|
+
}
|
|
293
|
+
function _mask(source, mask, output, offset, length) {
|
|
294
|
+
for (let i = 0; i < length; i++) {
|
|
295
|
+
output[offset + i] = source[i] ^ mask[i & 3];
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
function _unmask(buffer, mask) {
|
|
299
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
300
|
+
buffer[i] ^= mask[i & 3];
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
function toArrayBuffer(buf) {
|
|
304
|
+
if (buf.length === buf.buffer.byteLength) {
|
|
305
|
+
return buf.buffer;
|
|
306
|
+
}
|
|
307
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
|
|
308
|
+
}
|
|
309
|
+
function toBuffer(data) {
|
|
310
|
+
toBuffer.readOnly = true;
|
|
311
|
+
if (Buffer.isBuffer(data)) return data;
|
|
312
|
+
let buf;
|
|
313
|
+
if (data instanceof ArrayBuffer) {
|
|
314
|
+
buf = new FastBuffer(data);
|
|
315
|
+
} else if (ArrayBuffer.isView(data)) {
|
|
316
|
+
buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
|
|
317
|
+
} else {
|
|
318
|
+
buf = Buffer.from(data);
|
|
319
|
+
toBuffer.readOnly = false;
|
|
320
|
+
}
|
|
321
|
+
return buf;
|
|
322
|
+
}
|
|
323
|
+
module.exports = {
|
|
324
|
+
concat,
|
|
325
|
+
mask: _mask,
|
|
326
|
+
toArrayBuffer,
|
|
327
|
+
toBuffer,
|
|
328
|
+
unmask: _unmask
|
|
329
|
+
};
|
|
330
|
+
if (!process.env.WS_NO_BUFFER_UTIL) {
|
|
331
|
+
try {
|
|
332
|
+
const bufferUtil = require_bufferutil();
|
|
333
|
+
module.exports.mask = function(source, mask, output, offset, length) {
|
|
334
|
+
if (length < 48) _mask(source, mask, output, offset, length);
|
|
335
|
+
else bufferUtil.mask(source, mask, output, offset, length);
|
|
336
|
+
};
|
|
337
|
+
module.exports.unmask = function(buffer, mask) {
|
|
338
|
+
if (buffer.length < 32) _unmask(buffer, mask);
|
|
339
|
+
else bufferUtil.unmask(buffer, mask);
|
|
340
|
+
};
|
|
341
|
+
} catch (e) {
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/limiter.js
|
|
348
|
+
var require_limiter = __commonJS({
|
|
349
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/limiter.js"(exports, module) {
|
|
350
|
+
var kDone = Symbol("kDone");
|
|
351
|
+
var kRun = Symbol("kRun");
|
|
352
|
+
var Limiter = class {
|
|
353
|
+
/**
|
|
354
|
+
* Creates a new `Limiter`.
|
|
355
|
+
*
|
|
356
|
+
* @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
|
|
357
|
+
* to run concurrently
|
|
358
|
+
*/
|
|
359
|
+
constructor(concurrency) {
|
|
360
|
+
this[kDone] = () => {
|
|
361
|
+
this.pending--;
|
|
362
|
+
this[kRun]();
|
|
363
|
+
};
|
|
364
|
+
this.concurrency = concurrency || Infinity;
|
|
365
|
+
this.jobs = [];
|
|
366
|
+
this.pending = 0;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Adds a job to the queue.
|
|
370
|
+
*
|
|
371
|
+
* @param {Function} job The job to run
|
|
372
|
+
* @public
|
|
373
|
+
*/
|
|
374
|
+
add(job) {
|
|
375
|
+
this.jobs.push(job);
|
|
376
|
+
this[kRun]();
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Removes a job from the queue and runs it if possible.
|
|
380
|
+
*
|
|
381
|
+
* @private
|
|
382
|
+
*/
|
|
383
|
+
[kRun]() {
|
|
384
|
+
if (this.pending === this.concurrency) return;
|
|
385
|
+
if (this.jobs.length) {
|
|
386
|
+
const job = this.jobs.shift();
|
|
387
|
+
this.pending++;
|
|
388
|
+
job(this[kDone]);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
module.exports = Limiter;
|
|
393
|
+
}
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/permessage-deflate.js
|
|
397
|
+
var require_permessage_deflate = __commonJS({
|
|
398
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
|
|
399
|
+
var zlib = __require("zlib");
|
|
400
|
+
var bufferUtil = require_buffer_util();
|
|
401
|
+
var Limiter = require_limiter();
|
|
402
|
+
var { kStatusCode } = require_constants();
|
|
403
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
404
|
+
var TRAILER = Buffer.from([0, 0, 255, 255]);
|
|
405
|
+
var kPerMessageDeflate = Symbol("permessage-deflate");
|
|
406
|
+
var kTotalLength = Symbol("total-length");
|
|
407
|
+
var kCallback = Symbol("callback");
|
|
408
|
+
var kBuffers = Symbol("buffers");
|
|
409
|
+
var kError = Symbol("error");
|
|
410
|
+
var zlibLimiter;
|
|
411
|
+
var PerMessageDeflate = class {
|
|
412
|
+
/**
|
|
413
|
+
* Creates a PerMessageDeflate instance.
|
|
414
|
+
*
|
|
415
|
+
* @param {Object} [options] Configuration options
|
|
416
|
+
* @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
|
|
417
|
+
* for, or request, a custom client window size
|
|
418
|
+
* @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
|
|
419
|
+
* acknowledge disabling of client context takeover
|
|
420
|
+
* @param {Number} [options.concurrencyLimit=10] The number of concurrent
|
|
421
|
+
* calls to zlib
|
|
422
|
+
* @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
|
|
423
|
+
* use of a custom server window size
|
|
424
|
+
* @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
|
|
425
|
+
* disabling of server context takeover
|
|
426
|
+
* @param {Number} [options.threshold=1024] Size (in bytes) below which
|
|
427
|
+
* messages should not be compressed if context takeover is disabled
|
|
428
|
+
* @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
|
|
429
|
+
* deflate
|
|
430
|
+
* @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
|
|
431
|
+
* inflate
|
|
432
|
+
* @param {Boolean} [isServer=false] Create the instance in either server or
|
|
433
|
+
* client mode
|
|
434
|
+
* @param {Number} [maxPayload=0] The maximum allowed message length
|
|
435
|
+
*/
|
|
436
|
+
constructor(options, isServer, maxPayload) {
|
|
437
|
+
this._maxPayload = maxPayload | 0;
|
|
438
|
+
this._options = options || {};
|
|
439
|
+
this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
|
|
440
|
+
this._isServer = !!isServer;
|
|
441
|
+
this._deflate = null;
|
|
442
|
+
this._inflate = null;
|
|
443
|
+
this.params = null;
|
|
444
|
+
if (!zlibLimiter) {
|
|
445
|
+
const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
|
|
446
|
+
zlibLimiter = new Limiter(concurrency);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* @type {String}
|
|
451
|
+
*/
|
|
452
|
+
static get extensionName() {
|
|
453
|
+
return "permessage-deflate";
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Create an extension negotiation offer.
|
|
457
|
+
*
|
|
458
|
+
* @return {Object} Extension parameters
|
|
459
|
+
* @public
|
|
460
|
+
*/
|
|
461
|
+
offer() {
|
|
462
|
+
const params = {};
|
|
463
|
+
if (this._options.serverNoContextTakeover) {
|
|
464
|
+
params.server_no_context_takeover = true;
|
|
465
|
+
}
|
|
466
|
+
if (this._options.clientNoContextTakeover) {
|
|
467
|
+
params.client_no_context_takeover = true;
|
|
468
|
+
}
|
|
469
|
+
if (this._options.serverMaxWindowBits) {
|
|
470
|
+
params.server_max_window_bits = this._options.serverMaxWindowBits;
|
|
471
|
+
}
|
|
472
|
+
if (this._options.clientMaxWindowBits) {
|
|
473
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
474
|
+
} else if (this._options.clientMaxWindowBits == null) {
|
|
475
|
+
params.client_max_window_bits = true;
|
|
476
|
+
}
|
|
477
|
+
return params;
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Accept an extension negotiation offer/response.
|
|
481
|
+
*
|
|
482
|
+
* @param {Array} configurations The extension negotiation offers/reponse
|
|
483
|
+
* @return {Object} Accepted configuration
|
|
484
|
+
* @public
|
|
485
|
+
*/
|
|
486
|
+
accept(configurations) {
|
|
487
|
+
configurations = this.normalizeParams(configurations);
|
|
488
|
+
this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
|
|
489
|
+
return this.params;
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Releases all resources used by the extension.
|
|
493
|
+
*
|
|
494
|
+
* @public
|
|
495
|
+
*/
|
|
496
|
+
cleanup() {
|
|
497
|
+
if (this._inflate) {
|
|
498
|
+
this._inflate.close();
|
|
499
|
+
this._inflate = null;
|
|
500
|
+
}
|
|
501
|
+
if (this._deflate) {
|
|
502
|
+
const callback = this._deflate[kCallback];
|
|
503
|
+
this._deflate.close();
|
|
504
|
+
this._deflate = null;
|
|
505
|
+
if (callback) {
|
|
506
|
+
callback(
|
|
507
|
+
new Error(
|
|
508
|
+
"The deflate stream was closed while data was being processed"
|
|
509
|
+
)
|
|
510
|
+
);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Accept an extension negotiation offer.
|
|
516
|
+
*
|
|
517
|
+
* @param {Array} offers The extension negotiation offers
|
|
518
|
+
* @return {Object} Accepted configuration
|
|
519
|
+
* @private
|
|
520
|
+
*/
|
|
521
|
+
acceptAsServer(offers) {
|
|
522
|
+
const opts = this._options;
|
|
523
|
+
const accepted = offers.find((params) => {
|
|
524
|
+
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) {
|
|
525
|
+
return false;
|
|
526
|
+
}
|
|
527
|
+
return true;
|
|
528
|
+
});
|
|
529
|
+
if (!accepted) {
|
|
530
|
+
throw new Error("None of the extension offers can be accepted");
|
|
531
|
+
}
|
|
532
|
+
if (opts.serverNoContextTakeover) {
|
|
533
|
+
accepted.server_no_context_takeover = true;
|
|
534
|
+
}
|
|
535
|
+
if (opts.clientNoContextTakeover) {
|
|
536
|
+
accepted.client_no_context_takeover = true;
|
|
537
|
+
}
|
|
538
|
+
if (typeof opts.serverMaxWindowBits === "number") {
|
|
539
|
+
accepted.server_max_window_bits = opts.serverMaxWindowBits;
|
|
540
|
+
}
|
|
541
|
+
if (typeof opts.clientMaxWindowBits === "number") {
|
|
542
|
+
accepted.client_max_window_bits = opts.clientMaxWindowBits;
|
|
543
|
+
} else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
|
|
544
|
+
delete accepted.client_max_window_bits;
|
|
545
|
+
}
|
|
546
|
+
return accepted;
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Accept the extension negotiation response.
|
|
550
|
+
*
|
|
551
|
+
* @param {Array} response The extension negotiation response
|
|
552
|
+
* @return {Object} Accepted configuration
|
|
553
|
+
* @private
|
|
554
|
+
*/
|
|
555
|
+
acceptAsClient(response) {
|
|
556
|
+
const params = response[0];
|
|
557
|
+
if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
|
|
558
|
+
throw new Error('Unexpected parameter "client_no_context_takeover"');
|
|
559
|
+
}
|
|
560
|
+
if (!params.client_max_window_bits) {
|
|
561
|
+
if (typeof this._options.clientMaxWindowBits === "number") {
|
|
562
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
563
|
+
}
|
|
564
|
+
} else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
|
|
565
|
+
throw new Error(
|
|
566
|
+
'Unexpected or invalid parameter "client_max_window_bits"'
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
return params;
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Normalize parameters.
|
|
573
|
+
*
|
|
574
|
+
* @param {Array} configurations The extension negotiation offers/reponse
|
|
575
|
+
* @return {Array} The offers/response with normalized parameters
|
|
576
|
+
* @private
|
|
577
|
+
*/
|
|
578
|
+
normalizeParams(configurations) {
|
|
579
|
+
configurations.forEach((params) => {
|
|
580
|
+
Object.keys(params).forEach((key) => {
|
|
581
|
+
let value = params[key];
|
|
582
|
+
if (value.length > 1) {
|
|
583
|
+
throw new Error(`Parameter "${key}" must have only a single value`);
|
|
584
|
+
}
|
|
585
|
+
value = value[0];
|
|
586
|
+
if (key === "client_max_window_bits") {
|
|
587
|
+
if (value !== true) {
|
|
588
|
+
const num = +value;
|
|
589
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
590
|
+
throw new TypeError(
|
|
591
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
value = num;
|
|
595
|
+
} else if (!this._isServer) {
|
|
596
|
+
throw new TypeError(
|
|
597
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
} else if (key === "server_max_window_bits") {
|
|
601
|
+
const num = +value;
|
|
602
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
603
|
+
throw new TypeError(
|
|
604
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
value = num;
|
|
608
|
+
} else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
|
|
609
|
+
if (value !== true) {
|
|
610
|
+
throw new TypeError(
|
|
611
|
+
`Invalid value for parameter "${key}": ${value}`
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
} else {
|
|
615
|
+
throw new Error(`Unknown parameter "${key}"`);
|
|
616
|
+
}
|
|
617
|
+
params[key] = value;
|
|
618
|
+
});
|
|
619
|
+
});
|
|
620
|
+
return configurations;
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Decompress data. Concurrency limited.
|
|
624
|
+
*
|
|
625
|
+
* @param {Buffer} data Compressed data
|
|
626
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
627
|
+
* @param {Function} callback Callback
|
|
628
|
+
* @public
|
|
629
|
+
*/
|
|
630
|
+
decompress(data, fin, callback) {
|
|
631
|
+
zlibLimiter.add((done) => {
|
|
632
|
+
this._decompress(data, fin, (err, result) => {
|
|
633
|
+
done();
|
|
634
|
+
callback(err, result);
|
|
635
|
+
});
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Compress data. Concurrency limited.
|
|
640
|
+
*
|
|
641
|
+
* @param {(Buffer|String)} data Data to compress
|
|
642
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
643
|
+
* @param {Function} callback Callback
|
|
644
|
+
* @public
|
|
645
|
+
*/
|
|
646
|
+
compress(data, fin, callback) {
|
|
647
|
+
zlibLimiter.add((done) => {
|
|
648
|
+
this._compress(data, fin, (err, result) => {
|
|
649
|
+
done();
|
|
650
|
+
callback(err, result);
|
|
651
|
+
});
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Decompress data.
|
|
656
|
+
*
|
|
657
|
+
* @param {Buffer} data Compressed data
|
|
658
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
659
|
+
* @param {Function} callback Callback
|
|
660
|
+
* @private
|
|
661
|
+
*/
|
|
662
|
+
_decompress(data, fin, callback) {
|
|
663
|
+
const endpoint = this._isServer ? "client" : "server";
|
|
664
|
+
if (!this._inflate) {
|
|
665
|
+
const key = `${endpoint}_max_window_bits`;
|
|
666
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
667
|
+
this._inflate = zlib.createInflateRaw({
|
|
668
|
+
...this._options.zlibInflateOptions,
|
|
669
|
+
windowBits
|
|
670
|
+
});
|
|
671
|
+
this._inflate[kPerMessageDeflate] = this;
|
|
672
|
+
this._inflate[kTotalLength] = 0;
|
|
673
|
+
this._inflate[kBuffers] = [];
|
|
674
|
+
this._inflate.on("error", inflateOnError);
|
|
675
|
+
this._inflate.on("data", inflateOnData);
|
|
676
|
+
}
|
|
677
|
+
this._inflate[kCallback] = callback;
|
|
678
|
+
this._inflate.write(data);
|
|
679
|
+
if (fin) this._inflate.write(TRAILER);
|
|
680
|
+
this._inflate.flush(() => {
|
|
681
|
+
const err = this._inflate[kError];
|
|
682
|
+
if (err) {
|
|
683
|
+
this._inflate.close();
|
|
684
|
+
this._inflate = null;
|
|
685
|
+
callback(err);
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
const data2 = bufferUtil.concat(
|
|
689
|
+
this._inflate[kBuffers],
|
|
690
|
+
this._inflate[kTotalLength]
|
|
691
|
+
);
|
|
692
|
+
if (this._inflate._readableState.endEmitted) {
|
|
693
|
+
this._inflate.close();
|
|
694
|
+
this._inflate = null;
|
|
695
|
+
} else {
|
|
696
|
+
this._inflate[kTotalLength] = 0;
|
|
697
|
+
this._inflate[kBuffers] = [];
|
|
698
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
699
|
+
this._inflate.reset();
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
callback(null, data2);
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Compress data.
|
|
707
|
+
*
|
|
708
|
+
* @param {(Buffer|String)} data Data to compress
|
|
709
|
+
* @param {Boolean} fin Specifies whether or not this is the last fragment
|
|
710
|
+
* @param {Function} callback Callback
|
|
711
|
+
* @private
|
|
712
|
+
*/
|
|
713
|
+
_compress(data, fin, callback) {
|
|
714
|
+
const endpoint = this._isServer ? "server" : "client";
|
|
715
|
+
if (!this._deflate) {
|
|
716
|
+
const key = `${endpoint}_max_window_bits`;
|
|
717
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
718
|
+
this._deflate = zlib.createDeflateRaw({
|
|
719
|
+
...this._options.zlibDeflateOptions,
|
|
720
|
+
windowBits
|
|
721
|
+
});
|
|
722
|
+
this._deflate[kTotalLength] = 0;
|
|
723
|
+
this._deflate[kBuffers] = [];
|
|
724
|
+
this._deflate.on("data", deflateOnData);
|
|
725
|
+
}
|
|
726
|
+
this._deflate[kCallback] = callback;
|
|
727
|
+
this._deflate.write(data);
|
|
728
|
+
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
|
|
729
|
+
if (!this._deflate) {
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
let data2 = bufferUtil.concat(
|
|
733
|
+
this._deflate[kBuffers],
|
|
734
|
+
this._deflate[kTotalLength]
|
|
735
|
+
);
|
|
736
|
+
if (fin) {
|
|
737
|
+
data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
|
|
738
|
+
}
|
|
739
|
+
this._deflate[kCallback] = null;
|
|
740
|
+
this._deflate[kTotalLength] = 0;
|
|
741
|
+
this._deflate[kBuffers] = [];
|
|
742
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
743
|
+
this._deflate.reset();
|
|
744
|
+
}
|
|
745
|
+
callback(null, data2);
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
module.exports = PerMessageDeflate;
|
|
750
|
+
function deflateOnData(chunk) {
|
|
751
|
+
this[kBuffers].push(chunk);
|
|
752
|
+
this[kTotalLength] += chunk.length;
|
|
753
|
+
}
|
|
754
|
+
function inflateOnData(chunk) {
|
|
755
|
+
this[kTotalLength] += chunk.length;
|
|
756
|
+
if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
|
|
757
|
+
this[kBuffers].push(chunk);
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
this[kError] = new RangeError("Max payload size exceeded");
|
|
761
|
+
this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
|
|
762
|
+
this[kError][kStatusCode] = 1009;
|
|
763
|
+
this.removeListener("data", inflateOnData);
|
|
764
|
+
this.reset();
|
|
765
|
+
}
|
|
766
|
+
function inflateOnError(err) {
|
|
767
|
+
this[kPerMessageDeflate]._inflate = null;
|
|
768
|
+
if (this[kError]) {
|
|
769
|
+
this[kCallback](this[kError]);
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
err[kStatusCode] = 1007;
|
|
773
|
+
this[kCallback](err);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
});
|
|
777
|
+
|
|
778
|
+
// ../../node_modules/.bun/utf-8-validate@6.0.5/node_modules/utf-8-validate/fallback.js
|
|
779
|
+
var require_fallback2 = __commonJS({
|
|
780
|
+
"../../node_modules/.bun/utf-8-validate@6.0.5/node_modules/utf-8-validate/fallback.js"(exports, module) {
|
|
781
|
+
function isValidUTF8(buf) {
|
|
782
|
+
const len = buf.length;
|
|
783
|
+
let i = 0;
|
|
784
|
+
while (i < len) {
|
|
785
|
+
if ((buf[i] & 128) === 0) {
|
|
786
|
+
i++;
|
|
787
|
+
} else if ((buf[i] & 224) === 192) {
|
|
788
|
+
if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
|
|
789
|
+
return false;
|
|
790
|
+
}
|
|
791
|
+
i += 2;
|
|
792
|
+
} else if ((buf[i] & 240) === 224) {
|
|
793
|
+
if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // overlong
|
|
794
|
+
buf[i] === 237 && (buf[i + 1] & 224) === 160) {
|
|
795
|
+
return false;
|
|
796
|
+
}
|
|
797
|
+
i += 3;
|
|
798
|
+
} else if ((buf[i] & 248) === 240) {
|
|
799
|
+
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
|
|
800
|
+
buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
|
|
801
|
+
return false;
|
|
802
|
+
}
|
|
803
|
+
i += 4;
|
|
804
|
+
} else {
|
|
805
|
+
return false;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return true;
|
|
809
|
+
}
|
|
810
|
+
module.exports = isValidUTF8;
|
|
811
|
+
}
|
|
812
|
+
});
|
|
813
|
+
|
|
814
|
+
// ../../node_modules/.bun/utf-8-validate@6.0.5/node_modules/utf-8-validate/index.js
|
|
815
|
+
var require_utf_8_validate = __commonJS({
|
|
816
|
+
"../../node_modules/.bun/utf-8-validate@6.0.5/node_modules/utf-8-validate/index.js"(exports, module) {
|
|
817
|
+
try {
|
|
818
|
+
module.exports = require_node_gyp_build2()(__dirname);
|
|
819
|
+
} catch (e) {
|
|
820
|
+
module.exports = require_fallback2();
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
});
|
|
824
|
+
|
|
825
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/validation.js
|
|
826
|
+
var require_validation = __commonJS({
|
|
827
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/validation.js"(exports, module) {
|
|
828
|
+
var { isUtf8 } = __require("buffer");
|
|
829
|
+
var { hasBlob } = require_constants();
|
|
830
|
+
var tokenChars = [
|
|
831
|
+
0,
|
|
832
|
+
0,
|
|
833
|
+
0,
|
|
834
|
+
0,
|
|
835
|
+
0,
|
|
836
|
+
0,
|
|
837
|
+
0,
|
|
838
|
+
0,
|
|
839
|
+
0,
|
|
840
|
+
0,
|
|
841
|
+
0,
|
|
842
|
+
0,
|
|
843
|
+
0,
|
|
844
|
+
0,
|
|
845
|
+
0,
|
|
846
|
+
0,
|
|
847
|
+
// 0 - 15
|
|
848
|
+
0,
|
|
849
|
+
0,
|
|
850
|
+
0,
|
|
851
|
+
0,
|
|
852
|
+
0,
|
|
853
|
+
0,
|
|
854
|
+
0,
|
|
855
|
+
0,
|
|
856
|
+
0,
|
|
857
|
+
0,
|
|
858
|
+
0,
|
|
859
|
+
0,
|
|
860
|
+
0,
|
|
861
|
+
0,
|
|
862
|
+
0,
|
|
863
|
+
0,
|
|
864
|
+
// 16 - 31
|
|
865
|
+
0,
|
|
866
|
+
1,
|
|
867
|
+
0,
|
|
868
|
+
1,
|
|
869
|
+
1,
|
|
870
|
+
1,
|
|
871
|
+
1,
|
|
872
|
+
1,
|
|
873
|
+
0,
|
|
874
|
+
0,
|
|
875
|
+
1,
|
|
876
|
+
1,
|
|
877
|
+
0,
|
|
878
|
+
1,
|
|
879
|
+
1,
|
|
880
|
+
0,
|
|
881
|
+
// 32 - 47
|
|
882
|
+
1,
|
|
883
|
+
1,
|
|
884
|
+
1,
|
|
885
|
+
1,
|
|
886
|
+
1,
|
|
887
|
+
1,
|
|
888
|
+
1,
|
|
889
|
+
1,
|
|
890
|
+
1,
|
|
891
|
+
1,
|
|
892
|
+
0,
|
|
893
|
+
0,
|
|
894
|
+
0,
|
|
895
|
+
0,
|
|
896
|
+
0,
|
|
897
|
+
0,
|
|
898
|
+
// 48 - 63
|
|
899
|
+
0,
|
|
900
|
+
1,
|
|
901
|
+
1,
|
|
902
|
+
1,
|
|
903
|
+
1,
|
|
904
|
+
1,
|
|
905
|
+
1,
|
|
906
|
+
1,
|
|
907
|
+
1,
|
|
908
|
+
1,
|
|
909
|
+
1,
|
|
910
|
+
1,
|
|
911
|
+
1,
|
|
912
|
+
1,
|
|
913
|
+
1,
|
|
914
|
+
1,
|
|
915
|
+
// 64 - 79
|
|
916
|
+
1,
|
|
917
|
+
1,
|
|
918
|
+
1,
|
|
919
|
+
1,
|
|
920
|
+
1,
|
|
921
|
+
1,
|
|
922
|
+
1,
|
|
923
|
+
1,
|
|
924
|
+
1,
|
|
925
|
+
1,
|
|
926
|
+
1,
|
|
927
|
+
0,
|
|
928
|
+
0,
|
|
929
|
+
0,
|
|
930
|
+
1,
|
|
931
|
+
1,
|
|
932
|
+
// 80 - 95
|
|
933
|
+
1,
|
|
934
|
+
1,
|
|
935
|
+
1,
|
|
936
|
+
1,
|
|
937
|
+
1,
|
|
938
|
+
1,
|
|
939
|
+
1,
|
|
940
|
+
1,
|
|
941
|
+
1,
|
|
942
|
+
1,
|
|
943
|
+
1,
|
|
944
|
+
1,
|
|
945
|
+
1,
|
|
946
|
+
1,
|
|
947
|
+
1,
|
|
948
|
+
1,
|
|
949
|
+
// 96 - 111
|
|
950
|
+
1,
|
|
951
|
+
1,
|
|
952
|
+
1,
|
|
953
|
+
1,
|
|
954
|
+
1,
|
|
955
|
+
1,
|
|
956
|
+
1,
|
|
957
|
+
1,
|
|
958
|
+
1,
|
|
959
|
+
1,
|
|
960
|
+
1,
|
|
961
|
+
0,
|
|
962
|
+
1,
|
|
963
|
+
0,
|
|
964
|
+
1,
|
|
965
|
+
0
|
|
966
|
+
// 112 - 127
|
|
967
|
+
];
|
|
968
|
+
function isValidStatusCode(code) {
|
|
969
|
+
return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
|
|
970
|
+
}
|
|
971
|
+
function _isValidUTF8(buf) {
|
|
972
|
+
const len = buf.length;
|
|
973
|
+
let i = 0;
|
|
974
|
+
while (i < len) {
|
|
975
|
+
if ((buf[i] & 128) === 0) {
|
|
976
|
+
i++;
|
|
977
|
+
} else if ((buf[i] & 224) === 192) {
|
|
978
|
+
if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
|
|
979
|
+
return false;
|
|
980
|
+
}
|
|
981
|
+
i += 2;
|
|
982
|
+
} else if ((buf[i] & 240) === 224) {
|
|
983
|
+
if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
|
|
984
|
+
buf[i] === 237 && (buf[i + 1] & 224) === 160) {
|
|
985
|
+
return false;
|
|
986
|
+
}
|
|
987
|
+
i += 3;
|
|
988
|
+
} else if ((buf[i] & 248) === 240) {
|
|
989
|
+
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
|
|
990
|
+
buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
|
|
991
|
+
return false;
|
|
992
|
+
}
|
|
993
|
+
i += 4;
|
|
994
|
+
} else {
|
|
995
|
+
return false;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
return true;
|
|
999
|
+
}
|
|
1000
|
+
function isBlob(value) {
|
|
1001
|
+
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");
|
|
1002
|
+
}
|
|
1003
|
+
module.exports = {
|
|
1004
|
+
isBlob,
|
|
1005
|
+
isValidStatusCode,
|
|
1006
|
+
isValidUTF8: _isValidUTF8,
|
|
1007
|
+
tokenChars
|
|
1008
|
+
};
|
|
1009
|
+
if (isUtf8) {
|
|
1010
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
1011
|
+
return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
|
|
1012
|
+
};
|
|
1013
|
+
} else if (!process.env.WS_NO_UTF_8_VALIDATE) {
|
|
1014
|
+
try {
|
|
1015
|
+
const isValidUTF8 = require_utf_8_validate();
|
|
1016
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
1017
|
+
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
|
|
1018
|
+
};
|
|
1019
|
+
} catch (e) {
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
});
|
|
1024
|
+
|
|
1025
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/receiver.js
|
|
1026
|
+
var require_receiver = __commonJS({
|
|
1027
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/receiver.js"(exports, module) {
|
|
1028
|
+
var { Writable } = __require("stream");
|
|
1029
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
1030
|
+
var {
|
|
1031
|
+
BINARY_TYPES,
|
|
1032
|
+
EMPTY_BUFFER,
|
|
1033
|
+
kStatusCode,
|
|
1034
|
+
kWebSocket
|
|
1035
|
+
} = require_constants();
|
|
1036
|
+
var { concat, toArrayBuffer, unmask } = require_buffer_util();
|
|
1037
|
+
var { isValidStatusCode, isValidUTF8 } = require_validation();
|
|
1038
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
1039
|
+
var GET_INFO = 0;
|
|
1040
|
+
var GET_PAYLOAD_LENGTH_16 = 1;
|
|
1041
|
+
var GET_PAYLOAD_LENGTH_64 = 2;
|
|
1042
|
+
var GET_MASK = 3;
|
|
1043
|
+
var GET_DATA = 4;
|
|
1044
|
+
var INFLATING = 5;
|
|
1045
|
+
var DEFER_EVENT = 6;
|
|
1046
|
+
var Receiver2 = class extends Writable {
|
|
1047
|
+
/**
|
|
1048
|
+
* Creates a Receiver instance.
|
|
1049
|
+
*
|
|
1050
|
+
* @param {Object} [options] Options object
|
|
1051
|
+
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
|
|
1052
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
1053
|
+
* multiple times in the same tick
|
|
1054
|
+
* @param {String} [options.binaryType=nodebuffer] The type for binary data
|
|
1055
|
+
* @param {Object} [options.extensions] An object containing the negotiated
|
|
1056
|
+
* extensions
|
|
1057
|
+
* @param {Boolean} [options.isServer=false] Specifies whether to operate in
|
|
1058
|
+
* client or server mode
|
|
1059
|
+
* @param {Number} [options.maxPayload=0] The maximum allowed message length
|
|
1060
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
1061
|
+
* not to skip UTF-8 validation for text and close messages
|
|
1062
|
+
*/
|
|
1063
|
+
constructor(options = {}) {
|
|
1064
|
+
super();
|
|
1065
|
+
this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
|
|
1066
|
+
this._binaryType = options.binaryType || BINARY_TYPES[0];
|
|
1067
|
+
this._extensions = options.extensions || {};
|
|
1068
|
+
this._isServer = !!options.isServer;
|
|
1069
|
+
this._maxPayload = options.maxPayload | 0;
|
|
1070
|
+
this._skipUTF8Validation = !!options.skipUTF8Validation;
|
|
1071
|
+
this[kWebSocket] = void 0;
|
|
1072
|
+
this._bufferedBytes = 0;
|
|
1073
|
+
this._buffers = [];
|
|
1074
|
+
this._compressed = false;
|
|
1075
|
+
this._payloadLength = 0;
|
|
1076
|
+
this._mask = void 0;
|
|
1077
|
+
this._fragmented = 0;
|
|
1078
|
+
this._masked = false;
|
|
1079
|
+
this._fin = false;
|
|
1080
|
+
this._opcode = 0;
|
|
1081
|
+
this._totalPayloadLength = 0;
|
|
1082
|
+
this._messageLength = 0;
|
|
1083
|
+
this._fragments = [];
|
|
1084
|
+
this._errored = false;
|
|
1085
|
+
this._loop = false;
|
|
1086
|
+
this._state = GET_INFO;
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Implements `Writable.prototype._write()`.
|
|
1090
|
+
*
|
|
1091
|
+
* @param {Buffer} chunk The chunk of data to write
|
|
1092
|
+
* @param {String} encoding The character encoding of `chunk`
|
|
1093
|
+
* @param {Function} cb Callback
|
|
1094
|
+
* @private
|
|
1095
|
+
*/
|
|
1096
|
+
_write(chunk, encoding, cb) {
|
|
1097
|
+
if (this._opcode === 8 && this._state == GET_INFO) return cb();
|
|
1098
|
+
this._bufferedBytes += chunk.length;
|
|
1099
|
+
this._buffers.push(chunk);
|
|
1100
|
+
this.startLoop(cb);
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Consumes `n` bytes from the buffered data.
|
|
1104
|
+
*
|
|
1105
|
+
* @param {Number} n The number of bytes to consume
|
|
1106
|
+
* @return {Buffer} The consumed bytes
|
|
1107
|
+
* @private
|
|
1108
|
+
*/
|
|
1109
|
+
consume(n) {
|
|
1110
|
+
this._bufferedBytes -= n;
|
|
1111
|
+
if (n === this._buffers[0].length) return this._buffers.shift();
|
|
1112
|
+
if (n < this._buffers[0].length) {
|
|
1113
|
+
const buf = this._buffers[0];
|
|
1114
|
+
this._buffers[0] = new FastBuffer(
|
|
1115
|
+
buf.buffer,
|
|
1116
|
+
buf.byteOffset + n,
|
|
1117
|
+
buf.length - n
|
|
1118
|
+
);
|
|
1119
|
+
return new FastBuffer(buf.buffer, buf.byteOffset, n);
|
|
1120
|
+
}
|
|
1121
|
+
const dst = Buffer.allocUnsafe(n);
|
|
1122
|
+
do {
|
|
1123
|
+
const buf = this._buffers[0];
|
|
1124
|
+
const offset = dst.length - n;
|
|
1125
|
+
if (n >= buf.length) {
|
|
1126
|
+
dst.set(this._buffers.shift(), offset);
|
|
1127
|
+
} else {
|
|
1128
|
+
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
|
|
1129
|
+
this._buffers[0] = new FastBuffer(
|
|
1130
|
+
buf.buffer,
|
|
1131
|
+
buf.byteOffset + n,
|
|
1132
|
+
buf.length - n
|
|
1133
|
+
);
|
|
1134
|
+
}
|
|
1135
|
+
n -= buf.length;
|
|
1136
|
+
} while (n > 0);
|
|
1137
|
+
return dst;
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* Starts the parsing loop.
|
|
1141
|
+
*
|
|
1142
|
+
* @param {Function} cb Callback
|
|
1143
|
+
* @private
|
|
1144
|
+
*/
|
|
1145
|
+
startLoop(cb) {
|
|
1146
|
+
this._loop = true;
|
|
1147
|
+
do {
|
|
1148
|
+
switch (this._state) {
|
|
1149
|
+
case GET_INFO:
|
|
1150
|
+
this.getInfo(cb);
|
|
1151
|
+
break;
|
|
1152
|
+
case GET_PAYLOAD_LENGTH_16:
|
|
1153
|
+
this.getPayloadLength16(cb);
|
|
1154
|
+
break;
|
|
1155
|
+
case GET_PAYLOAD_LENGTH_64:
|
|
1156
|
+
this.getPayloadLength64(cb);
|
|
1157
|
+
break;
|
|
1158
|
+
case GET_MASK:
|
|
1159
|
+
this.getMask();
|
|
1160
|
+
break;
|
|
1161
|
+
case GET_DATA:
|
|
1162
|
+
this.getData(cb);
|
|
1163
|
+
break;
|
|
1164
|
+
case INFLATING:
|
|
1165
|
+
case DEFER_EVENT:
|
|
1166
|
+
this._loop = false;
|
|
1167
|
+
return;
|
|
1168
|
+
}
|
|
1169
|
+
} while (this._loop);
|
|
1170
|
+
if (!this._errored) cb();
|
|
1171
|
+
}
|
|
1172
|
+
/**
|
|
1173
|
+
* Reads the first two bytes of a frame.
|
|
1174
|
+
*
|
|
1175
|
+
* @param {Function} cb Callback
|
|
1176
|
+
* @private
|
|
1177
|
+
*/
|
|
1178
|
+
getInfo(cb) {
|
|
1179
|
+
if (this._bufferedBytes < 2) {
|
|
1180
|
+
this._loop = false;
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
const buf = this.consume(2);
|
|
1184
|
+
if ((buf[0] & 48) !== 0) {
|
|
1185
|
+
const error = this.createError(
|
|
1186
|
+
RangeError,
|
|
1187
|
+
"RSV2 and RSV3 must be clear",
|
|
1188
|
+
true,
|
|
1189
|
+
1002,
|
|
1190
|
+
"WS_ERR_UNEXPECTED_RSV_2_3"
|
|
1191
|
+
);
|
|
1192
|
+
cb(error);
|
|
1193
|
+
return;
|
|
1194
|
+
}
|
|
1195
|
+
const compressed = (buf[0] & 64) === 64;
|
|
1196
|
+
if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
|
|
1197
|
+
const error = this.createError(
|
|
1198
|
+
RangeError,
|
|
1199
|
+
"RSV1 must be clear",
|
|
1200
|
+
true,
|
|
1201
|
+
1002,
|
|
1202
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
1203
|
+
);
|
|
1204
|
+
cb(error);
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1207
|
+
this._fin = (buf[0] & 128) === 128;
|
|
1208
|
+
this._opcode = buf[0] & 15;
|
|
1209
|
+
this._payloadLength = buf[1] & 127;
|
|
1210
|
+
if (this._opcode === 0) {
|
|
1211
|
+
if (compressed) {
|
|
1212
|
+
const error = this.createError(
|
|
1213
|
+
RangeError,
|
|
1214
|
+
"RSV1 must be clear",
|
|
1215
|
+
true,
|
|
1216
|
+
1002,
|
|
1217
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
1218
|
+
);
|
|
1219
|
+
cb(error);
|
|
1220
|
+
return;
|
|
1221
|
+
}
|
|
1222
|
+
if (!this._fragmented) {
|
|
1223
|
+
const error = this.createError(
|
|
1224
|
+
RangeError,
|
|
1225
|
+
"invalid opcode 0",
|
|
1226
|
+
true,
|
|
1227
|
+
1002,
|
|
1228
|
+
"WS_ERR_INVALID_OPCODE"
|
|
1229
|
+
);
|
|
1230
|
+
cb(error);
|
|
1231
|
+
return;
|
|
1232
|
+
}
|
|
1233
|
+
this._opcode = this._fragmented;
|
|
1234
|
+
} else if (this._opcode === 1 || this._opcode === 2) {
|
|
1235
|
+
if (this._fragmented) {
|
|
1236
|
+
const error = this.createError(
|
|
1237
|
+
RangeError,
|
|
1238
|
+
`invalid opcode ${this._opcode}`,
|
|
1239
|
+
true,
|
|
1240
|
+
1002,
|
|
1241
|
+
"WS_ERR_INVALID_OPCODE"
|
|
1242
|
+
);
|
|
1243
|
+
cb(error);
|
|
1244
|
+
return;
|
|
1245
|
+
}
|
|
1246
|
+
this._compressed = compressed;
|
|
1247
|
+
} else if (this._opcode > 7 && this._opcode < 11) {
|
|
1248
|
+
if (!this._fin) {
|
|
1249
|
+
const error = this.createError(
|
|
1250
|
+
RangeError,
|
|
1251
|
+
"FIN must be set",
|
|
1252
|
+
true,
|
|
1253
|
+
1002,
|
|
1254
|
+
"WS_ERR_EXPECTED_FIN"
|
|
1255
|
+
);
|
|
1256
|
+
cb(error);
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
if (compressed) {
|
|
1260
|
+
const error = this.createError(
|
|
1261
|
+
RangeError,
|
|
1262
|
+
"RSV1 must be clear",
|
|
1263
|
+
true,
|
|
1264
|
+
1002,
|
|
1265
|
+
"WS_ERR_UNEXPECTED_RSV_1"
|
|
1266
|
+
);
|
|
1267
|
+
cb(error);
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
1270
|
+
if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
|
|
1271
|
+
const error = this.createError(
|
|
1272
|
+
RangeError,
|
|
1273
|
+
`invalid payload length ${this._payloadLength}`,
|
|
1274
|
+
true,
|
|
1275
|
+
1002,
|
|
1276
|
+
"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
|
|
1277
|
+
);
|
|
1278
|
+
cb(error);
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1281
|
+
} else {
|
|
1282
|
+
const error = this.createError(
|
|
1283
|
+
RangeError,
|
|
1284
|
+
`invalid opcode ${this._opcode}`,
|
|
1285
|
+
true,
|
|
1286
|
+
1002,
|
|
1287
|
+
"WS_ERR_INVALID_OPCODE"
|
|
1288
|
+
);
|
|
1289
|
+
cb(error);
|
|
1290
|
+
return;
|
|
1291
|
+
}
|
|
1292
|
+
if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
|
|
1293
|
+
this._masked = (buf[1] & 128) === 128;
|
|
1294
|
+
if (this._isServer) {
|
|
1295
|
+
if (!this._masked) {
|
|
1296
|
+
const error = this.createError(
|
|
1297
|
+
RangeError,
|
|
1298
|
+
"MASK must be set",
|
|
1299
|
+
true,
|
|
1300
|
+
1002,
|
|
1301
|
+
"WS_ERR_EXPECTED_MASK"
|
|
1302
|
+
);
|
|
1303
|
+
cb(error);
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
} else if (this._masked) {
|
|
1307
|
+
const error = this.createError(
|
|
1308
|
+
RangeError,
|
|
1309
|
+
"MASK must be clear",
|
|
1310
|
+
true,
|
|
1311
|
+
1002,
|
|
1312
|
+
"WS_ERR_UNEXPECTED_MASK"
|
|
1313
|
+
);
|
|
1314
|
+
cb(error);
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
|
|
1318
|
+
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
|
|
1319
|
+
else this.haveLength(cb);
|
|
1320
|
+
}
|
|
1321
|
+
/**
|
|
1322
|
+
* Gets extended payload length (7+16).
|
|
1323
|
+
*
|
|
1324
|
+
* @param {Function} cb Callback
|
|
1325
|
+
* @private
|
|
1326
|
+
*/
|
|
1327
|
+
getPayloadLength16(cb) {
|
|
1328
|
+
if (this._bufferedBytes < 2) {
|
|
1329
|
+
this._loop = false;
|
|
1330
|
+
return;
|
|
1331
|
+
}
|
|
1332
|
+
this._payloadLength = this.consume(2).readUInt16BE(0);
|
|
1333
|
+
this.haveLength(cb);
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* Gets extended payload length (7+64).
|
|
1337
|
+
*
|
|
1338
|
+
* @param {Function} cb Callback
|
|
1339
|
+
* @private
|
|
1340
|
+
*/
|
|
1341
|
+
getPayloadLength64(cb) {
|
|
1342
|
+
if (this._bufferedBytes < 8) {
|
|
1343
|
+
this._loop = false;
|
|
1344
|
+
return;
|
|
1345
|
+
}
|
|
1346
|
+
const buf = this.consume(8);
|
|
1347
|
+
const num = buf.readUInt32BE(0);
|
|
1348
|
+
if (num > Math.pow(2, 53 - 32) - 1) {
|
|
1349
|
+
const error = this.createError(
|
|
1350
|
+
RangeError,
|
|
1351
|
+
"Unsupported WebSocket frame: payload length > 2^53 - 1",
|
|
1352
|
+
false,
|
|
1353
|
+
1009,
|
|
1354
|
+
"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
|
|
1355
|
+
);
|
|
1356
|
+
cb(error);
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1359
|
+
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
|
|
1360
|
+
this.haveLength(cb);
|
|
1361
|
+
}
|
|
1362
|
+
/**
|
|
1363
|
+
* Payload length has been read.
|
|
1364
|
+
*
|
|
1365
|
+
* @param {Function} cb Callback
|
|
1366
|
+
* @private
|
|
1367
|
+
*/
|
|
1368
|
+
haveLength(cb) {
|
|
1369
|
+
if (this._payloadLength && this._opcode < 8) {
|
|
1370
|
+
this._totalPayloadLength += this._payloadLength;
|
|
1371
|
+
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
|
|
1372
|
+
const error = this.createError(
|
|
1373
|
+
RangeError,
|
|
1374
|
+
"Max payload size exceeded",
|
|
1375
|
+
false,
|
|
1376
|
+
1009,
|
|
1377
|
+
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
|
|
1378
|
+
);
|
|
1379
|
+
cb(error);
|
|
1380
|
+
return;
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
if (this._masked) this._state = GET_MASK;
|
|
1384
|
+
else this._state = GET_DATA;
|
|
1385
|
+
}
|
|
1386
|
+
/**
|
|
1387
|
+
* Reads mask bytes.
|
|
1388
|
+
*
|
|
1389
|
+
* @private
|
|
1390
|
+
*/
|
|
1391
|
+
getMask() {
|
|
1392
|
+
if (this._bufferedBytes < 4) {
|
|
1393
|
+
this._loop = false;
|
|
1394
|
+
return;
|
|
1395
|
+
}
|
|
1396
|
+
this._mask = this.consume(4);
|
|
1397
|
+
this._state = GET_DATA;
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* Reads data bytes.
|
|
1401
|
+
*
|
|
1402
|
+
* @param {Function} cb Callback
|
|
1403
|
+
* @private
|
|
1404
|
+
*/
|
|
1405
|
+
getData(cb) {
|
|
1406
|
+
let data = EMPTY_BUFFER;
|
|
1407
|
+
if (this._payloadLength) {
|
|
1408
|
+
if (this._bufferedBytes < this._payloadLength) {
|
|
1409
|
+
this._loop = false;
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
data = this.consume(this._payloadLength);
|
|
1413
|
+
if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
|
|
1414
|
+
unmask(data, this._mask);
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
if (this._opcode > 7) {
|
|
1418
|
+
this.controlMessage(data, cb);
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
if (this._compressed) {
|
|
1422
|
+
this._state = INFLATING;
|
|
1423
|
+
this.decompress(data, cb);
|
|
1424
|
+
return;
|
|
1425
|
+
}
|
|
1426
|
+
if (data.length) {
|
|
1427
|
+
this._messageLength = this._totalPayloadLength;
|
|
1428
|
+
this._fragments.push(data);
|
|
1429
|
+
}
|
|
1430
|
+
this.dataMessage(cb);
|
|
1431
|
+
}
|
|
1432
|
+
/**
|
|
1433
|
+
* Decompresses data.
|
|
1434
|
+
*
|
|
1435
|
+
* @param {Buffer} data Compressed data
|
|
1436
|
+
* @param {Function} cb Callback
|
|
1437
|
+
* @private
|
|
1438
|
+
*/
|
|
1439
|
+
decompress(data, cb) {
|
|
1440
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
1441
|
+
perMessageDeflate.decompress(data, this._fin, (err, buf) => {
|
|
1442
|
+
if (err) return cb(err);
|
|
1443
|
+
if (buf.length) {
|
|
1444
|
+
this._messageLength += buf.length;
|
|
1445
|
+
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
|
|
1446
|
+
const error = this.createError(
|
|
1447
|
+
RangeError,
|
|
1448
|
+
"Max payload size exceeded",
|
|
1449
|
+
false,
|
|
1450
|
+
1009,
|
|
1451
|
+
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
|
|
1452
|
+
);
|
|
1453
|
+
cb(error);
|
|
1454
|
+
return;
|
|
1455
|
+
}
|
|
1456
|
+
this._fragments.push(buf);
|
|
1457
|
+
}
|
|
1458
|
+
this.dataMessage(cb);
|
|
1459
|
+
if (this._state === GET_INFO) this.startLoop(cb);
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* Handles a data message.
|
|
1464
|
+
*
|
|
1465
|
+
* @param {Function} cb Callback
|
|
1466
|
+
* @private
|
|
1467
|
+
*/
|
|
1468
|
+
dataMessage(cb) {
|
|
1469
|
+
if (!this._fin) {
|
|
1470
|
+
this._state = GET_INFO;
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
const messageLength = this._messageLength;
|
|
1474
|
+
const fragments = this._fragments;
|
|
1475
|
+
this._totalPayloadLength = 0;
|
|
1476
|
+
this._messageLength = 0;
|
|
1477
|
+
this._fragmented = 0;
|
|
1478
|
+
this._fragments = [];
|
|
1479
|
+
if (this._opcode === 2) {
|
|
1480
|
+
let data;
|
|
1481
|
+
if (this._binaryType === "nodebuffer") {
|
|
1482
|
+
data = concat(fragments, messageLength);
|
|
1483
|
+
} else if (this._binaryType === "arraybuffer") {
|
|
1484
|
+
data = toArrayBuffer(concat(fragments, messageLength));
|
|
1485
|
+
} else if (this._binaryType === "blob") {
|
|
1486
|
+
data = new Blob(fragments);
|
|
1487
|
+
} else {
|
|
1488
|
+
data = fragments;
|
|
1489
|
+
}
|
|
1490
|
+
if (this._allowSynchronousEvents) {
|
|
1491
|
+
this.emit("message", data, true);
|
|
1492
|
+
this._state = GET_INFO;
|
|
1493
|
+
} else {
|
|
1494
|
+
this._state = DEFER_EVENT;
|
|
1495
|
+
setImmediate(() => {
|
|
1496
|
+
this.emit("message", data, true);
|
|
1497
|
+
this._state = GET_INFO;
|
|
1498
|
+
this.startLoop(cb);
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
} else {
|
|
1502
|
+
const buf = concat(fragments, messageLength);
|
|
1503
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
1504
|
+
const error = this.createError(
|
|
1505
|
+
Error,
|
|
1506
|
+
"invalid UTF-8 sequence",
|
|
1507
|
+
true,
|
|
1508
|
+
1007,
|
|
1509
|
+
"WS_ERR_INVALID_UTF8"
|
|
1510
|
+
);
|
|
1511
|
+
cb(error);
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1514
|
+
if (this._state === INFLATING || this._allowSynchronousEvents) {
|
|
1515
|
+
this.emit("message", buf, false);
|
|
1516
|
+
this._state = GET_INFO;
|
|
1517
|
+
} else {
|
|
1518
|
+
this._state = DEFER_EVENT;
|
|
1519
|
+
setImmediate(() => {
|
|
1520
|
+
this.emit("message", buf, false);
|
|
1521
|
+
this._state = GET_INFO;
|
|
1522
|
+
this.startLoop(cb);
|
|
1523
|
+
});
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
/**
|
|
1528
|
+
* Handles a control message.
|
|
1529
|
+
*
|
|
1530
|
+
* @param {Buffer} data Data to handle
|
|
1531
|
+
* @return {(Error|RangeError|undefined)} A possible error
|
|
1532
|
+
* @private
|
|
1533
|
+
*/
|
|
1534
|
+
controlMessage(data, cb) {
|
|
1535
|
+
if (this._opcode === 8) {
|
|
1536
|
+
if (data.length === 0) {
|
|
1537
|
+
this._loop = false;
|
|
1538
|
+
this.emit("conclude", 1005, EMPTY_BUFFER);
|
|
1539
|
+
this.end();
|
|
1540
|
+
} else {
|
|
1541
|
+
const code = data.readUInt16BE(0);
|
|
1542
|
+
if (!isValidStatusCode(code)) {
|
|
1543
|
+
const error = this.createError(
|
|
1544
|
+
RangeError,
|
|
1545
|
+
`invalid status code ${code}`,
|
|
1546
|
+
true,
|
|
1547
|
+
1002,
|
|
1548
|
+
"WS_ERR_INVALID_CLOSE_CODE"
|
|
1549
|
+
);
|
|
1550
|
+
cb(error);
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
const buf = new FastBuffer(
|
|
1554
|
+
data.buffer,
|
|
1555
|
+
data.byteOffset + 2,
|
|
1556
|
+
data.length - 2
|
|
1557
|
+
);
|
|
1558
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
1559
|
+
const error = this.createError(
|
|
1560
|
+
Error,
|
|
1561
|
+
"invalid UTF-8 sequence",
|
|
1562
|
+
true,
|
|
1563
|
+
1007,
|
|
1564
|
+
"WS_ERR_INVALID_UTF8"
|
|
1565
|
+
);
|
|
1566
|
+
cb(error);
|
|
1567
|
+
return;
|
|
1568
|
+
}
|
|
1569
|
+
this._loop = false;
|
|
1570
|
+
this.emit("conclude", code, buf);
|
|
1571
|
+
this.end();
|
|
1572
|
+
}
|
|
1573
|
+
this._state = GET_INFO;
|
|
1574
|
+
return;
|
|
1575
|
+
}
|
|
1576
|
+
if (this._allowSynchronousEvents) {
|
|
1577
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
1578
|
+
this._state = GET_INFO;
|
|
1579
|
+
} else {
|
|
1580
|
+
this._state = DEFER_EVENT;
|
|
1581
|
+
setImmediate(() => {
|
|
1582
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
1583
|
+
this._state = GET_INFO;
|
|
1584
|
+
this.startLoop(cb);
|
|
1585
|
+
});
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
/**
|
|
1589
|
+
* Builds an error object.
|
|
1590
|
+
*
|
|
1591
|
+
* @param {function(new:Error|RangeError)} ErrorCtor The error constructor
|
|
1592
|
+
* @param {String} message The error message
|
|
1593
|
+
* @param {Boolean} prefix Specifies whether or not to add a default prefix to
|
|
1594
|
+
* `message`
|
|
1595
|
+
* @param {Number} statusCode The status code
|
|
1596
|
+
* @param {String} errorCode The exposed error code
|
|
1597
|
+
* @return {(Error|RangeError)} The error
|
|
1598
|
+
* @private
|
|
1599
|
+
*/
|
|
1600
|
+
createError(ErrorCtor, message, prefix, statusCode, errorCode) {
|
|
1601
|
+
this._loop = false;
|
|
1602
|
+
this._errored = true;
|
|
1603
|
+
const err = new ErrorCtor(
|
|
1604
|
+
prefix ? `Invalid WebSocket frame: ${message}` : message
|
|
1605
|
+
);
|
|
1606
|
+
Error.captureStackTrace(err, this.createError);
|
|
1607
|
+
err.code = errorCode;
|
|
1608
|
+
err[kStatusCode] = statusCode;
|
|
1609
|
+
return err;
|
|
1610
|
+
}
|
|
1611
|
+
};
|
|
1612
|
+
module.exports = Receiver2;
|
|
1613
|
+
}
|
|
1614
|
+
});
|
|
1615
|
+
|
|
1616
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/sender.js
|
|
1617
|
+
var require_sender = __commonJS({
|
|
1618
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/sender.js"(exports, module) {
|
|
1619
|
+
var { Duplex } = __require("stream");
|
|
1620
|
+
var { randomFillSync } = __require("crypto");
|
|
1621
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
1622
|
+
var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
|
|
1623
|
+
var { isBlob, isValidStatusCode } = require_validation();
|
|
1624
|
+
var { mask: applyMask, toBuffer } = require_buffer_util();
|
|
1625
|
+
var kByteLength = Symbol("kByteLength");
|
|
1626
|
+
var maskBuffer = Buffer.alloc(4);
|
|
1627
|
+
var RANDOM_POOL_SIZE = 8 * 1024;
|
|
1628
|
+
var randomPool;
|
|
1629
|
+
var randomPoolPointer = RANDOM_POOL_SIZE;
|
|
1630
|
+
var DEFAULT = 0;
|
|
1631
|
+
var DEFLATING = 1;
|
|
1632
|
+
var GET_BLOB_DATA = 2;
|
|
1633
|
+
var Sender2 = class _Sender {
|
|
1634
|
+
/**
|
|
1635
|
+
* Creates a Sender instance.
|
|
1636
|
+
*
|
|
1637
|
+
* @param {Duplex} socket The connection socket
|
|
1638
|
+
* @param {Object} [extensions] An object containing the negotiated extensions
|
|
1639
|
+
* @param {Function} [generateMask] The function used to generate the masking
|
|
1640
|
+
* key
|
|
1641
|
+
*/
|
|
1642
|
+
constructor(socket, extensions, generateMask) {
|
|
1643
|
+
this._extensions = extensions || {};
|
|
1644
|
+
if (generateMask) {
|
|
1645
|
+
this._generateMask = generateMask;
|
|
1646
|
+
this._maskBuffer = Buffer.alloc(4);
|
|
1647
|
+
}
|
|
1648
|
+
this._socket = socket;
|
|
1649
|
+
this._firstFragment = true;
|
|
1650
|
+
this._compress = false;
|
|
1651
|
+
this._bufferedBytes = 0;
|
|
1652
|
+
this._queue = [];
|
|
1653
|
+
this._state = DEFAULT;
|
|
1654
|
+
this.onerror = NOOP;
|
|
1655
|
+
this[kWebSocket] = void 0;
|
|
1656
|
+
}
|
|
1657
|
+
/**
|
|
1658
|
+
* Frames a piece of data according to the HyBi WebSocket protocol.
|
|
1659
|
+
*
|
|
1660
|
+
* @param {(Buffer|String)} data The data to frame
|
|
1661
|
+
* @param {Object} options Options object
|
|
1662
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
1663
|
+
* FIN bit
|
|
1664
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
1665
|
+
* masking key
|
|
1666
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1667
|
+
* `data`
|
|
1668
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
1669
|
+
* key
|
|
1670
|
+
* @param {Number} options.opcode The opcode
|
|
1671
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
1672
|
+
* modified
|
|
1673
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
1674
|
+
* RSV1 bit
|
|
1675
|
+
* @return {(Buffer|String)[]} The framed data
|
|
1676
|
+
* @public
|
|
1677
|
+
*/
|
|
1678
|
+
static frame(data, options) {
|
|
1679
|
+
let mask;
|
|
1680
|
+
let merge = false;
|
|
1681
|
+
let offset = 2;
|
|
1682
|
+
let skipMasking = false;
|
|
1683
|
+
if (options.mask) {
|
|
1684
|
+
mask = options.maskBuffer || maskBuffer;
|
|
1685
|
+
if (options.generateMask) {
|
|
1686
|
+
options.generateMask(mask);
|
|
1687
|
+
} else {
|
|
1688
|
+
if (randomPoolPointer === RANDOM_POOL_SIZE) {
|
|
1689
|
+
if (randomPool === void 0) {
|
|
1690
|
+
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
|
|
1691
|
+
}
|
|
1692
|
+
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
|
|
1693
|
+
randomPoolPointer = 0;
|
|
1694
|
+
}
|
|
1695
|
+
mask[0] = randomPool[randomPoolPointer++];
|
|
1696
|
+
mask[1] = randomPool[randomPoolPointer++];
|
|
1697
|
+
mask[2] = randomPool[randomPoolPointer++];
|
|
1698
|
+
mask[3] = randomPool[randomPoolPointer++];
|
|
1699
|
+
}
|
|
1700
|
+
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
|
|
1701
|
+
offset = 6;
|
|
1702
|
+
}
|
|
1703
|
+
let dataLength;
|
|
1704
|
+
if (typeof data === "string") {
|
|
1705
|
+
if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
|
|
1706
|
+
dataLength = options[kByteLength];
|
|
1707
|
+
} else {
|
|
1708
|
+
data = Buffer.from(data);
|
|
1709
|
+
dataLength = data.length;
|
|
1710
|
+
}
|
|
1711
|
+
} else {
|
|
1712
|
+
dataLength = data.length;
|
|
1713
|
+
merge = options.mask && options.readOnly && !skipMasking;
|
|
1714
|
+
}
|
|
1715
|
+
let payloadLength = dataLength;
|
|
1716
|
+
if (dataLength >= 65536) {
|
|
1717
|
+
offset += 8;
|
|
1718
|
+
payloadLength = 127;
|
|
1719
|
+
} else if (dataLength > 125) {
|
|
1720
|
+
offset += 2;
|
|
1721
|
+
payloadLength = 126;
|
|
1722
|
+
}
|
|
1723
|
+
const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
|
|
1724
|
+
target[0] = options.fin ? options.opcode | 128 : options.opcode;
|
|
1725
|
+
if (options.rsv1) target[0] |= 64;
|
|
1726
|
+
target[1] = payloadLength;
|
|
1727
|
+
if (payloadLength === 126) {
|
|
1728
|
+
target.writeUInt16BE(dataLength, 2);
|
|
1729
|
+
} else if (payloadLength === 127) {
|
|
1730
|
+
target[2] = target[3] = 0;
|
|
1731
|
+
target.writeUIntBE(dataLength, 4, 6);
|
|
1732
|
+
}
|
|
1733
|
+
if (!options.mask) return [target, data];
|
|
1734
|
+
target[1] |= 128;
|
|
1735
|
+
target[offset - 4] = mask[0];
|
|
1736
|
+
target[offset - 3] = mask[1];
|
|
1737
|
+
target[offset - 2] = mask[2];
|
|
1738
|
+
target[offset - 1] = mask[3];
|
|
1739
|
+
if (skipMasking) return [target, data];
|
|
1740
|
+
if (merge) {
|
|
1741
|
+
applyMask(data, mask, target, offset, dataLength);
|
|
1742
|
+
return [target];
|
|
1743
|
+
}
|
|
1744
|
+
applyMask(data, mask, data, 0, dataLength);
|
|
1745
|
+
return [target, data];
|
|
1746
|
+
}
|
|
1747
|
+
/**
|
|
1748
|
+
* Sends a close message to the other peer.
|
|
1749
|
+
*
|
|
1750
|
+
* @param {Number} [code] The status code component of the body
|
|
1751
|
+
* @param {(String|Buffer)} [data] The message component of the body
|
|
1752
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask the message
|
|
1753
|
+
* @param {Function} [cb] Callback
|
|
1754
|
+
* @public
|
|
1755
|
+
*/
|
|
1756
|
+
close(code, data, mask, cb) {
|
|
1757
|
+
let buf;
|
|
1758
|
+
if (code === void 0) {
|
|
1759
|
+
buf = EMPTY_BUFFER;
|
|
1760
|
+
} else if (typeof code !== "number" || !isValidStatusCode(code)) {
|
|
1761
|
+
throw new TypeError("First argument must be a valid error code number");
|
|
1762
|
+
} else if (data === void 0 || !data.length) {
|
|
1763
|
+
buf = Buffer.allocUnsafe(2);
|
|
1764
|
+
buf.writeUInt16BE(code, 0);
|
|
1765
|
+
} else {
|
|
1766
|
+
const length = Buffer.byteLength(data);
|
|
1767
|
+
if (length > 123) {
|
|
1768
|
+
throw new RangeError("The message must not be greater than 123 bytes");
|
|
1769
|
+
}
|
|
1770
|
+
buf = Buffer.allocUnsafe(2 + length);
|
|
1771
|
+
buf.writeUInt16BE(code, 0);
|
|
1772
|
+
if (typeof data === "string") {
|
|
1773
|
+
buf.write(data, 2);
|
|
1774
|
+
} else {
|
|
1775
|
+
buf.set(data, 2);
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
const options = {
|
|
1779
|
+
[kByteLength]: buf.length,
|
|
1780
|
+
fin: true,
|
|
1781
|
+
generateMask: this._generateMask,
|
|
1782
|
+
mask,
|
|
1783
|
+
maskBuffer: this._maskBuffer,
|
|
1784
|
+
opcode: 8,
|
|
1785
|
+
readOnly: false,
|
|
1786
|
+
rsv1: false
|
|
1787
|
+
};
|
|
1788
|
+
if (this._state !== DEFAULT) {
|
|
1789
|
+
this.enqueue([this.dispatch, buf, false, options, cb]);
|
|
1790
|
+
} else {
|
|
1791
|
+
this.sendFrame(_Sender.frame(buf, options), cb);
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
/**
|
|
1795
|
+
* Sends a ping message to the other peer.
|
|
1796
|
+
*
|
|
1797
|
+
* @param {*} data The message to send
|
|
1798
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
|
|
1799
|
+
* @param {Function} [cb] Callback
|
|
1800
|
+
* @public
|
|
1801
|
+
*/
|
|
1802
|
+
ping(data, mask, cb) {
|
|
1803
|
+
let byteLength;
|
|
1804
|
+
let readOnly;
|
|
1805
|
+
if (typeof data === "string") {
|
|
1806
|
+
byteLength = Buffer.byteLength(data);
|
|
1807
|
+
readOnly = false;
|
|
1808
|
+
} else if (isBlob(data)) {
|
|
1809
|
+
byteLength = data.size;
|
|
1810
|
+
readOnly = false;
|
|
1811
|
+
} else {
|
|
1812
|
+
data = toBuffer(data);
|
|
1813
|
+
byteLength = data.length;
|
|
1814
|
+
readOnly = toBuffer.readOnly;
|
|
1815
|
+
}
|
|
1816
|
+
if (byteLength > 125) {
|
|
1817
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1818
|
+
}
|
|
1819
|
+
const options = {
|
|
1820
|
+
[kByteLength]: byteLength,
|
|
1821
|
+
fin: true,
|
|
1822
|
+
generateMask: this._generateMask,
|
|
1823
|
+
mask,
|
|
1824
|
+
maskBuffer: this._maskBuffer,
|
|
1825
|
+
opcode: 9,
|
|
1826
|
+
readOnly,
|
|
1827
|
+
rsv1: false
|
|
1828
|
+
};
|
|
1829
|
+
if (isBlob(data)) {
|
|
1830
|
+
if (this._state !== DEFAULT) {
|
|
1831
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1832
|
+
} else {
|
|
1833
|
+
this.getBlobData(data, false, options, cb);
|
|
1834
|
+
}
|
|
1835
|
+
} else if (this._state !== DEFAULT) {
|
|
1836
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1837
|
+
} else {
|
|
1838
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
/**
|
|
1842
|
+
* Sends a pong message to the other peer.
|
|
1843
|
+
*
|
|
1844
|
+
* @param {*} data The message to send
|
|
1845
|
+
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
|
|
1846
|
+
* @param {Function} [cb] Callback
|
|
1847
|
+
* @public
|
|
1848
|
+
*/
|
|
1849
|
+
pong(data, mask, cb) {
|
|
1850
|
+
let byteLength;
|
|
1851
|
+
let readOnly;
|
|
1852
|
+
if (typeof data === "string") {
|
|
1853
|
+
byteLength = Buffer.byteLength(data);
|
|
1854
|
+
readOnly = false;
|
|
1855
|
+
} else if (isBlob(data)) {
|
|
1856
|
+
byteLength = data.size;
|
|
1857
|
+
readOnly = false;
|
|
1858
|
+
} else {
|
|
1859
|
+
data = toBuffer(data);
|
|
1860
|
+
byteLength = data.length;
|
|
1861
|
+
readOnly = toBuffer.readOnly;
|
|
1862
|
+
}
|
|
1863
|
+
if (byteLength > 125) {
|
|
1864
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1865
|
+
}
|
|
1866
|
+
const options = {
|
|
1867
|
+
[kByteLength]: byteLength,
|
|
1868
|
+
fin: true,
|
|
1869
|
+
generateMask: this._generateMask,
|
|
1870
|
+
mask,
|
|
1871
|
+
maskBuffer: this._maskBuffer,
|
|
1872
|
+
opcode: 10,
|
|
1873
|
+
readOnly,
|
|
1874
|
+
rsv1: false
|
|
1875
|
+
};
|
|
1876
|
+
if (isBlob(data)) {
|
|
1877
|
+
if (this._state !== DEFAULT) {
|
|
1878
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1879
|
+
} else {
|
|
1880
|
+
this.getBlobData(data, false, options, cb);
|
|
1881
|
+
}
|
|
1882
|
+
} else if (this._state !== DEFAULT) {
|
|
1883
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1884
|
+
} else {
|
|
1885
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
/**
|
|
1889
|
+
* Sends a data message to the other peer.
|
|
1890
|
+
*
|
|
1891
|
+
* @param {*} data The message to send
|
|
1892
|
+
* @param {Object} options Options object
|
|
1893
|
+
* @param {Boolean} [options.binary=false] Specifies whether `data` is binary
|
|
1894
|
+
* or text
|
|
1895
|
+
* @param {Boolean} [options.compress=false] Specifies whether or not to
|
|
1896
|
+
* compress `data`
|
|
1897
|
+
* @param {Boolean} [options.fin=false] Specifies whether the fragment is the
|
|
1898
|
+
* last one
|
|
1899
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1900
|
+
* `data`
|
|
1901
|
+
* @param {Function} [cb] Callback
|
|
1902
|
+
* @public
|
|
1903
|
+
*/
|
|
1904
|
+
send(data, options, cb) {
|
|
1905
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
1906
|
+
let opcode = options.binary ? 2 : 1;
|
|
1907
|
+
let rsv1 = options.compress;
|
|
1908
|
+
let byteLength;
|
|
1909
|
+
let readOnly;
|
|
1910
|
+
if (typeof data === "string") {
|
|
1911
|
+
byteLength = Buffer.byteLength(data);
|
|
1912
|
+
readOnly = false;
|
|
1913
|
+
} else if (isBlob(data)) {
|
|
1914
|
+
byteLength = data.size;
|
|
1915
|
+
readOnly = false;
|
|
1916
|
+
} else {
|
|
1917
|
+
data = toBuffer(data);
|
|
1918
|
+
byteLength = data.length;
|
|
1919
|
+
readOnly = toBuffer.readOnly;
|
|
1920
|
+
}
|
|
1921
|
+
if (this._firstFragment) {
|
|
1922
|
+
this._firstFragment = false;
|
|
1923
|
+
if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
|
|
1924
|
+
rsv1 = byteLength >= perMessageDeflate._threshold;
|
|
1925
|
+
}
|
|
1926
|
+
this._compress = rsv1;
|
|
1927
|
+
} else {
|
|
1928
|
+
rsv1 = false;
|
|
1929
|
+
opcode = 0;
|
|
1930
|
+
}
|
|
1931
|
+
if (options.fin) this._firstFragment = true;
|
|
1932
|
+
const opts = {
|
|
1933
|
+
[kByteLength]: byteLength,
|
|
1934
|
+
fin: options.fin,
|
|
1935
|
+
generateMask: this._generateMask,
|
|
1936
|
+
mask: options.mask,
|
|
1937
|
+
maskBuffer: this._maskBuffer,
|
|
1938
|
+
opcode,
|
|
1939
|
+
readOnly,
|
|
1940
|
+
rsv1
|
|
1941
|
+
};
|
|
1942
|
+
if (isBlob(data)) {
|
|
1943
|
+
if (this._state !== DEFAULT) {
|
|
1944
|
+
this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
|
|
1945
|
+
} else {
|
|
1946
|
+
this.getBlobData(data, this._compress, opts, cb);
|
|
1947
|
+
}
|
|
1948
|
+
} else if (this._state !== DEFAULT) {
|
|
1949
|
+
this.enqueue([this.dispatch, data, this._compress, opts, cb]);
|
|
1950
|
+
} else {
|
|
1951
|
+
this.dispatch(data, this._compress, opts, cb);
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* Gets the contents of a blob as binary data.
|
|
1956
|
+
*
|
|
1957
|
+
* @param {Blob} blob The blob
|
|
1958
|
+
* @param {Boolean} [compress=false] Specifies whether or not to compress
|
|
1959
|
+
* the data
|
|
1960
|
+
* @param {Object} options Options object
|
|
1961
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
1962
|
+
* FIN bit
|
|
1963
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
1964
|
+
* masking key
|
|
1965
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
1966
|
+
* `data`
|
|
1967
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
1968
|
+
* key
|
|
1969
|
+
* @param {Number} options.opcode The opcode
|
|
1970
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
1971
|
+
* modified
|
|
1972
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
1973
|
+
* RSV1 bit
|
|
1974
|
+
* @param {Function} [cb] Callback
|
|
1975
|
+
* @private
|
|
1976
|
+
*/
|
|
1977
|
+
getBlobData(blob, compress, options, cb) {
|
|
1978
|
+
this._bufferedBytes += options[kByteLength];
|
|
1979
|
+
this._state = GET_BLOB_DATA;
|
|
1980
|
+
blob.arrayBuffer().then((arrayBuffer) => {
|
|
1981
|
+
if (this._socket.destroyed) {
|
|
1982
|
+
const err = new Error(
|
|
1983
|
+
"The socket was closed while the blob was being read"
|
|
1984
|
+
);
|
|
1985
|
+
process.nextTick(callCallbacks, this, err, cb);
|
|
1986
|
+
return;
|
|
1987
|
+
}
|
|
1988
|
+
this._bufferedBytes -= options[kByteLength];
|
|
1989
|
+
const data = toBuffer(arrayBuffer);
|
|
1990
|
+
if (!compress) {
|
|
1991
|
+
this._state = DEFAULT;
|
|
1992
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
1993
|
+
this.dequeue();
|
|
1994
|
+
} else {
|
|
1995
|
+
this.dispatch(data, compress, options, cb);
|
|
1996
|
+
}
|
|
1997
|
+
}).catch((err) => {
|
|
1998
|
+
process.nextTick(onError, this, err, cb);
|
|
1999
|
+
});
|
|
2000
|
+
}
|
|
2001
|
+
/**
|
|
2002
|
+
* Dispatches a message.
|
|
2003
|
+
*
|
|
2004
|
+
* @param {(Buffer|String)} data The message to send
|
|
2005
|
+
* @param {Boolean} [compress=false] Specifies whether or not to compress
|
|
2006
|
+
* `data`
|
|
2007
|
+
* @param {Object} options Options object
|
|
2008
|
+
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
|
|
2009
|
+
* FIN bit
|
|
2010
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
2011
|
+
* masking key
|
|
2012
|
+
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
|
|
2013
|
+
* `data`
|
|
2014
|
+
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
|
|
2015
|
+
* key
|
|
2016
|
+
* @param {Number} options.opcode The opcode
|
|
2017
|
+
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
|
|
2018
|
+
* modified
|
|
2019
|
+
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
|
|
2020
|
+
* RSV1 bit
|
|
2021
|
+
* @param {Function} [cb] Callback
|
|
2022
|
+
* @private
|
|
2023
|
+
*/
|
|
2024
|
+
dispatch(data, compress, options, cb) {
|
|
2025
|
+
if (!compress) {
|
|
2026
|
+
this.sendFrame(_Sender.frame(data, options), cb);
|
|
2027
|
+
return;
|
|
2028
|
+
}
|
|
2029
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
2030
|
+
this._bufferedBytes += options[kByteLength];
|
|
2031
|
+
this._state = DEFLATING;
|
|
2032
|
+
perMessageDeflate.compress(data, options.fin, (_, buf) => {
|
|
2033
|
+
if (this._socket.destroyed) {
|
|
2034
|
+
const err = new Error(
|
|
2035
|
+
"The socket was closed while data was being compressed"
|
|
2036
|
+
);
|
|
2037
|
+
callCallbacks(this, err, cb);
|
|
2038
|
+
return;
|
|
2039
|
+
}
|
|
2040
|
+
this._bufferedBytes -= options[kByteLength];
|
|
2041
|
+
this._state = DEFAULT;
|
|
2042
|
+
options.readOnly = false;
|
|
2043
|
+
this.sendFrame(_Sender.frame(buf, options), cb);
|
|
2044
|
+
this.dequeue();
|
|
2045
|
+
});
|
|
2046
|
+
}
|
|
2047
|
+
/**
|
|
2048
|
+
* Executes queued send operations.
|
|
2049
|
+
*
|
|
2050
|
+
* @private
|
|
2051
|
+
*/
|
|
2052
|
+
dequeue() {
|
|
2053
|
+
while (this._state === DEFAULT && this._queue.length) {
|
|
2054
|
+
const params = this._queue.shift();
|
|
2055
|
+
this._bufferedBytes -= params[3][kByteLength];
|
|
2056
|
+
Reflect.apply(params[0], this, params.slice(1));
|
|
2057
|
+
}
|
|
2058
|
+
}
|
|
2059
|
+
/**
|
|
2060
|
+
* Enqueues a send operation.
|
|
2061
|
+
*
|
|
2062
|
+
* @param {Array} params Send operation parameters.
|
|
2063
|
+
* @private
|
|
2064
|
+
*/
|
|
2065
|
+
enqueue(params) {
|
|
2066
|
+
this._bufferedBytes += params[3][kByteLength];
|
|
2067
|
+
this._queue.push(params);
|
|
2068
|
+
}
|
|
2069
|
+
/**
|
|
2070
|
+
* Sends a frame.
|
|
2071
|
+
*
|
|
2072
|
+
* @param {(Buffer | String)[]} list The frame to send
|
|
2073
|
+
* @param {Function} [cb] Callback
|
|
2074
|
+
* @private
|
|
2075
|
+
*/
|
|
2076
|
+
sendFrame(list, cb) {
|
|
2077
|
+
if (list.length === 2) {
|
|
2078
|
+
this._socket.cork();
|
|
2079
|
+
this._socket.write(list[0]);
|
|
2080
|
+
this._socket.write(list[1], cb);
|
|
2081
|
+
this._socket.uncork();
|
|
2082
|
+
} else {
|
|
2083
|
+
this._socket.write(list[0], cb);
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
};
|
|
2087
|
+
module.exports = Sender2;
|
|
2088
|
+
function callCallbacks(sender, err, cb) {
|
|
2089
|
+
if (typeof cb === "function") cb(err);
|
|
2090
|
+
for (let i = 0; i < sender._queue.length; i++) {
|
|
2091
|
+
const params = sender._queue[i];
|
|
2092
|
+
const callback = params[params.length - 1];
|
|
2093
|
+
if (typeof callback === "function") callback(err);
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
function onError(sender, err, cb) {
|
|
2097
|
+
callCallbacks(sender, err, cb);
|
|
2098
|
+
sender.onerror(err);
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
});
|
|
2102
|
+
|
|
2103
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/event-target.js
|
|
2104
|
+
var require_event_target = __commonJS({
|
|
2105
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/event-target.js"(exports, module) {
|
|
2106
|
+
var { kForOnEventAttribute, kListener } = require_constants();
|
|
2107
|
+
var kCode = Symbol("kCode");
|
|
2108
|
+
var kData = Symbol("kData");
|
|
2109
|
+
var kError = Symbol("kError");
|
|
2110
|
+
var kMessage = Symbol("kMessage");
|
|
2111
|
+
var kReason = Symbol("kReason");
|
|
2112
|
+
var kTarget = Symbol("kTarget");
|
|
2113
|
+
var kType = Symbol("kType");
|
|
2114
|
+
var kWasClean = Symbol("kWasClean");
|
|
2115
|
+
var Event = class {
|
|
2116
|
+
/**
|
|
2117
|
+
* Create a new `Event`.
|
|
2118
|
+
*
|
|
2119
|
+
* @param {String} type The name of the event
|
|
2120
|
+
* @throws {TypeError} If the `type` argument is not specified
|
|
2121
|
+
*/
|
|
2122
|
+
constructor(type) {
|
|
2123
|
+
this[kTarget] = null;
|
|
2124
|
+
this[kType] = type;
|
|
2125
|
+
}
|
|
2126
|
+
/**
|
|
2127
|
+
* @type {*}
|
|
2128
|
+
*/
|
|
2129
|
+
get target() {
|
|
2130
|
+
return this[kTarget];
|
|
2131
|
+
}
|
|
2132
|
+
/**
|
|
2133
|
+
* @type {String}
|
|
2134
|
+
*/
|
|
2135
|
+
get type() {
|
|
2136
|
+
return this[kType];
|
|
2137
|
+
}
|
|
2138
|
+
};
|
|
2139
|
+
Object.defineProperty(Event.prototype, "target", { enumerable: true });
|
|
2140
|
+
Object.defineProperty(Event.prototype, "type", { enumerable: true });
|
|
2141
|
+
var CloseEvent = class extends Event {
|
|
2142
|
+
/**
|
|
2143
|
+
* Create a new `CloseEvent`.
|
|
2144
|
+
*
|
|
2145
|
+
* @param {String} type The name of the event
|
|
2146
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
2147
|
+
* attributes via object members of the same name
|
|
2148
|
+
* @param {Number} [options.code=0] The status code explaining why the
|
|
2149
|
+
* connection was closed
|
|
2150
|
+
* @param {String} [options.reason=''] A human-readable string explaining why
|
|
2151
|
+
* the connection was closed
|
|
2152
|
+
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
|
|
2153
|
+
* connection was cleanly closed
|
|
2154
|
+
*/
|
|
2155
|
+
constructor(type, options = {}) {
|
|
2156
|
+
super(type);
|
|
2157
|
+
this[kCode] = options.code === void 0 ? 0 : options.code;
|
|
2158
|
+
this[kReason] = options.reason === void 0 ? "" : options.reason;
|
|
2159
|
+
this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
|
|
2160
|
+
}
|
|
2161
|
+
/**
|
|
2162
|
+
* @type {Number}
|
|
2163
|
+
*/
|
|
2164
|
+
get code() {
|
|
2165
|
+
return this[kCode];
|
|
2166
|
+
}
|
|
2167
|
+
/**
|
|
2168
|
+
* @type {String}
|
|
2169
|
+
*/
|
|
2170
|
+
get reason() {
|
|
2171
|
+
return this[kReason];
|
|
2172
|
+
}
|
|
2173
|
+
/**
|
|
2174
|
+
* @type {Boolean}
|
|
2175
|
+
*/
|
|
2176
|
+
get wasClean() {
|
|
2177
|
+
return this[kWasClean];
|
|
2178
|
+
}
|
|
2179
|
+
};
|
|
2180
|
+
Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
|
|
2181
|
+
Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
|
|
2182
|
+
Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
|
|
2183
|
+
var ErrorEvent = class extends Event {
|
|
2184
|
+
/**
|
|
2185
|
+
* Create a new `ErrorEvent`.
|
|
2186
|
+
*
|
|
2187
|
+
* @param {String} type The name of the event
|
|
2188
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
2189
|
+
* attributes via object members of the same name
|
|
2190
|
+
* @param {*} [options.error=null] The error that generated this event
|
|
2191
|
+
* @param {String} [options.message=''] The error message
|
|
2192
|
+
*/
|
|
2193
|
+
constructor(type, options = {}) {
|
|
2194
|
+
super(type);
|
|
2195
|
+
this[kError] = options.error === void 0 ? null : options.error;
|
|
2196
|
+
this[kMessage] = options.message === void 0 ? "" : options.message;
|
|
2197
|
+
}
|
|
2198
|
+
/**
|
|
2199
|
+
* @type {*}
|
|
2200
|
+
*/
|
|
2201
|
+
get error() {
|
|
2202
|
+
return this[kError];
|
|
2203
|
+
}
|
|
2204
|
+
/**
|
|
2205
|
+
* @type {String}
|
|
2206
|
+
*/
|
|
2207
|
+
get message() {
|
|
2208
|
+
return this[kMessage];
|
|
2209
|
+
}
|
|
2210
|
+
};
|
|
2211
|
+
Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
|
|
2212
|
+
Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
|
|
2213
|
+
var MessageEvent = class extends Event {
|
|
2214
|
+
/**
|
|
2215
|
+
* Create a new `MessageEvent`.
|
|
2216
|
+
*
|
|
2217
|
+
* @param {String} type The name of the event
|
|
2218
|
+
* @param {Object} [options] A dictionary object that allows for setting
|
|
2219
|
+
* attributes via object members of the same name
|
|
2220
|
+
* @param {*} [options.data=null] The message content
|
|
2221
|
+
*/
|
|
2222
|
+
constructor(type, options = {}) {
|
|
2223
|
+
super(type);
|
|
2224
|
+
this[kData] = options.data === void 0 ? null : options.data;
|
|
2225
|
+
}
|
|
2226
|
+
/**
|
|
2227
|
+
* @type {*}
|
|
2228
|
+
*/
|
|
2229
|
+
get data() {
|
|
2230
|
+
return this[kData];
|
|
2231
|
+
}
|
|
2232
|
+
};
|
|
2233
|
+
Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
|
|
2234
|
+
var EventTarget = {
|
|
2235
|
+
/**
|
|
2236
|
+
* Register an event listener.
|
|
2237
|
+
*
|
|
2238
|
+
* @param {String} type A string representing the event type to listen for
|
|
2239
|
+
* @param {(Function|Object)} handler The listener to add
|
|
2240
|
+
* @param {Object} [options] An options object specifies characteristics about
|
|
2241
|
+
* the event listener
|
|
2242
|
+
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
|
|
2243
|
+
* listener should be invoked at most once after being added. If `true`,
|
|
2244
|
+
* the listener would be automatically removed when invoked.
|
|
2245
|
+
* @public
|
|
2246
|
+
*/
|
|
2247
|
+
addEventListener(type, handler, options = {}) {
|
|
2248
|
+
for (const listener of this.listeners(type)) {
|
|
2249
|
+
if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
2250
|
+
return;
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
let wrapper;
|
|
2254
|
+
if (type === "message") {
|
|
2255
|
+
wrapper = function onMessage(data, isBinary) {
|
|
2256
|
+
const event = new MessageEvent("message", {
|
|
2257
|
+
data: isBinary ? data : data.toString()
|
|
2258
|
+
});
|
|
2259
|
+
event[kTarget] = this;
|
|
2260
|
+
callListener(handler, this, event);
|
|
2261
|
+
};
|
|
2262
|
+
} else if (type === "close") {
|
|
2263
|
+
wrapper = function onClose(code, message) {
|
|
2264
|
+
const event = new CloseEvent("close", {
|
|
2265
|
+
code,
|
|
2266
|
+
reason: message.toString(),
|
|
2267
|
+
wasClean: this._closeFrameReceived && this._closeFrameSent
|
|
2268
|
+
});
|
|
2269
|
+
event[kTarget] = this;
|
|
2270
|
+
callListener(handler, this, event);
|
|
2271
|
+
};
|
|
2272
|
+
} else if (type === "error") {
|
|
2273
|
+
wrapper = function onError(error) {
|
|
2274
|
+
const event = new ErrorEvent("error", {
|
|
2275
|
+
error,
|
|
2276
|
+
message: error.message
|
|
2277
|
+
});
|
|
2278
|
+
event[kTarget] = this;
|
|
2279
|
+
callListener(handler, this, event);
|
|
2280
|
+
};
|
|
2281
|
+
} else if (type === "open") {
|
|
2282
|
+
wrapper = function onOpen() {
|
|
2283
|
+
const event = new Event("open");
|
|
2284
|
+
event[kTarget] = this;
|
|
2285
|
+
callListener(handler, this, event);
|
|
2286
|
+
};
|
|
2287
|
+
} else {
|
|
2288
|
+
return;
|
|
2289
|
+
}
|
|
2290
|
+
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
|
|
2291
|
+
wrapper[kListener] = handler;
|
|
2292
|
+
if (options.once) {
|
|
2293
|
+
this.once(type, wrapper);
|
|
2294
|
+
} else {
|
|
2295
|
+
this.on(type, wrapper);
|
|
2296
|
+
}
|
|
2297
|
+
},
|
|
2298
|
+
/**
|
|
2299
|
+
* Remove an event listener.
|
|
2300
|
+
*
|
|
2301
|
+
* @param {String} type A string representing the event type to remove
|
|
2302
|
+
* @param {(Function|Object)} handler The listener to remove
|
|
2303
|
+
* @public
|
|
2304
|
+
*/
|
|
2305
|
+
removeEventListener(type, handler) {
|
|
2306
|
+
for (const listener of this.listeners(type)) {
|
|
2307
|
+
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
2308
|
+
this.removeListener(type, listener);
|
|
2309
|
+
break;
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
}
|
|
2313
|
+
};
|
|
2314
|
+
module.exports = {
|
|
2315
|
+
CloseEvent,
|
|
2316
|
+
ErrorEvent,
|
|
2317
|
+
Event,
|
|
2318
|
+
EventTarget,
|
|
2319
|
+
MessageEvent
|
|
2320
|
+
};
|
|
2321
|
+
function callListener(listener, thisArg, event) {
|
|
2322
|
+
if (typeof listener === "object" && listener.handleEvent) {
|
|
2323
|
+
listener.handleEvent.call(listener, event);
|
|
2324
|
+
} else {
|
|
2325
|
+
listener.call(thisArg, event);
|
|
2326
|
+
}
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
});
|
|
2330
|
+
|
|
2331
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/extension.js
|
|
2332
|
+
var require_extension = __commonJS({
|
|
2333
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/extension.js"(exports, module) {
|
|
2334
|
+
var { tokenChars } = require_validation();
|
|
2335
|
+
function push(dest, name, elem) {
|
|
2336
|
+
if (dest[name] === void 0) dest[name] = [elem];
|
|
2337
|
+
else dest[name].push(elem);
|
|
2338
|
+
}
|
|
2339
|
+
function parse(header) {
|
|
2340
|
+
const offers = /* @__PURE__ */ Object.create(null);
|
|
2341
|
+
let params = /* @__PURE__ */ Object.create(null);
|
|
2342
|
+
let mustUnescape = false;
|
|
2343
|
+
let isEscaping = false;
|
|
2344
|
+
let inQuotes = false;
|
|
2345
|
+
let extensionName;
|
|
2346
|
+
let paramName;
|
|
2347
|
+
let start = -1;
|
|
2348
|
+
let code = -1;
|
|
2349
|
+
let end = -1;
|
|
2350
|
+
let i = 0;
|
|
2351
|
+
for (; i < header.length; i++) {
|
|
2352
|
+
code = header.charCodeAt(i);
|
|
2353
|
+
if (extensionName === void 0) {
|
|
2354
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
2355
|
+
if (start === -1) start = i;
|
|
2356
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
2357
|
+
if (end === -1 && start !== -1) end = i;
|
|
2358
|
+
} else if (code === 59 || code === 44) {
|
|
2359
|
+
if (start === -1) {
|
|
2360
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2361
|
+
}
|
|
2362
|
+
if (end === -1) end = i;
|
|
2363
|
+
const name = header.slice(start, end);
|
|
2364
|
+
if (code === 44) {
|
|
2365
|
+
push(offers, name, params);
|
|
2366
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2367
|
+
} else {
|
|
2368
|
+
extensionName = name;
|
|
2369
|
+
}
|
|
2370
|
+
start = end = -1;
|
|
2371
|
+
} else {
|
|
2372
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2373
|
+
}
|
|
2374
|
+
} else if (paramName === void 0) {
|
|
2375
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
2376
|
+
if (start === -1) start = i;
|
|
2377
|
+
} else if (code === 32 || code === 9) {
|
|
2378
|
+
if (end === -1 && start !== -1) end = i;
|
|
2379
|
+
} else if (code === 59 || code === 44) {
|
|
2380
|
+
if (start === -1) {
|
|
2381
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2382
|
+
}
|
|
2383
|
+
if (end === -1) end = i;
|
|
2384
|
+
push(params, header.slice(start, end), true);
|
|
2385
|
+
if (code === 44) {
|
|
2386
|
+
push(offers, extensionName, params);
|
|
2387
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2388
|
+
extensionName = void 0;
|
|
2389
|
+
}
|
|
2390
|
+
start = end = -1;
|
|
2391
|
+
} else if (code === 61 && start !== -1 && end === -1) {
|
|
2392
|
+
paramName = header.slice(start, i);
|
|
2393
|
+
start = end = -1;
|
|
2394
|
+
} else {
|
|
2395
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2396
|
+
}
|
|
2397
|
+
} else {
|
|
2398
|
+
if (isEscaping) {
|
|
2399
|
+
if (tokenChars[code] !== 1) {
|
|
2400
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2401
|
+
}
|
|
2402
|
+
if (start === -1) start = i;
|
|
2403
|
+
else if (!mustUnescape) mustUnescape = true;
|
|
2404
|
+
isEscaping = false;
|
|
2405
|
+
} else if (inQuotes) {
|
|
2406
|
+
if (tokenChars[code] === 1) {
|
|
2407
|
+
if (start === -1) start = i;
|
|
2408
|
+
} else if (code === 34 && start !== -1) {
|
|
2409
|
+
inQuotes = false;
|
|
2410
|
+
end = i;
|
|
2411
|
+
} else if (code === 92) {
|
|
2412
|
+
isEscaping = true;
|
|
2413
|
+
} else {
|
|
2414
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2415
|
+
}
|
|
2416
|
+
} else if (code === 34 && header.charCodeAt(i - 1) === 61) {
|
|
2417
|
+
inQuotes = true;
|
|
2418
|
+
} else if (end === -1 && tokenChars[code] === 1) {
|
|
2419
|
+
if (start === -1) start = i;
|
|
2420
|
+
} else if (start !== -1 && (code === 32 || code === 9)) {
|
|
2421
|
+
if (end === -1) end = i;
|
|
2422
|
+
} else if (code === 59 || code === 44) {
|
|
2423
|
+
if (start === -1) {
|
|
2424
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2425
|
+
}
|
|
2426
|
+
if (end === -1) end = i;
|
|
2427
|
+
let value = header.slice(start, end);
|
|
2428
|
+
if (mustUnescape) {
|
|
2429
|
+
value = value.replace(/\\/g, "");
|
|
2430
|
+
mustUnescape = false;
|
|
2431
|
+
}
|
|
2432
|
+
push(params, paramName, value);
|
|
2433
|
+
if (code === 44) {
|
|
2434
|
+
push(offers, extensionName, params);
|
|
2435
|
+
params = /* @__PURE__ */ Object.create(null);
|
|
2436
|
+
extensionName = void 0;
|
|
2437
|
+
}
|
|
2438
|
+
paramName = void 0;
|
|
2439
|
+
start = end = -1;
|
|
2440
|
+
} else {
|
|
2441
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
if (start === -1 || inQuotes || code === 32 || code === 9) {
|
|
2446
|
+
throw new SyntaxError("Unexpected end of input");
|
|
2447
|
+
}
|
|
2448
|
+
if (end === -1) end = i;
|
|
2449
|
+
const token = header.slice(start, end);
|
|
2450
|
+
if (extensionName === void 0) {
|
|
2451
|
+
push(offers, token, params);
|
|
2452
|
+
} else {
|
|
2453
|
+
if (paramName === void 0) {
|
|
2454
|
+
push(params, token, true);
|
|
2455
|
+
} else if (mustUnescape) {
|
|
2456
|
+
push(params, paramName, token.replace(/\\/g, ""));
|
|
2457
|
+
} else {
|
|
2458
|
+
push(params, paramName, token);
|
|
2459
|
+
}
|
|
2460
|
+
push(offers, extensionName, params);
|
|
2461
|
+
}
|
|
2462
|
+
return offers;
|
|
2463
|
+
}
|
|
2464
|
+
function format(extensions) {
|
|
2465
|
+
return Object.keys(extensions).map((extension) => {
|
|
2466
|
+
let configurations = extensions[extension];
|
|
2467
|
+
if (!Array.isArray(configurations)) configurations = [configurations];
|
|
2468
|
+
return configurations.map((params) => {
|
|
2469
|
+
return [extension].concat(
|
|
2470
|
+
Object.keys(params).map((k) => {
|
|
2471
|
+
let values = params[k];
|
|
2472
|
+
if (!Array.isArray(values)) values = [values];
|
|
2473
|
+
return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
|
|
2474
|
+
})
|
|
2475
|
+
).join("; ");
|
|
2476
|
+
}).join(", ");
|
|
2477
|
+
}).join(", ");
|
|
2478
|
+
}
|
|
2479
|
+
module.exports = { format, parse };
|
|
2480
|
+
}
|
|
2481
|
+
});
|
|
2482
|
+
|
|
2483
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/websocket.js
|
|
2484
|
+
var require_websocket = __commonJS({
|
|
2485
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/websocket.js"(exports, module) {
|
|
2486
|
+
var EventEmitter = __require("events");
|
|
2487
|
+
var https = __require("https");
|
|
2488
|
+
var http = __require("http");
|
|
2489
|
+
var net = __require("net");
|
|
2490
|
+
var tls = __require("tls");
|
|
2491
|
+
var { randomBytes, createHash } = __require("crypto");
|
|
2492
|
+
var { Duplex, Readable } = __require("stream");
|
|
2493
|
+
var { URL: URL2 } = __require("url");
|
|
2494
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
2495
|
+
var Receiver2 = require_receiver();
|
|
2496
|
+
var Sender2 = require_sender();
|
|
2497
|
+
var { isBlob } = require_validation();
|
|
2498
|
+
var {
|
|
2499
|
+
BINARY_TYPES,
|
|
2500
|
+
EMPTY_BUFFER,
|
|
2501
|
+
GUID,
|
|
2502
|
+
kForOnEventAttribute,
|
|
2503
|
+
kListener,
|
|
2504
|
+
kStatusCode,
|
|
2505
|
+
kWebSocket,
|
|
2506
|
+
NOOP
|
|
2507
|
+
} = require_constants();
|
|
2508
|
+
var {
|
|
2509
|
+
EventTarget: { addEventListener, removeEventListener }
|
|
2510
|
+
} = require_event_target();
|
|
2511
|
+
var { format, parse } = require_extension();
|
|
2512
|
+
var { toBuffer } = require_buffer_util();
|
|
2513
|
+
var closeTimeout = 30 * 1e3;
|
|
2514
|
+
var kAborted = Symbol("kAborted");
|
|
2515
|
+
var protocolVersions = [8, 13];
|
|
2516
|
+
var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
|
|
2517
|
+
var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
|
|
2518
|
+
var WebSocket2 = class _WebSocket extends EventEmitter {
|
|
2519
|
+
/**
|
|
2520
|
+
* Create a new `WebSocket`.
|
|
2521
|
+
*
|
|
2522
|
+
* @param {(String|URL)} address The URL to which to connect
|
|
2523
|
+
* @param {(String|String[])} [protocols] The subprotocols
|
|
2524
|
+
* @param {Object} [options] Connection options
|
|
2525
|
+
*/
|
|
2526
|
+
constructor(address, protocols, options) {
|
|
2527
|
+
super();
|
|
2528
|
+
this._binaryType = BINARY_TYPES[0];
|
|
2529
|
+
this._closeCode = 1006;
|
|
2530
|
+
this._closeFrameReceived = false;
|
|
2531
|
+
this._closeFrameSent = false;
|
|
2532
|
+
this._closeMessage = EMPTY_BUFFER;
|
|
2533
|
+
this._closeTimer = null;
|
|
2534
|
+
this._errorEmitted = false;
|
|
2535
|
+
this._extensions = {};
|
|
2536
|
+
this._paused = false;
|
|
2537
|
+
this._protocol = "";
|
|
2538
|
+
this._readyState = _WebSocket.CONNECTING;
|
|
2539
|
+
this._receiver = null;
|
|
2540
|
+
this._sender = null;
|
|
2541
|
+
this._socket = null;
|
|
2542
|
+
if (address !== null) {
|
|
2543
|
+
this._bufferedAmount = 0;
|
|
2544
|
+
this._isServer = false;
|
|
2545
|
+
this._redirects = 0;
|
|
2546
|
+
if (protocols === void 0) {
|
|
2547
|
+
protocols = [];
|
|
2548
|
+
} else if (!Array.isArray(protocols)) {
|
|
2549
|
+
if (typeof protocols === "object" && protocols !== null) {
|
|
2550
|
+
options = protocols;
|
|
2551
|
+
protocols = [];
|
|
2552
|
+
} else {
|
|
2553
|
+
protocols = [protocols];
|
|
2554
|
+
}
|
|
2555
|
+
}
|
|
2556
|
+
initAsClient(this, address, protocols, options);
|
|
2557
|
+
} else {
|
|
2558
|
+
this._autoPong = options.autoPong;
|
|
2559
|
+
this._isServer = true;
|
|
2560
|
+
}
|
|
2561
|
+
}
|
|
2562
|
+
/**
|
|
2563
|
+
* For historical reasons, the custom "nodebuffer" type is used by the default
|
|
2564
|
+
* instead of "blob".
|
|
2565
|
+
*
|
|
2566
|
+
* @type {String}
|
|
2567
|
+
*/
|
|
2568
|
+
get binaryType() {
|
|
2569
|
+
return this._binaryType;
|
|
2570
|
+
}
|
|
2571
|
+
set binaryType(type) {
|
|
2572
|
+
if (!BINARY_TYPES.includes(type)) return;
|
|
2573
|
+
this._binaryType = type;
|
|
2574
|
+
if (this._receiver) this._receiver._binaryType = type;
|
|
2575
|
+
}
|
|
2576
|
+
/**
|
|
2577
|
+
* @type {Number}
|
|
2578
|
+
*/
|
|
2579
|
+
get bufferedAmount() {
|
|
2580
|
+
if (!this._socket) return this._bufferedAmount;
|
|
2581
|
+
return this._socket._writableState.length + this._sender._bufferedBytes;
|
|
2582
|
+
}
|
|
2583
|
+
/**
|
|
2584
|
+
* @type {String}
|
|
2585
|
+
*/
|
|
2586
|
+
get extensions() {
|
|
2587
|
+
return Object.keys(this._extensions).join();
|
|
2588
|
+
}
|
|
2589
|
+
/**
|
|
2590
|
+
* @type {Boolean}
|
|
2591
|
+
*/
|
|
2592
|
+
get isPaused() {
|
|
2593
|
+
return this._paused;
|
|
2594
|
+
}
|
|
2595
|
+
/**
|
|
2596
|
+
* @type {Function}
|
|
2597
|
+
*/
|
|
2598
|
+
/* istanbul ignore next */
|
|
2599
|
+
get onclose() {
|
|
2600
|
+
return null;
|
|
2601
|
+
}
|
|
2602
|
+
/**
|
|
2603
|
+
* @type {Function}
|
|
2604
|
+
*/
|
|
2605
|
+
/* istanbul ignore next */
|
|
2606
|
+
get onerror() {
|
|
2607
|
+
return null;
|
|
2608
|
+
}
|
|
2609
|
+
/**
|
|
2610
|
+
* @type {Function}
|
|
2611
|
+
*/
|
|
2612
|
+
/* istanbul ignore next */
|
|
2613
|
+
get onopen() {
|
|
2614
|
+
return null;
|
|
2615
|
+
}
|
|
2616
|
+
/**
|
|
2617
|
+
* @type {Function}
|
|
2618
|
+
*/
|
|
2619
|
+
/* istanbul ignore next */
|
|
2620
|
+
get onmessage() {
|
|
2621
|
+
return null;
|
|
2622
|
+
}
|
|
2623
|
+
/**
|
|
2624
|
+
* @type {String}
|
|
2625
|
+
*/
|
|
2626
|
+
get protocol() {
|
|
2627
|
+
return this._protocol;
|
|
2628
|
+
}
|
|
2629
|
+
/**
|
|
2630
|
+
* @type {Number}
|
|
2631
|
+
*/
|
|
2632
|
+
get readyState() {
|
|
2633
|
+
return this._readyState;
|
|
2634
|
+
}
|
|
2635
|
+
/**
|
|
2636
|
+
* @type {String}
|
|
2637
|
+
*/
|
|
2638
|
+
get url() {
|
|
2639
|
+
return this._url;
|
|
2640
|
+
}
|
|
2641
|
+
/**
|
|
2642
|
+
* Set up the socket and the internal resources.
|
|
2643
|
+
*
|
|
2644
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
2645
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
2646
|
+
* @param {Object} options Options object
|
|
2647
|
+
* @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
|
|
2648
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
2649
|
+
* multiple times in the same tick
|
|
2650
|
+
* @param {Function} [options.generateMask] The function used to generate the
|
|
2651
|
+
* masking key
|
|
2652
|
+
* @param {Number} [options.maxPayload=0] The maximum allowed message size
|
|
2653
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
2654
|
+
* not to skip UTF-8 validation for text and close messages
|
|
2655
|
+
* @private
|
|
2656
|
+
*/
|
|
2657
|
+
setSocket(socket, head, options) {
|
|
2658
|
+
const receiver = new Receiver2({
|
|
2659
|
+
allowSynchronousEvents: options.allowSynchronousEvents,
|
|
2660
|
+
binaryType: this.binaryType,
|
|
2661
|
+
extensions: this._extensions,
|
|
2662
|
+
isServer: this._isServer,
|
|
2663
|
+
maxPayload: options.maxPayload,
|
|
2664
|
+
skipUTF8Validation: options.skipUTF8Validation
|
|
2665
|
+
});
|
|
2666
|
+
const sender = new Sender2(socket, this._extensions, options.generateMask);
|
|
2667
|
+
this._receiver = receiver;
|
|
2668
|
+
this._sender = sender;
|
|
2669
|
+
this._socket = socket;
|
|
2670
|
+
receiver[kWebSocket] = this;
|
|
2671
|
+
sender[kWebSocket] = this;
|
|
2672
|
+
socket[kWebSocket] = this;
|
|
2673
|
+
receiver.on("conclude", receiverOnConclude);
|
|
2674
|
+
receiver.on("drain", receiverOnDrain);
|
|
2675
|
+
receiver.on("error", receiverOnError);
|
|
2676
|
+
receiver.on("message", receiverOnMessage);
|
|
2677
|
+
receiver.on("ping", receiverOnPing);
|
|
2678
|
+
receiver.on("pong", receiverOnPong);
|
|
2679
|
+
sender.onerror = senderOnError;
|
|
2680
|
+
if (socket.setTimeout) socket.setTimeout(0);
|
|
2681
|
+
if (socket.setNoDelay) socket.setNoDelay();
|
|
2682
|
+
if (head.length > 0) socket.unshift(head);
|
|
2683
|
+
socket.on("close", socketOnClose);
|
|
2684
|
+
socket.on("data", socketOnData);
|
|
2685
|
+
socket.on("end", socketOnEnd);
|
|
2686
|
+
socket.on("error", socketOnError);
|
|
2687
|
+
this._readyState = _WebSocket.OPEN;
|
|
2688
|
+
this.emit("open");
|
|
2689
|
+
}
|
|
2690
|
+
/**
|
|
2691
|
+
* Emit the `'close'` event.
|
|
2692
|
+
*
|
|
2693
|
+
* @private
|
|
2694
|
+
*/
|
|
2695
|
+
emitClose() {
|
|
2696
|
+
if (!this._socket) {
|
|
2697
|
+
this._readyState = _WebSocket.CLOSED;
|
|
2698
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
2699
|
+
return;
|
|
2700
|
+
}
|
|
2701
|
+
if (this._extensions[PerMessageDeflate.extensionName]) {
|
|
2702
|
+
this._extensions[PerMessageDeflate.extensionName].cleanup();
|
|
2703
|
+
}
|
|
2704
|
+
this._receiver.removeAllListeners();
|
|
2705
|
+
this._readyState = _WebSocket.CLOSED;
|
|
2706
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
2707
|
+
}
|
|
2708
|
+
/**
|
|
2709
|
+
* Start a closing handshake.
|
|
2710
|
+
*
|
|
2711
|
+
* +----------+ +-----------+ +----------+
|
|
2712
|
+
* - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
|
|
2713
|
+
* | +----------+ +-----------+ +----------+ |
|
|
2714
|
+
* +----------+ +-----------+ |
|
|
2715
|
+
* CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
|
|
2716
|
+
* +----------+ +-----------+ |
|
|
2717
|
+
* | | | +---+ |
|
|
2718
|
+
* +------------------------+-->|fin| - - - -
|
|
2719
|
+
* | +---+ | +---+
|
|
2720
|
+
* - - - - -|fin|<---------------------+
|
|
2721
|
+
* +---+
|
|
2722
|
+
*
|
|
2723
|
+
* @param {Number} [code] Status code explaining why the connection is closing
|
|
2724
|
+
* @param {(String|Buffer)} [data] The reason why the connection is
|
|
2725
|
+
* closing
|
|
2726
|
+
* @public
|
|
2727
|
+
*/
|
|
2728
|
+
close(code, data) {
|
|
2729
|
+
if (this.readyState === _WebSocket.CLOSED) return;
|
|
2730
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2731
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
2732
|
+
abortHandshake(this, this._req, msg);
|
|
2733
|
+
return;
|
|
2734
|
+
}
|
|
2735
|
+
if (this.readyState === _WebSocket.CLOSING) {
|
|
2736
|
+
if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
|
|
2737
|
+
this._socket.end();
|
|
2738
|
+
}
|
|
2739
|
+
return;
|
|
2740
|
+
}
|
|
2741
|
+
this._readyState = _WebSocket.CLOSING;
|
|
2742
|
+
this._sender.close(code, data, !this._isServer, (err) => {
|
|
2743
|
+
if (err) return;
|
|
2744
|
+
this._closeFrameSent = true;
|
|
2745
|
+
if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
|
|
2746
|
+
this._socket.end();
|
|
2747
|
+
}
|
|
2748
|
+
});
|
|
2749
|
+
setCloseTimer(this);
|
|
2750
|
+
}
|
|
2751
|
+
/**
|
|
2752
|
+
* Pause the socket.
|
|
2753
|
+
*
|
|
2754
|
+
* @public
|
|
2755
|
+
*/
|
|
2756
|
+
pause() {
|
|
2757
|
+
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
|
|
2758
|
+
return;
|
|
2759
|
+
}
|
|
2760
|
+
this._paused = true;
|
|
2761
|
+
this._socket.pause();
|
|
2762
|
+
}
|
|
2763
|
+
/**
|
|
2764
|
+
* Send a ping.
|
|
2765
|
+
*
|
|
2766
|
+
* @param {*} [data] The data to send
|
|
2767
|
+
* @param {Boolean} [mask] Indicates whether or not to mask `data`
|
|
2768
|
+
* @param {Function} [cb] Callback which is executed when the ping is sent
|
|
2769
|
+
* @public
|
|
2770
|
+
*/
|
|
2771
|
+
ping(data, mask, cb) {
|
|
2772
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2773
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2774
|
+
}
|
|
2775
|
+
if (typeof data === "function") {
|
|
2776
|
+
cb = data;
|
|
2777
|
+
data = mask = void 0;
|
|
2778
|
+
} else if (typeof mask === "function") {
|
|
2779
|
+
cb = mask;
|
|
2780
|
+
mask = void 0;
|
|
2781
|
+
}
|
|
2782
|
+
if (typeof data === "number") data = data.toString();
|
|
2783
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2784
|
+
sendAfterClose(this, data, cb);
|
|
2785
|
+
return;
|
|
2786
|
+
}
|
|
2787
|
+
if (mask === void 0) mask = !this._isServer;
|
|
2788
|
+
this._sender.ping(data || EMPTY_BUFFER, mask, cb);
|
|
2789
|
+
}
|
|
2790
|
+
/**
|
|
2791
|
+
* Send a pong.
|
|
2792
|
+
*
|
|
2793
|
+
* @param {*} [data] The data to send
|
|
2794
|
+
* @param {Boolean} [mask] Indicates whether or not to mask `data`
|
|
2795
|
+
* @param {Function} [cb] Callback which is executed when the pong is sent
|
|
2796
|
+
* @public
|
|
2797
|
+
*/
|
|
2798
|
+
pong(data, mask, cb) {
|
|
2799
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2800
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2801
|
+
}
|
|
2802
|
+
if (typeof data === "function") {
|
|
2803
|
+
cb = data;
|
|
2804
|
+
data = mask = void 0;
|
|
2805
|
+
} else if (typeof mask === "function") {
|
|
2806
|
+
cb = mask;
|
|
2807
|
+
mask = void 0;
|
|
2808
|
+
}
|
|
2809
|
+
if (typeof data === "number") data = data.toString();
|
|
2810
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2811
|
+
sendAfterClose(this, data, cb);
|
|
2812
|
+
return;
|
|
2813
|
+
}
|
|
2814
|
+
if (mask === void 0) mask = !this._isServer;
|
|
2815
|
+
this._sender.pong(data || EMPTY_BUFFER, mask, cb);
|
|
2816
|
+
}
|
|
2817
|
+
/**
|
|
2818
|
+
* Resume the socket.
|
|
2819
|
+
*
|
|
2820
|
+
* @public
|
|
2821
|
+
*/
|
|
2822
|
+
resume() {
|
|
2823
|
+
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
|
|
2824
|
+
return;
|
|
2825
|
+
}
|
|
2826
|
+
this._paused = false;
|
|
2827
|
+
if (!this._receiver._writableState.needDrain) this._socket.resume();
|
|
2828
|
+
}
|
|
2829
|
+
/**
|
|
2830
|
+
* Send a data message.
|
|
2831
|
+
*
|
|
2832
|
+
* @param {*} data The message to send
|
|
2833
|
+
* @param {Object} [options] Options object
|
|
2834
|
+
* @param {Boolean} [options.binary] Specifies whether `data` is binary or
|
|
2835
|
+
* text
|
|
2836
|
+
* @param {Boolean} [options.compress] Specifies whether or not to compress
|
|
2837
|
+
* `data`
|
|
2838
|
+
* @param {Boolean} [options.fin=true] Specifies whether the fragment is the
|
|
2839
|
+
* last one
|
|
2840
|
+
* @param {Boolean} [options.mask] Specifies whether or not to mask `data`
|
|
2841
|
+
* @param {Function} [cb] Callback which is executed when data is written out
|
|
2842
|
+
* @public
|
|
2843
|
+
*/
|
|
2844
|
+
send(data, options, cb) {
|
|
2845
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2846
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2847
|
+
}
|
|
2848
|
+
if (typeof options === "function") {
|
|
2849
|
+
cb = options;
|
|
2850
|
+
options = {};
|
|
2851
|
+
}
|
|
2852
|
+
if (typeof data === "number") data = data.toString();
|
|
2853
|
+
if (this.readyState !== _WebSocket.OPEN) {
|
|
2854
|
+
sendAfterClose(this, data, cb);
|
|
2855
|
+
return;
|
|
2856
|
+
}
|
|
2857
|
+
const opts = {
|
|
2858
|
+
binary: typeof data !== "string",
|
|
2859
|
+
mask: !this._isServer,
|
|
2860
|
+
compress: true,
|
|
2861
|
+
fin: true,
|
|
2862
|
+
...options
|
|
2863
|
+
};
|
|
2864
|
+
if (!this._extensions[PerMessageDeflate.extensionName]) {
|
|
2865
|
+
opts.compress = false;
|
|
2866
|
+
}
|
|
2867
|
+
this._sender.send(data || EMPTY_BUFFER, opts, cb);
|
|
2868
|
+
}
|
|
2869
|
+
/**
|
|
2870
|
+
* Forcibly close the connection.
|
|
2871
|
+
*
|
|
2872
|
+
* @public
|
|
2873
|
+
*/
|
|
2874
|
+
terminate() {
|
|
2875
|
+
if (this.readyState === _WebSocket.CLOSED) return;
|
|
2876
|
+
if (this.readyState === _WebSocket.CONNECTING) {
|
|
2877
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
2878
|
+
abortHandshake(this, this._req, msg);
|
|
2879
|
+
return;
|
|
2880
|
+
}
|
|
2881
|
+
if (this._socket) {
|
|
2882
|
+
this._readyState = _WebSocket.CLOSING;
|
|
2883
|
+
this._socket.destroy();
|
|
2884
|
+
}
|
|
2885
|
+
}
|
|
2886
|
+
};
|
|
2887
|
+
Object.defineProperty(WebSocket2, "CONNECTING", {
|
|
2888
|
+
enumerable: true,
|
|
2889
|
+
value: readyStates.indexOf("CONNECTING")
|
|
2890
|
+
});
|
|
2891
|
+
Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
|
|
2892
|
+
enumerable: true,
|
|
2893
|
+
value: readyStates.indexOf("CONNECTING")
|
|
2894
|
+
});
|
|
2895
|
+
Object.defineProperty(WebSocket2, "OPEN", {
|
|
2896
|
+
enumerable: true,
|
|
2897
|
+
value: readyStates.indexOf("OPEN")
|
|
2898
|
+
});
|
|
2899
|
+
Object.defineProperty(WebSocket2.prototype, "OPEN", {
|
|
2900
|
+
enumerable: true,
|
|
2901
|
+
value: readyStates.indexOf("OPEN")
|
|
2902
|
+
});
|
|
2903
|
+
Object.defineProperty(WebSocket2, "CLOSING", {
|
|
2904
|
+
enumerable: true,
|
|
2905
|
+
value: readyStates.indexOf("CLOSING")
|
|
2906
|
+
});
|
|
2907
|
+
Object.defineProperty(WebSocket2.prototype, "CLOSING", {
|
|
2908
|
+
enumerable: true,
|
|
2909
|
+
value: readyStates.indexOf("CLOSING")
|
|
2910
|
+
});
|
|
2911
|
+
Object.defineProperty(WebSocket2, "CLOSED", {
|
|
2912
|
+
enumerable: true,
|
|
2913
|
+
value: readyStates.indexOf("CLOSED")
|
|
2914
|
+
});
|
|
2915
|
+
Object.defineProperty(WebSocket2.prototype, "CLOSED", {
|
|
2916
|
+
enumerable: true,
|
|
2917
|
+
value: readyStates.indexOf("CLOSED")
|
|
2918
|
+
});
|
|
2919
|
+
[
|
|
2920
|
+
"binaryType",
|
|
2921
|
+
"bufferedAmount",
|
|
2922
|
+
"extensions",
|
|
2923
|
+
"isPaused",
|
|
2924
|
+
"protocol",
|
|
2925
|
+
"readyState",
|
|
2926
|
+
"url"
|
|
2927
|
+
].forEach((property) => {
|
|
2928
|
+
Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
|
|
2929
|
+
});
|
|
2930
|
+
["open", "error", "close", "message"].forEach((method) => {
|
|
2931
|
+
Object.defineProperty(WebSocket2.prototype, `on${method}`, {
|
|
2932
|
+
enumerable: true,
|
|
2933
|
+
get() {
|
|
2934
|
+
for (const listener of this.listeners(method)) {
|
|
2935
|
+
if (listener[kForOnEventAttribute]) return listener[kListener];
|
|
2936
|
+
}
|
|
2937
|
+
return null;
|
|
2938
|
+
},
|
|
2939
|
+
set(handler) {
|
|
2940
|
+
for (const listener of this.listeners(method)) {
|
|
2941
|
+
if (listener[kForOnEventAttribute]) {
|
|
2942
|
+
this.removeListener(method, listener);
|
|
2943
|
+
break;
|
|
2944
|
+
}
|
|
2945
|
+
}
|
|
2946
|
+
if (typeof handler !== "function") return;
|
|
2947
|
+
this.addEventListener(method, handler, {
|
|
2948
|
+
[kForOnEventAttribute]: true
|
|
2949
|
+
});
|
|
2950
|
+
}
|
|
2951
|
+
});
|
|
2952
|
+
});
|
|
2953
|
+
WebSocket2.prototype.addEventListener = addEventListener;
|
|
2954
|
+
WebSocket2.prototype.removeEventListener = removeEventListener;
|
|
2955
|
+
module.exports = WebSocket2;
|
|
2956
|
+
function initAsClient(websocket, address, protocols, options) {
|
|
2957
|
+
const opts = {
|
|
2958
|
+
allowSynchronousEvents: true,
|
|
2959
|
+
autoPong: true,
|
|
2960
|
+
protocolVersion: protocolVersions[1],
|
|
2961
|
+
maxPayload: 100 * 1024 * 1024,
|
|
2962
|
+
skipUTF8Validation: false,
|
|
2963
|
+
perMessageDeflate: true,
|
|
2964
|
+
followRedirects: false,
|
|
2965
|
+
maxRedirects: 10,
|
|
2966
|
+
...options,
|
|
2967
|
+
socketPath: void 0,
|
|
2968
|
+
hostname: void 0,
|
|
2969
|
+
protocol: void 0,
|
|
2970
|
+
timeout: void 0,
|
|
2971
|
+
method: "GET",
|
|
2972
|
+
host: void 0,
|
|
2973
|
+
path: void 0,
|
|
2974
|
+
port: void 0
|
|
2975
|
+
};
|
|
2976
|
+
websocket._autoPong = opts.autoPong;
|
|
2977
|
+
if (!protocolVersions.includes(opts.protocolVersion)) {
|
|
2978
|
+
throw new RangeError(
|
|
2979
|
+
`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
|
|
2980
|
+
);
|
|
2981
|
+
}
|
|
2982
|
+
let parsedUrl;
|
|
2983
|
+
if (address instanceof URL2) {
|
|
2984
|
+
parsedUrl = address;
|
|
2985
|
+
} else {
|
|
2986
|
+
try {
|
|
2987
|
+
parsedUrl = new URL2(address);
|
|
2988
|
+
} catch (e) {
|
|
2989
|
+
throw new SyntaxError(`Invalid URL: ${address}`);
|
|
2990
|
+
}
|
|
2991
|
+
}
|
|
2992
|
+
if (parsedUrl.protocol === "http:") {
|
|
2993
|
+
parsedUrl.protocol = "ws:";
|
|
2994
|
+
} else if (parsedUrl.protocol === "https:") {
|
|
2995
|
+
parsedUrl.protocol = "wss:";
|
|
2996
|
+
}
|
|
2997
|
+
websocket._url = parsedUrl.href;
|
|
2998
|
+
const isSecure = parsedUrl.protocol === "wss:";
|
|
2999
|
+
const isIpcUrl = parsedUrl.protocol === "ws+unix:";
|
|
3000
|
+
let invalidUrlMessage;
|
|
3001
|
+
if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
|
|
3002
|
+
invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
|
|
3003
|
+
} else if (isIpcUrl && !parsedUrl.pathname) {
|
|
3004
|
+
invalidUrlMessage = "The URL's pathname is empty";
|
|
3005
|
+
} else if (parsedUrl.hash) {
|
|
3006
|
+
invalidUrlMessage = "The URL contains a fragment identifier";
|
|
3007
|
+
}
|
|
3008
|
+
if (invalidUrlMessage) {
|
|
3009
|
+
const err = new SyntaxError(invalidUrlMessage);
|
|
3010
|
+
if (websocket._redirects === 0) {
|
|
3011
|
+
throw err;
|
|
3012
|
+
} else {
|
|
3013
|
+
emitErrorAndClose(websocket, err);
|
|
3014
|
+
return;
|
|
3015
|
+
}
|
|
3016
|
+
}
|
|
3017
|
+
const defaultPort = isSecure ? 443 : 80;
|
|
3018
|
+
const key = randomBytes(16).toString("base64");
|
|
3019
|
+
const request = isSecure ? https.request : http.request;
|
|
3020
|
+
const protocolSet = /* @__PURE__ */ new Set();
|
|
3021
|
+
let perMessageDeflate;
|
|
3022
|
+
opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
|
|
3023
|
+
opts.defaultPort = opts.defaultPort || defaultPort;
|
|
3024
|
+
opts.port = parsedUrl.port || defaultPort;
|
|
3025
|
+
opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
|
|
3026
|
+
opts.headers = {
|
|
3027
|
+
...opts.headers,
|
|
3028
|
+
"Sec-WebSocket-Version": opts.protocolVersion,
|
|
3029
|
+
"Sec-WebSocket-Key": key,
|
|
3030
|
+
Connection: "Upgrade",
|
|
3031
|
+
Upgrade: "websocket"
|
|
3032
|
+
};
|
|
3033
|
+
opts.path = parsedUrl.pathname + parsedUrl.search;
|
|
3034
|
+
opts.timeout = opts.handshakeTimeout;
|
|
3035
|
+
if (opts.perMessageDeflate) {
|
|
3036
|
+
perMessageDeflate = new PerMessageDeflate(
|
|
3037
|
+
opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
|
|
3038
|
+
false,
|
|
3039
|
+
opts.maxPayload
|
|
3040
|
+
);
|
|
3041
|
+
opts.headers["Sec-WebSocket-Extensions"] = format({
|
|
3042
|
+
[PerMessageDeflate.extensionName]: perMessageDeflate.offer()
|
|
3043
|
+
});
|
|
3044
|
+
}
|
|
3045
|
+
if (protocols.length) {
|
|
3046
|
+
for (const protocol of protocols) {
|
|
3047
|
+
if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
|
|
3048
|
+
throw new SyntaxError(
|
|
3049
|
+
"An invalid or duplicated subprotocol was specified"
|
|
3050
|
+
);
|
|
3051
|
+
}
|
|
3052
|
+
protocolSet.add(protocol);
|
|
3053
|
+
}
|
|
3054
|
+
opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
|
|
3055
|
+
}
|
|
3056
|
+
if (opts.origin) {
|
|
3057
|
+
if (opts.protocolVersion < 13) {
|
|
3058
|
+
opts.headers["Sec-WebSocket-Origin"] = opts.origin;
|
|
3059
|
+
} else {
|
|
3060
|
+
opts.headers.Origin = opts.origin;
|
|
3061
|
+
}
|
|
3062
|
+
}
|
|
3063
|
+
if (parsedUrl.username || parsedUrl.password) {
|
|
3064
|
+
opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
|
|
3065
|
+
}
|
|
3066
|
+
if (isIpcUrl) {
|
|
3067
|
+
const parts = opts.path.split(":");
|
|
3068
|
+
opts.socketPath = parts[0];
|
|
3069
|
+
opts.path = parts[1];
|
|
3070
|
+
}
|
|
3071
|
+
let req;
|
|
3072
|
+
if (opts.followRedirects) {
|
|
3073
|
+
if (websocket._redirects === 0) {
|
|
3074
|
+
websocket._originalIpc = isIpcUrl;
|
|
3075
|
+
websocket._originalSecure = isSecure;
|
|
3076
|
+
websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
|
|
3077
|
+
const headers = options && options.headers;
|
|
3078
|
+
options = { ...options, headers: {} };
|
|
3079
|
+
if (headers) {
|
|
3080
|
+
for (const [key2, value] of Object.entries(headers)) {
|
|
3081
|
+
options.headers[key2.toLowerCase()] = value;
|
|
3082
|
+
}
|
|
3083
|
+
}
|
|
3084
|
+
} else if (websocket.listenerCount("redirect") === 0) {
|
|
3085
|
+
const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
|
|
3086
|
+
if (!isSameHost || websocket._originalSecure && !isSecure) {
|
|
3087
|
+
delete opts.headers.authorization;
|
|
3088
|
+
delete opts.headers.cookie;
|
|
3089
|
+
if (!isSameHost) delete opts.headers.host;
|
|
3090
|
+
opts.auth = void 0;
|
|
3091
|
+
}
|
|
3092
|
+
}
|
|
3093
|
+
if (opts.auth && !options.headers.authorization) {
|
|
3094
|
+
options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
|
|
3095
|
+
}
|
|
3096
|
+
req = websocket._req = request(opts);
|
|
3097
|
+
if (websocket._redirects) {
|
|
3098
|
+
websocket.emit("redirect", websocket.url, req);
|
|
3099
|
+
}
|
|
3100
|
+
} else {
|
|
3101
|
+
req = websocket._req = request(opts);
|
|
3102
|
+
}
|
|
3103
|
+
if (opts.timeout) {
|
|
3104
|
+
req.on("timeout", () => {
|
|
3105
|
+
abortHandshake(websocket, req, "Opening handshake has timed out");
|
|
3106
|
+
});
|
|
3107
|
+
}
|
|
3108
|
+
req.on("error", (err) => {
|
|
3109
|
+
if (req === null || req[kAborted]) return;
|
|
3110
|
+
req = websocket._req = null;
|
|
3111
|
+
emitErrorAndClose(websocket, err);
|
|
3112
|
+
});
|
|
3113
|
+
req.on("response", (res) => {
|
|
3114
|
+
const location = res.headers.location;
|
|
3115
|
+
const statusCode = res.statusCode;
|
|
3116
|
+
if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
|
|
3117
|
+
if (++websocket._redirects > opts.maxRedirects) {
|
|
3118
|
+
abortHandshake(websocket, req, "Maximum redirects exceeded");
|
|
3119
|
+
return;
|
|
3120
|
+
}
|
|
3121
|
+
req.abort();
|
|
3122
|
+
let addr;
|
|
3123
|
+
try {
|
|
3124
|
+
addr = new URL2(location, address);
|
|
3125
|
+
} catch (e) {
|
|
3126
|
+
const err = new SyntaxError(`Invalid URL: ${location}`);
|
|
3127
|
+
emitErrorAndClose(websocket, err);
|
|
3128
|
+
return;
|
|
3129
|
+
}
|
|
3130
|
+
initAsClient(websocket, addr, protocols, options);
|
|
3131
|
+
} else if (!websocket.emit("unexpected-response", req, res)) {
|
|
3132
|
+
abortHandshake(
|
|
3133
|
+
websocket,
|
|
3134
|
+
req,
|
|
3135
|
+
`Unexpected server response: ${res.statusCode}`
|
|
3136
|
+
);
|
|
3137
|
+
}
|
|
3138
|
+
});
|
|
3139
|
+
req.on("upgrade", (res, socket, head) => {
|
|
3140
|
+
websocket.emit("upgrade", res);
|
|
3141
|
+
if (websocket.readyState !== WebSocket2.CONNECTING) return;
|
|
3142
|
+
req = websocket._req = null;
|
|
3143
|
+
const upgrade = res.headers.upgrade;
|
|
3144
|
+
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
|
|
3145
|
+
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
3146
|
+
return;
|
|
3147
|
+
}
|
|
3148
|
+
const digest = createHash("sha1").update(key + GUID).digest("base64");
|
|
3149
|
+
if (res.headers["sec-websocket-accept"] !== digest) {
|
|
3150
|
+
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
3151
|
+
return;
|
|
3152
|
+
}
|
|
3153
|
+
const serverProt = res.headers["sec-websocket-protocol"];
|
|
3154
|
+
let protError;
|
|
3155
|
+
if (serverProt !== void 0) {
|
|
3156
|
+
if (!protocolSet.size) {
|
|
3157
|
+
protError = "Server sent a subprotocol but none was requested";
|
|
3158
|
+
} else if (!protocolSet.has(serverProt)) {
|
|
3159
|
+
protError = "Server sent an invalid subprotocol";
|
|
3160
|
+
}
|
|
3161
|
+
} else if (protocolSet.size) {
|
|
3162
|
+
protError = "Server sent no subprotocol";
|
|
3163
|
+
}
|
|
3164
|
+
if (protError) {
|
|
3165
|
+
abortHandshake(websocket, socket, protError);
|
|
3166
|
+
return;
|
|
3167
|
+
}
|
|
3168
|
+
if (serverProt) websocket._protocol = serverProt;
|
|
3169
|
+
const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
|
|
3170
|
+
if (secWebSocketExtensions !== void 0) {
|
|
3171
|
+
if (!perMessageDeflate) {
|
|
3172
|
+
const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
|
|
3173
|
+
abortHandshake(websocket, socket, message);
|
|
3174
|
+
return;
|
|
3175
|
+
}
|
|
3176
|
+
let extensions;
|
|
3177
|
+
try {
|
|
3178
|
+
extensions = parse(secWebSocketExtensions);
|
|
3179
|
+
} catch (err) {
|
|
3180
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
3181
|
+
abortHandshake(websocket, socket, message);
|
|
3182
|
+
return;
|
|
3183
|
+
}
|
|
3184
|
+
const extensionNames = Object.keys(extensions);
|
|
3185
|
+
if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
|
|
3186
|
+
const message = "Server indicated an extension that was not requested";
|
|
3187
|
+
abortHandshake(websocket, socket, message);
|
|
3188
|
+
return;
|
|
3189
|
+
}
|
|
3190
|
+
try {
|
|
3191
|
+
perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
|
|
3192
|
+
} catch (err) {
|
|
3193
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
3194
|
+
abortHandshake(websocket, socket, message);
|
|
3195
|
+
return;
|
|
3196
|
+
}
|
|
3197
|
+
websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
|
|
3198
|
+
}
|
|
3199
|
+
websocket.setSocket(socket, head, {
|
|
3200
|
+
allowSynchronousEvents: opts.allowSynchronousEvents,
|
|
3201
|
+
generateMask: opts.generateMask,
|
|
3202
|
+
maxPayload: opts.maxPayload,
|
|
3203
|
+
skipUTF8Validation: opts.skipUTF8Validation
|
|
3204
|
+
});
|
|
3205
|
+
});
|
|
3206
|
+
if (opts.finishRequest) {
|
|
3207
|
+
opts.finishRequest(req, websocket);
|
|
3208
|
+
} else {
|
|
3209
|
+
req.end();
|
|
3210
|
+
}
|
|
3211
|
+
}
|
|
3212
|
+
function emitErrorAndClose(websocket, err) {
|
|
3213
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3214
|
+
websocket._errorEmitted = true;
|
|
3215
|
+
websocket.emit("error", err);
|
|
3216
|
+
websocket.emitClose();
|
|
3217
|
+
}
|
|
3218
|
+
function netConnect(options) {
|
|
3219
|
+
options.path = options.socketPath;
|
|
3220
|
+
return net.connect(options);
|
|
3221
|
+
}
|
|
3222
|
+
function tlsConnect(options) {
|
|
3223
|
+
options.path = void 0;
|
|
3224
|
+
if (!options.servername && options.servername !== "") {
|
|
3225
|
+
options.servername = net.isIP(options.host) ? "" : options.host;
|
|
3226
|
+
}
|
|
3227
|
+
return tls.connect(options);
|
|
3228
|
+
}
|
|
3229
|
+
function abortHandshake(websocket, stream, message) {
|
|
3230
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3231
|
+
const err = new Error(message);
|
|
3232
|
+
Error.captureStackTrace(err, abortHandshake);
|
|
3233
|
+
if (stream.setHeader) {
|
|
3234
|
+
stream[kAborted] = true;
|
|
3235
|
+
stream.abort();
|
|
3236
|
+
if (stream.socket && !stream.socket.destroyed) {
|
|
3237
|
+
stream.socket.destroy();
|
|
3238
|
+
}
|
|
3239
|
+
process.nextTick(emitErrorAndClose, websocket, err);
|
|
3240
|
+
} else {
|
|
3241
|
+
stream.destroy(err);
|
|
3242
|
+
stream.once("error", websocket.emit.bind(websocket, "error"));
|
|
3243
|
+
stream.once("close", websocket.emitClose.bind(websocket));
|
|
3244
|
+
}
|
|
3245
|
+
}
|
|
3246
|
+
function sendAfterClose(websocket, data, cb) {
|
|
3247
|
+
if (data) {
|
|
3248
|
+
const length = isBlob(data) ? data.size : toBuffer(data).length;
|
|
3249
|
+
if (websocket._socket) websocket._sender._bufferedBytes += length;
|
|
3250
|
+
else websocket._bufferedAmount += length;
|
|
3251
|
+
}
|
|
3252
|
+
if (cb) {
|
|
3253
|
+
const err = new Error(
|
|
3254
|
+
`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
|
|
3255
|
+
);
|
|
3256
|
+
process.nextTick(cb, err);
|
|
3257
|
+
}
|
|
3258
|
+
}
|
|
3259
|
+
function receiverOnConclude(code, reason) {
|
|
3260
|
+
const websocket = this[kWebSocket];
|
|
3261
|
+
websocket._closeFrameReceived = true;
|
|
3262
|
+
websocket._closeMessage = reason;
|
|
3263
|
+
websocket._closeCode = code;
|
|
3264
|
+
if (websocket._socket[kWebSocket] === void 0) return;
|
|
3265
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
3266
|
+
process.nextTick(resume, websocket._socket);
|
|
3267
|
+
if (code === 1005) websocket.close();
|
|
3268
|
+
else websocket.close(code, reason);
|
|
3269
|
+
}
|
|
3270
|
+
function receiverOnDrain() {
|
|
3271
|
+
const websocket = this[kWebSocket];
|
|
3272
|
+
if (!websocket.isPaused) websocket._socket.resume();
|
|
3273
|
+
}
|
|
3274
|
+
function receiverOnError(err) {
|
|
3275
|
+
const websocket = this[kWebSocket];
|
|
3276
|
+
if (websocket._socket[kWebSocket] !== void 0) {
|
|
3277
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
3278
|
+
process.nextTick(resume, websocket._socket);
|
|
3279
|
+
websocket.close(err[kStatusCode]);
|
|
3280
|
+
}
|
|
3281
|
+
if (!websocket._errorEmitted) {
|
|
3282
|
+
websocket._errorEmitted = true;
|
|
3283
|
+
websocket.emit("error", err);
|
|
3284
|
+
}
|
|
3285
|
+
}
|
|
3286
|
+
function receiverOnFinish() {
|
|
3287
|
+
this[kWebSocket].emitClose();
|
|
3288
|
+
}
|
|
3289
|
+
function receiverOnMessage(data, isBinary) {
|
|
3290
|
+
this[kWebSocket].emit("message", data, isBinary);
|
|
3291
|
+
}
|
|
3292
|
+
function receiverOnPing(data) {
|
|
3293
|
+
const websocket = this[kWebSocket];
|
|
3294
|
+
if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
|
|
3295
|
+
websocket.emit("ping", data);
|
|
3296
|
+
}
|
|
3297
|
+
function receiverOnPong(data) {
|
|
3298
|
+
this[kWebSocket].emit("pong", data);
|
|
3299
|
+
}
|
|
3300
|
+
function resume(stream) {
|
|
3301
|
+
stream.resume();
|
|
3302
|
+
}
|
|
3303
|
+
function senderOnError(err) {
|
|
3304
|
+
const websocket = this[kWebSocket];
|
|
3305
|
+
if (websocket.readyState === WebSocket2.CLOSED) return;
|
|
3306
|
+
if (websocket.readyState === WebSocket2.OPEN) {
|
|
3307
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3308
|
+
setCloseTimer(websocket);
|
|
3309
|
+
}
|
|
3310
|
+
this._socket.end();
|
|
3311
|
+
if (!websocket._errorEmitted) {
|
|
3312
|
+
websocket._errorEmitted = true;
|
|
3313
|
+
websocket.emit("error", err);
|
|
3314
|
+
}
|
|
3315
|
+
}
|
|
3316
|
+
function setCloseTimer(websocket) {
|
|
3317
|
+
websocket._closeTimer = setTimeout(
|
|
3318
|
+
websocket._socket.destroy.bind(websocket._socket),
|
|
3319
|
+
closeTimeout
|
|
3320
|
+
);
|
|
3321
|
+
}
|
|
3322
|
+
function socketOnClose() {
|
|
3323
|
+
const websocket = this[kWebSocket];
|
|
3324
|
+
this.removeListener("close", socketOnClose);
|
|
3325
|
+
this.removeListener("data", socketOnData);
|
|
3326
|
+
this.removeListener("end", socketOnEnd);
|
|
3327
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3328
|
+
let chunk;
|
|
3329
|
+
if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
|
|
3330
|
+
websocket._receiver.write(chunk);
|
|
3331
|
+
}
|
|
3332
|
+
websocket._receiver.end();
|
|
3333
|
+
this[kWebSocket] = void 0;
|
|
3334
|
+
clearTimeout(websocket._closeTimer);
|
|
3335
|
+
if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
|
|
3336
|
+
websocket.emitClose();
|
|
3337
|
+
} else {
|
|
3338
|
+
websocket._receiver.on("error", receiverOnFinish);
|
|
3339
|
+
websocket._receiver.on("finish", receiverOnFinish);
|
|
3340
|
+
}
|
|
3341
|
+
}
|
|
3342
|
+
function socketOnData(chunk) {
|
|
3343
|
+
if (!this[kWebSocket]._receiver.write(chunk)) {
|
|
3344
|
+
this.pause();
|
|
3345
|
+
}
|
|
3346
|
+
}
|
|
3347
|
+
function socketOnEnd() {
|
|
3348
|
+
const websocket = this[kWebSocket];
|
|
3349
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3350
|
+
websocket._receiver.end();
|
|
3351
|
+
this.end();
|
|
3352
|
+
}
|
|
3353
|
+
function socketOnError() {
|
|
3354
|
+
const websocket = this[kWebSocket];
|
|
3355
|
+
this.removeListener("error", socketOnError);
|
|
3356
|
+
this.on("error", NOOP);
|
|
3357
|
+
if (websocket) {
|
|
3358
|
+
websocket._readyState = WebSocket2.CLOSING;
|
|
3359
|
+
this.destroy();
|
|
3360
|
+
}
|
|
3361
|
+
}
|
|
3362
|
+
}
|
|
3363
|
+
});
|
|
3364
|
+
|
|
3365
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/stream.js
|
|
3366
|
+
var require_stream = __commonJS({
|
|
3367
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/stream.js"(exports, module) {
|
|
3368
|
+
require_websocket();
|
|
3369
|
+
var { Duplex } = __require("stream");
|
|
3370
|
+
function emitClose(stream) {
|
|
3371
|
+
stream.emit("close");
|
|
3372
|
+
}
|
|
3373
|
+
function duplexOnEnd() {
|
|
3374
|
+
if (!this.destroyed && this._writableState.finished) {
|
|
3375
|
+
this.destroy();
|
|
3376
|
+
}
|
|
3377
|
+
}
|
|
3378
|
+
function duplexOnError(err) {
|
|
3379
|
+
this.removeListener("error", duplexOnError);
|
|
3380
|
+
this.destroy();
|
|
3381
|
+
if (this.listenerCount("error") === 0) {
|
|
3382
|
+
this.emit("error", err);
|
|
3383
|
+
}
|
|
3384
|
+
}
|
|
3385
|
+
function createWebSocketStream2(ws, options) {
|
|
3386
|
+
let terminateOnDestroy = true;
|
|
3387
|
+
const duplex = new Duplex({
|
|
3388
|
+
...options,
|
|
3389
|
+
autoDestroy: false,
|
|
3390
|
+
emitClose: false,
|
|
3391
|
+
objectMode: false,
|
|
3392
|
+
writableObjectMode: false
|
|
3393
|
+
});
|
|
3394
|
+
ws.on("message", function message(msg, isBinary) {
|
|
3395
|
+
const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
|
|
3396
|
+
if (!duplex.push(data)) ws.pause();
|
|
3397
|
+
});
|
|
3398
|
+
ws.once("error", function error(err) {
|
|
3399
|
+
if (duplex.destroyed) return;
|
|
3400
|
+
terminateOnDestroy = false;
|
|
3401
|
+
duplex.destroy(err);
|
|
3402
|
+
});
|
|
3403
|
+
ws.once("close", function close() {
|
|
3404
|
+
if (duplex.destroyed) return;
|
|
3405
|
+
duplex.push(null);
|
|
3406
|
+
});
|
|
3407
|
+
duplex._destroy = function(err, callback) {
|
|
3408
|
+
if (ws.readyState === ws.CLOSED) {
|
|
3409
|
+
callback(err);
|
|
3410
|
+
process.nextTick(emitClose, duplex);
|
|
3411
|
+
return;
|
|
3412
|
+
}
|
|
3413
|
+
let called = false;
|
|
3414
|
+
ws.once("error", function error(err2) {
|
|
3415
|
+
called = true;
|
|
3416
|
+
callback(err2);
|
|
3417
|
+
});
|
|
3418
|
+
ws.once("close", function close() {
|
|
3419
|
+
if (!called) callback(err);
|
|
3420
|
+
process.nextTick(emitClose, duplex);
|
|
3421
|
+
});
|
|
3422
|
+
if (terminateOnDestroy) ws.terminate();
|
|
3423
|
+
};
|
|
3424
|
+
duplex._final = function(callback) {
|
|
3425
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
3426
|
+
ws.once("open", function open() {
|
|
3427
|
+
duplex._final(callback);
|
|
3428
|
+
});
|
|
3429
|
+
return;
|
|
3430
|
+
}
|
|
3431
|
+
if (ws._socket === null) return;
|
|
3432
|
+
if (ws._socket._writableState.finished) {
|
|
3433
|
+
callback();
|
|
3434
|
+
if (duplex._readableState.endEmitted) duplex.destroy();
|
|
3435
|
+
} else {
|
|
3436
|
+
ws._socket.once("finish", function finish() {
|
|
3437
|
+
callback();
|
|
3438
|
+
});
|
|
3439
|
+
ws.close();
|
|
3440
|
+
}
|
|
3441
|
+
};
|
|
3442
|
+
duplex._read = function() {
|
|
3443
|
+
if (ws.isPaused) ws.resume();
|
|
3444
|
+
};
|
|
3445
|
+
duplex._write = function(chunk, encoding, callback) {
|
|
3446
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
3447
|
+
ws.once("open", function open() {
|
|
3448
|
+
duplex._write(chunk, encoding, callback);
|
|
3449
|
+
});
|
|
3450
|
+
return;
|
|
3451
|
+
}
|
|
3452
|
+
ws.send(chunk, callback);
|
|
3453
|
+
};
|
|
3454
|
+
duplex.on("end", duplexOnEnd);
|
|
3455
|
+
duplex.on("error", duplexOnError);
|
|
3456
|
+
return duplex;
|
|
3457
|
+
}
|
|
3458
|
+
module.exports = createWebSocketStream2;
|
|
3459
|
+
}
|
|
3460
|
+
});
|
|
3461
|
+
|
|
3462
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/subprotocol.js
|
|
3463
|
+
var require_subprotocol = __commonJS({
|
|
3464
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/subprotocol.js"(exports, module) {
|
|
3465
|
+
var { tokenChars } = require_validation();
|
|
3466
|
+
function parse(header) {
|
|
3467
|
+
const protocols = /* @__PURE__ */ new Set();
|
|
3468
|
+
let start = -1;
|
|
3469
|
+
let end = -1;
|
|
3470
|
+
let i = 0;
|
|
3471
|
+
for (i; i < header.length; i++) {
|
|
3472
|
+
const code = header.charCodeAt(i);
|
|
3473
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
3474
|
+
if (start === -1) start = i;
|
|
3475
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
3476
|
+
if (end === -1 && start !== -1) end = i;
|
|
3477
|
+
} else if (code === 44) {
|
|
3478
|
+
if (start === -1) {
|
|
3479
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
3480
|
+
}
|
|
3481
|
+
if (end === -1) end = i;
|
|
3482
|
+
const protocol2 = header.slice(start, end);
|
|
3483
|
+
if (protocols.has(protocol2)) {
|
|
3484
|
+
throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
|
|
3485
|
+
}
|
|
3486
|
+
protocols.add(protocol2);
|
|
3487
|
+
start = end = -1;
|
|
3488
|
+
} else {
|
|
3489
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
3490
|
+
}
|
|
3491
|
+
}
|
|
3492
|
+
if (start === -1 || end !== -1) {
|
|
3493
|
+
throw new SyntaxError("Unexpected end of input");
|
|
3494
|
+
}
|
|
3495
|
+
const protocol = header.slice(start, i);
|
|
3496
|
+
if (protocols.has(protocol)) {
|
|
3497
|
+
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
|
|
3498
|
+
}
|
|
3499
|
+
protocols.add(protocol);
|
|
3500
|
+
return protocols;
|
|
3501
|
+
}
|
|
3502
|
+
module.exports = { parse };
|
|
3503
|
+
}
|
|
3504
|
+
});
|
|
3505
|
+
|
|
3506
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/websocket-server.js
|
|
3507
|
+
var require_websocket_server = __commonJS({
|
|
3508
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/lib/websocket-server.js"(exports, module) {
|
|
3509
|
+
var EventEmitter = __require("events");
|
|
3510
|
+
var http = __require("http");
|
|
3511
|
+
var { Duplex } = __require("stream");
|
|
3512
|
+
var { createHash } = __require("crypto");
|
|
3513
|
+
var extension = require_extension();
|
|
3514
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
3515
|
+
var subprotocol = require_subprotocol();
|
|
3516
|
+
var WebSocket2 = require_websocket();
|
|
3517
|
+
var { GUID, kWebSocket } = require_constants();
|
|
3518
|
+
var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
|
|
3519
|
+
var RUNNING = 0;
|
|
3520
|
+
var CLOSING = 1;
|
|
3521
|
+
var CLOSED = 2;
|
|
3522
|
+
var WebSocketServer2 = class extends EventEmitter {
|
|
3523
|
+
/**
|
|
3524
|
+
* Create a `WebSocketServer` instance.
|
|
3525
|
+
*
|
|
3526
|
+
* @param {Object} options Configuration options
|
|
3527
|
+
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
|
|
3528
|
+
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
|
|
3529
|
+
* multiple times in the same tick
|
|
3530
|
+
* @param {Boolean} [options.autoPong=true] Specifies whether or not to
|
|
3531
|
+
* automatically send a pong in response to a ping
|
|
3532
|
+
* @param {Number} [options.backlog=511] The maximum length of the queue of
|
|
3533
|
+
* pending connections
|
|
3534
|
+
* @param {Boolean} [options.clientTracking=true] Specifies whether or not to
|
|
3535
|
+
* track clients
|
|
3536
|
+
* @param {Function} [options.handleProtocols] A hook to handle protocols
|
|
3537
|
+
* @param {String} [options.host] The hostname where to bind the server
|
|
3538
|
+
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
|
|
3539
|
+
* size
|
|
3540
|
+
* @param {Boolean} [options.noServer=false] Enable no server mode
|
|
3541
|
+
* @param {String} [options.path] Accept only connections matching this path
|
|
3542
|
+
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
|
|
3543
|
+
* permessage-deflate
|
|
3544
|
+
* @param {Number} [options.port] The port where to bind the server
|
|
3545
|
+
* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
|
|
3546
|
+
* server to use
|
|
3547
|
+
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
3548
|
+
* not to skip UTF-8 validation for text and close messages
|
|
3549
|
+
* @param {Function} [options.verifyClient] A hook to reject connections
|
|
3550
|
+
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
|
|
3551
|
+
* class to use. It must be the `WebSocket` class or class that extends it
|
|
3552
|
+
* @param {Function} [callback] A listener for the `listening` event
|
|
3553
|
+
*/
|
|
3554
|
+
constructor(options, callback) {
|
|
3555
|
+
super();
|
|
3556
|
+
options = {
|
|
3557
|
+
allowSynchronousEvents: true,
|
|
3558
|
+
autoPong: true,
|
|
3559
|
+
maxPayload: 100 * 1024 * 1024,
|
|
3560
|
+
skipUTF8Validation: false,
|
|
3561
|
+
perMessageDeflate: false,
|
|
3562
|
+
handleProtocols: null,
|
|
3563
|
+
clientTracking: true,
|
|
3564
|
+
verifyClient: null,
|
|
3565
|
+
noServer: false,
|
|
3566
|
+
backlog: null,
|
|
3567
|
+
// use default (511 as implemented in net.js)
|
|
3568
|
+
server: null,
|
|
3569
|
+
host: null,
|
|
3570
|
+
path: null,
|
|
3571
|
+
port: null,
|
|
3572
|
+
WebSocket: WebSocket2,
|
|
3573
|
+
...options
|
|
3574
|
+
};
|
|
3575
|
+
if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
|
|
3576
|
+
throw new TypeError(
|
|
3577
|
+
'One and only one of the "port", "server", or "noServer" options must be specified'
|
|
3578
|
+
);
|
|
3579
|
+
}
|
|
3580
|
+
if (options.port != null) {
|
|
3581
|
+
this._server = http.createServer((req, res) => {
|
|
3582
|
+
const body = http.STATUS_CODES[426];
|
|
3583
|
+
res.writeHead(426, {
|
|
3584
|
+
"Content-Length": body.length,
|
|
3585
|
+
"Content-Type": "text/plain"
|
|
3586
|
+
});
|
|
3587
|
+
res.end(body);
|
|
3588
|
+
});
|
|
3589
|
+
this._server.listen(
|
|
3590
|
+
options.port,
|
|
3591
|
+
options.host,
|
|
3592
|
+
options.backlog,
|
|
3593
|
+
callback
|
|
3594
|
+
);
|
|
3595
|
+
} else if (options.server) {
|
|
3596
|
+
this._server = options.server;
|
|
3597
|
+
}
|
|
3598
|
+
if (this._server) {
|
|
3599
|
+
const emitConnection = this.emit.bind(this, "connection");
|
|
3600
|
+
this._removeListeners = addListeners(this._server, {
|
|
3601
|
+
listening: this.emit.bind(this, "listening"),
|
|
3602
|
+
error: this.emit.bind(this, "error"),
|
|
3603
|
+
upgrade: (req, socket, head) => {
|
|
3604
|
+
this.handleUpgrade(req, socket, head, emitConnection);
|
|
3605
|
+
}
|
|
3606
|
+
});
|
|
3607
|
+
}
|
|
3608
|
+
if (options.perMessageDeflate === true) options.perMessageDeflate = {};
|
|
3609
|
+
if (options.clientTracking) {
|
|
3610
|
+
this.clients = /* @__PURE__ */ new Set();
|
|
3611
|
+
this._shouldEmitClose = false;
|
|
3612
|
+
}
|
|
3613
|
+
this.options = options;
|
|
3614
|
+
this._state = RUNNING;
|
|
3615
|
+
}
|
|
3616
|
+
/**
|
|
3617
|
+
* Returns the bound address, the address family name, and port of the server
|
|
3618
|
+
* as reported by the operating system if listening on an IP socket.
|
|
3619
|
+
* If the server is listening on a pipe or UNIX domain socket, the name is
|
|
3620
|
+
* returned as a string.
|
|
3621
|
+
*
|
|
3622
|
+
* @return {(Object|String|null)} The address of the server
|
|
3623
|
+
* @public
|
|
3624
|
+
*/
|
|
3625
|
+
address() {
|
|
3626
|
+
if (this.options.noServer) {
|
|
3627
|
+
throw new Error('The server is operating in "noServer" mode');
|
|
3628
|
+
}
|
|
3629
|
+
if (!this._server) return null;
|
|
3630
|
+
return this._server.address();
|
|
3631
|
+
}
|
|
3632
|
+
/**
|
|
3633
|
+
* Stop the server from accepting new connections and emit the `'close'` event
|
|
3634
|
+
* when all existing connections are closed.
|
|
3635
|
+
*
|
|
3636
|
+
* @param {Function} [cb] A one-time listener for the `'close'` event
|
|
3637
|
+
* @public
|
|
3638
|
+
*/
|
|
3639
|
+
close(cb) {
|
|
3640
|
+
if (this._state === CLOSED) {
|
|
3641
|
+
if (cb) {
|
|
3642
|
+
this.once("close", () => {
|
|
3643
|
+
cb(new Error("The server is not running"));
|
|
3644
|
+
});
|
|
3645
|
+
}
|
|
3646
|
+
process.nextTick(emitClose, this);
|
|
3647
|
+
return;
|
|
3648
|
+
}
|
|
3649
|
+
if (cb) this.once("close", cb);
|
|
3650
|
+
if (this._state === CLOSING) return;
|
|
3651
|
+
this._state = CLOSING;
|
|
3652
|
+
if (this.options.noServer || this.options.server) {
|
|
3653
|
+
if (this._server) {
|
|
3654
|
+
this._removeListeners();
|
|
3655
|
+
this._removeListeners = this._server = null;
|
|
3656
|
+
}
|
|
3657
|
+
if (this.clients) {
|
|
3658
|
+
if (!this.clients.size) {
|
|
3659
|
+
process.nextTick(emitClose, this);
|
|
3660
|
+
} else {
|
|
3661
|
+
this._shouldEmitClose = true;
|
|
3662
|
+
}
|
|
3663
|
+
} else {
|
|
3664
|
+
process.nextTick(emitClose, this);
|
|
3665
|
+
}
|
|
3666
|
+
} else {
|
|
3667
|
+
const server = this._server;
|
|
3668
|
+
this._removeListeners();
|
|
3669
|
+
this._removeListeners = this._server = null;
|
|
3670
|
+
server.close(() => {
|
|
3671
|
+
emitClose(this);
|
|
3672
|
+
});
|
|
3673
|
+
}
|
|
3674
|
+
}
|
|
3675
|
+
/**
|
|
3676
|
+
* See if a given request should be handled by this server instance.
|
|
3677
|
+
*
|
|
3678
|
+
* @param {http.IncomingMessage} req Request object to inspect
|
|
3679
|
+
* @return {Boolean} `true` if the request is valid, else `false`
|
|
3680
|
+
* @public
|
|
3681
|
+
*/
|
|
3682
|
+
shouldHandle(req) {
|
|
3683
|
+
if (this.options.path) {
|
|
3684
|
+
const index = req.url.indexOf("?");
|
|
3685
|
+
const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
|
|
3686
|
+
if (pathname !== this.options.path) return false;
|
|
3687
|
+
}
|
|
3688
|
+
return true;
|
|
3689
|
+
}
|
|
3690
|
+
/**
|
|
3691
|
+
* Handle a HTTP Upgrade request.
|
|
3692
|
+
*
|
|
3693
|
+
* @param {http.IncomingMessage} req The request object
|
|
3694
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
3695
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
3696
|
+
* @param {Function} cb Callback
|
|
3697
|
+
* @public
|
|
3698
|
+
*/
|
|
3699
|
+
handleUpgrade(req, socket, head, cb) {
|
|
3700
|
+
socket.on("error", socketOnError);
|
|
3701
|
+
const key = req.headers["sec-websocket-key"];
|
|
3702
|
+
const upgrade = req.headers.upgrade;
|
|
3703
|
+
const version = +req.headers["sec-websocket-version"];
|
|
3704
|
+
if (req.method !== "GET") {
|
|
3705
|
+
const message = "Invalid HTTP method";
|
|
3706
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
|
|
3707
|
+
return;
|
|
3708
|
+
}
|
|
3709
|
+
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
|
|
3710
|
+
const message = "Invalid Upgrade header";
|
|
3711
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3712
|
+
return;
|
|
3713
|
+
}
|
|
3714
|
+
if (key === void 0 || !keyRegex.test(key)) {
|
|
3715
|
+
const message = "Missing or invalid Sec-WebSocket-Key header";
|
|
3716
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3717
|
+
return;
|
|
3718
|
+
}
|
|
3719
|
+
if (version !== 13 && version !== 8) {
|
|
3720
|
+
const message = "Missing or invalid Sec-WebSocket-Version header";
|
|
3721
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
|
|
3722
|
+
"Sec-WebSocket-Version": "13, 8"
|
|
3723
|
+
});
|
|
3724
|
+
return;
|
|
3725
|
+
}
|
|
3726
|
+
if (!this.shouldHandle(req)) {
|
|
3727
|
+
abortHandshake(socket, 400);
|
|
3728
|
+
return;
|
|
3729
|
+
}
|
|
3730
|
+
const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
|
|
3731
|
+
let protocols = /* @__PURE__ */ new Set();
|
|
3732
|
+
if (secWebSocketProtocol !== void 0) {
|
|
3733
|
+
try {
|
|
3734
|
+
protocols = subprotocol.parse(secWebSocketProtocol);
|
|
3735
|
+
} catch (err) {
|
|
3736
|
+
const message = "Invalid Sec-WebSocket-Protocol header";
|
|
3737
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3738
|
+
return;
|
|
3739
|
+
}
|
|
3740
|
+
}
|
|
3741
|
+
const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
|
|
3742
|
+
const extensions = {};
|
|
3743
|
+
if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
|
|
3744
|
+
const perMessageDeflate = new PerMessageDeflate(
|
|
3745
|
+
this.options.perMessageDeflate,
|
|
3746
|
+
true,
|
|
3747
|
+
this.options.maxPayload
|
|
3748
|
+
);
|
|
3749
|
+
try {
|
|
3750
|
+
const offers = extension.parse(secWebSocketExtensions);
|
|
3751
|
+
if (offers[PerMessageDeflate.extensionName]) {
|
|
3752
|
+
perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
|
|
3753
|
+
extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
|
|
3754
|
+
}
|
|
3755
|
+
} catch (err) {
|
|
3756
|
+
const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
|
|
3757
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3758
|
+
return;
|
|
3759
|
+
}
|
|
3760
|
+
}
|
|
3761
|
+
if (this.options.verifyClient) {
|
|
3762
|
+
const info = {
|
|
3763
|
+
origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
|
|
3764
|
+
secure: !!(req.socket.authorized || req.socket.encrypted),
|
|
3765
|
+
req
|
|
3766
|
+
};
|
|
3767
|
+
if (this.options.verifyClient.length === 2) {
|
|
3768
|
+
this.options.verifyClient(info, (verified, code, message, headers) => {
|
|
3769
|
+
if (!verified) {
|
|
3770
|
+
return abortHandshake(socket, code || 401, message, headers);
|
|
3771
|
+
}
|
|
3772
|
+
this.completeUpgrade(
|
|
3773
|
+
extensions,
|
|
3774
|
+
key,
|
|
3775
|
+
protocols,
|
|
3776
|
+
req,
|
|
3777
|
+
socket,
|
|
3778
|
+
head,
|
|
3779
|
+
cb
|
|
3780
|
+
);
|
|
3781
|
+
});
|
|
3782
|
+
return;
|
|
3783
|
+
}
|
|
3784
|
+
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
|
|
3785
|
+
}
|
|
3786
|
+
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
|
|
3787
|
+
}
|
|
3788
|
+
/**
|
|
3789
|
+
* Upgrade the connection to WebSocket.
|
|
3790
|
+
*
|
|
3791
|
+
* @param {Object} extensions The accepted extensions
|
|
3792
|
+
* @param {String} key The value of the `Sec-WebSocket-Key` header
|
|
3793
|
+
* @param {Set} protocols The subprotocols
|
|
3794
|
+
* @param {http.IncomingMessage} req The request object
|
|
3795
|
+
* @param {Duplex} socket The network socket between the server and client
|
|
3796
|
+
* @param {Buffer} head The first packet of the upgraded stream
|
|
3797
|
+
* @param {Function} cb Callback
|
|
3798
|
+
* @throws {Error} If called more than once with the same socket
|
|
3799
|
+
* @private
|
|
3800
|
+
*/
|
|
3801
|
+
completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
|
|
3802
|
+
if (!socket.readable || !socket.writable) return socket.destroy();
|
|
3803
|
+
if (socket[kWebSocket]) {
|
|
3804
|
+
throw new Error(
|
|
3805
|
+
"server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
|
|
3806
|
+
);
|
|
3807
|
+
}
|
|
3808
|
+
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
3809
|
+
const digest = createHash("sha1").update(key + GUID).digest("base64");
|
|
3810
|
+
const headers = [
|
|
3811
|
+
"HTTP/1.1 101 Switching Protocols",
|
|
3812
|
+
"Upgrade: websocket",
|
|
3813
|
+
"Connection: Upgrade",
|
|
3814
|
+
`Sec-WebSocket-Accept: ${digest}`
|
|
3815
|
+
];
|
|
3816
|
+
const ws = new this.options.WebSocket(null, void 0, this.options);
|
|
3817
|
+
if (protocols.size) {
|
|
3818
|
+
const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
|
|
3819
|
+
if (protocol) {
|
|
3820
|
+
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
|
|
3821
|
+
ws._protocol = protocol;
|
|
3822
|
+
}
|
|
3823
|
+
}
|
|
3824
|
+
if (extensions[PerMessageDeflate.extensionName]) {
|
|
3825
|
+
const params = extensions[PerMessageDeflate.extensionName].params;
|
|
3826
|
+
const value = extension.format({
|
|
3827
|
+
[PerMessageDeflate.extensionName]: [params]
|
|
3828
|
+
});
|
|
3829
|
+
headers.push(`Sec-WebSocket-Extensions: ${value}`);
|
|
3830
|
+
ws._extensions = extensions;
|
|
3831
|
+
}
|
|
3832
|
+
this.emit("headers", headers, req);
|
|
3833
|
+
socket.write(headers.concat("\r\n").join("\r\n"));
|
|
3834
|
+
socket.removeListener("error", socketOnError);
|
|
3835
|
+
ws.setSocket(socket, head, {
|
|
3836
|
+
allowSynchronousEvents: this.options.allowSynchronousEvents,
|
|
3837
|
+
maxPayload: this.options.maxPayload,
|
|
3838
|
+
skipUTF8Validation: this.options.skipUTF8Validation
|
|
3839
|
+
});
|
|
3840
|
+
if (this.clients) {
|
|
3841
|
+
this.clients.add(ws);
|
|
3842
|
+
ws.on("close", () => {
|
|
3843
|
+
this.clients.delete(ws);
|
|
3844
|
+
if (this._shouldEmitClose && !this.clients.size) {
|
|
3845
|
+
process.nextTick(emitClose, this);
|
|
3846
|
+
}
|
|
3847
|
+
});
|
|
3848
|
+
}
|
|
3849
|
+
cb(ws, req);
|
|
3850
|
+
}
|
|
3851
|
+
};
|
|
3852
|
+
module.exports = WebSocketServer2;
|
|
3853
|
+
function addListeners(server, map) {
|
|
3854
|
+
for (const event of Object.keys(map)) server.on(event, map[event]);
|
|
3855
|
+
return function removeListeners() {
|
|
3856
|
+
for (const event of Object.keys(map)) {
|
|
3857
|
+
server.removeListener(event, map[event]);
|
|
3858
|
+
}
|
|
3859
|
+
};
|
|
3860
|
+
}
|
|
3861
|
+
function emitClose(server) {
|
|
3862
|
+
server._state = CLOSED;
|
|
3863
|
+
server.emit("close");
|
|
3864
|
+
}
|
|
3865
|
+
function socketOnError() {
|
|
3866
|
+
this.destroy();
|
|
3867
|
+
}
|
|
3868
|
+
function abortHandshake(socket, code, message, headers) {
|
|
3869
|
+
message = message || http.STATUS_CODES[code];
|
|
3870
|
+
headers = {
|
|
3871
|
+
Connection: "close",
|
|
3872
|
+
"Content-Type": "text/html",
|
|
3873
|
+
"Content-Length": Buffer.byteLength(message),
|
|
3874
|
+
...headers
|
|
3875
|
+
};
|
|
3876
|
+
socket.once("finish", socket.destroy);
|
|
3877
|
+
socket.end(
|
|
3878
|
+
`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
|
|
3879
|
+
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
|
|
3880
|
+
);
|
|
3881
|
+
}
|
|
3882
|
+
function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
|
|
3883
|
+
if (server.listenerCount("wsClientError")) {
|
|
3884
|
+
const err = new Error(message);
|
|
3885
|
+
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
|
|
3886
|
+
server.emit("wsClientError", err, socket, req);
|
|
3887
|
+
} else {
|
|
3888
|
+
abortHandshake(socket, code, message, headers);
|
|
3889
|
+
}
|
|
3890
|
+
}
|
|
3891
|
+
}
|
|
3892
|
+
});
|
|
3893
|
+
|
|
3894
|
+
// ../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/wrapper.mjs
|
|
3895
|
+
var wrapper_exports = {};
|
|
3896
|
+
__export(wrapper_exports, {
|
|
3897
|
+
Receiver: () => import_receiver.default,
|
|
3898
|
+
Sender: () => import_sender.default,
|
|
3899
|
+
WebSocket: () => import_websocket.default,
|
|
3900
|
+
WebSocketServer: () => import_websocket_server.default,
|
|
3901
|
+
createWebSocketStream: () => import_stream.default,
|
|
3902
|
+
default: () => wrapper_default
|
|
3903
|
+
});
|
|
3904
|
+
var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
|
|
3905
|
+
var init_wrapper = __esm({
|
|
3906
|
+
"../../node_modules/.bun/ws@8.18.3+eb074c07ce2a86fc/node_modules/ws/wrapper.mjs"() {
|
|
3907
|
+
import_stream = __toESM(require_stream());
|
|
3908
|
+
import_receiver = __toESM(require_receiver());
|
|
3909
|
+
import_sender = __toESM(require_sender());
|
|
3910
|
+
import_websocket = __toESM(require_websocket());
|
|
3911
|
+
import_websocket_server = __toESM(require_websocket_server());
|
|
3912
|
+
wrapper_default = import_websocket.default;
|
|
3913
|
+
}
|
|
3914
|
+
});
|
|
3915
|
+
var GlobalWebSocket = void 0;
|
|
3916
|
+
if (typeof globalThis !== "undefined" && globalThis.WebSocket) {
|
|
3917
|
+
GlobalWebSocket = globalThis.WebSocket;
|
|
3918
|
+
}
|
|
3919
|
+
var READY_STATE_OPEN = 1;
|
|
5
3920
|
var WSClient = class {
|
|
6
3921
|
ws = null;
|
|
7
3922
|
url;
|
|
@@ -16,7 +3931,9 @@ var WSClient = class {
|
|
|
16
3931
|
syncState = Automerge.initSyncState();
|
|
17
3932
|
reconnectTimer = null;
|
|
18
3933
|
isExplicitlyDisconnected = false;
|
|
3934
|
+
options;
|
|
19
3935
|
constructor(options) {
|
|
3936
|
+
this.options = options;
|
|
20
3937
|
this.url = options.url;
|
|
21
3938
|
this.sessionId = options.sessionId;
|
|
22
3939
|
this.token = options.token;
|
|
@@ -27,34 +3944,75 @@ var WSClient = class {
|
|
|
27
3944
|
*/
|
|
28
3945
|
async connect() {
|
|
29
3946
|
this.isExplicitlyDisconnected = false;
|
|
3947
|
+
let WebSocketClass = this.options.WebSocketCtor || GlobalWebSocket;
|
|
3948
|
+
if (!WebSocketClass) {
|
|
3949
|
+
try {
|
|
3950
|
+
const wsModule = await Promise.resolve().then(() => (init_wrapper(), wrapper_exports));
|
|
3951
|
+
WebSocketClass = wsModule.default || wsModule;
|
|
3952
|
+
} catch (e) {
|
|
3953
|
+
}
|
|
3954
|
+
}
|
|
3955
|
+
if (!WebSocketClass) {
|
|
3956
|
+
throw new Error('No WebSocket implementation found. If using Node.js, please install "ws" and pass the constructor to the SDK options: { WebSocketCtor: WebSocket }.');
|
|
3957
|
+
}
|
|
30
3958
|
return new Promise((resolve, reject) => {
|
|
31
3959
|
try {
|
|
32
3960
|
const wsUrl = new URL(this.url);
|
|
33
3961
|
wsUrl.searchParams.set("sessionId", this.sessionId);
|
|
34
3962
|
wsUrl.searchParams.set("token", this.token);
|
|
35
|
-
this.ws = new
|
|
36
|
-
this.ws
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
3963
|
+
this.ws = new WebSocketClass(wsUrl.toString());
|
|
3964
|
+
if (!this.ws) throw new Error("Failed to create WebSocket");
|
|
3965
|
+
const socket = this.ws;
|
|
3966
|
+
if (typeof socket.on === "function") {
|
|
3967
|
+
socket.on("open", () => {
|
|
3968
|
+
this.emit("open", {});
|
|
3969
|
+
resolve();
|
|
3970
|
+
});
|
|
3971
|
+
socket.on("message", (data) => {
|
|
3972
|
+
try {
|
|
3973
|
+
const message = JSON.parse(data.toString());
|
|
3974
|
+
this.handleMessage(message);
|
|
3975
|
+
} catch (error) {
|
|
3976
|
+
console.error("[Granular] Failed to parse message:", error);
|
|
3977
|
+
}
|
|
3978
|
+
});
|
|
3979
|
+
socket.on("error", (error) => {
|
|
3980
|
+
this.emit("error", error);
|
|
3981
|
+
if (socket.readyState !== READY_STATE_OPEN) {
|
|
3982
|
+
reject(error);
|
|
3983
|
+
}
|
|
3984
|
+
});
|
|
3985
|
+
socket.on("close", () => {
|
|
3986
|
+
this.emit("close", {});
|
|
3987
|
+
this.handleDisconnect();
|
|
3988
|
+
});
|
|
3989
|
+
} else {
|
|
3990
|
+
this.ws.onopen = () => {
|
|
3991
|
+
this.emit("open", {});
|
|
3992
|
+
resolve();
|
|
3993
|
+
};
|
|
3994
|
+
this.ws.onmessage = (event) => {
|
|
3995
|
+
try {
|
|
3996
|
+
const data = event.data;
|
|
3997
|
+
const message = JSON.parse(data.toString());
|
|
3998
|
+
this.handleMessage(message);
|
|
3999
|
+
} catch (error) {
|
|
4000
|
+
console.error("[Granular] Failed to parse message:", error);
|
|
4001
|
+
}
|
|
4002
|
+
};
|
|
4003
|
+
this.ws.onerror = (event) => {
|
|
4004
|
+
const error = new Error("WebSocket error");
|
|
4005
|
+
error.event = event;
|
|
4006
|
+
this.emit("error", error);
|
|
4007
|
+
if (this.ws?.readyState !== READY_STATE_OPEN) {
|
|
4008
|
+
reject(error);
|
|
4009
|
+
}
|
|
4010
|
+
};
|
|
4011
|
+
this.ws.onclose = () => {
|
|
4012
|
+
this.emit("close", {});
|
|
4013
|
+
this.handleDisconnect();
|
|
4014
|
+
};
|
|
4015
|
+
}
|
|
58
4016
|
} catch (error) {
|
|
59
4017
|
reject(error);
|
|
60
4018
|
}
|
|
@@ -74,8 +4032,8 @@ var WSClient = class {
|
|
|
74
4032
|
console.log("[Granular DEBUG] Received message:", JSON.stringify(message).slice(0, 500));
|
|
75
4033
|
if ("type" in message && message.type === "sync") {
|
|
76
4034
|
const syncMessage = message;
|
|
4035
|
+
let bytes;
|
|
77
4036
|
try {
|
|
78
|
-
let bytes;
|
|
79
4037
|
const payload = syncMessage.message || syncMessage.data;
|
|
80
4038
|
if (typeof payload === "string") {
|
|
81
4039
|
const binaryString = atob(payload);
|
|
@@ -91,6 +4049,7 @@ var WSClient = class {
|
|
|
91
4049
|
} else {
|
|
92
4050
|
return;
|
|
93
4051
|
}
|
|
4052
|
+
console.log("[Granular DEBUG] Applying sync bytes:", bytes.length);
|
|
94
4053
|
const [newDoc, newSyncState] = Automerge.receiveSyncMessage(
|
|
95
4054
|
this.doc,
|
|
96
4055
|
this.syncState,
|
|
@@ -98,8 +4057,49 @@ var WSClient = class {
|
|
|
98
4057
|
);
|
|
99
4058
|
this.doc = newDoc;
|
|
100
4059
|
this.syncState = newSyncState;
|
|
4060
|
+
const docAny = this.doc;
|
|
4061
|
+
if (docAny.catalog) {
|
|
4062
|
+
console.log("[Granular DEBUG] Doc catalog sync applied. Keys in catalog:", Object.keys(docAny.catalog || {}));
|
|
4063
|
+
console.log("[Granular DEBUG] RawToolCatalogs:", Object.keys(docAny.catalog.rawToolCatalogs || {}));
|
|
4064
|
+
} else {
|
|
4065
|
+
console.log("[Granular DEBUG] Doc synced but no catalog yet. Keys in doc:", Object.keys(docAny));
|
|
4066
|
+
}
|
|
4067
|
+
this.emit("sync", this.doc);
|
|
4068
|
+
} catch (e) {
|
|
4069
|
+
try {
|
|
4070
|
+
console.log("[Granular DEBUG] receiveSyncMessage failed, trying applyChanges...");
|
|
4071
|
+
const [newDoc] = Automerge.applyChanges(this.doc, [bytes]);
|
|
4072
|
+
this.doc = newDoc;
|
|
4073
|
+
this.emit("sync", this.doc);
|
|
4074
|
+
console.log("[Granular DEBUG] applyChanges succeeded. Doc:", JSON.stringify(Automerge.toJS(this.doc)));
|
|
4075
|
+
} catch (applyError) {
|
|
4076
|
+
console.warn("[Granular] Failed to apply sync message (both sync & applyChanges)", e, applyError);
|
|
4077
|
+
}
|
|
4078
|
+
}
|
|
4079
|
+
return;
|
|
4080
|
+
}
|
|
4081
|
+
if ("type" in message && message.type === "snapshot") {
|
|
4082
|
+
const snapshotMessage = message;
|
|
4083
|
+
try {
|
|
4084
|
+
const bytes = new Uint8Array(snapshotMessage.data);
|
|
4085
|
+
console.log("[Granular DEBUG] Loading snapshot bytes:", bytes.length);
|
|
4086
|
+
this.doc = Automerge.load(bytes);
|
|
4087
|
+
this.emit("sync", this.doc);
|
|
4088
|
+
console.log("[Granular DEBUG] Snapshot loaded. Doc:", JSON.stringify(Automerge.toJS(this.doc)));
|
|
4089
|
+
} catch (e) {
|
|
4090
|
+
console.warn("[Granular] Failed to load snapshot message", e);
|
|
4091
|
+
}
|
|
4092
|
+
return;
|
|
4093
|
+
}
|
|
4094
|
+
if ("type" in message && message.type === "change") {
|
|
4095
|
+
const changeMessage = message;
|
|
4096
|
+
try {
|
|
4097
|
+
const bytes = new Uint8Array(changeMessage.data);
|
|
4098
|
+
const [newDoc] = Automerge.applyChanges(this.doc, [bytes]);
|
|
4099
|
+
this.doc = newDoc;
|
|
101
4100
|
this.emit("sync", this.doc);
|
|
102
4101
|
} catch (e) {
|
|
4102
|
+
console.warn("[Granular] Failed to apply change message", e);
|
|
103
4103
|
}
|
|
104
4104
|
return;
|
|
105
4105
|
}
|
|
@@ -137,7 +4137,7 @@ var WSClient = class {
|
|
|
137
4137
|
* @throws {Error} If connection is closed or timeout occurs
|
|
138
4138
|
*/
|
|
139
4139
|
async call(method, params) {
|
|
140
|
-
if (!this.ws || this.ws.readyState !==
|
|
4140
|
+
if (!this.ws || this.ws.readyState !== READY_STATE_OPEN) {
|
|
141
4141
|
throw new Error("WebSocket not connected");
|
|
142
4142
|
}
|
|
143
4143
|
const id = `rpc-${this.nextRpcId++}`;
|
|
@@ -266,6 +4266,10 @@ var Session = class {
|
|
|
266
4266
|
/** Tracks which tools are instance methods (className set, not static) */
|
|
267
4267
|
instanceTools = /* @__PURE__ */ new Set();
|
|
268
4268
|
currentDomainRevision = null;
|
|
4269
|
+
/** Local effect registry: name → full ToolWithHandler */
|
|
4270
|
+
effects = /* @__PURE__ */ new Map();
|
|
4271
|
+
/** Last known tools for diffing */
|
|
4272
|
+
lastKnownTools = /* @__PURE__ */ new Map();
|
|
269
4273
|
constructor(client, clientId) {
|
|
270
4274
|
this.client = client;
|
|
271
4275
|
this.clientId = clientId || `client_${Date.now()}`;
|
|
@@ -381,6 +4385,85 @@ var Session = class {
|
|
|
381
4385
|
rejected: result.rejected
|
|
382
4386
|
};
|
|
383
4387
|
}
|
|
4388
|
+
/**
|
|
4389
|
+
* Publish a single effect (tool) to the sandbox.
|
|
4390
|
+
*
|
|
4391
|
+
* Adds the effect to the local registry and re-publishes the
|
|
4392
|
+
* full tool catalog to the server. If an effect with the same
|
|
4393
|
+
* name already exists, it is replaced.
|
|
4394
|
+
*
|
|
4395
|
+
* @param effect - The effect (tool) to publish
|
|
4396
|
+
* @returns PublishToolsResult with domainRevision
|
|
4397
|
+
*
|
|
4398
|
+
* @example
|
|
4399
|
+
* ```typescript
|
|
4400
|
+
* await env.publishEffect({
|
|
4401
|
+
* name: 'get_bio',
|
|
4402
|
+
* description: 'Get biography of an author',
|
|
4403
|
+
* className: 'author',
|
|
4404
|
+
* inputSchema: { type: 'object', properties: { detailed: { type: 'boolean' } } },
|
|
4405
|
+
* handler: async (id, params) => ({ bio: `Bio of ${id}` }),
|
|
4406
|
+
* });
|
|
4407
|
+
* ```
|
|
4408
|
+
*/
|
|
4409
|
+
async publishEffect(effect) {
|
|
4410
|
+
this.effects.set(effect.name, effect);
|
|
4411
|
+
return this._syncEffects();
|
|
4412
|
+
}
|
|
4413
|
+
/**
|
|
4414
|
+
* Publish multiple effects (tools) at once.
|
|
4415
|
+
*
|
|
4416
|
+
* Adds all effects to the local registry and re-publishes the
|
|
4417
|
+
* full tool catalog in a single RPC call.
|
|
4418
|
+
*
|
|
4419
|
+
* @param effects - Array of effects to publish
|
|
4420
|
+
* @returns PublishToolsResult with domainRevision
|
|
4421
|
+
*
|
|
4422
|
+
* @example
|
|
4423
|
+
* ```typescript
|
|
4424
|
+
* await env.publishEffects([
|
|
4425
|
+
* { name: 'get_bio', description: '...', inputSchema: {}, handler: async (id) => ({}) },
|
|
4426
|
+
* { name: 'search', description: '...', inputSchema: {}, handler: async (params) => ({}) },
|
|
4427
|
+
* ]);
|
|
4428
|
+
* ```
|
|
4429
|
+
*/
|
|
4430
|
+
async publishEffects(effects) {
|
|
4431
|
+
for (const effect of effects) {
|
|
4432
|
+
this.effects.set(effect.name, effect);
|
|
4433
|
+
}
|
|
4434
|
+
return this._syncEffects();
|
|
4435
|
+
}
|
|
4436
|
+
/**
|
|
4437
|
+
* Remove an effect by name and re-publish the remaining catalog.
|
|
4438
|
+
*
|
|
4439
|
+
* @param name - The name of the effect to remove
|
|
4440
|
+
* @returns PublishToolsResult with domainRevision
|
|
4441
|
+
*/
|
|
4442
|
+
async unpublishEffect(name) {
|
|
4443
|
+
this.effects.delete(name);
|
|
4444
|
+
this.toolHandlers.delete(name);
|
|
4445
|
+
this.instanceTools.delete(name);
|
|
4446
|
+
return this._syncEffects();
|
|
4447
|
+
}
|
|
4448
|
+
/**
|
|
4449
|
+
* Remove all effects and publish an empty catalog.
|
|
4450
|
+
*
|
|
4451
|
+
* @returns PublishToolsResult with domainRevision
|
|
4452
|
+
*/
|
|
4453
|
+
async unpublishAllEffects() {
|
|
4454
|
+
this.effects.clear();
|
|
4455
|
+
this.toolHandlers.clear();
|
|
4456
|
+
this.instanceTools.clear();
|
|
4457
|
+
return this._syncEffects();
|
|
4458
|
+
}
|
|
4459
|
+
/**
|
|
4460
|
+
* Internal: re-publish the full effect catalog to the server.
|
|
4461
|
+
* Called after any mutation to the effects Map.
|
|
4462
|
+
*/
|
|
4463
|
+
async _syncEffects() {
|
|
4464
|
+
const allEffects = Array.from(this.effects.values());
|
|
4465
|
+
return this.publishTools(allEffects);
|
|
4466
|
+
}
|
|
384
4467
|
/**
|
|
385
4468
|
* Submit a job to execute code in the sandbox.
|
|
386
4469
|
*
|
|
@@ -398,9 +4481,9 @@ var Session = class {
|
|
|
398
4481
|
* execute locally and return the result to the sandbox.
|
|
399
4482
|
*/
|
|
400
4483
|
async submitJob(code, domainRevision) {
|
|
401
|
-
const revision = domainRevision || this.currentDomainRevision;
|
|
4484
|
+
const revision = domainRevision || this.currentDomainRevision || this.client.doc?.domain?.active || void 0;
|
|
402
4485
|
if (!revision) {
|
|
403
|
-
throw new Error("No domain revision available. Call publishTools()
|
|
4486
|
+
throw new Error("No domain revision available. Call publishTools() or ensure schema is activated.");
|
|
404
4487
|
}
|
|
405
4488
|
const result = await this.client.call("job.submit", {
|
|
406
4489
|
domainRevision: revision,
|
|
@@ -431,6 +4514,72 @@ var Session = class {
|
|
|
431
4514
|
async answerPrompt(promptId, answer) {
|
|
432
4515
|
await this.client.call("prompt.answer", { promptId, value: answer });
|
|
433
4516
|
}
|
|
4517
|
+
/**
|
|
4518
|
+
* Get the current list of available tools.
|
|
4519
|
+
* Consolidates tools from all connected clients.
|
|
4520
|
+
*/
|
|
4521
|
+
getTools() {
|
|
4522
|
+
const doc = this.client.doc;
|
|
4523
|
+
const toolMap = /* @__PURE__ */ new Map();
|
|
4524
|
+
const domainPkg = doc.domain?.packages?.domain;
|
|
4525
|
+
if (domainPkg?.tools && Array.isArray(domainPkg.tools)) {
|
|
4526
|
+
for (const tool of domainPkg.tools) {
|
|
4527
|
+
if (!tool?.name) continue;
|
|
4528
|
+
toolMap.set(tool.name, {
|
|
4529
|
+
name: tool.name,
|
|
4530
|
+
description: tool.description,
|
|
4531
|
+
inputSchema: tool.inputSchema,
|
|
4532
|
+
outputSchema: tool.outputSchema,
|
|
4533
|
+
className: tool.className || void 0,
|
|
4534
|
+
static: tool.static || false,
|
|
4535
|
+
ready: false,
|
|
4536
|
+
publishedAt: void 0
|
|
4537
|
+
});
|
|
4538
|
+
}
|
|
4539
|
+
}
|
|
4540
|
+
const catalogs = doc.catalog?.rawToolCatalogs || {};
|
|
4541
|
+
for (const [clientId, catalog] of Object.entries(catalogs)) {
|
|
4542
|
+
const cat = catalog;
|
|
4543
|
+
if (!cat.tools) continue;
|
|
4544
|
+
for (const tool of cat.tools) {
|
|
4545
|
+
if (!tool?.name) continue;
|
|
4546
|
+
const existing = toolMap.get(tool.name);
|
|
4547
|
+
if (existing?.publishedAt && cat.publishedAt && existing.publishedAt > cat.publishedAt) continue;
|
|
4548
|
+
const isLocal = clientId === this.clientId;
|
|
4549
|
+
const ready = isLocal ? this.effects.has(tool.name) || this.toolHandlers.has(tool.name) || this.instanceTools.has(tool.name) : true;
|
|
4550
|
+
toolMap.set(tool.name, {
|
|
4551
|
+
name: tool.name,
|
|
4552
|
+
description: tool.description,
|
|
4553
|
+
inputSchema: tool.inputSchema,
|
|
4554
|
+
outputSchema: tool.outputSchema,
|
|
4555
|
+
className: tool.className || existing?.className,
|
|
4556
|
+
static: tool.static || existing?.static || false,
|
|
4557
|
+
clientId,
|
|
4558
|
+
ready,
|
|
4559
|
+
publishedAt: cat.publishedAt
|
|
4560
|
+
});
|
|
4561
|
+
}
|
|
4562
|
+
}
|
|
4563
|
+
return Array.from(toolMap.values());
|
|
4564
|
+
}
|
|
4565
|
+
/**
|
|
4566
|
+
* Subscribe to tool changes (added, removed, updated).
|
|
4567
|
+
* @param callback - Function called with change events
|
|
4568
|
+
* @returns Unsubscribe function
|
|
4569
|
+
*/
|
|
4570
|
+
onToolsChanged(callback) {
|
|
4571
|
+
const handler = (data) => callback(data);
|
|
4572
|
+
if (!this.eventListeners.has("tools:changed")) {
|
|
4573
|
+
this.eventListeners.set("tools:changed", []);
|
|
4574
|
+
}
|
|
4575
|
+
this.eventListeners.get("tools:changed").push(handler);
|
|
4576
|
+
return () => {
|
|
4577
|
+
const listeners = this.eventListeners.get("tools:changed");
|
|
4578
|
+
if (listeners) {
|
|
4579
|
+
this.eventListeners.set("tools:changed", listeners.filter((h) => h !== handler));
|
|
4580
|
+
}
|
|
4581
|
+
};
|
|
4582
|
+
}
|
|
434
4583
|
/**
|
|
435
4584
|
* Get the current domain state and available tools
|
|
436
4585
|
*/
|
|
@@ -438,32 +4587,34 @@ var Session = class {
|
|
|
438
4587
|
return this.client.call("domain.getSummary", {});
|
|
439
4588
|
}
|
|
440
4589
|
/**
|
|
441
|
-
*
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
*
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
4590
|
+
* Fetch a domain package part from the backend (no fallback).
|
|
4591
|
+
*/
|
|
4592
|
+
async fetchDomainPart(part) {
|
|
4593
|
+
const result = await this.client.call("domain.fetchPackagePart", {
|
|
4594
|
+
moduleSpecifier: "@sandbox/domain",
|
|
4595
|
+
part
|
|
4596
|
+
});
|
|
4597
|
+
return result?.content ?? "";
|
|
4598
|
+
}
|
|
4599
|
+
/**
|
|
4600
|
+
* Get TypeScript class declarations for the current domain (for LLM/code gen).
|
|
4601
|
+
*/
|
|
4602
|
+
async getDomainTypes() {
|
|
4603
|
+
return this.fetchDomainPart("types");
|
|
4604
|
+
}
|
|
4605
|
+
/**
|
|
4606
|
+
* Get Markdown documentation for the current domain (human-readable).
|
|
4607
|
+
*/
|
|
4608
|
+
async getDomainDocs() {
|
|
4609
|
+
return this.fetchDomainPart("docs");
|
|
4610
|
+
}
|
|
4611
|
+
/**
|
|
4612
|
+
* Get domain documentation for LLMs. Returns types (preferred) or fallback.
|
|
456
4613
|
*/
|
|
457
4614
|
async getDomainDocumentation() {
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
part: "types"
|
|
462
|
-
});
|
|
463
|
-
if (typesResult.content) {
|
|
464
|
-
return typesResult.content;
|
|
465
|
-
}
|
|
466
|
-
} catch {
|
|
4615
|
+
const types = await this.getDomainTypes();
|
|
4616
|
+
if (types && (types.includes("export declare class") || types.includes("export async function"))) {
|
|
4617
|
+
return types;
|
|
467
4618
|
}
|
|
468
4619
|
const summary = await this.getDomain();
|
|
469
4620
|
return this.generateFallbackDocs(summary);
|
|
@@ -639,7 +4790,10 @@ import { ${allImports} } from "./sandbox-tools";
|
|
|
639
4790
|
});
|
|
640
4791
|
}
|
|
641
4792
|
setupEventHandlers() {
|
|
642
|
-
this.client.on("sync", (doc) =>
|
|
4793
|
+
this.client.on("sync", (doc) => {
|
|
4794
|
+
this.emit("sync", doc);
|
|
4795
|
+
this.checkForToolChanges();
|
|
4796
|
+
});
|
|
643
4797
|
this.client.on("prompt", (prompt) => this.emit("prompt", prompt));
|
|
644
4798
|
this.client.on("disconnect", () => this.emit("disconnect", {}));
|
|
645
4799
|
this.client.on("job.status", (data) => {
|
|
@@ -658,6 +4812,33 @@ import { ${allImports} } from "./sandbox-tools";
|
|
|
658
4812
|
handlers.forEach((h) => h(data));
|
|
659
4813
|
}
|
|
660
4814
|
}
|
|
4815
|
+
/**
|
|
4816
|
+
* Check for changes in the tool catalog and emit 'tools:changed' if needed
|
|
4817
|
+
*/
|
|
4818
|
+
checkForToolChanges() {
|
|
4819
|
+
const currentTools = this.getTools();
|
|
4820
|
+
const currentMap = new Map(currentTools.map((t) => [t.name, t]));
|
|
4821
|
+
const added = [];
|
|
4822
|
+
const removed = [];
|
|
4823
|
+
for (const [name, tool] of currentMap) {
|
|
4824
|
+
if (!this.lastKnownTools.has(name)) {
|
|
4825
|
+
added.push(name);
|
|
4826
|
+
}
|
|
4827
|
+
}
|
|
4828
|
+
for (const name of this.lastKnownTools.keys()) {
|
|
4829
|
+
if (!currentMap.has(name)) {
|
|
4830
|
+
removed.push(name);
|
|
4831
|
+
}
|
|
4832
|
+
}
|
|
4833
|
+
if (added.length > 0 || removed.length > 0) {
|
|
4834
|
+
this.lastKnownTools = currentMap;
|
|
4835
|
+
this.emit("tools:changed", {
|
|
4836
|
+
tools: currentTools,
|
|
4837
|
+
added,
|
|
4838
|
+
removed
|
|
4839
|
+
});
|
|
4840
|
+
}
|
|
4841
|
+
}
|
|
661
4842
|
};
|
|
662
4843
|
var JobImplementation = class {
|
|
663
4844
|
id;
|
|
@@ -731,6 +4912,18 @@ var JobImplementation = class {
|
|
|
731
4912
|
this._rejectResult(jobData.error || new Error("Job failed"));
|
|
732
4913
|
}
|
|
733
4914
|
});
|
|
4915
|
+
this.client.on("tool.call.start", (data) => {
|
|
4916
|
+
const d = data;
|
|
4917
|
+
if (d.jobId === id) {
|
|
4918
|
+
this.emit("toolCallStart", { callId: d.callId, toolName: d.toolName, input: d.input, timestamp: d.timestamp });
|
|
4919
|
+
}
|
|
4920
|
+
});
|
|
4921
|
+
this.client.on("tool.call.end", (data) => {
|
|
4922
|
+
const d = data;
|
|
4923
|
+
if (d.jobId === id) {
|
|
4924
|
+
this.emit("toolCallEnd", { callId: d.callId, toolName: d.toolName, result: d.result, error: d.error, durationMs: d.durationMs, timestamp: d.timestamp });
|
|
4925
|
+
}
|
|
4926
|
+
});
|
|
734
4927
|
}
|
|
735
4928
|
get result() {
|
|
736
4929
|
return this._resultPromise;
|
|
@@ -793,6 +4986,43 @@ var Environment = class _Environment extends Session {
|
|
|
793
4986
|
get apiEndpoint() {
|
|
794
4987
|
return this._apiEndpoint;
|
|
795
4988
|
}
|
|
4989
|
+
// ==================== GRAPH CONTAINER READINESS ====================
|
|
4990
|
+
/** The last known graph container status, updated by checkReadiness() or on heartbeat */
|
|
4991
|
+
graphContainerStatus = null;
|
|
4992
|
+
/**
|
|
4993
|
+
* Check if the graph container is ready and warm.
|
|
4994
|
+
*
|
|
4995
|
+
* Sends a lightweight heartbeat RPC to the Session DO which internally
|
|
4996
|
+
* pings the FalkorDB container. The response includes `graphContainerStatus`,
|
|
4997
|
+
* which is stored locally and emitted as a `readiness` event.
|
|
4998
|
+
*
|
|
4999
|
+
* Use this method to proactively warm the graph container before any
|
|
5000
|
+
* GraphQL query that requires it, or to poll the container's state in
|
|
5001
|
+
* the background.
|
|
5002
|
+
*
|
|
5003
|
+
* @returns The current graph container status object
|
|
5004
|
+
*
|
|
5005
|
+
* @example
|
|
5006
|
+
* ```typescript
|
|
5007
|
+
* const status = await env.checkReadiness();
|
|
5008
|
+
* console.log(status.status); // 'hot' | 'warming' | 'unknown'
|
|
5009
|
+
*
|
|
5010
|
+
* // Or listen for live updates
|
|
5011
|
+
* env.on('readiness', (status) => {
|
|
5012
|
+
* console.log('Graph is now:', status.status);
|
|
5013
|
+
* });
|
|
5014
|
+
* ```
|
|
5015
|
+
*/
|
|
5016
|
+
async checkReadiness() {
|
|
5017
|
+
const result = await this.client.call("client.heartbeat", {});
|
|
5018
|
+
const containerStatus = result?.graphContainerStatus ?? {
|
|
5019
|
+
lastKeepAliveAt: Date.now(),
|
|
5020
|
+
status: "unknown"
|
|
5021
|
+
};
|
|
5022
|
+
this.graphContainerStatus = containerStatus;
|
|
5023
|
+
this.emit("readiness", containerStatus);
|
|
5024
|
+
return containerStatus;
|
|
5025
|
+
}
|
|
796
5026
|
// ==================== ID ↔ GRAPH PATH MAPPING ====================
|
|
797
5027
|
/**
|
|
798
5028
|
* Convert a class name + real-world ID into a unique graph path.
|
|
@@ -1445,18 +5675,69 @@ var Environment = class _Environment extends Session {
|
|
|
1445
5675
|
async publishTools(tools, revision = "1.0.0") {
|
|
1446
5676
|
return super.publishTools(tools, revision);
|
|
1447
5677
|
}
|
|
5678
|
+
/**
|
|
5679
|
+
* Publish a single effect (tool) incrementally.
|
|
5680
|
+
*
|
|
5681
|
+
* Adds the effect to the local registry and re-publishes the
|
|
5682
|
+
* full tool catalog to the server. If an effect with the same
|
|
5683
|
+
* name already exists, it is replaced.
|
|
5684
|
+
*
|
|
5685
|
+
* @example
|
|
5686
|
+
* ```typescript
|
|
5687
|
+
* await env.publishEffect({
|
|
5688
|
+
* name: 'get_bio',
|
|
5689
|
+
* description: 'Get biography',
|
|
5690
|
+
* inputSchema: { type: 'object', properties: { detailed: { type: 'boolean' } } },
|
|
5691
|
+
* handler: async (params) => ({ bio: 'Hello' }),
|
|
5692
|
+
* });
|
|
5693
|
+
* ```
|
|
5694
|
+
*/
|
|
5695
|
+
async publishEffect(effect) {
|
|
5696
|
+
return super.publishEffect(effect);
|
|
5697
|
+
}
|
|
5698
|
+
/**
|
|
5699
|
+
* Publish multiple effects (tools) at once.
|
|
5700
|
+
*
|
|
5701
|
+
* Adds all effects to the local registry and re-publishes the
|
|
5702
|
+
* full tool catalog in a single RPC call.
|
|
5703
|
+
*/
|
|
5704
|
+
async publishEffects(effects) {
|
|
5705
|
+
return super.publishEffects(effects);
|
|
5706
|
+
}
|
|
5707
|
+
/**
|
|
5708
|
+
* Remove an effect by name and re-publish the remaining catalog.
|
|
5709
|
+
*/
|
|
5710
|
+
async unpublishEffect(name) {
|
|
5711
|
+
return super.unpublishEffect(name);
|
|
5712
|
+
}
|
|
5713
|
+
/**
|
|
5714
|
+
* Remove all effects and publish an empty catalog.
|
|
5715
|
+
*/
|
|
5716
|
+
async unpublishAllEffects() {
|
|
5717
|
+
return super.unpublishAllEffects();
|
|
5718
|
+
}
|
|
1448
5719
|
};
|
|
1449
5720
|
var Granular = class {
|
|
1450
5721
|
apiKey;
|
|
1451
5722
|
apiUrl;
|
|
1452
5723
|
httpUrl;
|
|
5724
|
+
WebSocketCtor;
|
|
5725
|
+
/** Sandbox-level effect registry: sandboxId → (toolName → ToolWithHandler) */
|
|
5726
|
+
sandboxEffects = /* @__PURE__ */ new Map();
|
|
5727
|
+
/** Active environments tracker: sandboxId → Environment[] */
|
|
5728
|
+
activeEnvironments = /* @__PURE__ */ new Map();
|
|
1453
5729
|
/**
|
|
1454
5730
|
* Create a new Granular client
|
|
1455
5731
|
* @param options - Client configuration
|
|
1456
5732
|
*/
|
|
1457
5733
|
constructor(options) {
|
|
1458
|
-
|
|
5734
|
+
const auth = options.token ?? options.apiKey;
|
|
5735
|
+
if (!auth) {
|
|
5736
|
+
throw new Error("Granular client requires either apiKey or token. Set GRANULAR_API_KEY or GRANULAR_TOKEN, or pass one in options.");
|
|
5737
|
+
}
|
|
5738
|
+
this.apiKey = auth;
|
|
1459
5739
|
this.apiUrl = options.apiUrl || "wss://api.granular.dev/v2/ws";
|
|
5740
|
+
this.WebSocketCtor = options.WebSocketCtor;
|
|
1460
5741
|
this.httpUrl = this.apiUrl.replace("wss://", "https://").replace("/ws", "");
|
|
1461
5742
|
}
|
|
1462
5743
|
/**
|
|
@@ -1527,7 +5808,7 @@ var Granular = class {
|
|
|
1527
5808
|
* ```
|
|
1528
5809
|
*/
|
|
1529
5810
|
async connect(options) {
|
|
1530
|
-
const clientId = `client_${Date.now()}`;
|
|
5811
|
+
const clientId = options.clientId || `client_${Date.now()}`;
|
|
1531
5812
|
const sandbox = await this.findOrCreateSandbox(options.sandbox);
|
|
1532
5813
|
for (const profileName of options.user.permissions) {
|
|
1533
5814
|
const profileId = await this.ensurePermissionProfile(sandbox.sandboxId, profileName);
|
|
@@ -1540,14 +5821,104 @@ var Granular = class {
|
|
|
1540
5821
|
const client = new WSClient({
|
|
1541
5822
|
url: this.apiUrl,
|
|
1542
5823
|
sessionId: envData.environmentId,
|
|
1543
|
-
token: this.apiKey
|
|
5824
|
+
token: this.apiKey,
|
|
5825
|
+
WebSocketCtor: this.WebSocketCtor
|
|
1544
5826
|
});
|
|
1545
5827
|
await client.connect();
|
|
1546
5828
|
const graphqlEndpoint = `${this.httpUrl}/orchestrator/graphql`;
|
|
1547
5829
|
const environment = new Environment(client, envData, clientId, this.apiKey, graphqlEndpoint);
|
|
5830
|
+
if (!this.activeEnvironments.has(sandbox.sandboxId)) {
|
|
5831
|
+
this.activeEnvironments.set(sandbox.sandboxId, []);
|
|
5832
|
+
}
|
|
5833
|
+
this.activeEnvironments.get(sandbox.sandboxId).push(environment);
|
|
5834
|
+
environment.on("disconnect", () => {
|
|
5835
|
+
const list = this.activeEnvironments.get(sandbox.sandboxId);
|
|
5836
|
+
if (list) {
|
|
5837
|
+
this.activeEnvironments.set(sandbox.sandboxId, list.filter((e) => e !== environment));
|
|
5838
|
+
}
|
|
5839
|
+
});
|
|
1548
5840
|
await environment.hello();
|
|
5841
|
+
const effects = this.sandboxEffects.get(sandbox.sandboxId);
|
|
5842
|
+
if (effects && effects.size > 0) {
|
|
5843
|
+
const effectsList = Array.from(effects.values());
|
|
5844
|
+
console.log(`[Granular] Auto-publishing ${effectsList.length} effects for sandbox ${sandbox.sandboxId}`);
|
|
5845
|
+
await environment.publishEffects(effectsList);
|
|
5846
|
+
}
|
|
1549
5847
|
return environment;
|
|
1550
5848
|
}
|
|
5849
|
+
// ── Sandbox-Level Effects ──
|
|
5850
|
+
/**
|
|
5851
|
+
* Register an effect (tool) for a specific sandbox.
|
|
5852
|
+
*
|
|
5853
|
+
* The effect will be automatically published to:
|
|
5854
|
+
* 1. Any currently active environments for this sandbox
|
|
5855
|
+
* 2. Any new environments created/connected for this sandbox
|
|
5856
|
+
*
|
|
5857
|
+
* @param sandboxNameOrId - The name or ID of the sandbox
|
|
5858
|
+
* @param effect - The tool definition and handler
|
|
5859
|
+
*/
|
|
5860
|
+
async registerEffect(sandboxNameOrId, effect) {
|
|
5861
|
+
const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
|
|
5862
|
+
const sandboxId = sandbox.sandboxId;
|
|
5863
|
+
if (!this.sandboxEffects.has(sandboxId)) {
|
|
5864
|
+
this.sandboxEffects.set(sandboxId, /* @__PURE__ */ new Map());
|
|
5865
|
+
}
|
|
5866
|
+
this.sandboxEffects.get(sandboxId).set(effect.name, effect);
|
|
5867
|
+
const activeEnvs = this.activeEnvironments.get(sandboxId) || [];
|
|
5868
|
+
for (const env of activeEnvs) {
|
|
5869
|
+
await env.publishEffect(effect);
|
|
5870
|
+
}
|
|
5871
|
+
}
|
|
5872
|
+
/**
|
|
5873
|
+
* Register multiple effects (tools) for a specific sandbox.
|
|
5874
|
+
*
|
|
5875
|
+
* batch version of `registerEffect`.
|
|
5876
|
+
*/
|
|
5877
|
+
async registerEffects(sandboxNameOrId, effects) {
|
|
5878
|
+
const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
|
|
5879
|
+
const sandboxId = sandbox.sandboxId;
|
|
5880
|
+
if (!this.sandboxEffects.has(sandboxId)) {
|
|
5881
|
+
this.sandboxEffects.set(sandboxId, /* @__PURE__ */ new Map());
|
|
5882
|
+
}
|
|
5883
|
+
const map = this.sandboxEffects.get(sandboxId);
|
|
5884
|
+
for (const effect of effects) {
|
|
5885
|
+
map.set(effect.name, effect);
|
|
5886
|
+
}
|
|
5887
|
+
const activeEnvs = this.activeEnvironments.get(sandboxId) || [];
|
|
5888
|
+
for (const env of activeEnvs) {
|
|
5889
|
+
await env.publishEffects(effects);
|
|
5890
|
+
}
|
|
5891
|
+
}
|
|
5892
|
+
/**
|
|
5893
|
+
* Unregister an effect from a sandbox.
|
|
5894
|
+
*
|
|
5895
|
+
* Removes it from the local registry and unpublishes it from
|
|
5896
|
+
* all active environments.
|
|
5897
|
+
*/
|
|
5898
|
+
async unregisterEffect(sandboxNameOrId, name) {
|
|
5899
|
+
const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
|
|
5900
|
+
const sandboxId = sandbox.sandboxId;
|
|
5901
|
+
const map = this.sandboxEffects.get(sandboxId);
|
|
5902
|
+
if (map) {
|
|
5903
|
+
map.delete(name);
|
|
5904
|
+
}
|
|
5905
|
+
const activeEnvs = this.activeEnvironments.get(sandboxId) || [];
|
|
5906
|
+
for (const env of activeEnvs) {
|
|
5907
|
+
await env.unpublishEffect(name);
|
|
5908
|
+
}
|
|
5909
|
+
}
|
|
5910
|
+
/**
|
|
5911
|
+
* Unregister all effects for a sandbox.
|
|
5912
|
+
*/
|
|
5913
|
+
async unregisterAllEffects(sandboxNameOrId) {
|
|
5914
|
+
const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
|
|
5915
|
+
const sandboxId = sandbox.sandboxId;
|
|
5916
|
+
this.sandboxEffects.delete(sandboxId);
|
|
5917
|
+
const activeEnvs = this.activeEnvironments.get(sandboxId) || [];
|
|
5918
|
+
for (const env of activeEnvs) {
|
|
5919
|
+
await env.unpublishAllEffects();
|
|
5920
|
+
}
|
|
5921
|
+
}
|
|
1551
5922
|
/**
|
|
1552
5923
|
* Find a sandbox by name or create it if it doesn't exist
|
|
1553
5924
|
*/
|