@elizaos/plugin-minecraft 2.0.0-alpha.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/README.md +8 -0
- package/dist/actions/attack.d.ts +3 -0
- package/dist/actions/attack.d.ts.map +1 -0
- package/dist/actions/chat.d.ts +3 -0
- package/dist/actions/chat.d.ts.map +1 -0
- package/dist/actions/connect.d.ts +3 -0
- package/dist/actions/connect.d.ts.map +1 -0
- package/dist/actions/control.d.ts +3 -0
- package/dist/actions/control.d.ts.map +1 -0
- package/dist/actions/dig.d.ts +3 -0
- package/dist/actions/dig.d.ts.map +1 -0
- package/dist/actions/disconnect.d.ts +3 -0
- package/dist/actions/disconnect.d.ts.map +1 -0
- package/dist/actions/goto.d.ts +3 -0
- package/dist/actions/goto.d.ts.map +1 -0
- package/dist/actions/index.d.ts +13 -0
- package/dist/actions/index.d.ts.map +1 -0
- package/dist/actions/look.d.ts +3 -0
- package/dist/actions/look.d.ts.map +1 -0
- package/dist/actions/place.d.ts +3 -0
- package/dist/actions/place.d.ts.map +1 -0
- package/dist/actions/scan.d.ts +3 -0
- package/dist/actions/scan.d.ts.map +1 -0
- package/dist/actions/stop.d.ts +3 -0
- package/dist/actions/stop.d.ts.map +1 -0
- package/dist/actions/utils.d.ts +7 -0
- package/dist/actions/utils.d.ts.map +1 -0
- package/dist/actions/waypoints.d.ts +6 -0
- package/dist/actions/waypoints.d.ts.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4664 -0
- package/dist/index.js.map +51 -0
- package/dist/protocol.d.ts +21 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/providers/index.d.ts +4 -0
- package/dist/providers/index.d.ts.map +1 -0
- package/dist/providers/vision.d.ts +3 -0
- package/dist/providers/vision.d.ts.map +1 -0
- package/dist/providers/waypoints.d.ts +3 -0
- package/dist/providers/waypoints.d.ts.map +1 -0
- package/dist/providers/world-state.d.ts +3 -0
- package/dist/providers/world-state.d.ts.map +1 -0
- package/dist/services/minecraft-service.d.ts +32 -0
- package/dist/services/minecraft-service.d.ts.map +1 -0
- package/dist/services/process-manager.d.ts +13 -0
- package/dist/services/process-manager.d.ts.map +1 -0
- package/dist/services/waypoints-service.d.ts +29 -0
- package/dist/services/waypoints-service.d.ts.map +1 -0
- package/dist/services/websocket-client.d.ts +13 -0
- package/dist/services/websocket-client.d.ts.map +1 -0
- package/dist/types.d.ts +48 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +61 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,4664 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
8
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
9
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
10
|
+
for (let key of __getOwnPropNames(mod))
|
|
11
|
+
if (!__hasOwnProp.call(to, key))
|
|
12
|
+
__defProp(to, key, {
|
|
13
|
+
get: () => mod[key],
|
|
14
|
+
enumerable: true
|
|
15
|
+
});
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
19
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
20
|
+
|
|
21
|
+
// ../../../node_modules/ws/lib/constants.js
|
|
22
|
+
var require_constants = __commonJS((exports, module) => {
|
|
23
|
+
var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
|
|
24
|
+
var hasBlob = typeof Blob !== "undefined";
|
|
25
|
+
if (hasBlob)
|
|
26
|
+
BINARY_TYPES.push("blob");
|
|
27
|
+
module.exports = {
|
|
28
|
+
BINARY_TYPES,
|
|
29
|
+
CLOSE_TIMEOUT: 30000,
|
|
30
|
+
EMPTY_BUFFER: Buffer.alloc(0),
|
|
31
|
+
GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
|
|
32
|
+
hasBlob,
|
|
33
|
+
kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
|
|
34
|
+
kListener: Symbol("kListener"),
|
|
35
|
+
kStatusCode: Symbol("status-code"),
|
|
36
|
+
kWebSocket: Symbol("websocket"),
|
|
37
|
+
NOOP: () => {}
|
|
38
|
+
};
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// ../../../node_modules/node-gyp-build/node-gyp-build.js
|
|
42
|
+
var require_node_gyp_build = __commonJS((exports, module) => {
|
|
43
|
+
var fs = __require("fs");
|
|
44
|
+
var path = __require("path");
|
|
45
|
+
var os = __require("os");
|
|
46
|
+
var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
|
|
47
|
+
var vars = process.config && process.config.variables || {};
|
|
48
|
+
var prebuildsOnly = !!process.env.PREBUILDS_ONLY;
|
|
49
|
+
var abi = process.versions.modules;
|
|
50
|
+
var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node";
|
|
51
|
+
var arch = process.env.npm_config_arch || os.arch();
|
|
52
|
+
var platform = process.env.npm_config_platform || os.platform();
|
|
53
|
+
var libc = process.env.LIBC || (isAlpine(platform) ? "musl" : "glibc");
|
|
54
|
+
var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || "";
|
|
55
|
+
var uv = (process.versions.uv || "").split(".")[0];
|
|
56
|
+
module.exports = load;
|
|
57
|
+
function load(dir) {
|
|
58
|
+
return runtimeRequire(load.resolve(dir));
|
|
59
|
+
}
|
|
60
|
+
load.resolve = load.path = function(dir) {
|
|
61
|
+
dir = path.resolve(dir || ".");
|
|
62
|
+
try {
|
|
63
|
+
var name = runtimeRequire(path.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
|
|
64
|
+
if (process.env[name + "_PREBUILD"])
|
|
65
|
+
dir = process.env[name + "_PREBUILD"];
|
|
66
|
+
} catch (err) {}
|
|
67
|
+
if (!prebuildsOnly) {
|
|
68
|
+
var release = getFirst(path.join(dir, "build/Release"), matchBuild);
|
|
69
|
+
if (release)
|
|
70
|
+
return release;
|
|
71
|
+
var debug = getFirst(path.join(dir, "build/Debug"), matchBuild);
|
|
72
|
+
if (debug)
|
|
73
|
+
return debug;
|
|
74
|
+
}
|
|
75
|
+
var prebuild = resolve(dir);
|
|
76
|
+
if (prebuild)
|
|
77
|
+
return prebuild;
|
|
78
|
+
var nearby = resolve(path.dirname(process.execPath));
|
|
79
|
+
if (nearby)
|
|
80
|
+
return nearby;
|
|
81
|
+
var target = [
|
|
82
|
+
"platform=" + platform,
|
|
83
|
+
"arch=" + arch,
|
|
84
|
+
"runtime=" + runtime,
|
|
85
|
+
"abi=" + abi,
|
|
86
|
+
"uv=" + uv,
|
|
87
|
+
armv ? "armv=" + armv : "",
|
|
88
|
+
"libc=" + libc,
|
|
89
|
+
"node=" + process.versions.node,
|
|
90
|
+
process.versions.electron ? "electron=" + process.versions.electron : "",
|
|
91
|
+
typeof __webpack_require__ === "function" ? "webpack=true" : ""
|
|
92
|
+
].filter(Boolean).join(" ");
|
|
93
|
+
throw new Error("No native build was found for " + target + `
|
|
94
|
+
loaded from: ` + dir + `
|
|
95
|
+
`);
|
|
96
|
+
function resolve(dir2) {
|
|
97
|
+
var tuples = readdirSync(path.join(dir2, "prebuilds")).map(parseTuple);
|
|
98
|
+
var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0];
|
|
99
|
+
if (!tuple)
|
|
100
|
+
return;
|
|
101
|
+
var prebuilds = path.join(dir2, "prebuilds", tuple.name);
|
|
102
|
+
var parsed = readdirSync(prebuilds).map(parseTags);
|
|
103
|
+
var candidates = parsed.filter(matchTags(runtime, abi));
|
|
104
|
+
var winner = candidates.sort(compareTags(runtime))[0];
|
|
105
|
+
if (winner)
|
|
106
|
+
return path.join(prebuilds, winner.file);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
function readdirSync(dir) {
|
|
110
|
+
try {
|
|
111
|
+
return fs.readdirSync(dir);
|
|
112
|
+
} catch (err) {
|
|
113
|
+
return [];
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function getFirst(dir, filter) {
|
|
117
|
+
var files = readdirSync(dir).filter(filter);
|
|
118
|
+
return files[0] && path.join(dir, files[0]);
|
|
119
|
+
}
|
|
120
|
+
function matchBuild(name) {
|
|
121
|
+
return /\.node$/.test(name);
|
|
122
|
+
}
|
|
123
|
+
function parseTuple(name) {
|
|
124
|
+
var arr = name.split("-");
|
|
125
|
+
if (arr.length !== 2)
|
|
126
|
+
return;
|
|
127
|
+
var platform2 = arr[0];
|
|
128
|
+
var architectures = arr[1].split("+");
|
|
129
|
+
if (!platform2)
|
|
130
|
+
return;
|
|
131
|
+
if (!architectures.length)
|
|
132
|
+
return;
|
|
133
|
+
if (!architectures.every(Boolean))
|
|
134
|
+
return;
|
|
135
|
+
return { name, platform: platform2, architectures };
|
|
136
|
+
}
|
|
137
|
+
function matchTuple(platform2, arch2) {
|
|
138
|
+
return function(tuple) {
|
|
139
|
+
if (tuple == null)
|
|
140
|
+
return false;
|
|
141
|
+
if (tuple.platform !== platform2)
|
|
142
|
+
return false;
|
|
143
|
+
return tuple.architectures.includes(arch2);
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
function compareTuples(a, b) {
|
|
147
|
+
return a.architectures.length - b.architectures.length;
|
|
148
|
+
}
|
|
149
|
+
function parseTags(file) {
|
|
150
|
+
var arr = file.split(".");
|
|
151
|
+
var extension = arr.pop();
|
|
152
|
+
var tags = { file, specificity: 0 };
|
|
153
|
+
if (extension !== "node")
|
|
154
|
+
return;
|
|
155
|
+
for (var i = 0;i < arr.length; i++) {
|
|
156
|
+
var tag = arr[i];
|
|
157
|
+
if (tag === "node" || tag === "electron" || tag === "node-webkit") {
|
|
158
|
+
tags.runtime = tag;
|
|
159
|
+
} else if (tag === "napi") {
|
|
160
|
+
tags.napi = true;
|
|
161
|
+
} else if (tag.slice(0, 3) === "abi") {
|
|
162
|
+
tags.abi = tag.slice(3);
|
|
163
|
+
} else if (tag.slice(0, 2) === "uv") {
|
|
164
|
+
tags.uv = tag.slice(2);
|
|
165
|
+
} else if (tag.slice(0, 4) === "armv") {
|
|
166
|
+
tags.armv = tag.slice(4);
|
|
167
|
+
} else if (tag === "glibc" || tag === "musl") {
|
|
168
|
+
tags.libc = tag;
|
|
169
|
+
} else {
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
tags.specificity++;
|
|
173
|
+
}
|
|
174
|
+
return tags;
|
|
175
|
+
}
|
|
176
|
+
function matchTags(runtime2, abi2) {
|
|
177
|
+
return function(tags) {
|
|
178
|
+
if (tags == null)
|
|
179
|
+
return false;
|
|
180
|
+
if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags))
|
|
181
|
+
return false;
|
|
182
|
+
if (tags.abi && tags.abi !== abi2 && !tags.napi)
|
|
183
|
+
return false;
|
|
184
|
+
if (tags.uv && tags.uv !== uv)
|
|
185
|
+
return false;
|
|
186
|
+
if (tags.armv && tags.armv !== armv)
|
|
187
|
+
return false;
|
|
188
|
+
if (tags.libc && tags.libc !== libc)
|
|
189
|
+
return false;
|
|
190
|
+
return true;
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function runtimeAgnostic(tags) {
|
|
194
|
+
return tags.runtime === "node" && tags.napi;
|
|
195
|
+
}
|
|
196
|
+
function compareTags(runtime2) {
|
|
197
|
+
return function(a, b) {
|
|
198
|
+
if (a.runtime !== b.runtime) {
|
|
199
|
+
return a.runtime === runtime2 ? -1 : 1;
|
|
200
|
+
} else if (a.abi !== b.abi) {
|
|
201
|
+
return a.abi ? -1 : 1;
|
|
202
|
+
} else if (a.specificity !== b.specificity) {
|
|
203
|
+
return a.specificity > b.specificity ? -1 : 1;
|
|
204
|
+
} else {
|
|
205
|
+
return 0;
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
function isNwjs() {
|
|
210
|
+
return !!(process.versions && process.versions.nw);
|
|
211
|
+
}
|
|
212
|
+
function isElectron() {
|
|
213
|
+
if (process.versions && process.versions.electron)
|
|
214
|
+
return true;
|
|
215
|
+
if (process.env.ELECTRON_RUN_AS_NODE)
|
|
216
|
+
return true;
|
|
217
|
+
return typeof window !== "undefined" && window.process && window.process.type === "renderer";
|
|
218
|
+
}
|
|
219
|
+
function isAlpine(platform2) {
|
|
220
|
+
return platform2 === "linux" && fs.existsSync("/etc/alpine-release");
|
|
221
|
+
}
|
|
222
|
+
load.parseTags = parseTags;
|
|
223
|
+
load.matchTags = matchTags;
|
|
224
|
+
load.compareTags = compareTags;
|
|
225
|
+
load.parseTuple = parseTuple;
|
|
226
|
+
load.matchTuple = matchTuple;
|
|
227
|
+
load.compareTuples = compareTuples;
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
// ../../../node_modules/node-gyp-build/index.js
|
|
231
|
+
var require_node_gyp_build2 = __commonJS((exports, module) => {
|
|
232
|
+
var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
|
|
233
|
+
if (typeof runtimeRequire.addon === "function") {
|
|
234
|
+
module.exports = runtimeRequire.addon.bind(runtimeRequire);
|
|
235
|
+
} else {
|
|
236
|
+
module.exports = require_node_gyp_build();
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
// ../../../node_modules/bufferutil/fallback.js
|
|
241
|
+
var require_fallback = __commonJS((exports, module) => {
|
|
242
|
+
var mask = (source, mask2, output, offset, length) => {
|
|
243
|
+
for (var i = 0;i < length; i++) {
|
|
244
|
+
output[offset + i] = source[i] ^ mask2[i & 3];
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
var unmask = (buffer, mask2) => {
|
|
248
|
+
const length = buffer.length;
|
|
249
|
+
for (var i = 0;i < length; i++) {
|
|
250
|
+
buffer[i] ^= mask2[i & 3];
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
module.exports = { mask, unmask };
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
// ../../../node_modules/bufferutil/index.js
|
|
257
|
+
var require_bufferutil = __commonJS((exports, module) => {
|
|
258
|
+
var __dirname = "/Users/shawwalters/eliza-ok/node_modules/bufferutil";
|
|
259
|
+
try {
|
|
260
|
+
module.exports = require_node_gyp_build2()(__dirname);
|
|
261
|
+
} catch (e) {
|
|
262
|
+
module.exports = require_fallback();
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
// ../../../node_modules/ws/lib/buffer-util.js
|
|
267
|
+
var require_buffer_util = __commonJS((exports, module) => {
|
|
268
|
+
var { EMPTY_BUFFER } = require_constants();
|
|
269
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
270
|
+
function concat(list, totalLength) {
|
|
271
|
+
if (list.length === 0)
|
|
272
|
+
return EMPTY_BUFFER;
|
|
273
|
+
if (list.length === 1)
|
|
274
|
+
return list[0];
|
|
275
|
+
const target = Buffer.allocUnsafe(totalLength);
|
|
276
|
+
let offset = 0;
|
|
277
|
+
for (let i = 0;i < list.length; i++) {
|
|
278
|
+
const buf = list[i];
|
|
279
|
+
target.set(buf, offset);
|
|
280
|
+
offset += buf.length;
|
|
281
|
+
}
|
|
282
|
+
if (offset < totalLength) {
|
|
283
|
+
return new FastBuffer(target.buffer, target.byteOffset, offset);
|
|
284
|
+
}
|
|
285
|
+
return target;
|
|
286
|
+
}
|
|
287
|
+
function _mask(source, mask, output, offset, length) {
|
|
288
|
+
for (let i = 0;i < length; i++) {
|
|
289
|
+
output[offset + i] = source[i] ^ mask[i & 3];
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
function _unmask(buffer, mask) {
|
|
293
|
+
for (let i = 0;i < buffer.length; i++) {
|
|
294
|
+
buffer[i] ^= mask[i & 3];
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
function toArrayBuffer(buf) {
|
|
298
|
+
if (buf.length === buf.buffer.byteLength) {
|
|
299
|
+
return buf.buffer;
|
|
300
|
+
}
|
|
301
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
|
|
302
|
+
}
|
|
303
|
+
function toBuffer(data) {
|
|
304
|
+
toBuffer.readOnly = true;
|
|
305
|
+
if (Buffer.isBuffer(data))
|
|
306
|
+
return data;
|
|
307
|
+
let buf;
|
|
308
|
+
if (data instanceof ArrayBuffer) {
|
|
309
|
+
buf = new FastBuffer(data);
|
|
310
|
+
} else if (ArrayBuffer.isView(data)) {
|
|
311
|
+
buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
|
|
312
|
+
} else {
|
|
313
|
+
buf = Buffer.from(data);
|
|
314
|
+
toBuffer.readOnly = false;
|
|
315
|
+
}
|
|
316
|
+
return buf;
|
|
317
|
+
}
|
|
318
|
+
module.exports = {
|
|
319
|
+
concat,
|
|
320
|
+
mask: _mask,
|
|
321
|
+
toArrayBuffer,
|
|
322
|
+
toBuffer,
|
|
323
|
+
unmask: _unmask
|
|
324
|
+
};
|
|
325
|
+
if (!process.env.WS_NO_BUFFER_UTIL) {
|
|
326
|
+
try {
|
|
327
|
+
const bufferUtil = require_bufferutil();
|
|
328
|
+
module.exports.mask = function(source, mask, output, offset, length) {
|
|
329
|
+
if (length < 48)
|
|
330
|
+
_mask(source, mask, output, offset, length);
|
|
331
|
+
else
|
|
332
|
+
bufferUtil.mask(source, mask, output, offset, length);
|
|
333
|
+
};
|
|
334
|
+
module.exports.unmask = function(buffer, mask) {
|
|
335
|
+
if (buffer.length < 32)
|
|
336
|
+
_unmask(buffer, mask);
|
|
337
|
+
else
|
|
338
|
+
bufferUtil.unmask(buffer, mask);
|
|
339
|
+
};
|
|
340
|
+
} catch (e) {}
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
// ../../../node_modules/ws/lib/limiter.js
|
|
345
|
+
var require_limiter = __commonJS((exports, module) => {
|
|
346
|
+
var kDone = Symbol("kDone");
|
|
347
|
+
var kRun = Symbol("kRun");
|
|
348
|
+
|
|
349
|
+
class Limiter {
|
|
350
|
+
constructor(concurrency) {
|
|
351
|
+
this[kDone] = () => {
|
|
352
|
+
this.pending--;
|
|
353
|
+
this[kRun]();
|
|
354
|
+
};
|
|
355
|
+
this.concurrency = concurrency || Infinity;
|
|
356
|
+
this.jobs = [];
|
|
357
|
+
this.pending = 0;
|
|
358
|
+
}
|
|
359
|
+
add(job) {
|
|
360
|
+
this.jobs.push(job);
|
|
361
|
+
this[kRun]();
|
|
362
|
+
}
|
|
363
|
+
[kRun]() {
|
|
364
|
+
if (this.pending === this.concurrency)
|
|
365
|
+
return;
|
|
366
|
+
if (this.jobs.length) {
|
|
367
|
+
const job = this.jobs.shift();
|
|
368
|
+
this.pending++;
|
|
369
|
+
job(this[kDone]);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
module.exports = Limiter;
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
// ../../../node_modules/ws/lib/permessage-deflate.js
|
|
377
|
+
var require_permessage_deflate = __commonJS((exports, module) => {
|
|
378
|
+
var zlib = __require("zlib");
|
|
379
|
+
var bufferUtil = require_buffer_util();
|
|
380
|
+
var Limiter = require_limiter();
|
|
381
|
+
var { kStatusCode } = require_constants();
|
|
382
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
383
|
+
var TRAILER = Buffer.from([0, 0, 255, 255]);
|
|
384
|
+
var kPerMessageDeflate = Symbol("permessage-deflate");
|
|
385
|
+
var kTotalLength = Symbol("total-length");
|
|
386
|
+
var kCallback = Symbol("callback");
|
|
387
|
+
var kBuffers = Symbol("buffers");
|
|
388
|
+
var kError = Symbol("error");
|
|
389
|
+
var zlibLimiter;
|
|
390
|
+
|
|
391
|
+
class PerMessageDeflate {
|
|
392
|
+
constructor(options, isServer, maxPayload) {
|
|
393
|
+
this._maxPayload = maxPayload | 0;
|
|
394
|
+
this._options = options || {};
|
|
395
|
+
this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024;
|
|
396
|
+
this._isServer = !!isServer;
|
|
397
|
+
this._deflate = null;
|
|
398
|
+
this._inflate = null;
|
|
399
|
+
this.params = null;
|
|
400
|
+
if (!zlibLimiter) {
|
|
401
|
+
const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10;
|
|
402
|
+
zlibLimiter = new Limiter(concurrency);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
static get extensionName() {
|
|
406
|
+
return "permessage-deflate";
|
|
407
|
+
}
|
|
408
|
+
offer() {
|
|
409
|
+
const params = {};
|
|
410
|
+
if (this._options.serverNoContextTakeover) {
|
|
411
|
+
params.server_no_context_takeover = true;
|
|
412
|
+
}
|
|
413
|
+
if (this._options.clientNoContextTakeover) {
|
|
414
|
+
params.client_no_context_takeover = true;
|
|
415
|
+
}
|
|
416
|
+
if (this._options.serverMaxWindowBits) {
|
|
417
|
+
params.server_max_window_bits = this._options.serverMaxWindowBits;
|
|
418
|
+
}
|
|
419
|
+
if (this._options.clientMaxWindowBits) {
|
|
420
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
421
|
+
} else if (this._options.clientMaxWindowBits == null) {
|
|
422
|
+
params.client_max_window_bits = true;
|
|
423
|
+
}
|
|
424
|
+
return params;
|
|
425
|
+
}
|
|
426
|
+
accept(configurations) {
|
|
427
|
+
configurations = this.normalizeParams(configurations);
|
|
428
|
+
this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
|
|
429
|
+
return this.params;
|
|
430
|
+
}
|
|
431
|
+
cleanup() {
|
|
432
|
+
if (this._inflate) {
|
|
433
|
+
this._inflate.close();
|
|
434
|
+
this._inflate = null;
|
|
435
|
+
}
|
|
436
|
+
if (this._deflate) {
|
|
437
|
+
const callback = this._deflate[kCallback];
|
|
438
|
+
this._deflate.close();
|
|
439
|
+
this._deflate = null;
|
|
440
|
+
if (callback) {
|
|
441
|
+
callback(new Error("The deflate stream was closed while data was being processed"));
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
acceptAsServer(offers) {
|
|
446
|
+
const opts = this._options;
|
|
447
|
+
const accepted = offers.find((params) => {
|
|
448
|
+
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) {
|
|
449
|
+
return false;
|
|
450
|
+
}
|
|
451
|
+
return true;
|
|
452
|
+
});
|
|
453
|
+
if (!accepted) {
|
|
454
|
+
throw new Error("None of the extension offers can be accepted");
|
|
455
|
+
}
|
|
456
|
+
if (opts.serverNoContextTakeover) {
|
|
457
|
+
accepted.server_no_context_takeover = true;
|
|
458
|
+
}
|
|
459
|
+
if (opts.clientNoContextTakeover) {
|
|
460
|
+
accepted.client_no_context_takeover = true;
|
|
461
|
+
}
|
|
462
|
+
if (typeof opts.serverMaxWindowBits === "number") {
|
|
463
|
+
accepted.server_max_window_bits = opts.serverMaxWindowBits;
|
|
464
|
+
}
|
|
465
|
+
if (typeof opts.clientMaxWindowBits === "number") {
|
|
466
|
+
accepted.client_max_window_bits = opts.clientMaxWindowBits;
|
|
467
|
+
} else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
|
|
468
|
+
delete accepted.client_max_window_bits;
|
|
469
|
+
}
|
|
470
|
+
return accepted;
|
|
471
|
+
}
|
|
472
|
+
acceptAsClient(response) {
|
|
473
|
+
const params = response[0];
|
|
474
|
+
if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
|
|
475
|
+
throw new Error('Unexpected parameter "client_no_context_takeover"');
|
|
476
|
+
}
|
|
477
|
+
if (!params.client_max_window_bits) {
|
|
478
|
+
if (typeof this._options.clientMaxWindowBits === "number") {
|
|
479
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
480
|
+
}
|
|
481
|
+
} else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
|
|
482
|
+
throw new Error('Unexpected or invalid parameter "client_max_window_bits"');
|
|
483
|
+
}
|
|
484
|
+
return params;
|
|
485
|
+
}
|
|
486
|
+
normalizeParams(configurations) {
|
|
487
|
+
configurations.forEach((params) => {
|
|
488
|
+
Object.keys(params).forEach((key) => {
|
|
489
|
+
let value = params[key];
|
|
490
|
+
if (value.length > 1) {
|
|
491
|
+
throw new Error(`Parameter "${key}" must have only a single value`);
|
|
492
|
+
}
|
|
493
|
+
value = value[0];
|
|
494
|
+
if (key === "client_max_window_bits") {
|
|
495
|
+
if (value !== true) {
|
|
496
|
+
const num = +value;
|
|
497
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
498
|
+
throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
|
|
499
|
+
}
|
|
500
|
+
value = num;
|
|
501
|
+
} else if (!this._isServer) {
|
|
502
|
+
throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
|
|
503
|
+
}
|
|
504
|
+
} else if (key === "server_max_window_bits") {
|
|
505
|
+
const num = +value;
|
|
506
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
507
|
+
throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
|
|
508
|
+
}
|
|
509
|
+
value = num;
|
|
510
|
+
} else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
|
|
511
|
+
if (value !== true) {
|
|
512
|
+
throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
|
|
513
|
+
}
|
|
514
|
+
} else {
|
|
515
|
+
throw new Error(`Unknown parameter "${key}"`);
|
|
516
|
+
}
|
|
517
|
+
params[key] = value;
|
|
518
|
+
});
|
|
519
|
+
});
|
|
520
|
+
return configurations;
|
|
521
|
+
}
|
|
522
|
+
decompress(data, fin, callback) {
|
|
523
|
+
zlibLimiter.add((done) => {
|
|
524
|
+
this._decompress(data, fin, (err, result) => {
|
|
525
|
+
done();
|
|
526
|
+
callback(err, result);
|
|
527
|
+
});
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
compress(data, fin, callback) {
|
|
531
|
+
zlibLimiter.add((done) => {
|
|
532
|
+
this._compress(data, fin, (err, result) => {
|
|
533
|
+
done();
|
|
534
|
+
callback(err, result);
|
|
535
|
+
});
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
_decompress(data, fin, callback) {
|
|
539
|
+
const endpoint = this._isServer ? "client" : "server";
|
|
540
|
+
if (!this._inflate) {
|
|
541
|
+
const key = `${endpoint}_max_window_bits`;
|
|
542
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
543
|
+
this._inflate = zlib.createInflateRaw({
|
|
544
|
+
...this._options.zlibInflateOptions,
|
|
545
|
+
windowBits
|
|
546
|
+
});
|
|
547
|
+
this._inflate[kPerMessageDeflate] = this;
|
|
548
|
+
this._inflate[kTotalLength] = 0;
|
|
549
|
+
this._inflate[kBuffers] = [];
|
|
550
|
+
this._inflate.on("error", inflateOnError);
|
|
551
|
+
this._inflate.on("data", inflateOnData);
|
|
552
|
+
}
|
|
553
|
+
this._inflate[kCallback] = callback;
|
|
554
|
+
this._inflate.write(data);
|
|
555
|
+
if (fin)
|
|
556
|
+
this._inflate.write(TRAILER);
|
|
557
|
+
this._inflate.flush(() => {
|
|
558
|
+
const err = this._inflate[kError];
|
|
559
|
+
if (err) {
|
|
560
|
+
this._inflate.close();
|
|
561
|
+
this._inflate = null;
|
|
562
|
+
callback(err);
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
const data2 = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
|
|
566
|
+
if (this._inflate._readableState.endEmitted) {
|
|
567
|
+
this._inflate.close();
|
|
568
|
+
this._inflate = null;
|
|
569
|
+
} else {
|
|
570
|
+
this._inflate[kTotalLength] = 0;
|
|
571
|
+
this._inflate[kBuffers] = [];
|
|
572
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
573
|
+
this._inflate.reset();
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
callback(null, data2);
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
_compress(data, fin, callback) {
|
|
580
|
+
const endpoint = this._isServer ? "server" : "client";
|
|
581
|
+
if (!this._deflate) {
|
|
582
|
+
const key = `${endpoint}_max_window_bits`;
|
|
583
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
584
|
+
this._deflate = zlib.createDeflateRaw({
|
|
585
|
+
...this._options.zlibDeflateOptions,
|
|
586
|
+
windowBits
|
|
587
|
+
});
|
|
588
|
+
this._deflate[kTotalLength] = 0;
|
|
589
|
+
this._deflate[kBuffers] = [];
|
|
590
|
+
this._deflate.on("data", deflateOnData);
|
|
591
|
+
}
|
|
592
|
+
this._deflate[kCallback] = callback;
|
|
593
|
+
this._deflate.write(data);
|
|
594
|
+
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
|
|
595
|
+
if (!this._deflate) {
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
let data2 = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
|
|
599
|
+
if (fin) {
|
|
600
|
+
data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
|
|
601
|
+
}
|
|
602
|
+
this._deflate[kCallback] = null;
|
|
603
|
+
this._deflate[kTotalLength] = 0;
|
|
604
|
+
this._deflate[kBuffers] = [];
|
|
605
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
606
|
+
this._deflate.reset();
|
|
607
|
+
}
|
|
608
|
+
callback(null, data2);
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
module.exports = PerMessageDeflate;
|
|
613
|
+
function deflateOnData(chunk) {
|
|
614
|
+
this[kBuffers].push(chunk);
|
|
615
|
+
this[kTotalLength] += chunk.length;
|
|
616
|
+
}
|
|
617
|
+
function inflateOnData(chunk) {
|
|
618
|
+
this[kTotalLength] += chunk.length;
|
|
619
|
+
if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
|
|
620
|
+
this[kBuffers].push(chunk);
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
this[kError] = new RangeError("Max payload size exceeded");
|
|
624
|
+
this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
|
|
625
|
+
this[kError][kStatusCode] = 1009;
|
|
626
|
+
this.removeListener("data", inflateOnData);
|
|
627
|
+
this.reset();
|
|
628
|
+
}
|
|
629
|
+
function inflateOnError(err) {
|
|
630
|
+
this[kPerMessageDeflate]._inflate = null;
|
|
631
|
+
if (this[kError]) {
|
|
632
|
+
this[kCallback](this[kError]);
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
err[kStatusCode] = 1007;
|
|
636
|
+
this[kCallback](err);
|
|
637
|
+
}
|
|
638
|
+
});
|
|
639
|
+
|
|
640
|
+
// ../../../node_modules/utf-8-validate/fallback.js
|
|
641
|
+
var require_fallback2 = __commonJS((exports, module) => {
|
|
642
|
+
function isValidUTF8(buf) {
|
|
643
|
+
const len = buf.length;
|
|
644
|
+
let i = 0;
|
|
645
|
+
while (i < len) {
|
|
646
|
+
if ((buf[i] & 128) === 0) {
|
|
647
|
+
i++;
|
|
648
|
+
} else if ((buf[i] & 224) === 192) {
|
|
649
|
+
if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
|
|
650
|
+
return false;
|
|
651
|
+
}
|
|
652
|
+
i += 2;
|
|
653
|
+
} else if ((buf[i] & 240) === 224) {
|
|
654
|
+
if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) {
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
657
|
+
i += 3;
|
|
658
|
+
} else if ((buf[i] & 248) === 240) {
|
|
659
|
+
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 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
|
|
660
|
+
return false;
|
|
661
|
+
}
|
|
662
|
+
i += 4;
|
|
663
|
+
} else {
|
|
664
|
+
return false;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
return true;
|
|
668
|
+
}
|
|
669
|
+
module.exports = isValidUTF8;
|
|
670
|
+
});
|
|
671
|
+
|
|
672
|
+
// ../../../node_modules/utf-8-validate/index.js
|
|
673
|
+
var require_utf_8_validate = __commonJS((exports, module) => {
|
|
674
|
+
var __dirname = "/Users/shawwalters/eliza-ok/node_modules/utf-8-validate";
|
|
675
|
+
try {
|
|
676
|
+
module.exports = require_node_gyp_build2()(__dirname);
|
|
677
|
+
} catch (e) {
|
|
678
|
+
module.exports = require_fallback2();
|
|
679
|
+
}
|
|
680
|
+
});
|
|
681
|
+
|
|
682
|
+
// ../../../node_modules/ws/lib/validation.js
|
|
683
|
+
var require_validation = __commonJS((exports, module) => {
|
|
684
|
+
var { isUtf8 } = __require("buffer");
|
|
685
|
+
var { hasBlob } = require_constants();
|
|
686
|
+
var tokenChars = [
|
|
687
|
+
0,
|
|
688
|
+
0,
|
|
689
|
+
0,
|
|
690
|
+
0,
|
|
691
|
+
0,
|
|
692
|
+
0,
|
|
693
|
+
0,
|
|
694
|
+
0,
|
|
695
|
+
0,
|
|
696
|
+
0,
|
|
697
|
+
0,
|
|
698
|
+
0,
|
|
699
|
+
0,
|
|
700
|
+
0,
|
|
701
|
+
0,
|
|
702
|
+
0,
|
|
703
|
+
0,
|
|
704
|
+
0,
|
|
705
|
+
0,
|
|
706
|
+
0,
|
|
707
|
+
0,
|
|
708
|
+
0,
|
|
709
|
+
0,
|
|
710
|
+
0,
|
|
711
|
+
0,
|
|
712
|
+
0,
|
|
713
|
+
0,
|
|
714
|
+
0,
|
|
715
|
+
0,
|
|
716
|
+
0,
|
|
717
|
+
0,
|
|
718
|
+
0,
|
|
719
|
+
0,
|
|
720
|
+
1,
|
|
721
|
+
0,
|
|
722
|
+
1,
|
|
723
|
+
1,
|
|
724
|
+
1,
|
|
725
|
+
1,
|
|
726
|
+
1,
|
|
727
|
+
0,
|
|
728
|
+
0,
|
|
729
|
+
1,
|
|
730
|
+
1,
|
|
731
|
+
0,
|
|
732
|
+
1,
|
|
733
|
+
1,
|
|
734
|
+
0,
|
|
735
|
+
1,
|
|
736
|
+
1,
|
|
737
|
+
1,
|
|
738
|
+
1,
|
|
739
|
+
1,
|
|
740
|
+
1,
|
|
741
|
+
1,
|
|
742
|
+
1,
|
|
743
|
+
1,
|
|
744
|
+
1,
|
|
745
|
+
0,
|
|
746
|
+
0,
|
|
747
|
+
0,
|
|
748
|
+
0,
|
|
749
|
+
0,
|
|
750
|
+
0,
|
|
751
|
+
0,
|
|
752
|
+
1,
|
|
753
|
+
1,
|
|
754
|
+
1,
|
|
755
|
+
1,
|
|
756
|
+
1,
|
|
757
|
+
1,
|
|
758
|
+
1,
|
|
759
|
+
1,
|
|
760
|
+
1,
|
|
761
|
+
1,
|
|
762
|
+
1,
|
|
763
|
+
1,
|
|
764
|
+
1,
|
|
765
|
+
1,
|
|
766
|
+
1,
|
|
767
|
+
1,
|
|
768
|
+
1,
|
|
769
|
+
1,
|
|
770
|
+
1,
|
|
771
|
+
1,
|
|
772
|
+
1,
|
|
773
|
+
1,
|
|
774
|
+
1,
|
|
775
|
+
1,
|
|
776
|
+
1,
|
|
777
|
+
1,
|
|
778
|
+
0,
|
|
779
|
+
0,
|
|
780
|
+
0,
|
|
781
|
+
1,
|
|
782
|
+
1,
|
|
783
|
+
1,
|
|
784
|
+
1,
|
|
785
|
+
1,
|
|
786
|
+
1,
|
|
787
|
+
1,
|
|
788
|
+
1,
|
|
789
|
+
1,
|
|
790
|
+
1,
|
|
791
|
+
1,
|
|
792
|
+
1,
|
|
793
|
+
1,
|
|
794
|
+
1,
|
|
795
|
+
1,
|
|
796
|
+
1,
|
|
797
|
+
1,
|
|
798
|
+
1,
|
|
799
|
+
1,
|
|
800
|
+
1,
|
|
801
|
+
1,
|
|
802
|
+
1,
|
|
803
|
+
1,
|
|
804
|
+
1,
|
|
805
|
+
1,
|
|
806
|
+
1,
|
|
807
|
+
1,
|
|
808
|
+
1,
|
|
809
|
+
1,
|
|
810
|
+
0,
|
|
811
|
+
1,
|
|
812
|
+
0,
|
|
813
|
+
1,
|
|
814
|
+
0
|
|
815
|
+
];
|
|
816
|
+
function isValidStatusCode(code) {
|
|
817
|
+
return code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3000 && code <= 4999;
|
|
818
|
+
}
|
|
819
|
+
function _isValidUTF8(buf) {
|
|
820
|
+
const len = buf.length;
|
|
821
|
+
let i = 0;
|
|
822
|
+
while (i < len) {
|
|
823
|
+
if ((buf[i] & 128) === 0) {
|
|
824
|
+
i++;
|
|
825
|
+
} else if ((buf[i] & 224) === 192) {
|
|
826
|
+
if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
|
|
827
|
+
return false;
|
|
828
|
+
}
|
|
829
|
+
i += 2;
|
|
830
|
+
} else if ((buf[i] & 240) === 224) {
|
|
831
|
+
if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) {
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
i += 3;
|
|
835
|
+
} else if ((buf[i] & 248) === 240) {
|
|
836
|
+
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 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
|
|
837
|
+
return false;
|
|
838
|
+
}
|
|
839
|
+
i += 4;
|
|
840
|
+
} else {
|
|
841
|
+
return false;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
return true;
|
|
845
|
+
}
|
|
846
|
+
function isBlob(value) {
|
|
847
|
+
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");
|
|
848
|
+
}
|
|
849
|
+
module.exports = {
|
|
850
|
+
isBlob,
|
|
851
|
+
isValidStatusCode,
|
|
852
|
+
isValidUTF8: _isValidUTF8,
|
|
853
|
+
tokenChars
|
|
854
|
+
};
|
|
855
|
+
if (isUtf8) {
|
|
856
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
857
|
+
return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
|
|
858
|
+
};
|
|
859
|
+
} else if (!process.env.WS_NO_UTF_8_VALIDATE) {
|
|
860
|
+
try {
|
|
861
|
+
const isValidUTF8 = require_utf_8_validate();
|
|
862
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
863
|
+
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
|
|
864
|
+
};
|
|
865
|
+
} catch (e) {}
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
|
|
869
|
+
// ../../../node_modules/ws/lib/receiver.js
|
|
870
|
+
var require_receiver = __commonJS((exports, module) => {
|
|
871
|
+
var { Writable } = __require("stream");
|
|
872
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
873
|
+
var {
|
|
874
|
+
BINARY_TYPES,
|
|
875
|
+
EMPTY_BUFFER,
|
|
876
|
+
kStatusCode,
|
|
877
|
+
kWebSocket
|
|
878
|
+
} = require_constants();
|
|
879
|
+
var { concat, toArrayBuffer, unmask } = require_buffer_util();
|
|
880
|
+
var { isValidStatusCode, isValidUTF8 } = require_validation();
|
|
881
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
882
|
+
var GET_INFO = 0;
|
|
883
|
+
var GET_PAYLOAD_LENGTH_16 = 1;
|
|
884
|
+
var GET_PAYLOAD_LENGTH_64 = 2;
|
|
885
|
+
var GET_MASK = 3;
|
|
886
|
+
var GET_DATA = 4;
|
|
887
|
+
var INFLATING = 5;
|
|
888
|
+
var DEFER_EVENT = 6;
|
|
889
|
+
|
|
890
|
+
class Receiver extends Writable {
|
|
891
|
+
constructor(options = {}) {
|
|
892
|
+
super();
|
|
893
|
+
this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true;
|
|
894
|
+
this._binaryType = options.binaryType || BINARY_TYPES[0];
|
|
895
|
+
this._extensions = options.extensions || {};
|
|
896
|
+
this._isServer = !!options.isServer;
|
|
897
|
+
this._maxPayload = options.maxPayload | 0;
|
|
898
|
+
this._skipUTF8Validation = !!options.skipUTF8Validation;
|
|
899
|
+
this[kWebSocket] = undefined;
|
|
900
|
+
this._bufferedBytes = 0;
|
|
901
|
+
this._buffers = [];
|
|
902
|
+
this._compressed = false;
|
|
903
|
+
this._payloadLength = 0;
|
|
904
|
+
this._mask = undefined;
|
|
905
|
+
this._fragmented = 0;
|
|
906
|
+
this._masked = false;
|
|
907
|
+
this._fin = false;
|
|
908
|
+
this._opcode = 0;
|
|
909
|
+
this._totalPayloadLength = 0;
|
|
910
|
+
this._messageLength = 0;
|
|
911
|
+
this._fragments = [];
|
|
912
|
+
this._errored = false;
|
|
913
|
+
this._loop = false;
|
|
914
|
+
this._state = GET_INFO;
|
|
915
|
+
}
|
|
916
|
+
_write(chunk, encoding, cb) {
|
|
917
|
+
if (this._opcode === 8 && this._state == GET_INFO)
|
|
918
|
+
return cb();
|
|
919
|
+
this._bufferedBytes += chunk.length;
|
|
920
|
+
this._buffers.push(chunk);
|
|
921
|
+
this.startLoop(cb);
|
|
922
|
+
}
|
|
923
|
+
consume(n) {
|
|
924
|
+
this._bufferedBytes -= n;
|
|
925
|
+
if (n === this._buffers[0].length)
|
|
926
|
+
return this._buffers.shift();
|
|
927
|
+
if (n < this._buffers[0].length) {
|
|
928
|
+
const buf = this._buffers[0];
|
|
929
|
+
this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
|
|
930
|
+
return new FastBuffer(buf.buffer, buf.byteOffset, n);
|
|
931
|
+
}
|
|
932
|
+
const dst = Buffer.allocUnsafe(n);
|
|
933
|
+
do {
|
|
934
|
+
const buf = this._buffers[0];
|
|
935
|
+
const offset = dst.length - n;
|
|
936
|
+
if (n >= buf.length) {
|
|
937
|
+
dst.set(this._buffers.shift(), offset);
|
|
938
|
+
} else {
|
|
939
|
+
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
|
|
940
|
+
this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
|
|
941
|
+
}
|
|
942
|
+
n -= buf.length;
|
|
943
|
+
} while (n > 0);
|
|
944
|
+
return dst;
|
|
945
|
+
}
|
|
946
|
+
startLoop(cb) {
|
|
947
|
+
this._loop = true;
|
|
948
|
+
do {
|
|
949
|
+
switch (this._state) {
|
|
950
|
+
case GET_INFO:
|
|
951
|
+
this.getInfo(cb);
|
|
952
|
+
break;
|
|
953
|
+
case GET_PAYLOAD_LENGTH_16:
|
|
954
|
+
this.getPayloadLength16(cb);
|
|
955
|
+
break;
|
|
956
|
+
case GET_PAYLOAD_LENGTH_64:
|
|
957
|
+
this.getPayloadLength64(cb);
|
|
958
|
+
break;
|
|
959
|
+
case GET_MASK:
|
|
960
|
+
this.getMask();
|
|
961
|
+
break;
|
|
962
|
+
case GET_DATA:
|
|
963
|
+
this.getData(cb);
|
|
964
|
+
break;
|
|
965
|
+
case INFLATING:
|
|
966
|
+
case DEFER_EVENT:
|
|
967
|
+
this._loop = false;
|
|
968
|
+
return;
|
|
969
|
+
}
|
|
970
|
+
} while (this._loop);
|
|
971
|
+
if (!this._errored)
|
|
972
|
+
cb();
|
|
973
|
+
}
|
|
974
|
+
getInfo(cb) {
|
|
975
|
+
if (this._bufferedBytes < 2) {
|
|
976
|
+
this._loop = false;
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
const buf = this.consume(2);
|
|
980
|
+
if ((buf[0] & 48) !== 0) {
|
|
981
|
+
const error = this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3");
|
|
982
|
+
cb(error);
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
const compressed = (buf[0] & 64) === 64;
|
|
986
|
+
if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
|
|
987
|
+
const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
|
|
988
|
+
cb(error);
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
this._fin = (buf[0] & 128) === 128;
|
|
992
|
+
this._opcode = buf[0] & 15;
|
|
993
|
+
this._payloadLength = buf[1] & 127;
|
|
994
|
+
if (this._opcode === 0) {
|
|
995
|
+
if (compressed) {
|
|
996
|
+
const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
|
|
997
|
+
cb(error);
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
if (!this._fragmented) {
|
|
1001
|
+
const error = this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE");
|
|
1002
|
+
cb(error);
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
this._opcode = this._fragmented;
|
|
1006
|
+
} else if (this._opcode === 1 || this._opcode === 2) {
|
|
1007
|
+
if (this._fragmented) {
|
|
1008
|
+
const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
|
|
1009
|
+
cb(error);
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
this._compressed = compressed;
|
|
1013
|
+
} else if (this._opcode > 7 && this._opcode < 11) {
|
|
1014
|
+
if (!this._fin) {
|
|
1015
|
+
const error = this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN");
|
|
1016
|
+
cb(error);
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
if (compressed) {
|
|
1020
|
+
const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
|
|
1021
|
+
cb(error);
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
|
|
1025
|
+
const error = this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");
|
|
1026
|
+
cb(error);
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
} else {
|
|
1030
|
+
const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
|
|
1031
|
+
cb(error);
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
if (!this._fin && !this._fragmented)
|
|
1035
|
+
this._fragmented = this._opcode;
|
|
1036
|
+
this._masked = (buf[1] & 128) === 128;
|
|
1037
|
+
if (this._isServer) {
|
|
1038
|
+
if (!this._masked) {
|
|
1039
|
+
const error = this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK");
|
|
1040
|
+
cb(error);
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
} else if (this._masked) {
|
|
1044
|
+
const error = this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK");
|
|
1045
|
+
cb(error);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
if (this._payloadLength === 126)
|
|
1049
|
+
this._state = GET_PAYLOAD_LENGTH_16;
|
|
1050
|
+
else if (this._payloadLength === 127)
|
|
1051
|
+
this._state = GET_PAYLOAD_LENGTH_64;
|
|
1052
|
+
else
|
|
1053
|
+
this.haveLength(cb);
|
|
1054
|
+
}
|
|
1055
|
+
getPayloadLength16(cb) {
|
|
1056
|
+
if (this._bufferedBytes < 2) {
|
|
1057
|
+
this._loop = false;
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
1060
|
+
this._payloadLength = this.consume(2).readUInt16BE(0);
|
|
1061
|
+
this.haveLength(cb);
|
|
1062
|
+
}
|
|
1063
|
+
getPayloadLength64(cb) {
|
|
1064
|
+
if (this._bufferedBytes < 8) {
|
|
1065
|
+
this._loop = false;
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
const buf = this.consume(8);
|
|
1069
|
+
const num = buf.readUInt32BE(0);
|
|
1070
|
+
if (num > Math.pow(2, 53 - 32) - 1) {
|
|
1071
|
+
const error = this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");
|
|
1072
|
+
cb(error);
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
|
|
1076
|
+
this.haveLength(cb);
|
|
1077
|
+
}
|
|
1078
|
+
haveLength(cb) {
|
|
1079
|
+
if (this._payloadLength && this._opcode < 8) {
|
|
1080
|
+
this._totalPayloadLength += this._payloadLength;
|
|
1081
|
+
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
|
|
1082
|
+
const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
|
|
1083
|
+
cb(error);
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
if (this._masked)
|
|
1088
|
+
this._state = GET_MASK;
|
|
1089
|
+
else
|
|
1090
|
+
this._state = GET_DATA;
|
|
1091
|
+
}
|
|
1092
|
+
getMask() {
|
|
1093
|
+
if (this._bufferedBytes < 4) {
|
|
1094
|
+
this._loop = false;
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
this._mask = this.consume(4);
|
|
1098
|
+
this._state = GET_DATA;
|
|
1099
|
+
}
|
|
1100
|
+
getData(cb) {
|
|
1101
|
+
let data = EMPTY_BUFFER;
|
|
1102
|
+
if (this._payloadLength) {
|
|
1103
|
+
if (this._bufferedBytes < this._payloadLength) {
|
|
1104
|
+
this._loop = false;
|
|
1105
|
+
return;
|
|
1106
|
+
}
|
|
1107
|
+
data = this.consume(this._payloadLength);
|
|
1108
|
+
if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
|
|
1109
|
+
unmask(data, this._mask);
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
if (this._opcode > 7) {
|
|
1113
|
+
this.controlMessage(data, cb);
|
|
1114
|
+
return;
|
|
1115
|
+
}
|
|
1116
|
+
if (this._compressed) {
|
|
1117
|
+
this._state = INFLATING;
|
|
1118
|
+
this.decompress(data, cb);
|
|
1119
|
+
return;
|
|
1120
|
+
}
|
|
1121
|
+
if (data.length) {
|
|
1122
|
+
this._messageLength = this._totalPayloadLength;
|
|
1123
|
+
this._fragments.push(data);
|
|
1124
|
+
}
|
|
1125
|
+
this.dataMessage(cb);
|
|
1126
|
+
}
|
|
1127
|
+
decompress(data, cb) {
|
|
1128
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
1129
|
+
perMessageDeflate.decompress(data, this._fin, (err, buf) => {
|
|
1130
|
+
if (err)
|
|
1131
|
+
return cb(err);
|
|
1132
|
+
if (buf.length) {
|
|
1133
|
+
this._messageLength += buf.length;
|
|
1134
|
+
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
|
|
1135
|
+
const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
|
|
1136
|
+
cb(error);
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
this._fragments.push(buf);
|
|
1140
|
+
}
|
|
1141
|
+
this.dataMessage(cb);
|
|
1142
|
+
if (this._state === GET_INFO)
|
|
1143
|
+
this.startLoop(cb);
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
dataMessage(cb) {
|
|
1147
|
+
if (!this._fin) {
|
|
1148
|
+
this._state = GET_INFO;
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
const messageLength = this._messageLength;
|
|
1152
|
+
const fragments = this._fragments;
|
|
1153
|
+
this._totalPayloadLength = 0;
|
|
1154
|
+
this._messageLength = 0;
|
|
1155
|
+
this._fragmented = 0;
|
|
1156
|
+
this._fragments = [];
|
|
1157
|
+
if (this._opcode === 2) {
|
|
1158
|
+
let data;
|
|
1159
|
+
if (this._binaryType === "nodebuffer") {
|
|
1160
|
+
data = concat(fragments, messageLength);
|
|
1161
|
+
} else if (this._binaryType === "arraybuffer") {
|
|
1162
|
+
data = toArrayBuffer(concat(fragments, messageLength));
|
|
1163
|
+
} else if (this._binaryType === "blob") {
|
|
1164
|
+
data = new Blob(fragments);
|
|
1165
|
+
} else {
|
|
1166
|
+
data = fragments;
|
|
1167
|
+
}
|
|
1168
|
+
if (this._allowSynchronousEvents) {
|
|
1169
|
+
this.emit("message", data, true);
|
|
1170
|
+
this._state = GET_INFO;
|
|
1171
|
+
} else {
|
|
1172
|
+
this._state = DEFER_EVENT;
|
|
1173
|
+
setImmediate(() => {
|
|
1174
|
+
this.emit("message", data, true);
|
|
1175
|
+
this._state = GET_INFO;
|
|
1176
|
+
this.startLoop(cb);
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
} else {
|
|
1180
|
+
const buf = concat(fragments, messageLength);
|
|
1181
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
1182
|
+
const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
|
|
1183
|
+
cb(error);
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
if (this._state === INFLATING || this._allowSynchronousEvents) {
|
|
1187
|
+
this.emit("message", buf, false);
|
|
1188
|
+
this._state = GET_INFO;
|
|
1189
|
+
} else {
|
|
1190
|
+
this._state = DEFER_EVENT;
|
|
1191
|
+
setImmediate(() => {
|
|
1192
|
+
this.emit("message", buf, false);
|
|
1193
|
+
this._state = GET_INFO;
|
|
1194
|
+
this.startLoop(cb);
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
controlMessage(data, cb) {
|
|
1200
|
+
if (this._opcode === 8) {
|
|
1201
|
+
if (data.length === 0) {
|
|
1202
|
+
this._loop = false;
|
|
1203
|
+
this.emit("conclude", 1005, EMPTY_BUFFER);
|
|
1204
|
+
this.end();
|
|
1205
|
+
} else {
|
|
1206
|
+
const code = data.readUInt16BE(0);
|
|
1207
|
+
if (!isValidStatusCode(code)) {
|
|
1208
|
+
const error = this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE");
|
|
1209
|
+
cb(error);
|
|
1210
|
+
return;
|
|
1211
|
+
}
|
|
1212
|
+
const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
|
|
1213
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
1214
|
+
const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
|
|
1215
|
+
cb(error);
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
this._loop = false;
|
|
1219
|
+
this.emit("conclude", code, buf);
|
|
1220
|
+
this.end();
|
|
1221
|
+
}
|
|
1222
|
+
this._state = GET_INFO;
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
1225
|
+
if (this._allowSynchronousEvents) {
|
|
1226
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
1227
|
+
this._state = GET_INFO;
|
|
1228
|
+
} else {
|
|
1229
|
+
this._state = DEFER_EVENT;
|
|
1230
|
+
setImmediate(() => {
|
|
1231
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
1232
|
+
this._state = GET_INFO;
|
|
1233
|
+
this.startLoop(cb);
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
createError(ErrorCtor, message, prefix, statusCode, errorCode) {
|
|
1238
|
+
this._loop = false;
|
|
1239
|
+
this._errored = true;
|
|
1240
|
+
const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
|
|
1241
|
+
Error.captureStackTrace(err, this.createError);
|
|
1242
|
+
err.code = errorCode;
|
|
1243
|
+
err[kStatusCode] = statusCode;
|
|
1244
|
+
return err;
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
module.exports = Receiver;
|
|
1248
|
+
});
|
|
1249
|
+
|
|
1250
|
+
// ../../../node_modules/ws/lib/sender.js
|
|
1251
|
+
var require_sender = __commonJS((exports, module) => {
|
|
1252
|
+
var { Duplex } = __require("stream");
|
|
1253
|
+
var { randomFillSync } = __require("crypto");
|
|
1254
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
1255
|
+
var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
|
|
1256
|
+
var { isBlob, isValidStatusCode } = require_validation();
|
|
1257
|
+
var { mask: applyMask, toBuffer } = require_buffer_util();
|
|
1258
|
+
var kByteLength = Symbol("kByteLength");
|
|
1259
|
+
var maskBuffer = Buffer.alloc(4);
|
|
1260
|
+
var RANDOM_POOL_SIZE = 8 * 1024;
|
|
1261
|
+
var randomPool;
|
|
1262
|
+
var randomPoolPointer = RANDOM_POOL_SIZE;
|
|
1263
|
+
var DEFAULT = 0;
|
|
1264
|
+
var DEFLATING = 1;
|
|
1265
|
+
var GET_BLOB_DATA = 2;
|
|
1266
|
+
|
|
1267
|
+
class Sender {
|
|
1268
|
+
constructor(socket, extensions, generateMask) {
|
|
1269
|
+
this._extensions = extensions || {};
|
|
1270
|
+
if (generateMask) {
|
|
1271
|
+
this._generateMask = generateMask;
|
|
1272
|
+
this._maskBuffer = Buffer.alloc(4);
|
|
1273
|
+
}
|
|
1274
|
+
this._socket = socket;
|
|
1275
|
+
this._firstFragment = true;
|
|
1276
|
+
this._compress = false;
|
|
1277
|
+
this._bufferedBytes = 0;
|
|
1278
|
+
this._queue = [];
|
|
1279
|
+
this._state = DEFAULT;
|
|
1280
|
+
this.onerror = NOOP;
|
|
1281
|
+
this[kWebSocket] = undefined;
|
|
1282
|
+
}
|
|
1283
|
+
static frame(data, options) {
|
|
1284
|
+
let mask;
|
|
1285
|
+
let merge = false;
|
|
1286
|
+
let offset = 2;
|
|
1287
|
+
let skipMasking = false;
|
|
1288
|
+
if (options.mask) {
|
|
1289
|
+
mask = options.maskBuffer || maskBuffer;
|
|
1290
|
+
if (options.generateMask) {
|
|
1291
|
+
options.generateMask(mask);
|
|
1292
|
+
} else {
|
|
1293
|
+
if (randomPoolPointer === RANDOM_POOL_SIZE) {
|
|
1294
|
+
if (randomPool === undefined) {
|
|
1295
|
+
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
|
|
1296
|
+
}
|
|
1297
|
+
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
|
|
1298
|
+
randomPoolPointer = 0;
|
|
1299
|
+
}
|
|
1300
|
+
mask[0] = randomPool[randomPoolPointer++];
|
|
1301
|
+
mask[1] = randomPool[randomPoolPointer++];
|
|
1302
|
+
mask[2] = randomPool[randomPoolPointer++];
|
|
1303
|
+
mask[3] = randomPool[randomPoolPointer++];
|
|
1304
|
+
}
|
|
1305
|
+
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
|
|
1306
|
+
offset = 6;
|
|
1307
|
+
}
|
|
1308
|
+
let dataLength;
|
|
1309
|
+
if (typeof data === "string") {
|
|
1310
|
+
if ((!options.mask || skipMasking) && options[kByteLength] !== undefined) {
|
|
1311
|
+
dataLength = options[kByteLength];
|
|
1312
|
+
} else {
|
|
1313
|
+
data = Buffer.from(data);
|
|
1314
|
+
dataLength = data.length;
|
|
1315
|
+
}
|
|
1316
|
+
} else {
|
|
1317
|
+
dataLength = data.length;
|
|
1318
|
+
merge = options.mask && options.readOnly && !skipMasking;
|
|
1319
|
+
}
|
|
1320
|
+
let payloadLength = dataLength;
|
|
1321
|
+
if (dataLength >= 65536) {
|
|
1322
|
+
offset += 8;
|
|
1323
|
+
payloadLength = 127;
|
|
1324
|
+
} else if (dataLength > 125) {
|
|
1325
|
+
offset += 2;
|
|
1326
|
+
payloadLength = 126;
|
|
1327
|
+
}
|
|
1328
|
+
const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
|
|
1329
|
+
target[0] = options.fin ? options.opcode | 128 : options.opcode;
|
|
1330
|
+
if (options.rsv1)
|
|
1331
|
+
target[0] |= 64;
|
|
1332
|
+
target[1] = payloadLength;
|
|
1333
|
+
if (payloadLength === 126) {
|
|
1334
|
+
target.writeUInt16BE(dataLength, 2);
|
|
1335
|
+
} else if (payloadLength === 127) {
|
|
1336
|
+
target[2] = target[3] = 0;
|
|
1337
|
+
target.writeUIntBE(dataLength, 4, 6);
|
|
1338
|
+
}
|
|
1339
|
+
if (!options.mask)
|
|
1340
|
+
return [target, data];
|
|
1341
|
+
target[1] |= 128;
|
|
1342
|
+
target[offset - 4] = mask[0];
|
|
1343
|
+
target[offset - 3] = mask[1];
|
|
1344
|
+
target[offset - 2] = mask[2];
|
|
1345
|
+
target[offset - 1] = mask[3];
|
|
1346
|
+
if (skipMasking)
|
|
1347
|
+
return [target, data];
|
|
1348
|
+
if (merge) {
|
|
1349
|
+
applyMask(data, mask, target, offset, dataLength);
|
|
1350
|
+
return [target];
|
|
1351
|
+
}
|
|
1352
|
+
applyMask(data, mask, data, 0, dataLength);
|
|
1353
|
+
return [target, data];
|
|
1354
|
+
}
|
|
1355
|
+
close(code, data, mask, cb) {
|
|
1356
|
+
let buf;
|
|
1357
|
+
if (code === undefined) {
|
|
1358
|
+
buf = EMPTY_BUFFER;
|
|
1359
|
+
} else if (typeof code !== "number" || !isValidStatusCode(code)) {
|
|
1360
|
+
throw new TypeError("First argument must be a valid error code number");
|
|
1361
|
+
} else if (data === undefined || !data.length) {
|
|
1362
|
+
buf = Buffer.allocUnsafe(2);
|
|
1363
|
+
buf.writeUInt16BE(code, 0);
|
|
1364
|
+
} else {
|
|
1365
|
+
const length = Buffer.byteLength(data);
|
|
1366
|
+
if (length > 123) {
|
|
1367
|
+
throw new RangeError("The message must not be greater than 123 bytes");
|
|
1368
|
+
}
|
|
1369
|
+
buf = Buffer.allocUnsafe(2 + length);
|
|
1370
|
+
buf.writeUInt16BE(code, 0);
|
|
1371
|
+
if (typeof data === "string") {
|
|
1372
|
+
buf.write(data, 2);
|
|
1373
|
+
} else {
|
|
1374
|
+
buf.set(data, 2);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
const options = {
|
|
1378
|
+
[kByteLength]: buf.length,
|
|
1379
|
+
fin: true,
|
|
1380
|
+
generateMask: this._generateMask,
|
|
1381
|
+
mask,
|
|
1382
|
+
maskBuffer: this._maskBuffer,
|
|
1383
|
+
opcode: 8,
|
|
1384
|
+
readOnly: false,
|
|
1385
|
+
rsv1: false
|
|
1386
|
+
};
|
|
1387
|
+
if (this._state !== DEFAULT) {
|
|
1388
|
+
this.enqueue([this.dispatch, buf, false, options, cb]);
|
|
1389
|
+
} else {
|
|
1390
|
+
this.sendFrame(Sender.frame(buf, options), cb);
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
ping(data, mask, cb) {
|
|
1394
|
+
let byteLength;
|
|
1395
|
+
let readOnly;
|
|
1396
|
+
if (typeof data === "string") {
|
|
1397
|
+
byteLength = Buffer.byteLength(data);
|
|
1398
|
+
readOnly = false;
|
|
1399
|
+
} else if (isBlob(data)) {
|
|
1400
|
+
byteLength = data.size;
|
|
1401
|
+
readOnly = false;
|
|
1402
|
+
} else {
|
|
1403
|
+
data = toBuffer(data);
|
|
1404
|
+
byteLength = data.length;
|
|
1405
|
+
readOnly = toBuffer.readOnly;
|
|
1406
|
+
}
|
|
1407
|
+
if (byteLength > 125) {
|
|
1408
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1409
|
+
}
|
|
1410
|
+
const options = {
|
|
1411
|
+
[kByteLength]: byteLength,
|
|
1412
|
+
fin: true,
|
|
1413
|
+
generateMask: this._generateMask,
|
|
1414
|
+
mask,
|
|
1415
|
+
maskBuffer: this._maskBuffer,
|
|
1416
|
+
opcode: 9,
|
|
1417
|
+
readOnly,
|
|
1418
|
+
rsv1: false
|
|
1419
|
+
};
|
|
1420
|
+
if (isBlob(data)) {
|
|
1421
|
+
if (this._state !== DEFAULT) {
|
|
1422
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1423
|
+
} else {
|
|
1424
|
+
this.getBlobData(data, false, options, cb);
|
|
1425
|
+
}
|
|
1426
|
+
} else if (this._state !== DEFAULT) {
|
|
1427
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1428
|
+
} else {
|
|
1429
|
+
this.sendFrame(Sender.frame(data, options), cb);
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
pong(data, mask, cb) {
|
|
1433
|
+
let byteLength;
|
|
1434
|
+
let readOnly;
|
|
1435
|
+
if (typeof data === "string") {
|
|
1436
|
+
byteLength = Buffer.byteLength(data);
|
|
1437
|
+
readOnly = false;
|
|
1438
|
+
} else if (isBlob(data)) {
|
|
1439
|
+
byteLength = data.size;
|
|
1440
|
+
readOnly = false;
|
|
1441
|
+
} else {
|
|
1442
|
+
data = toBuffer(data);
|
|
1443
|
+
byteLength = data.length;
|
|
1444
|
+
readOnly = toBuffer.readOnly;
|
|
1445
|
+
}
|
|
1446
|
+
if (byteLength > 125) {
|
|
1447
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1448
|
+
}
|
|
1449
|
+
const options = {
|
|
1450
|
+
[kByteLength]: byteLength,
|
|
1451
|
+
fin: true,
|
|
1452
|
+
generateMask: this._generateMask,
|
|
1453
|
+
mask,
|
|
1454
|
+
maskBuffer: this._maskBuffer,
|
|
1455
|
+
opcode: 10,
|
|
1456
|
+
readOnly,
|
|
1457
|
+
rsv1: false
|
|
1458
|
+
};
|
|
1459
|
+
if (isBlob(data)) {
|
|
1460
|
+
if (this._state !== DEFAULT) {
|
|
1461
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1462
|
+
} else {
|
|
1463
|
+
this.getBlobData(data, false, options, cb);
|
|
1464
|
+
}
|
|
1465
|
+
} else if (this._state !== DEFAULT) {
|
|
1466
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1467
|
+
} else {
|
|
1468
|
+
this.sendFrame(Sender.frame(data, options), cb);
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
send(data, options, cb) {
|
|
1472
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
1473
|
+
let opcode = options.binary ? 2 : 1;
|
|
1474
|
+
let rsv1 = options.compress;
|
|
1475
|
+
let byteLength;
|
|
1476
|
+
let readOnly;
|
|
1477
|
+
if (typeof data === "string") {
|
|
1478
|
+
byteLength = Buffer.byteLength(data);
|
|
1479
|
+
readOnly = false;
|
|
1480
|
+
} else if (isBlob(data)) {
|
|
1481
|
+
byteLength = data.size;
|
|
1482
|
+
readOnly = false;
|
|
1483
|
+
} else {
|
|
1484
|
+
data = toBuffer(data);
|
|
1485
|
+
byteLength = data.length;
|
|
1486
|
+
readOnly = toBuffer.readOnly;
|
|
1487
|
+
}
|
|
1488
|
+
if (this._firstFragment) {
|
|
1489
|
+
this._firstFragment = false;
|
|
1490
|
+
if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
|
|
1491
|
+
rsv1 = byteLength >= perMessageDeflate._threshold;
|
|
1492
|
+
}
|
|
1493
|
+
this._compress = rsv1;
|
|
1494
|
+
} else {
|
|
1495
|
+
rsv1 = false;
|
|
1496
|
+
opcode = 0;
|
|
1497
|
+
}
|
|
1498
|
+
if (options.fin)
|
|
1499
|
+
this._firstFragment = true;
|
|
1500
|
+
const opts = {
|
|
1501
|
+
[kByteLength]: byteLength,
|
|
1502
|
+
fin: options.fin,
|
|
1503
|
+
generateMask: this._generateMask,
|
|
1504
|
+
mask: options.mask,
|
|
1505
|
+
maskBuffer: this._maskBuffer,
|
|
1506
|
+
opcode,
|
|
1507
|
+
readOnly,
|
|
1508
|
+
rsv1
|
|
1509
|
+
};
|
|
1510
|
+
if (isBlob(data)) {
|
|
1511
|
+
if (this._state !== DEFAULT) {
|
|
1512
|
+
this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
|
|
1513
|
+
} else {
|
|
1514
|
+
this.getBlobData(data, this._compress, opts, cb);
|
|
1515
|
+
}
|
|
1516
|
+
} else if (this._state !== DEFAULT) {
|
|
1517
|
+
this.enqueue([this.dispatch, data, this._compress, opts, cb]);
|
|
1518
|
+
} else {
|
|
1519
|
+
this.dispatch(data, this._compress, opts, cb);
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
getBlobData(blob, compress, options, cb) {
|
|
1523
|
+
this._bufferedBytes += options[kByteLength];
|
|
1524
|
+
this._state = GET_BLOB_DATA;
|
|
1525
|
+
blob.arrayBuffer().then((arrayBuffer) => {
|
|
1526
|
+
if (this._socket.destroyed) {
|
|
1527
|
+
const err = new Error("The socket was closed while the blob was being read");
|
|
1528
|
+
process.nextTick(callCallbacks, this, err, cb);
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
this._bufferedBytes -= options[kByteLength];
|
|
1532
|
+
const data = toBuffer(arrayBuffer);
|
|
1533
|
+
if (!compress) {
|
|
1534
|
+
this._state = DEFAULT;
|
|
1535
|
+
this.sendFrame(Sender.frame(data, options), cb);
|
|
1536
|
+
this.dequeue();
|
|
1537
|
+
} else {
|
|
1538
|
+
this.dispatch(data, compress, options, cb);
|
|
1539
|
+
}
|
|
1540
|
+
}).catch((err) => {
|
|
1541
|
+
process.nextTick(onError, this, err, cb);
|
|
1542
|
+
});
|
|
1543
|
+
}
|
|
1544
|
+
dispatch(data, compress, options, cb) {
|
|
1545
|
+
if (!compress) {
|
|
1546
|
+
this.sendFrame(Sender.frame(data, options), cb);
|
|
1547
|
+
return;
|
|
1548
|
+
}
|
|
1549
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
1550
|
+
this._bufferedBytes += options[kByteLength];
|
|
1551
|
+
this._state = DEFLATING;
|
|
1552
|
+
perMessageDeflate.compress(data, options.fin, (_, buf) => {
|
|
1553
|
+
if (this._socket.destroyed) {
|
|
1554
|
+
const err = new Error("The socket was closed while data was being compressed");
|
|
1555
|
+
callCallbacks(this, err, cb);
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
this._bufferedBytes -= options[kByteLength];
|
|
1559
|
+
this._state = DEFAULT;
|
|
1560
|
+
options.readOnly = false;
|
|
1561
|
+
this.sendFrame(Sender.frame(buf, options), cb);
|
|
1562
|
+
this.dequeue();
|
|
1563
|
+
});
|
|
1564
|
+
}
|
|
1565
|
+
dequeue() {
|
|
1566
|
+
while (this._state === DEFAULT && this._queue.length) {
|
|
1567
|
+
const params = this._queue.shift();
|
|
1568
|
+
this._bufferedBytes -= params[3][kByteLength];
|
|
1569
|
+
Reflect.apply(params[0], this, params.slice(1));
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
enqueue(params) {
|
|
1573
|
+
this._bufferedBytes += params[3][kByteLength];
|
|
1574
|
+
this._queue.push(params);
|
|
1575
|
+
}
|
|
1576
|
+
sendFrame(list, cb) {
|
|
1577
|
+
if (list.length === 2) {
|
|
1578
|
+
this._socket.cork();
|
|
1579
|
+
this._socket.write(list[0]);
|
|
1580
|
+
this._socket.write(list[1], cb);
|
|
1581
|
+
this._socket.uncork();
|
|
1582
|
+
} else {
|
|
1583
|
+
this._socket.write(list[0], cb);
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
module.exports = Sender;
|
|
1588
|
+
function callCallbacks(sender, err, cb) {
|
|
1589
|
+
if (typeof cb === "function")
|
|
1590
|
+
cb(err);
|
|
1591
|
+
for (let i = 0;i < sender._queue.length; i++) {
|
|
1592
|
+
const params = sender._queue[i];
|
|
1593
|
+
const callback = params[params.length - 1];
|
|
1594
|
+
if (typeof callback === "function")
|
|
1595
|
+
callback(err);
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
function onError(sender, err, cb) {
|
|
1599
|
+
callCallbacks(sender, err, cb);
|
|
1600
|
+
sender.onerror(err);
|
|
1601
|
+
}
|
|
1602
|
+
});
|
|
1603
|
+
|
|
1604
|
+
// ../../../node_modules/ws/lib/event-target.js
|
|
1605
|
+
var require_event_target = __commonJS((exports, module) => {
|
|
1606
|
+
var { kForOnEventAttribute, kListener } = require_constants();
|
|
1607
|
+
var kCode = Symbol("kCode");
|
|
1608
|
+
var kData = Symbol("kData");
|
|
1609
|
+
var kError = Symbol("kError");
|
|
1610
|
+
var kMessage = Symbol("kMessage");
|
|
1611
|
+
var kReason = Symbol("kReason");
|
|
1612
|
+
var kTarget = Symbol("kTarget");
|
|
1613
|
+
var kType = Symbol("kType");
|
|
1614
|
+
var kWasClean = Symbol("kWasClean");
|
|
1615
|
+
|
|
1616
|
+
class Event {
|
|
1617
|
+
constructor(type) {
|
|
1618
|
+
this[kTarget] = null;
|
|
1619
|
+
this[kType] = type;
|
|
1620
|
+
}
|
|
1621
|
+
get target() {
|
|
1622
|
+
return this[kTarget];
|
|
1623
|
+
}
|
|
1624
|
+
get type() {
|
|
1625
|
+
return this[kType];
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
Object.defineProperty(Event.prototype, "target", { enumerable: true });
|
|
1629
|
+
Object.defineProperty(Event.prototype, "type", { enumerable: true });
|
|
1630
|
+
|
|
1631
|
+
class CloseEvent extends Event {
|
|
1632
|
+
constructor(type, options = {}) {
|
|
1633
|
+
super(type);
|
|
1634
|
+
this[kCode] = options.code === undefined ? 0 : options.code;
|
|
1635
|
+
this[kReason] = options.reason === undefined ? "" : options.reason;
|
|
1636
|
+
this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
|
|
1637
|
+
}
|
|
1638
|
+
get code() {
|
|
1639
|
+
return this[kCode];
|
|
1640
|
+
}
|
|
1641
|
+
get reason() {
|
|
1642
|
+
return this[kReason];
|
|
1643
|
+
}
|
|
1644
|
+
get wasClean() {
|
|
1645
|
+
return this[kWasClean];
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
|
|
1649
|
+
Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
|
|
1650
|
+
Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
|
|
1651
|
+
|
|
1652
|
+
class ErrorEvent extends Event {
|
|
1653
|
+
constructor(type, options = {}) {
|
|
1654
|
+
super(type);
|
|
1655
|
+
this[kError] = options.error === undefined ? null : options.error;
|
|
1656
|
+
this[kMessage] = options.message === undefined ? "" : options.message;
|
|
1657
|
+
}
|
|
1658
|
+
get error() {
|
|
1659
|
+
return this[kError];
|
|
1660
|
+
}
|
|
1661
|
+
get message() {
|
|
1662
|
+
return this[kMessage];
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
|
|
1666
|
+
Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
|
|
1667
|
+
|
|
1668
|
+
class MessageEvent extends Event {
|
|
1669
|
+
constructor(type, options = {}) {
|
|
1670
|
+
super(type);
|
|
1671
|
+
this[kData] = options.data === undefined ? null : options.data;
|
|
1672
|
+
}
|
|
1673
|
+
get data() {
|
|
1674
|
+
return this[kData];
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
|
|
1678
|
+
var EventTarget = {
|
|
1679
|
+
addEventListener(type, handler, options = {}) {
|
|
1680
|
+
for (const listener of this.listeners(type)) {
|
|
1681
|
+
if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
1682
|
+
return;
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
let wrapper;
|
|
1686
|
+
if (type === "message") {
|
|
1687
|
+
wrapper = function onMessage(data, isBinary) {
|
|
1688
|
+
const event = new MessageEvent("message", {
|
|
1689
|
+
data: isBinary ? data : data.toString()
|
|
1690
|
+
});
|
|
1691
|
+
event[kTarget] = this;
|
|
1692
|
+
callListener(handler, this, event);
|
|
1693
|
+
};
|
|
1694
|
+
} else if (type === "close") {
|
|
1695
|
+
wrapper = function onClose(code, message) {
|
|
1696
|
+
const event = new CloseEvent("close", {
|
|
1697
|
+
code,
|
|
1698
|
+
reason: message.toString(),
|
|
1699
|
+
wasClean: this._closeFrameReceived && this._closeFrameSent
|
|
1700
|
+
});
|
|
1701
|
+
event[kTarget] = this;
|
|
1702
|
+
callListener(handler, this, event);
|
|
1703
|
+
};
|
|
1704
|
+
} else if (type === "error") {
|
|
1705
|
+
wrapper = function onError(error) {
|
|
1706
|
+
const event = new ErrorEvent("error", {
|
|
1707
|
+
error,
|
|
1708
|
+
message: error.message
|
|
1709
|
+
});
|
|
1710
|
+
event[kTarget] = this;
|
|
1711
|
+
callListener(handler, this, event);
|
|
1712
|
+
};
|
|
1713
|
+
} else if (type === "open") {
|
|
1714
|
+
wrapper = function onOpen() {
|
|
1715
|
+
const event = new Event("open");
|
|
1716
|
+
event[kTarget] = this;
|
|
1717
|
+
callListener(handler, this, event);
|
|
1718
|
+
};
|
|
1719
|
+
} else {
|
|
1720
|
+
return;
|
|
1721
|
+
}
|
|
1722
|
+
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
|
|
1723
|
+
wrapper[kListener] = handler;
|
|
1724
|
+
if (options.once) {
|
|
1725
|
+
this.once(type, wrapper);
|
|
1726
|
+
} else {
|
|
1727
|
+
this.on(type, wrapper);
|
|
1728
|
+
}
|
|
1729
|
+
},
|
|
1730
|
+
removeEventListener(type, handler) {
|
|
1731
|
+
for (const listener of this.listeners(type)) {
|
|
1732
|
+
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
1733
|
+
this.removeListener(type, listener);
|
|
1734
|
+
break;
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
};
|
|
1739
|
+
module.exports = {
|
|
1740
|
+
CloseEvent,
|
|
1741
|
+
ErrorEvent,
|
|
1742
|
+
Event,
|
|
1743
|
+
EventTarget,
|
|
1744
|
+
MessageEvent
|
|
1745
|
+
};
|
|
1746
|
+
function callListener(listener, thisArg, event) {
|
|
1747
|
+
if (typeof listener === "object" && listener.handleEvent) {
|
|
1748
|
+
listener.handleEvent.call(listener, event);
|
|
1749
|
+
} else {
|
|
1750
|
+
listener.call(thisArg, event);
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
});
|
|
1754
|
+
|
|
1755
|
+
// ../../../node_modules/ws/lib/extension.js
|
|
1756
|
+
var require_extension = __commonJS((exports, module) => {
|
|
1757
|
+
var { tokenChars } = require_validation();
|
|
1758
|
+
function push(dest, name, elem) {
|
|
1759
|
+
if (dest[name] === undefined)
|
|
1760
|
+
dest[name] = [elem];
|
|
1761
|
+
else
|
|
1762
|
+
dest[name].push(elem);
|
|
1763
|
+
}
|
|
1764
|
+
function parse(header) {
|
|
1765
|
+
const offers = Object.create(null);
|
|
1766
|
+
let params = Object.create(null);
|
|
1767
|
+
let mustUnescape = false;
|
|
1768
|
+
let isEscaping = false;
|
|
1769
|
+
let inQuotes = false;
|
|
1770
|
+
let extensionName;
|
|
1771
|
+
let paramName;
|
|
1772
|
+
let start = -1;
|
|
1773
|
+
let code = -1;
|
|
1774
|
+
let end = -1;
|
|
1775
|
+
let i = 0;
|
|
1776
|
+
for (;i < header.length; i++) {
|
|
1777
|
+
code = header.charCodeAt(i);
|
|
1778
|
+
if (extensionName === undefined) {
|
|
1779
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
1780
|
+
if (start === -1)
|
|
1781
|
+
start = i;
|
|
1782
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
1783
|
+
if (end === -1 && start !== -1)
|
|
1784
|
+
end = i;
|
|
1785
|
+
} else if (code === 59 || code === 44) {
|
|
1786
|
+
if (start === -1) {
|
|
1787
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1788
|
+
}
|
|
1789
|
+
if (end === -1)
|
|
1790
|
+
end = i;
|
|
1791
|
+
const name = header.slice(start, end);
|
|
1792
|
+
if (code === 44) {
|
|
1793
|
+
push(offers, name, params);
|
|
1794
|
+
params = Object.create(null);
|
|
1795
|
+
} else {
|
|
1796
|
+
extensionName = name;
|
|
1797
|
+
}
|
|
1798
|
+
start = end = -1;
|
|
1799
|
+
} else {
|
|
1800
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1801
|
+
}
|
|
1802
|
+
} else if (paramName === undefined) {
|
|
1803
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
1804
|
+
if (start === -1)
|
|
1805
|
+
start = i;
|
|
1806
|
+
} else if (code === 32 || code === 9) {
|
|
1807
|
+
if (end === -1 && start !== -1)
|
|
1808
|
+
end = i;
|
|
1809
|
+
} else if (code === 59 || code === 44) {
|
|
1810
|
+
if (start === -1) {
|
|
1811
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1812
|
+
}
|
|
1813
|
+
if (end === -1)
|
|
1814
|
+
end = i;
|
|
1815
|
+
push(params, header.slice(start, end), true);
|
|
1816
|
+
if (code === 44) {
|
|
1817
|
+
push(offers, extensionName, params);
|
|
1818
|
+
params = Object.create(null);
|
|
1819
|
+
extensionName = undefined;
|
|
1820
|
+
}
|
|
1821
|
+
start = end = -1;
|
|
1822
|
+
} else if (code === 61 && start !== -1 && end === -1) {
|
|
1823
|
+
paramName = header.slice(start, i);
|
|
1824
|
+
start = end = -1;
|
|
1825
|
+
} else {
|
|
1826
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1827
|
+
}
|
|
1828
|
+
} else {
|
|
1829
|
+
if (isEscaping) {
|
|
1830
|
+
if (tokenChars[code] !== 1) {
|
|
1831
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1832
|
+
}
|
|
1833
|
+
if (start === -1)
|
|
1834
|
+
start = i;
|
|
1835
|
+
else if (!mustUnescape)
|
|
1836
|
+
mustUnescape = true;
|
|
1837
|
+
isEscaping = false;
|
|
1838
|
+
} else if (inQuotes) {
|
|
1839
|
+
if (tokenChars[code] === 1) {
|
|
1840
|
+
if (start === -1)
|
|
1841
|
+
start = i;
|
|
1842
|
+
} else if (code === 34 && start !== -1) {
|
|
1843
|
+
inQuotes = false;
|
|
1844
|
+
end = i;
|
|
1845
|
+
} else if (code === 92) {
|
|
1846
|
+
isEscaping = true;
|
|
1847
|
+
} else {
|
|
1848
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1849
|
+
}
|
|
1850
|
+
} else if (code === 34 && header.charCodeAt(i - 1) === 61) {
|
|
1851
|
+
inQuotes = true;
|
|
1852
|
+
} else if (end === -1 && tokenChars[code] === 1) {
|
|
1853
|
+
if (start === -1)
|
|
1854
|
+
start = i;
|
|
1855
|
+
} else if (start !== -1 && (code === 32 || code === 9)) {
|
|
1856
|
+
if (end === -1)
|
|
1857
|
+
end = i;
|
|
1858
|
+
} else if (code === 59 || code === 44) {
|
|
1859
|
+
if (start === -1) {
|
|
1860
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1861
|
+
}
|
|
1862
|
+
if (end === -1)
|
|
1863
|
+
end = i;
|
|
1864
|
+
let value = header.slice(start, end);
|
|
1865
|
+
if (mustUnescape) {
|
|
1866
|
+
value = value.replace(/\\/g, "");
|
|
1867
|
+
mustUnescape = false;
|
|
1868
|
+
}
|
|
1869
|
+
push(params, paramName, value);
|
|
1870
|
+
if (code === 44) {
|
|
1871
|
+
push(offers, extensionName, params);
|
|
1872
|
+
params = Object.create(null);
|
|
1873
|
+
extensionName = undefined;
|
|
1874
|
+
}
|
|
1875
|
+
paramName = undefined;
|
|
1876
|
+
start = end = -1;
|
|
1877
|
+
} else {
|
|
1878
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
if (start === -1 || inQuotes || code === 32 || code === 9) {
|
|
1883
|
+
throw new SyntaxError("Unexpected end of input");
|
|
1884
|
+
}
|
|
1885
|
+
if (end === -1)
|
|
1886
|
+
end = i;
|
|
1887
|
+
const token = header.slice(start, end);
|
|
1888
|
+
if (extensionName === undefined) {
|
|
1889
|
+
push(offers, token, params);
|
|
1890
|
+
} else {
|
|
1891
|
+
if (paramName === undefined) {
|
|
1892
|
+
push(params, token, true);
|
|
1893
|
+
} else if (mustUnescape) {
|
|
1894
|
+
push(params, paramName, token.replace(/\\/g, ""));
|
|
1895
|
+
} else {
|
|
1896
|
+
push(params, paramName, token);
|
|
1897
|
+
}
|
|
1898
|
+
push(offers, extensionName, params);
|
|
1899
|
+
}
|
|
1900
|
+
return offers;
|
|
1901
|
+
}
|
|
1902
|
+
function format(extensions) {
|
|
1903
|
+
return Object.keys(extensions).map((extension) => {
|
|
1904
|
+
let configurations = extensions[extension];
|
|
1905
|
+
if (!Array.isArray(configurations))
|
|
1906
|
+
configurations = [configurations];
|
|
1907
|
+
return configurations.map((params) => {
|
|
1908
|
+
return [extension].concat(Object.keys(params).map((k) => {
|
|
1909
|
+
let values = params[k];
|
|
1910
|
+
if (!Array.isArray(values))
|
|
1911
|
+
values = [values];
|
|
1912
|
+
return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
|
|
1913
|
+
})).join("; ");
|
|
1914
|
+
}).join(", ");
|
|
1915
|
+
}).join(", ");
|
|
1916
|
+
}
|
|
1917
|
+
module.exports = { format, parse };
|
|
1918
|
+
});
|
|
1919
|
+
|
|
1920
|
+
// ../../../node_modules/ws/lib/websocket.js
|
|
1921
|
+
var require_websocket = __commonJS((exports, module) => {
|
|
1922
|
+
var EventEmitter = __require("events");
|
|
1923
|
+
var https = __require("https");
|
|
1924
|
+
var http = __require("http");
|
|
1925
|
+
var net = __require("net");
|
|
1926
|
+
var tls = __require("tls");
|
|
1927
|
+
var { randomBytes, createHash } = __require("crypto");
|
|
1928
|
+
var { Duplex, Readable } = __require("stream");
|
|
1929
|
+
var { URL } = __require("url");
|
|
1930
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
1931
|
+
var Receiver = require_receiver();
|
|
1932
|
+
var Sender = require_sender();
|
|
1933
|
+
var { isBlob } = require_validation();
|
|
1934
|
+
var {
|
|
1935
|
+
BINARY_TYPES,
|
|
1936
|
+
CLOSE_TIMEOUT,
|
|
1937
|
+
EMPTY_BUFFER,
|
|
1938
|
+
GUID,
|
|
1939
|
+
kForOnEventAttribute,
|
|
1940
|
+
kListener,
|
|
1941
|
+
kStatusCode,
|
|
1942
|
+
kWebSocket,
|
|
1943
|
+
NOOP
|
|
1944
|
+
} = require_constants();
|
|
1945
|
+
var {
|
|
1946
|
+
EventTarget: { addEventListener, removeEventListener }
|
|
1947
|
+
} = require_event_target();
|
|
1948
|
+
var { format, parse } = require_extension();
|
|
1949
|
+
var { toBuffer } = require_buffer_util();
|
|
1950
|
+
var kAborted = Symbol("kAborted");
|
|
1951
|
+
var protocolVersions = [8, 13];
|
|
1952
|
+
var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
|
|
1953
|
+
var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
|
|
1954
|
+
|
|
1955
|
+
class WebSocket extends EventEmitter {
|
|
1956
|
+
constructor(address, protocols, options) {
|
|
1957
|
+
super();
|
|
1958
|
+
this._binaryType = BINARY_TYPES[0];
|
|
1959
|
+
this._closeCode = 1006;
|
|
1960
|
+
this._closeFrameReceived = false;
|
|
1961
|
+
this._closeFrameSent = false;
|
|
1962
|
+
this._closeMessage = EMPTY_BUFFER;
|
|
1963
|
+
this._closeTimer = null;
|
|
1964
|
+
this._errorEmitted = false;
|
|
1965
|
+
this._extensions = {};
|
|
1966
|
+
this._paused = false;
|
|
1967
|
+
this._protocol = "";
|
|
1968
|
+
this._readyState = WebSocket.CONNECTING;
|
|
1969
|
+
this._receiver = null;
|
|
1970
|
+
this._sender = null;
|
|
1971
|
+
this._socket = null;
|
|
1972
|
+
if (address !== null) {
|
|
1973
|
+
this._bufferedAmount = 0;
|
|
1974
|
+
this._isServer = false;
|
|
1975
|
+
this._redirects = 0;
|
|
1976
|
+
if (protocols === undefined) {
|
|
1977
|
+
protocols = [];
|
|
1978
|
+
} else if (!Array.isArray(protocols)) {
|
|
1979
|
+
if (typeof protocols === "object" && protocols !== null) {
|
|
1980
|
+
options = protocols;
|
|
1981
|
+
protocols = [];
|
|
1982
|
+
} else {
|
|
1983
|
+
protocols = [protocols];
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
initAsClient(this, address, protocols, options);
|
|
1987
|
+
} else {
|
|
1988
|
+
this._autoPong = options.autoPong;
|
|
1989
|
+
this._closeTimeout = options.closeTimeout;
|
|
1990
|
+
this._isServer = true;
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
get binaryType() {
|
|
1994
|
+
return this._binaryType;
|
|
1995
|
+
}
|
|
1996
|
+
set binaryType(type) {
|
|
1997
|
+
if (!BINARY_TYPES.includes(type))
|
|
1998
|
+
return;
|
|
1999
|
+
this._binaryType = type;
|
|
2000
|
+
if (this._receiver)
|
|
2001
|
+
this._receiver._binaryType = type;
|
|
2002
|
+
}
|
|
2003
|
+
get bufferedAmount() {
|
|
2004
|
+
if (!this._socket)
|
|
2005
|
+
return this._bufferedAmount;
|
|
2006
|
+
return this._socket._writableState.length + this._sender._bufferedBytes;
|
|
2007
|
+
}
|
|
2008
|
+
get extensions() {
|
|
2009
|
+
return Object.keys(this._extensions).join();
|
|
2010
|
+
}
|
|
2011
|
+
get isPaused() {
|
|
2012
|
+
return this._paused;
|
|
2013
|
+
}
|
|
2014
|
+
get onclose() {
|
|
2015
|
+
return null;
|
|
2016
|
+
}
|
|
2017
|
+
get onerror() {
|
|
2018
|
+
return null;
|
|
2019
|
+
}
|
|
2020
|
+
get onopen() {
|
|
2021
|
+
return null;
|
|
2022
|
+
}
|
|
2023
|
+
get onmessage() {
|
|
2024
|
+
return null;
|
|
2025
|
+
}
|
|
2026
|
+
get protocol() {
|
|
2027
|
+
return this._protocol;
|
|
2028
|
+
}
|
|
2029
|
+
get readyState() {
|
|
2030
|
+
return this._readyState;
|
|
2031
|
+
}
|
|
2032
|
+
get url() {
|
|
2033
|
+
return this._url;
|
|
2034
|
+
}
|
|
2035
|
+
setSocket(socket, head, options) {
|
|
2036
|
+
const receiver = new Receiver({
|
|
2037
|
+
allowSynchronousEvents: options.allowSynchronousEvents,
|
|
2038
|
+
binaryType: this.binaryType,
|
|
2039
|
+
extensions: this._extensions,
|
|
2040
|
+
isServer: this._isServer,
|
|
2041
|
+
maxPayload: options.maxPayload,
|
|
2042
|
+
skipUTF8Validation: options.skipUTF8Validation
|
|
2043
|
+
});
|
|
2044
|
+
const sender = new Sender(socket, this._extensions, options.generateMask);
|
|
2045
|
+
this._receiver = receiver;
|
|
2046
|
+
this._sender = sender;
|
|
2047
|
+
this._socket = socket;
|
|
2048
|
+
receiver[kWebSocket] = this;
|
|
2049
|
+
sender[kWebSocket] = this;
|
|
2050
|
+
socket[kWebSocket] = this;
|
|
2051
|
+
receiver.on("conclude", receiverOnConclude);
|
|
2052
|
+
receiver.on("drain", receiverOnDrain);
|
|
2053
|
+
receiver.on("error", receiverOnError);
|
|
2054
|
+
receiver.on("message", receiverOnMessage);
|
|
2055
|
+
receiver.on("ping", receiverOnPing);
|
|
2056
|
+
receiver.on("pong", receiverOnPong);
|
|
2057
|
+
sender.onerror = senderOnError;
|
|
2058
|
+
if (socket.setTimeout)
|
|
2059
|
+
socket.setTimeout(0);
|
|
2060
|
+
if (socket.setNoDelay)
|
|
2061
|
+
socket.setNoDelay();
|
|
2062
|
+
if (head.length > 0)
|
|
2063
|
+
socket.unshift(head);
|
|
2064
|
+
socket.on("close", socketOnClose);
|
|
2065
|
+
socket.on("data", socketOnData);
|
|
2066
|
+
socket.on("end", socketOnEnd);
|
|
2067
|
+
socket.on("error", socketOnError);
|
|
2068
|
+
this._readyState = WebSocket.OPEN;
|
|
2069
|
+
this.emit("open");
|
|
2070
|
+
}
|
|
2071
|
+
emitClose() {
|
|
2072
|
+
if (!this._socket) {
|
|
2073
|
+
this._readyState = WebSocket.CLOSED;
|
|
2074
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
2075
|
+
return;
|
|
2076
|
+
}
|
|
2077
|
+
if (this._extensions[PerMessageDeflate.extensionName]) {
|
|
2078
|
+
this._extensions[PerMessageDeflate.extensionName].cleanup();
|
|
2079
|
+
}
|
|
2080
|
+
this._receiver.removeAllListeners();
|
|
2081
|
+
this._readyState = WebSocket.CLOSED;
|
|
2082
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
2083
|
+
}
|
|
2084
|
+
close(code, data) {
|
|
2085
|
+
if (this.readyState === WebSocket.CLOSED)
|
|
2086
|
+
return;
|
|
2087
|
+
if (this.readyState === WebSocket.CONNECTING) {
|
|
2088
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
2089
|
+
abortHandshake(this, this._req, msg);
|
|
2090
|
+
return;
|
|
2091
|
+
}
|
|
2092
|
+
if (this.readyState === WebSocket.CLOSING) {
|
|
2093
|
+
if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
|
|
2094
|
+
this._socket.end();
|
|
2095
|
+
}
|
|
2096
|
+
return;
|
|
2097
|
+
}
|
|
2098
|
+
this._readyState = WebSocket.CLOSING;
|
|
2099
|
+
this._sender.close(code, data, !this._isServer, (err) => {
|
|
2100
|
+
if (err)
|
|
2101
|
+
return;
|
|
2102
|
+
this._closeFrameSent = true;
|
|
2103
|
+
if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
|
|
2104
|
+
this._socket.end();
|
|
2105
|
+
}
|
|
2106
|
+
});
|
|
2107
|
+
setCloseTimer(this);
|
|
2108
|
+
}
|
|
2109
|
+
pause() {
|
|
2110
|
+
if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
|
|
2111
|
+
return;
|
|
2112
|
+
}
|
|
2113
|
+
this._paused = true;
|
|
2114
|
+
this._socket.pause();
|
|
2115
|
+
}
|
|
2116
|
+
ping(data, mask, cb) {
|
|
2117
|
+
if (this.readyState === WebSocket.CONNECTING) {
|
|
2118
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2119
|
+
}
|
|
2120
|
+
if (typeof data === "function") {
|
|
2121
|
+
cb = data;
|
|
2122
|
+
data = mask = undefined;
|
|
2123
|
+
} else if (typeof mask === "function") {
|
|
2124
|
+
cb = mask;
|
|
2125
|
+
mask = undefined;
|
|
2126
|
+
}
|
|
2127
|
+
if (typeof data === "number")
|
|
2128
|
+
data = data.toString();
|
|
2129
|
+
if (this.readyState !== WebSocket.OPEN) {
|
|
2130
|
+
sendAfterClose(this, data, cb);
|
|
2131
|
+
return;
|
|
2132
|
+
}
|
|
2133
|
+
if (mask === undefined)
|
|
2134
|
+
mask = !this._isServer;
|
|
2135
|
+
this._sender.ping(data || EMPTY_BUFFER, mask, cb);
|
|
2136
|
+
}
|
|
2137
|
+
pong(data, mask, cb) {
|
|
2138
|
+
if (this.readyState === WebSocket.CONNECTING) {
|
|
2139
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2140
|
+
}
|
|
2141
|
+
if (typeof data === "function") {
|
|
2142
|
+
cb = data;
|
|
2143
|
+
data = mask = undefined;
|
|
2144
|
+
} else if (typeof mask === "function") {
|
|
2145
|
+
cb = mask;
|
|
2146
|
+
mask = undefined;
|
|
2147
|
+
}
|
|
2148
|
+
if (typeof data === "number")
|
|
2149
|
+
data = data.toString();
|
|
2150
|
+
if (this.readyState !== WebSocket.OPEN) {
|
|
2151
|
+
sendAfterClose(this, data, cb);
|
|
2152
|
+
return;
|
|
2153
|
+
}
|
|
2154
|
+
if (mask === undefined)
|
|
2155
|
+
mask = !this._isServer;
|
|
2156
|
+
this._sender.pong(data || EMPTY_BUFFER, mask, cb);
|
|
2157
|
+
}
|
|
2158
|
+
resume() {
|
|
2159
|
+
if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
|
|
2160
|
+
return;
|
|
2161
|
+
}
|
|
2162
|
+
this._paused = false;
|
|
2163
|
+
if (!this._receiver._writableState.needDrain)
|
|
2164
|
+
this._socket.resume();
|
|
2165
|
+
}
|
|
2166
|
+
send(data, options, cb) {
|
|
2167
|
+
if (this.readyState === WebSocket.CONNECTING) {
|
|
2168
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
2169
|
+
}
|
|
2170
|
+
if (typeof options === "function") {
|
|
2171
|
+
cb = options;
|
|
2172
|
+
options = {};
|
|
2173
|
+
}
|
|
2174
|
+
if (typeof data === "number")
|
|
2175
|
+
data = data.toString();
|
|
2176
|
+
if (this.readyState !== WebSocket.OPEN) {
|
|
2177
|
+
sendAfterClose(this, data, cb);
|
|
2178
|
+
return;
|
|
2179
|
+
}
|
|
2180
|
+
const opts = {
|
|
2181
|
+
binary: typeof data !== "string",
|
|
2182
|
+
mask: !this._isServer,
|
|
2183
|
+
compress: true,
|
|
2184
|
+
fin: true,
|
|
2185
|
+
...options
|
|
2186
|
+
};
|
|
2187
|
+
if (!this._extensions[PerMessageDeflate.extensionName]) {
|
|
2188
|
+
opts.compress = false;
|
|
2189
|
+
}
|
|
2190
|
+
this._sender.send(data || EMPTY_BUFFER, opts, cb);
|
|
2191
|
+
}
|
|
2192
|
+
terminate() {
|
|
2193
|
+
if (this.readyState === WebSocket.CLOSED)
|
|
2194
|
+
return;
|
|
2195
|
+
if (this.readyState === WebSocket.CONNECTING) {
|
|
2196
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
2197
|
+
abortHandshake(this, this._req, msg);
|
|
2198
|
+
return;
|
|
2199
|
+
}
|
|
2200
|
+
if (this._socket) {
|
|
2201
|
+
this._readyState = WebSocket.CLOSING;
|
|
2202
|
+
this._socket.destroy();
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
}
|
|
2206
|
+
Object.defineProperty(WebSocket, "CONNECTING", {
|
|
2207
|
+
enumerable: true,
|
|
2208
|
+
value: readyStates.indexOf("CONNECTING")
|
|
2209
|
+
});
|
|
2210
|
+
Object.defineProperty(WebSocket.prototype, "CONNECTING", {
|
|
2211
|
+
enumerable: true,
|
|
2212
|
+
value: readyStates.indexOf("CONNECTING")
|
|
2213
|
+
});
|
|
2214
|
+
Object.defineProperty(WebSocket, "OPEN", {
|
|
2215
|
+
enumerable: true,
|
|
2216
|
+
value: readyStates.indexOf("OPEN")
|
|
2217
|
+
});
|
|
2218
|
+
Object.defineProperty(WebSocket.prototype, "OPEN", {
|
|
2219
|
+
enumerable: true,
|
|
2220
|
+
value: readyStates.indexOf("OPEN")
|
|
2221
|
+
});
|
|
2222
|
+
Object.defineProperty(WebSocket, "CLOSING", {
|
|
2223
|
+
enumerable: true,
|
|
2224
|
+
value: readyStates.indexOf("CLOSING")
|
|
2225
|
+
});
|
|
2226
|
+
Object.defineProperty(WebSocket.prototype, "CLOSING", {
|
|
2227
|
+
enumerable: true,
|
|
2228
|
+
value: readyStates.indexOf("CLOSING")
|
|
2229
|
+
});
|
|
2230
|
+
Object.defineProperty(WebSocket, "CLOSED", {
|
|
2231
|
+
enumerable: true,
|
|
2232
|
+
value: readyStates.indexOf("CLOSED")
|
|
2233
|
+
});
|
|
2234
|
+
Object.defineProperty(WebSocket.prototype, "CLOSED", {
|
|
2235
|
+
enumerable: true,
|
|
2236
|
+
value: readyStates.indexOf("CLOSED")
|
|
2237
|
+
});
|
|
2238
|
+
[
|
|
2239
|
+
"binaryType",
|
|
2240
|
+
"bufferedAmount",
|
|
2241
|
+
"extensions",
|
|
2242
|
+
"isPaused",
|
|
2243
|
+
"protocol",
|
|
2244
|
+
"readyState",
|
|
2245
|
+
"url"
|
|
2246
|
+
].forEach((property) => {
|
|
2247
|
+
Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
|
|
2248
|
+
});
|
|
2249
|
+
["open", "error", "close", "message"].forEach((method) => {
|
|
2250
|
+
Object.defineProperty(WebSocket.prototype, `on${method}`, {
|
|
2251
|
+
enumerable: true,
|
|
2252
|
+
get() {
|
|
2253
|
+
for (const listener of this.listeners(method)) {
|
|
2254
|
+
if (listener[kForOnEventAttribute])
|
|
2255
|
+
return listener[kListener];
|
|
2256
|
+
}
|
|
2257
|
+
return null;
|
|
2258
|
+
},
|
|
2259
|
+
set(handler) {
|
|
2260
|
+
for (const listener of this.listeners(method)) {
|
|
2261
|
+
if (listener[kForOnEventAttribute]) {
|
|
2262
|
+
this.removeListener(method, listener);
|
|
2263
|
+
break;
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
if (typeof handler !== "function")
|
|
2267
|
+
return;
|
|
2268
|
+
this.addEventListener(method, handler, {
|
|
2269
|
+
[kForOnEventAttribute]: true
|
|
2270
|
+
});
|
|
2271
|
+
}
|
|
2272
|
+
});
|
|
2273
|
+
});
|
|
2274
|
+
WebSocket.prototype.addEventListener = addEventListener;
|
|
2275
|
+
WebSocket.prototype.removeEventListener = removeEventListener;
|
|
2276
|
+
module.exports = WebSocket;
|
|
2277
|
+
function initAsClient(websocket, address, protocols, options) {
|
|
2278
|
+
const opts = {
|
|
2279
|
+
allowSynchronousEvents: true,
|
|
2280
|
+
autoPong: true,
|
|
2281
|
+
closeTimeout: CLOSE_TIMEOUT,
|
|
2282
|
+
protocolVersion: protocolVersions[1],
|
|
2283
|
+
maxPayload: 100 * 1024 * 1024,
|
|
2284
|
+
skipUTF8Validation: false,
|
|
2285
|
+
perMessageDeflate: true,
|
|
2286
|
+
followRedirects: false,
|
|
2287
|
+
maxRedirects: 10,
|
|
2288
|
+
...options,
|
|
2289
|
+
socketPath: undefined,
|
|
2290
|
+
hostname: undefined,
|
|
2291
|
+
protocol: undefined,
|
|
2292
|
+
timeout: undefined,
|
|
2293
|
+
method: "GET",
|
|
2294
|
+
host: undefined,
|
|
2295
|
+
path: undefined,
|
|
2296
|
+
port: undefined
|
|
2297
|
+
};
|
|
2298
|
+
websocket._autoPong = opts.autoPong;
|
|
2299
|
+
websocket._closeTimeout = opts.closeTimeout;
|
|
2300
|
+
if (!protocolVersions.includes(opts.protocolVersion)) {
|
|
2301
|
+
throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(", ")})`);
|
|
2302
|
+
}
|
|
2303
|
+
let parsedUrl;
|
|
2304
|
+
if (address instanceof URL) {
|
|
2305
|
+
parsedUrl = address;
|
|
2306
|
+
} else {
|
|
2307
|
+
try {
|
|
2308
|
+
parsedUrl = new URL(address);
|
|
2309
|
+
} catch (e) {
|
|
2310
|
+
throw new SyntaxError(`Invalid URL: ${address}`);
|
|
2311
|
+
}
|
|
2312
|
+
}
|
|
2313
|
+
if (parsedUrl.protocol === "http:") {
|
|
2314
|
+
parsedUrl.protocol = "ws:";
|
|
2315
|
+
} else if (parsedUrl.protocol === "https:") {
|
|
2316
|
+
parsedUrl.protocol = "wss:";
|
|
2317
|
+
}
|
|
2318
|
+
websocket._url = parsedUrl.href;
|
|
2319
|
+
const isSecure = parsedUrl.protocol === "wss:";
|
|
2320
|
+
const isIpcUrl = parsedUrl.protocol === "ws+unix:";
|
|
2321
|
+
let invalidUrlMessage;
|
|
2322
|
+
if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
|
|
2323
|
+
invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", ` + '"http:", "https:", or "ws+unix:"';
|
|
2324
|
+
} else if (isIpcUrl && !parsedUrl.pathname) {
|
|
2325
|
+
invalidUrlMessage = "The URL's pathname is empty";
|
|
2326
|
+
} else if (parsedUrl.hash) {
|
|
2327
|
+
invalidUrlMessage = "The URL contains a fragment identifier";
|
|
2328
|
+
}
|
|
2329
|
+
if (invalidUrlMessage) {
|
|
2330
|
+
const err = new SyntaxError(invalidUrlMessage);
|
|
2331
|
+
if (websocket._redirects === 0) {
|
|
2332
|
+
throw err;
|
|
2333
|
+
} else {
|
|
2334
|
+
emitErrorAndClose(websocket, err);
|
|
2335
|
+
return;
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
const defaultPort = isSecure ? 443 : 80;
|
|
2339
|
+
const key = randomBytes(16).toString("base64");
|
|
2340
|
+
const request = isSecure ? https.request : http.request;
|
|
2341
|
+
const protocolSet = new Set;
|
|
2342
|
+
let perMessageDeflate;
|
|
2343
|
+
opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
|
|
2344
|
+
opts.defaultPort = opts.defaultPort || defaultPort;
|
|
2345
|
+
opts.port = parsedUrl.port || defaultPort;
|
|
2346
|
+
opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
|
|
2347
|
+
opts.headers = {
|
|
2348
|
+
...opts.headers,
|
|
2349
|
+
"Sec-WebSocket-Version": opts.protocolVersion,
|
|
2350
|
+
"Sec-WebSocket-Key": key,
|
|
2351
|
+
Connection: "Upgrade",
|
|
2352
|
+
Upgrade: "websocket"
|
|
2353
|
+
};
|
|
2354
|
+
opts.path = parsedUrl.pathname + parsedUrl.search;
|
|
2355
|
+
opts.timeout = opts.handshakeTimeout;
|
|
2356
|
+
if (opts.perMessageDeflate) {
|
|
2357
|
+
perMessageDeflate = new PerMessageDeflate(opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload);
|
|
2358
|
+
opts.headers["Sec-WebSocket-Extensions"] = format({
|
|
2359
|
+
[PerMessageDeflate.extensionName]: perMessageDeflate.offer()
|
|
2360
|
+
});
|
|
2361
|
+
}
|
|
2362
|
+
if (protocols.length) {
|
|
2363
|
+
for (const protocol of protocols) {
|
|
2364
|
+
if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
|
|
2365
|
+
throw new SyntaxError("An invalid or duplicated subprotocol was specified");
|
|
2366
|
+
}
|
|
2367
|
+
protocolSet.add(protocol);
|
|
2368
|
+
}
|
|
2369
|
+
opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
|
|
2370
|
+
}
|
|
2371
|
+
if (opts.origin) {
|
|
2372
|
+
if (opts.protocolVersion < 13) {
|
|
2373
|
+
opts.headers["Sec-WebSocket-Origin"] = opts.origin;
|
|
2374
|
+
} else {
|
|
2375
|
+
opts.headers.Origin = opts.origin;
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
if (parsedUrl.username || parsedUrl.password) {
|
|
2379
|
+
opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
|
|
2380
|
+
}
|
|
2381
|
+
if (isIpcUrl) {
|
|
2382
|
+
const parts = opts.path.split(":");
|
|
2383
|
+
opts.socketPath = parts[0];
|
|
2384
|
+
opts.path = parts[1];
|
|
2385
|
+
}
|
|
2386
|
+
let req;
|
|
2387
|
+
if (opts.followRedirects) {
|
|
2388
|
+
if (websocket._redirects === 0) {
|
|
2389
|
+
websocket._originalIpc = isIpcUrl;
|
|
2390
|
+
websocket._originalSecure = isSecure;
|
|
2391
|
+
websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
|
|
2392
|
+
const headers = options && options.headers;
|
|
2393
|
+
options = { ...options, headers: {} };
|
|
2394
|
+
if (headers) {
|
|
2395
|
+
for (const [key2, value] of Object.entries(headers)) {
|
|
2396
|
+
options.headers[key2.toLowerCase()] = value;
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
} else if (websocket.listenerCount("redirect") === 0) {
|
|
2400
|
+
const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
|
|
2401
|
+
if (!isSameHost || websocket._originalSecure && !isSecure) {
|
|
2402
|
+
delete opts.headers.authorization;
|
|
2403
|
+
delete opts.headers.cookie;
|
|
2404
|
+
if (!isSameHost)
|
|
2405
|
+
delete opts.headers.host;
|
|
2406
|
+
opts.auth = undefined;
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
if (opts.auth && !options.headers.authorization) {
|
|
2410
|
+
options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
|
|
2411
|
+
}
|
|
2412
|
+
req = websocket._req = request(opts);
|
|
2413
|
+
if (websocket._redirects) {
|
|
2414
|
+
websocket.emit("redirect", websocket.url, req);
|
|
2415
|
+
}
|
|
2416
|
+
} else {
|
|
2417
|
+
req = websocket._req = request(opts);
|
|
2418
|
+
}
|
|
2419
|
+
if (opts.timeout) {
|
|
2420
|
+
req.on("timeout", () => {
|
|
2421
|
+
abortHandshake(websocket, req, "Opening handshake has timed out");
|
|
2422
|
+
});
|
|
2423
|
+
}
|
|
2424
|
+
req.on("error", (err) => {
|
|
2425
|
+
if (req === null || req[kAborted])
|
|
2426
|
+
return;
|
|
2427
|
+
req = websocket._req = null;
|
|
2428
|
+
emitErrorAndClose(websocket, err);
|
|
2429
|
+
});
|
|
2430
|
+
req.on("response", (res) => {
|
|
2431
|
+
const location = res.headers.location;
|
|
2432
|
+
const statusCode = res.statusCode;
|
|
2433
|
+
if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
|
|
2434
|
+
if (++websocket._redirects > opts.maxRedirects) {
|
|
2435
|
+
abortHandshake(websocket, req, "Maximum redirects exceeded");
|
|
2436
|
+
return;
|
|
2437
|
+
}
|
|
2438
|
+
req.abort();
|
|
2439
|
+
let addr;
|
|
2440
|
+
try {
|
|
2441
|
+
addr = new URL(location, address);
|
|
2442
|
+
} catch (e) {
|
|
2443
|
+
const err = new SyntaxError(`Invalid URL: ${location}`);
|
|
2444
|
+
emitErrorAndClose(websocket, err);
|
|
2445
|
+
return;
|
|
2446
|
+
}
|
|
2447
|
+
initAsClient(websocket, addr, protocols, options);
|
|
2448
|
+
} else if (!websocket.emit("unexpected-response", req, res)) {
|
|
2449
|
+
abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
|
|
2450
|
+
}
|
|
2451
|
+
});
|
|
2452
|
+
req.on("upgrade", (res, socket, head) => {
|
|
2453
|
+
websocket.emit("upgrade", res);
|
|
2454
|
+
if (websocket.readyState !== WebSocket.CONNECTING)
|
|
2455
|
+
return;
|
|
2456
|
+
req = websocket._req = null;
|
|
2457
|
+
const upgrade = res.headers.upgrade;
|
|
2458
|
+
if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
|
|
2459
|
+
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
2460
|
+
return;
|
|
2461
|
+
}
|
|
2462
|
+
const digest = createHash("sha1").update(key + GUID).digest("base64");
|
|
2463
|
+
if (res.headers["sec-websocket-accept"] !== digest) {
|
|
2464
|
+
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
2465
|
+
return;
|
|
2466
|
+
}
|
|
2467
|
+
const serverProt = res.headers["sec-websocket-protocol"];
|
|
2468
|
+
let protError;
|
|
2469
|
+
if (serverProt !== undefined) {
|
|
2470
|
+
if (!protocolSet.size) {
|
|
2471
|
+
protError = "Server sent a subprotocol but none was requested";
|
|
2472
|
+
} else if (!protocolSet.has(serverProt)) {
|
|
2473
|
+
protError = "Server sent an invalid subprotocol";
|
|
2474
|
+
}
|
|
2475
|
+
} else if (protocolSet.size) {
|
|
2476
|
+
protError = "Server sent no subprotocol";
|
|
2477
|
+
}
|
|
2478
|
+
if (protError) {
|
|
2479
|
+
abortHandshake(websocket, socket, protError);
|
|
2480
|
+
return;
|
|
2481
|
+
}
|
|
2482
|
+
if (serverProt)
|
|
2483
|
+
websocket._protocol = serverProt;
|
|
2484
|
+
const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
|
|
2485
|
+
if (secWebSocketExtensions !== undefined) {
|
|
2486
|
+
if (!perMessageDeflate) {
|
|
2487
|
+
const message = "Server sent a Sec-WebSocket-Extensions header but no extension " + "was requested";
|
|
2488
|
+
abortHandshake(websocket, socket, message);
|
|
2489
|
+
return;
|
|
2490
|
+
}
|
|
2491
|
+
let extensions;
|
|
2492
|
+
try {
|
|
2493
|
+
extensions = parse(secWebSocketExtensions);
|
|
2494
|
+
} catch (err) {
|
|
2495
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
2496
|
+
abortHandshake(websocket, socket, message);
|
|
2497
|
+
return;
|
|
2498
|
+
}
|
|
2499
|
+
const extensionNames = Object.keys(extensions);
|
|
2500
|
+
if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
|
|
2501
|
+
const message = "Server indicated an extension that was not requested";
|
|
2502
|
+
abortHandshake(websocket, socket, message);
|
|
2503
|
+
return;
|
|
2504
|
+
}
|
|
2505
|
+
try {
|
|
2506
|
+
perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
|
|
2507
|
+
} catch (err) {
|
|
2508
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
2509
|
+
abortHandshake(websocket, socket, message);
|
|
2510
|
+
return;
|
|
2511
|
+
}
|
|
2512
|
+
websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
|
|
2513
|
+
}
|
|
2514
|
+
websocket.setSocket(socket, head, {
|
|
2515
|
+
allowSynchronousEvents: opts.allowSynchronousEvents,
|
|
2516
|
+
generateMask: opts.generateMask,
|
|
2517
|
+
maxPayload: opts.maxPayload,
|
|
2518
|
+
skipUTF8Validation: opts.skipUTF8Validation
|
|
2519
|
+
});
|
|
2520
|
+
});
|
|
2521
|
+
if (opts.finishRequest) {
|
|
2522
|
+
opts.finishRequest(req, websocket);
|
|
2523
|
+
} else {
|
|
2524
|
+
req.end();
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
function emitErrorAndClose(websocket, err) {
|
|
2528
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2529
|
+
websocket._errorEmitted = true;
|
|
2530
|
+
websocket.emit("error", err);
|
|
2531
|
+
websocket.emitClose();
|
|
2532
|
+
}
|
|
2533
|
+
function netConnect(options) {
|
|
2534
|
+
options.path = options.socketPath;
|
|
2535
|
+
return net.connect(options);
|
|
2536
|
+
}
|
|
2537
|
+
function tlsConnect(options) {
|
|
2538
|
+
options.path = undefined;
|
|
2539
|
+
if (!options.servername && options.servername !== "") {
|
|
2540
|
+
options.servername = net.isIP(options.host) ? "" : options.host;
|
|
2541
|
+
}
|
|
2542
|
+
return tls.connect(options);
|
|
2543
|
+
}
|
|
2544
|
+
function abortHandshake(websocket, stream, message) {
|
|
2545
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2546
|
+
const err = new Error(message);
|
|
2547
|
+
Error.captureStackTrace(err, abortHandshake);
|
|
2548
|
+
if (stream.setHeader) {
|
|
2549
|
+
stream[kAborted] = true;
|
|
2550
|
+
stream.abort();
|
|
2551
|
+
if (stream.socket && !stream.socket.destroyed) {
|
|
2552
|
+
stream.socket.destroy();
|
|
2553
|
+
}
|
|
2554
|
+
process.nextTick(emitErrorAndClose, websocket, err);
|
|
2555
|
+
} else {
|
|
2556
|
+
stream.destroy(err);
|
|
2557
|
+
stream.once("error", websocket.emit.bind(websocket, "error"));
|
|
2558
|
+
stream.once("close", websocket.emitClose.bind(websocket));
|
|
2559
|
+
}
|
|
2560
|
+
}
|
|
2561
|
+
function sendAfterClose(websocket, data, cb) {
|
|
2562
|
+
if (data) {
|
|
2563
|
+
const length = isBlob(data) ? data.size : toBuffer(data).length;
|
|
2564
|
+
if (websocket._socket)
|
|
2565
|
+
websocket._sender._bufferedBytes += length;
|
|
2566
|
+
else
|
|
2567
|
+
websocket._bufferedAmount += length;
|
|
2568
|
+
}
|
|
2569
|
+
if (cb) {
|
|
2570
|
+
const err = new Error(`WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})`);
|
|
2571
|
+
process.nextTick(cb, err);
|
|
2572
|
+
}
|
|
2573
|
+
}
|
|
2574
|
+
function receiverOnConclude(code, reason) {
|
|
2575
|
+
const websocket = this[kWebSocket];
|
|
2576
|
+
websocket._closeFrameReceived = true;
|
|
2577
|
+
websocket._closeMessage = reason;
|
|
2578
|
+
websocket._closeCode = code;
|
|
2579
|
+
if (websocket._socket[kWebSocket] === undefined)
|
|
2580
|
+
return;
|
|
2581
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
2582
|
+
process.nextTick(resume, websocket._socket);
|
|
2583
|
+
if (code === 1005)
|
|
2584
|
+
websocket.close();
|
|
2585
|
+
else
|
|
2586
|
+
websocket.close(code, reason);
|
|
2587
|
+
}
|
|
2588
|
+
function receiverOnDrain() {
|
|
2589
|
+
const websocket = this[kWebSocket];
|
|
2590
|
+
if (!websocket.isPaused)
|
|
2591
|
+
websocket._socket.resume();
|
|
2592
|
+
}
|
|
2593
|
+
function receiverOnError(err) {
|
|
2594
|
+
const websocket = this[kWebSocket];
|
|
2595
|
+
if (websocket._socket[kWebSocket] !== undefined) {
|
|
2596
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
2597
|
+
process.nextTick(resume, websocket._socket);
|
|
2598
|
+
websocket.close(err[kStatusCode]);
|
|
2599
|
+
}
|
|
2600
|
+
if (!websocket._errorEmitted) {
|
|
2601
|
+
websocket._errorEmitted = true;
|
|
2602
|
+
websocket.emit("error", err);
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
function receiverOnFinish() {
|
|
2606
|
+
this[kWebSocket].emitClose();
|
|
2607
|
+
}
|
|
2608
|
+
function receiverOnMessage(data, isBinary) {
|
|
2609
|
+
this[kWebSocket].emit("message", data, isBinary);
|
|
2610
|
+
}
|
|
2611
|
+
function receiverOnPing(data) {
|
|
2612
|
+
const websocket = this[kWebSocket];
|
|
2613
|
+
if (websocket._autoPong)
|
|
2614
|
+
websocket.pong(data, !this._isServer, NOOP);
|
|
2615
|
+
websocket.emit("ping", data);
|
|
2616
|
+
}
|
|
2617
|
+
function receiverOnPong(data) {
|
|
2618
|
+
this[kWebSocket].emit("pong", data);
|
|
2619
|
+
}
|
|
2620
|
+
function resume(stream) {
|
|
2621
|
+
stream.resume();
|
|
2622
|
+
}
|
|
2623
|
+
function senderOnError(err) {
|
|
2624
|
+
const websocket = this[kWebSocket];
|
|
2625
|
+
if (websocket.readyState === WebSocket.CLOSED)
|
|
2626
|
+
return;
|
|
2627
|
+
if (websocket.readyState === WebSocket.OPEN) {
|
|
2628
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2629
|
+
setCloseTimer(websocket);
|
|
2630
|
+
}
|
|
2631
|
+
this._socket.end();
|
|
2632
|
+
if (!websocket._errorEmitted) {
|
|
2633
|
+
websocket._errorEmitted = true;
|
|
2634
|
+
websocket.emit("error", err);
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
function setCloseTimer(websocket) {
|
|
2638
|
+
websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
|
|
2639
|
+
}
|
|
2640
|
+
function socketOnClose() {
|
|
2641
|
+
const websocket = this[kWebSocket];
|
|
2642
|
+
this.removeListener("close", socketOnClose);
|
|
2643
|
+
this.removeListener("data", socketOnData);
|
|
2644
|
+
this.removeListener("end", socketOnEnd);
|
|
2645
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2646
|
+
if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
|
|
2647
|
+
const chunk = this.read(this._readableState.length);
|
|
2648
|
+
websocket._receiver.write(chunk);
|
|
2649
|
+
}
|
|
2650
|
+
websocket._receiver.end();
|
|
2651
|
+
this[kWebSocket] = undefined;
|
|
2652
|
+
clearTimeout(websocket._closeTimer);
|
|
2653
|
+
if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
|
|
2654
|
+
websocket.emitClose();
|
|
2655
|
+
} else {
|
|
2656
|
+
websocket._receiver.on("error", receiverOnFinish);
|
|
2657
|
+
websocket._receiver.on("finish", receiverOnFinish);
|
|
2658
|
+
}
|
|
2659
|
+
}
|
|
2660
|
+
function socketOnData(chunk) {
|
|
2661
|
+
if (!this[kWebSocket]._receiver.write(chunk)) {
|
|
2662
|
+
this.pause();
|
|
2663
|
+
}
|
|
2664
|
+
}
|
|
2665
|
+
function socketOnEnd() {
|
|
2666
|
+
const websocket = this[kWebSocket];
|
|
2667
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2668
|
+
websocket._receiver.end();
|
|
2669
|
+
this.end();
|
|
2670
|
+
}
|
|
2671
|
+
function socketOnError() {
|
|
2672
|
+
const websocket = this[kWebSocket];
|
|
2673
|
+
this.removeListener("error", socketOnError);
|
|
2674
|
+
this.on("error", NOOP);
|
|
2675
|
+
if (websocket) {
|
|
2676
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2677
|
+
this.destroy();
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
});
|
|
2681
|
+
|
|
2682
|
+
// ../../../node_modules/ws/lib/stream.js
|
|
2683
|
+
var require_stream = __commonJS((exports, module) => {
|
|
2684
|
+
var WebSocket = require_websocket();
|
|
2685
|
+
var { Duplex } = __require("stream");
|
|
2686
|
+
function emitClose(stream) {
|
|
2687
|
+
stream.emit("close");
|
|
2688
|
+
}
|
|
2689
|
+
function duplexOnEnd() {
|
|
2690
|
+
if (!this.destroyed && this._writableState.finished) {
|
|
2691
|
+
this.destroy();
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
function duplexOnError(err) {
|
|
2695
|
+
this.removeListener("error", duplexOnError);
|
|
2696
|
+
this.destroy();
|
|
2697
|
+
if (this.listenerCount("error") === 0) {
|
|
2698
|
+
this.emit("error", err);
|
|
2699
|
+
}
|
|
2700
|
+
}
|
|
2701
|
+
function createWebSocketStream(ws, options) {
|
|
2702
|
+
let terminateOnDestroy = true;
|
|
2703
|
+
const duplex = new Duplex({
|
|
2704
|
+
...options,
|
|
2705
|
+
autoDestroy: false,
|
|
2706
|
+
emitClose: false,
|
|
2707
|
+
objectMode: false,
|
|
2708
|
+
writableObjectMode: false
|
|
2709
|
+
});
|
|
2710
|
+
ws.on("message", function message(msg, isBinary) {
|
|
2711
|
+
const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
|
|
2712
|
+
if (!duplex.push(data))
|
|
2713
|
+
ws.pause();
|
|
2714
|
+
});
|
|
2715
|
+
ws.once("error", function error(err) {
|
|
2716
|
+
if (duplex.destroyed)
|
|
2717
|
+
return;
|
|
2718
|
+
terminateOnDestroy = false;
|
|
2719
|
+
duplex.destroy(err);
|
|
2720
|
+
});
|
|
2721
|
+
ws.once("close", function close() {
|
|
2722
|
+
if (duplex.destroyed)
|
|
2723
|
+
return;
|
|
2724
|
+
duplex.push(null);
|
|
2725
|
+
});
|
|
2726
|
+
duplex._destroy = function(err, callback) {
|
|
2727
|
+
if (ws.readyState === ws.CLOSED) {
|
|
2728
|
+
callback(err);
|
|
2729
|
+
process.nextTick(emitClose, duplex);
|
|
2730
|
+
return;
|
|
2731
|
+
}
|
|
2732
|
+
let called = false;
|
|
2733
|
+
ws.once("error", function error(err2) {
|
|
2734
|
+
called = true;
|
|
2735
|
+
callback(err2);
|
|
2736
|
+
});
|
|
2737
|
+
ws.once("close", function close() {
|
|
2738
|
+
if (!called)
|
|
2739
|
+
callback(err);
|
|
2740
|
+
process.nextTick(emitClose, duplex);
|
|
2741
|
+
});
|
|
2742
|
+
if (terminateOnDestroy)
|
|
2743
|
+
ws.terminate();
|
|
2744
|
+
};
|
|
2745
|
+
duplex._final = function(callback) {
|
|
2746
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
2747
|
+
ws.once("open", function open() {
|
|
2748
|
+
duplex._final(callback);
|
|
2749
|
+
});
|
|
2750
|
+
return;
|
|
2751
|
+
}
|
|
2752
|
+
if (ws._socket === null)
|
|
2753
|
+
return;
|
|
2754
|
+
if (ws._socket._writableState.finished) {
|
|
2755
|
+
callback();
|
|
2756
|
+
if (duplex._readableState.endEmitted)
|
|
2757
|
+
duplex.destroy();
|
|
2758
|
+
} else {
|
|
2759
|
+
ws._socket.once("finish", function finish() {
|
|
2760
|
+
callback();
|
|
2761
|
+
});
|
|
2762
|
+
ws.close();
|
|
2763
|
+
}
|
|
2764
|
+
};
|
|
2765
|
+
duplex._read = function() {
|
|
2766
|
+
if (ws.isPaused)
|
|
2767
|
+
ws.resume();
|
|
2768
|
+
};
|
|
2769
|
+
duplex._write = function(chunk, encoding, callback) {
|
|
2770
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
2771
|
+
ws.once("open", function open() {
|
|
2772
|
+
duplex._write(chunk, encoding, callback);
|
|
2773
|
+
});
|
|
2774
|
+
return;
|
|
2775
|
+
}
|
|
2776
|
+
ws.send(chunk, callback);
|
|
2777
|
+
};
|
|
2778
|
+
duplex.on("end", duplexOnEnd);
|
|
2779
|
+
duplex.on("error", duplexOnError);
|
|
2780
|
+
return duplex;
|
|
2781
|
+
}
|
|
2782
|
+
module.exports = createWebSocketStream;
|
|
2783
|
+
});
|
|
2784
|
+
|
|
2785
|
+
// ../../../node_modules/ws/lib/subprotocol.js
|
|
2786
|
+
var require_subprotocol = __commonJS((exports, module) => {
|
|
2787
|
+
var { tokenChars } = require_validation();
|
|
2788
|
+
function parse(header) {
|
|
2789
|
+
const protocols = new Set;
|
|
2790
|
+
let start = -1;
|
|
2791
|
+
let end = -1;
|
|
2792
|
+
let i = 0;
|
|
2793
|
+
for (i;i < header.length; i++) {
|
|
2794
|
+
const code = header.charCodeAt(i);
|
|
2795
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
2796
|
+
if (start === -1)
|
|
2797
|
+
start = i;
|
|
2798
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
2799
|
+
if (end === -1 && start !== -1)
|
|
2800
|
+
end = i;
|
|
2801
|
+
} else if (code === 44) {
|
|
2802
|
+
if (start === -1) {
|
|
2803
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2804
|
+
}
|
|
2805
|
+
if (end === -1)
|
|
2806
|
+
end = i;
|
|
2807
|
+
const protocol2 = header.slice(start, end);
|
|
2808
|
+
if (protocols.has(protocol2)) {
|
|
2809
|
+
throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
|
|
2810
|
+
}
|
|
2811
|
+
protocols.add(protocol2);
|
|
2812
|
+
start = end = -1;
|
|
2813
|
+
} else {
|
|
2814
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2817
|
+
if (start === -1 || end !== -1) {
|
|
2818
|
+
throw new SyntaxError("Unexpected end of input");
|
|
2819
|
+
}
|
|
2820
|
+
const protocol = header.slice(start, i);
|
|
2821
|
+
if (protocols.has(protocol)) {
|
|
2822
|
+
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
|
|
2823
|
+
}
|
|
2824
|
+
protocols.add(protocol);
|
|
2825
|
+
return protocols;
|
|
2826
|
+
}
|
|
2827
|
+
module.exports = { parse };
|
|
2828
|
+
});
|
|
2829
|
+
|
|
2830
|
+
// ../../../node_modules/ws/lib/websocket-server.js
|
|
2831
|
+
var require_websocket_server = __commonJS((exports, module) => {
|
|
2832
|
+
var EventEmitter = __require("events");
|
|
2833
|
+
var http = __require("http");
|
|
2834
|
+
var { Duplex } = __require("stream");
|
|
2835
|
+
var { createHash } = __require("crypto");
|
|
2836
|
+
var extension = require_extension();
|
|
2837
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
2838
|
+
var subprotocol = require_subprotocol();
|
|
2839
|
+
var WebSocket = require_websocket();
|
|
2840
|
+
var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
|
|
2841
|
+
var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
|
|
2842
|
+
var RUNNING = 0;
|
|
2843
|
+
var CLOSING = 1;
|
|
2844
|
+
var CLOSED = 2;
|
|
2845
|
+
|
|
2846
|
+
class WebSocketServer extends EventEmitter {
|
|
2847
|
+
constructor(options, callback) {
|
|
2848
|
+
super();
|
|
2849
|
+
options = {
|
|
2850
|
+
allowSynchronousEvents: true,
|
|
2851
|
+
autoPong: true,
|
|
2852
|
+
maxPayload: 100 * 1024 * 1024,
|
|
2853
|
+
skipUTF8Validation: false,
|
|
2854
|
+
perMessageDeflate: false,
|
|
2855
|
+
handleProtocols: null,
|
|
2856
|
+
clientTracking: true,
|
|
2857
|
+
closeTimeout: CLOSE_TIMEOUT,
|
|
2858
|
+
verifyClient: null,
|
|
2859
|
+
noServer: false,
|
|
2860
|
+
backlog: null,
|
|
2861
|
+
server: null,
|
|
2862
|
+
host: null,
|
|
2863
|
+
path: null,
|
|
2864
|
+
port: null,
|
|
2865
|
+
WebSocket,
|
|
2866
|
+
...options
|
|
2867
|
+
};
|
|
2868
|
+
if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
|
|
2869
|
+
throw new TypeError('One and only one of the "port", "server", or "noServer" options ' + "must be specified");
|
|
2870
|
+
}
|
|
2871
|
+
if (options.port != null) {
|
|
2872
|
+
this._server = http.createServer((req, res) => {
|
|
2873
|
+
const body = http.STATUS_CODES[426];
|
|
2874
|
+
res.writeHead(426, {
|
|
2875
|
+
"Content-Length": body.length,
|
|
2876
|
+
"Content-Type": "text/plain"
|
|
2877
|
+
});
|
|
2878
|
+
res.end(body);
|
|
2879
|
+
});
|
|
2880
|
+
this._server.listen(options.port, options.host, options.backlog, callback);
|
|
2881
|
+
} else if (options.server) {
|
|
2882
|
+
this._server = options.server;
|
|
2883
|
+
}
|
|
2884
|
+
if (this._server) {
|
|
2885
|
+
const emitConnection = this.emit.bind(this, "connection");
|
|
2886
|
+
this._removeListeners = addListeners(this._server, {
|
|
2887
|
+
listening: this.emit.bind(this, "listening"),
|
|
2888
|
+
error: this.emit.bind(this, "error"),
|
|
2889
|
+
upgrade: (req, socket, head) => {
|
|
2890
|
+
this.handleUpgrade(req, socket, head, emitConnection);
|
|
2891
|
+
}
|
|
2892
|
+
});
|
|
2893
|
+
}
|
|
2894
|
+
if (options.perMessageDeflate === true)
|
|
2895
|
+
options.perMessageDeflate = {};
|
|
2896
|
+
if (options.clientTracking) {
|
|
2897
|
+
this.clients = new Set;
|
|
2898
|
+
this._shouldEmitClose = false;
|
|
2899
|
+
}
|
|
2900
|
+
this.options = options;
|
|
2901
|
+
this._state = RUNNING;
|
|
2902
|
+
}
|
|
2903
|
+
address() {
|
|
2904
|
+
if (this.options.noServer) {
|
|
2905
|
+
throw new Error('The server is operating in "noServer" mode');
|
|
2906
|
+
}
|
|
2907
|
+
if (!this._server)
|
|
2908
|
+
return null;
|
|
2909
|
+
return this._server.address();
|
|
2910
|
+
}
|
|
2911
|
+
close(cb) {
|
|
2912
|
+
if (this._state === CLOSED) {
|
|
2913
|
+
if (cb) {
|
|
2914
|
+
this.once("close", () => {
|
|
2915
|
+
cb(new Error("The server is not running"));
|
|
2916
|
+
});
|
|
2917
|
+
}
|
|
2918
|
+
process.nextTick(emitClose, this);
|
|
2919
|
+
return;
|
|
2920
|
+
}
|
|
2921
|
+
if (cb)
|
|
2922
|
+
this.once("close", cb);
|
|
2923
|
+
if (this._state === CLOSING)
|
|
2924
|
+
return;
|
|
2925
|
+
this._state = CLOSING;
|
|
2926
|
+
if (this.options.noServer || this.options.server) {
|
|
2927
|
+
if (this._server) {
|
|
2928
|
+
this._removeListeners();
|
|
2929
|
+
this._removeListeners = this._server = null;
|
|
2930
|
+
}
|
|
2931
|
+
if (this.clients) {
|
|
2932
|
+
if (!this.clients.size) {
|
|
2933
|
+
process.nextTick(emitClose, this);
|
|
2934
|
+
} else {
|
|
2935
|
+
this._shouldEmitClose = true;
|
|
2936
|
+
}
|
|
2937
|
+
} else {
|
|
2938
|
+
process.nextTick(emitClose, this);
|
|
2939
|
+
}
|
|
2940
|
+
} else {
|
|
2941
|
+
const server = this._server;
|
|
2942
|
+
this._removeListeners();
|
|
2943
|
+
this._removeListeners = this._server = null;
|
|
2944
|
+
server.close(() => {
|
|
2945
|
+
emitClose(this);
|
|
2946
|
+
});
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
shouldHandle(req) {
|
|
2950
|
+
if (this.options.path) {
|
|
2951
|
+
const index = req.url.indexOf("?");
|
|
2952
|
+
const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
|
|
2953
|
+
if (pathname !== this.options.path)
|
|
2954
|
+
return false;
|
|
2955
|
+
}
|
|
2956
|
+
return true;
|
|
2957
|
+
}
|
|
2958
|
+
handleUpgrade(req, socket, head, cb) {
|
|
2959
|
+
socket.on("error", socketOnError);
|
|
2960
|
+
const key = req.headers["sec-websocket-key"];
|
|
2961
|
+
const upgrade = req.headers.upgrade;
|
|
2962
|
+
const version = +req.headers["sec-websocket-version"];
|
|
2963
|
+
if (req.method !== "GET") {
|
|
2964
|
+
const message = "Invalid HTTP method";
|
|
2965
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
|
|
2966
|
+
return;
|
|
2967
|
+
}
|
|
2968
|
+
if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
|
|
2969
|
+
const message = "Invalid Upgrade header";
|
|
2970
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
2971
|
+
return;
|
|
2972
|
+
}
|
|
2973
|
+
if (key === undefined || !keyRegex.test(key)) {
|
|
2974
|
+
const message = "Missing or invalid Sec-WebSocket-Key header";
|
|
2975
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
2976
|
+
return;
|
|
2977
|
+
}
|
|
2978
|
+
if (version !== 13 && version !== 8) {
|
|
2979
|
+
const message = "Missing or invalid Sec-WebSocket-Version header";
|
|
2980
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
|
|
2981
|
+
"Sec-WebSocket-Version": "13, 8"
|
|
2982
|
+
});
|
|
2983
|
+
return;
|
|
2984
|
+
}
|
|
2985
|
+
if (!this.shouldHandle(req)) {
|
|
2986
|
+
abortHandshake(socket, 400);
|
|
2987
|
+
return;
|
|
2988
|
+
}
|
|
2989
|
+
const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
|
|
2990
|
+
let protocols = new Set;
|
|
2991
|
+
if (secWebSocketProtocol !== undefined) {
|
|
2992
|
+
try {
|
|
2993
|
+
protocols = subprotocol.parse(secWebSocketProtocol);
|
|
2994
|
+
} catch (err) {
|
|
2995
|
+
const message = "Invalid Sec-WebSocket-Protocol header";
|
|
2996
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
2997
|
+
return;
|
|
2998
|
+
}
|
|
2999
|
+
}
|
|
3000
|
+
const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
|
|
3001
|
+
const extensions = {};
|
|
3002
|
+
if (this.options.perMessageDeflate && secWebSocketExtensions !== undefined) {
|
|
3003
|
+
const perMessageDeflate = new PerMessageDeflate(this.options.perMessageDeflate, true, this.options.maxPayload);
|
|
3004
|
+
try {
|
|
3005
|
+
const offers = extension.parse(secWebSocketExtensions);
|
|
3006
|
+
if (offers[PerMessageDeflate.extensionName]) {
|
|
3007
|
+
perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
|
|
3008
|
+
extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
|
|
3009
|
+
}
|
|
3010
|
+
} catch (err) {
|
|
3011
|
+
const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
|
|
3012
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3013
|
+
return;
|
|
3014
|
+
}
|
|
3015
|
+
}
|
|
3016
|
+
if (this.options.verifyClient) {
|
|
3017
|
+
const info = {
|
|
3018
|
+
origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
|
|
3019
|
+
secure: !!(req.socket.authorized || req.socket.encrypted),
|
|
3020
|
+
req
|
|
3021
|
+
};
|
|
3022
|
+
if (this.options.verifyClient.length === 2) {
|
|
3023
|
+
this.options.verifyClient(info, (verified, code, message, headers) => {
|
|
3024
|
+
if (!verified) {
|
|
3025
|
+
return abortHandshake(socket, code || 401, message, headers);
|
|
3026
|
+
}
|
|
3027
|
+
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
|
|
3028
|
+
});
|
|
3029
|
+
return;
|
|
3030
|
+
}
|
|
3031
|
+
if (!this.options.verifyClient(info))
|
|
3032
|
+
return abortHandshake(socket, 401);
|
|
3033
|
+
}
|
|
3034
|
+
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
|
|
3035
|
+
}
|
|
3036
|
+
completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
|
|
3037
|
+
if (!socket.readable || !socket.writable)
|
|
3038
|
+
return socket.destroy();
|
|
3039
|
+
if (socket[kWebSocket]) {
|
|
3040
|
+
throw new Error("server.handleUpgrade() was called more than once with the same " + "socket, possibly due to a misconfiguration");
|
|
3041
|
+
}
|
|
3042
|
+
if (this._state > RUNNING)
|
|
3043
|
+
return abortHandshake(socket, 503);
|
|
3044
|
+
const digest = createHash("sha1").update(key + GUID).digest("base64");
|
|
3045
|
+
const headers = [
|
|
3046
|
+
"HTTP/1.1 101 Switching Protocols",
|
|
3047
|
+
"Upgrade: websocket",
|
|
3048
|
+
"Connection: Upgrade",
|
|
3049
|
+
`Sec-WebSocket-Accept: ${digest}`
|
|
3050
|
+
];
|
|
3051
|
+
const ws = new this.options.WebSocket(null, undefined, this.options);
|
|
3052
|
+
if (protocols.size) {
|
|
3053
|
+
const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
|
|
3054
|
+
if (protocol) {
|
|
3055
|
+
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
|
|
3056
|
+
ws._protocol = protocol;
|
|
3057
|
+
}
|
|
3058
|
+
}
|
|
3059
|
+
if (extensions[PerMessageDeflate.extensionName]) {
|
|
3060
|
+
const params = extensions[PerMessageDeflate.extensionName].params;
|
|
3061
|
+
const value = extension.format({
|
|
3062
|
+
[PerMessageDeflate.extensionName]: [params]
|
|
3063
|
+
});
|
|
3064
|
+
headers.push(`Sec-WebSocket-Extensions: ${value}`);
|
|
3065
|
+
ws._extensions = extensions;
|
|
3066
|
+
}
|
|
3067
|
+
this.emit("headers", headers, req);
|
|
3068
|
+
socket.write(headers.concat(`\r
|
|
3069
|
+
`).join(`\r
|
|
3070
|
+
`));
|
|
3071
|
+
socket.removeListener("error", socketOnError);
|
|
3072
|
+
ws.setSocket(socket, head, {
|
|
3073
|
+
allowSynchronousEvents: this.options.allowSynchronousEvents,
|
|
3074
|
+
maxPayload: this.options.maxPayload,
|
|
3075
|
+
skipUTF8Validation: this.options.skipUTF8Validation
|
|
3076
|
+
});
|
|
3077
|
+
if (this.clients) {
|
|
3078
|
+
this.clients.add(ws);
|
|
3079
|
+
ws.on("close", () => {
|
|
3080
|
+
this.clients.delete(ws);
|
|
3081
|
+
if (this._shouldEmitClose && !this.clients.size) {
|
|
3082
|
+
process.nextTick(emitClose, this);
|
|
3083
|
+
}
|
|
3084
|
+
});
|
|
3085
|
+
}
|
|
3086
|
+
cb(ws, req);
|
|
3087
|
+
}
|
|
3088
|
+
}
|
|
3089
|
+
module.exports = WebSocketServer;
|
|
3090
|
+
function addListeners(server, map) {
|
|
3091
|
+
for (const event of Object.keys(map))
|
|
3092
|
+
server.on(event, map[event]);
|
|
3093
|
+
return function removeListeners() {
|
|
3094
|
+
for (const event of Object.keys(map)) {
|
|
3095
|
+
server.removeListener(event, map[event]);
|
|
3096
|
+
}
|
|
3097
|
+
};
|
|
3098
|
+
}
|
|
3099
|
+
function emitClose(server) {
|
|
3100
|
+
server._state = CLOSED;
|
|
3101
|
+
server.emit("close");
|
|
3102
|
+
}
|
|
3103
|
+
function socketOnError() {
|
|
3104
|
+
this.destroy();
|
|
3105
|
+
}
|
|
3106
|
+
function abortHandshake(socket, code, message, headers) {
|
|
3107
|
+
message = message || http.STATUS_CODES[code];
|
|
3108
|
+
headers = {
|
|
3109
|
+
Connection: "close",
|
|
3110
|
+
"Content-Type": "text/html",
|
|
3111
|
+
"Content-Length": Buffer.byteLength(message),
|
|
3112
|
+
...headers
|
|
3113
|
+
};
|
|
3114
|
+
socket.once("finish", socket.destroy);
|
|
3115
|
+
socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
|
|
3116
|
+
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join(`\r
|
|
3117
|
+
`) + `\r
|
|
3118
|
+
\r
|
|
3119
|
+
` + message);
|
|
3120
|
+
}
|
|
3121
|
+
function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
|
|
3122
|
+
if (server.listenerCount("wsClientError")) {
|
|
3123
|
+
const err = new Error(message);
|
|
3124
|
+
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
|
|
3125
|
+
server.emit("wsClientError", err, socket, req);
|
|
3126
|
+
} else {
|
|
3127
|
+
abortHandshake(socket, code, message, headers);
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
});
|
|
3131
|
+
|
|
3132
|
+
// src/index.ts
|
|
3133
|
+
import { logger as logger5 } from "@elizaos/core";
|
|
3134
|
+
import { z as z9 } from "zod";
|
|
3135
|
+
|
|
3136
|
+
// src/services/minecraft-service.ts
|
|
3137
|
+
import { logger as logger3, Service } from "@elizaos/core";
|
|
3138
|
+
|
|
3139
|
+
// src/types.ts
|
|
3140
|
+
import { z } from "zod";
|
|
3141
|
+
var minecraftWorldStateSchema = z.object({
|
|
3142
|
+
connected: z.boolean(),
|
|
3143
|
+
username: z.string().nullable().optional(),
|
|
3144
|
+
version: z.string().nullable().optional(),
|
|
3145
|
+
health: z.number().nullable().optional(),
|
|
3146
|
+
food: z.number().nullable().optional(),
|
|
3147
|
+
experience: z.number().nullable().optional(),
|
|
3148
|
+
position: z.object({ x: z.number(), y: z.number(), z: z.number() }).nullable().optional(),
|
|
3149
|
+
yaw: z.number().nullable().optional(),
|
|
3150
|
+
pitch: z.number().nullable().optional(),
|
|
3151
|
+
time: z.number().nullable().optional(),
|
|
3152
|
+
isRaining: z.boolean().nullable().optional(),
|
|
3153
|
+
inventory: z.array(z.object({
|
|
3154
|
+
name: z.string(),
|
|
3155
|
+
displayName: z.string(),
|
|
3156
|
+
count: z.number(),
|
|
3157
|
+
slot: z.number()
|
|
3158
|
+
})).optional(),
|
|
3159
|
+
nearbyEntities: z.array(z.object({
|
|
3160
|
+
id: z.number(),
|
|
3161
|
+
type: z.string(),
|
|
3162
|
+
name: z.string().nullable(),
|
|
3163
|
+
username: z.string().nullable(),
|
|
3164
|
+
kind: z.string().nullable(),
|
|
3165
|
+
position: z.object({ x: z.number(), y: z.number(), z: z.number() })
|
|
3166
|
+
})).optional()
|
|
3167
|
+
}).passthrough();
|
|
3168
|
+
|
|
3169
|
+
// src/services/process-manager.ts
|
|
3170
|
+
import { spawn } from "node:child_process";
|
|
3171
|
+
import { existsSync } from "node:fs";
|
|
3172
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
3173
|
+
import { dirname, join } from "node:path";
|
|
3174
|
+
import { fileURLToPath } from "node:url";
|
|
3175
|
+
import { logger } from "@elizaos/core";
|
|
3176
|
+
|
|
3177
|
+
class MinecraftProcessManager {
|
|
3178
|
+
serverPort;
|
|
3179
|
+
process = null;
|
|
3180
|
+
isRunning = false;
|
|
3181
|
+
entryPath = null;
|
|
3182
|
+
constructor(serverPort) {
|
|
3183
|
+
this.serverPort = serverPort;
|
|
3184
|
+
this.entryPath = this.findEntry();
|
|
3185
|
+
}
|
|
3186
|
+
findEntry() {
|
|
3187
|
+
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
3188
|
+
const possible = [
|
|
3189
|
+
join(moduleDir, "../../../mineflayer-server/dist/index.js"),
|
|
3190
|
+
join(moduleDir, "../../../mineflayer-server/src/index.ts"),
|
|
3191
|
+
join(moduleDir, "../../../../mineflayer-server/dist/index.js"),
|
|
3192
|
+
join(moduleDir, "../../../../mineflayer-server/src/index.ts")
|
|
3193
|
+
];
|
|
3194
|
+
for (const p of possible) {
|
|
3195
|
+
if (existsSync(p)) {
|
|
3196
|
+
logger.info(`Found mineflayer-server entry at: ${p}`);
|
|
3197
|
+
return p;
|
|
3198
|
+
}
|
|
3199
|
+
}
|
|
3200
|
+
logger.error("Could not find mineflayer-server entry file");
|
|
3201
|
+
logger.error(`Searched paths: ${possible.join(", ")}`);
|
|
3202
|
+
return null;
|
|
3203
|
+
}
|
|
3204
|
+
async start() {
|
|
3205
|
+
if (this.isRunning)
|
|
3206
|
+
return;
|
|
3207
|
+
if (!this.entryPath) {
|
|
3208
|
+
throw new Error("mineflayer-server entry not found (run: bun run build:server)");
|
|
3209
|
+
}
|
|
3210
|
+
const env = {
|
|
3211
|
+
...process.env,
|
|
3212
|
+
MC_SERVER_PORT: this.serverPort.toString(),
|
|
3213
|
+
NODE_ENV: "development"
|
|
3214
|
+
};
|
|
3215
|
+
const entry = this.entryPath;
|
|
3216
|
+
const isTypeScript = entry.endsWith(".ts");
|
|
3217
|
+
return await new Promise((resolve, reject) => {
|
|
3218
|
+
if (isTypeScript) {
|
|
3219
|
+
const require2 = createRequire2(import.meta.url);
|
|
3220
|
+
const tsxPath = require2.resolve("tsx/cli", { paths: [process.cwd()] });
|
|
3221
|
+
this.process = spawn("node", [tsxPath, entry], { env });
|
|
3222
|
+
} else {
|
|
3223
|
+
this.process = spawn("node", [entry], { env });
|
|
3224
|
+
}
|
|
3225
|
+
this.process.stdout?.on("data", (data) => {
|
|
3226
|
+
const msg = data.toString().trim();
|
|
3227
|
+
logger.debug(`[MinecraftServer] ${msg}`);
|
|
3228
|
+
if (msg.includes("listening on port")) {
|
|
3229
|
+
this.isRunning = true;
|
|
3230
|
+
resolve();
|
|
3231
|
+
}
|
|
3232
|
+
});
|
|
3233
|
+
this.process.stderr?.on("data", (data) => {
|
|
3234
|
+
logger.error(`[MinecraftServer Error] ${data.toString()}`);
|
|
3235
|
+
});
|
|
3236
|
+
this.process.on("error", (err) => {
|
|
3237
|
+
this.isRunning = false;
|
|
3238
|
+
reject(err);
|
|
3239
|
+
});
|
|
3240
|
+
this.process.on("exit", (code) => {
|
|
3241
|
+
logger.info(`Minecraft server process exited with code ${code ?? "unknown"}`);
|
|
3242
|
+
this.isRunning = false;
|
|
3243
|
+
});
|
|
3244
|
+
setTimeout(() => {
|
|
3245
|
+
if (!this.isRunning) {
|
|
3246
|
+
reject(new Error("mineflayer-server failed to start (timeout)"));
|
|
3247
|
+
}
|
|
3248
|
+
}, 15000);
|
|
3249
|
+
});
|
|
3250
|
+
}
|
|
3251
|
+
async stop() {
|
|
3252
|
+
if (!this.process || !this.isRunning)
|
|
3253
|
+
return;
|
|
3254
|
+
await new Promise((resolve) => {
|
|
3255
|
+
this.process?.on("exit", () => resolve());
|
|
3256
|
+
this.process?.kill("SIGTERM");
|
|
3257
|
+
setTimeout(() => {
|
|
3258
|
+
if (this.isRunning && this.process) {
|
|
3259
|
+
this.process.kill("SIGKILL");
|
|
3260
|
+
}
|
|
3261
|
+
}, 5000);
|
|
3262
|
+
});
|
|
3263
|
+
}
|
|
3264
|
+
isServerRunning() {
|
|
3265
|
+
return this.isRunning;
|
|
3266
|
+
}
|
|
3267
|
+
getServerUrl() {
|
|
3268
|
+
return `ws://localhost:${this.serverPort}`;
|
|
3269
|
+
}
|
|
3270
|
+
}
|
|
3271
|
+
|
|
3272
|
+
// src/services/websocket-client.ts
|
|
3273
|
+
import { logger as logger2 } from "@elizaos/core";
|
|
3274
|
+
|
|
3275
|
+
// ../../../node_modules/ws/wrapper.mjs
|
|
3276
|
+
var import_stream = __toESM(require_stream(), 1);
|
|
3277
|
+
var import_receiver = __toESM(require_receiver(), 1);
|
|
3278
|
+
var import_sender = __toESM(require_sender(), 1);
|
|
3279
|
+
var import_websocket = __toESM(require_websocket(), 1);
|
|
3280
|
+
var import_websocket_server = __toESM(require_websocket_server(), 1);
|
|
3281
|
+
var wrapper_default = import_websocket.default;
|
|
3282
|
+
|
|
3283
|
+
// src/services/websocket-client.ts
|
|
3284
|
+
import { z as z2 } from "zod";
|
|
3285
|
+
var jsonValueSchema = z2.lazy(() => z2.union([
|
|
3286
|
+
z2.null(),
|
|
3287
|
+
z2.boolean(),
|
|
3288
|
+
z2.number(),
|
|
3289
|
+
z2.string(),
|
|
3290
|
+
z2.array(jsonValueSchema),
|
|
3291
|
+
z2.record(z2.string(), jsonValueSchema)
|
|
3292
|
+
]));
|
|
3293
|
+
var responseSchema = z2.object({
|
|
3294
|
+
type: z2.string(),
|
|
3295
|
+
requestId: z2.string(),
|
|
3296
|
+
success: z2.boolean(),
|
|
3297
|
+
data: z2.record(z2.string(), jsonValueSchema).optional(),
|
|
3298
|
+
error: z2.string().optional()
|
|
3299
|
+
});
|
|
3300
|
+
|
|
3301
|
+
class MinecraftWebSocketClient {
|
|
3302
|
+
serverUrl;
|
|
3303
|
+
ws = null;
|
|
3304
|
+
pending = new Map;
|
|
3305
|
+
constructor(serverUrl) {
|
|
3306
|
+
this.serverUrl = serverUrl;
|
|
3307
|
+
}
|
|
3308
|
+
async connect() {
|
|
3309
|
+
if (this.ws && this.ws.readyState === wrapper_default.OPEN)
|
|
3310
|
+
return;
|
|
3311
|
+
await new Promise((resolve, reject) => {
|
|
3312
|
+
const ws = new wrapper_default(this.serverUrl);
|
|
3313
|
+
this.ws = ws;
|
|
3314
|
+
ws.on("open", () => resolve());
|
|
3315
|
+
ws.on("error", (err) => reject(err));
|
|
3316
|
+
ws.on("message", (data) => this.onMessage(data.toString("utf8")));
|
|
3317
|
+
ws.on("close", () => {
|
|
3318
|
+
for (const [requestId, entry] of this.pending) {
|
|
3319
|
+
clearTimeout(entry.timeoutId);
|
|
3320
|
+
entry.reject(new Error(`WebSocket closed while waiting for ${requestId}`));
|
|
3321
|
+
}
|
|
3322
|
+
this.pending.clear();
|
|
3323
|
+
});
|
|
3324
|
+
});
|
|
3325
|
+
logger2.info(`[Minecraft] Connected to ${this.serverUrl}`);
|
|
3326
|
+
}
|
|
3327
|
+
disconnect() {
|
|
3328
|
+
this.ws?.close();
|
|
3329
|
+
this.ws = null;
|
|
3330
|
+
}
|
|
3331
|
+
async health() {
|
|
3332
|
+
const resp = await this.sendMessage("health", undefined, {});
|
|
3333
|
+
return resp.success && resp.data?.status === "ok";
|
|
3334
|
+
}
|
|
3335
|
+
async sendMessage(type, botId, data, timeoutMs = 30000) {
|
|
3336
|
+
if (!this.ws || this.ws.readyState !== wrapper_default.OPEN) {
|
|
3337
|
+
throw new Error("Not connected to Mineflayer bridge server");
|
|
3338
|
+
}
|
|
3339
|
+
const requestId = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
3340
|
+
const msg = {
|
|
3341
|
+
type,
|
|
3342
|
+
requestId,
|
|
3343
|
+
...botId ? { botId } : {},
|
|
3344
|
+
...Object.keys(data).length > 0 ? { data } : {}
|
|
3345
|
+
};
|
|
3346
|
+
const payload = JSON.stringify(msg);
|
|
3347
|
+
const response = await new Promise((resolve, reject) => {
|
|
3348
|
+
const timeoutId = setTimeout(() => {
|
|
3349
|
+
this.pending.delete(requestId);
|
|
3350
|
+
reject(new Error(`Request timeout: ${type}`));
|
|
3351
|
+
}, timeoutMs);
|
|
3352
|
+
this.pending.set(requestId, { resolve, reject, timeoutId });
|
|
3353
|
+
this.ws?.send(payload, (err) => {
|
|
3354
|
+
if (err) {
|
|
3355
|
+
clearTimeout(timeoutId);
|
|
3356
|
+
this.pending.delete(requestId);
|
|
3357
|
+
reject(err);
|
|
3358
|
+
}
|
|
3359
|
+
});
|
|
3360
|
+
});
|
|
3361
|
+
if (!response.success) {
|
|
3362
|
+
throw new Error(response.error ?? `Request failed: ${type}`);
|
|
3363
|
+
}
|
|
3364
|
+
return response;
|
|
3365
|
+
}
|
|
3366
|
+
onMessage(text) {
|
|
3367
|
+
let parsed;
|
|
3368
|
+
try {
|
|
3369
|
+
const json = JSON.parse(text);
|
|
3370
|
+
parsed = responseSchema.parse(json);
|
|
3371
|
+
} catch (err) {
|
|
3372
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3373
|
+
logger2.error(`[Minecraft] Failed to parse server message: ${msg}`);
|
|
3374
|
+
return;
|
|
3375
|
+
}
|
|
3376
|
+
const pending = this.pending.get(parsed.requestId);
|
|
3377
|
+
if (!pending)
|
|
3378
|
+
return;
|
|
3379
|
+
clearTimeout(pending.timeoutId);
|
|
3380
|
+
this.pending.delete(parsed.requestId);
|
|
3381
|
+
pending.resolve(parsed);
|
|
3382
|
+
}
|
|
3383
|
+
}
|
|
3384
|
+
|
|
3385
|
+
// src/services/minecraft-service.ts
|
|
3386
|
+
var MINECRAFT_SERVICE_TYPE = "minecraft";
|
|
3387
|
+
|
|
3388
|
+
class Session {
|
|
3389
|
+
botId;
|
|
3390
|
+
createdAt;
|
|
3391
|
+
constructor(botId, createdAt = new Date) {
|
|
3392
|
+
this.botId = botId;
|
|
3393
|
+
this.createdAt = createdAt;
|
|
3394
|
+
}
|
|
3395
|
+
}
|
|
3396
|
+
|
|
3397
|
+
class MinecraftService extends Service {
|
|
3398
|
+
static serviceType = MINECRAFT_SERVICE_TYPE;
|
|
3399
|
+
capabilityDescription = "Minecraft automation service (Mineflayer bridge)";
|
|
3400
|
+
session = null;
|
|
3401
|
+
processManager;
|
|
3402
|
+
client;
|
|
3403
|
+
isInitialized = false;
|
|
3404
|
+
constructor(runtime) {
|
|
3405
|
+
super(runtime);
|
|
3406
|
+
if (!runtime)
|
|
3407
|
+
throw new Error("MinecraftService requires a runtime");
|
|
3408
|
+
this.runtime = runtime;
|
|
3409
|
+
const portSetting = runtime.getSetting("MC_SERVER_PORT");
|
|
3410
|
+
const port = typeof portSetting === "number" ? portSetting : Number(portSetting ?? 3457);
|
|
3411
|
+
const serverPort = Number.isFinite(port) ? port : 3457;
|
|
3412
|
+
this.processManager = new MinecraftProcessManager(serverPort);
|
|
3413
|
+
this.client = new MinecraftWebSocketClient(this.processManager.getServerUrl());
|
|
3414
|
+
}
|
|
3415
|
+
static async start(runtime) {
|
|
3416
|
+
const service = new MinecraftService(runtime);
|
|
3417
|
+
try {
|
|
3418
|
+
await service.processManager.start();
|
|
3419
|
+
} catch (err) {
|
|
3420
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3421
|
+
logger3.warn(`Failed to start Mineflayer server process: ${msg}`);
|
|
3422
|
+
}
|
|
3423
|
+
await service.initialize();
|
|
3424
|
+
return service;
|
|
3425
|
+
}
|
|
3426
|
+
async initialize() {
|
|
3427
|
+
if (this.isInitialized)
|
|
3428
|
+
return;
|
|
3429
|
+
await this.client.connect();
|
|
3430
|
+
await this.waitForReady();
|
|
3431
|
+
this.isInitialized = true;
|
|
3432
|
+
}
|
|
3433
|
+
async stop() {
|
|
3434
|
+
if (this.session) {
|
|
3435
|
+
try {
|
|
3436
|
+
await this.destroyBot(this.session.botId);
|
|
3437
|
+
} catch {}
|
|
3438
|
+
}
|
|
3439
|
+
this.client.disconnect();
|
|
3440
|
+
await this.processManager.stop();
|
|
3441
|
+
this.isInitialized = false;
|
|
3442
|
+
}
|
|
3443
|
+
getClient() {
|
|
3444
|
+
if (!this.isInitialized) {
|
|
3445
|
+
throw new Error("Minecraft service not initialized");
|
|
3446
|
+
}
|
|
3447
|
+
return this.client;
|
|
3448
|
+
}
|
|
3449
|
+
getCurrentSession() {
|
|
3450
|
+
return this.session;
|
|
3451
|
+
}
|
|
3452
|
+
async createBot(overrides) {
|
|
3453
|
+
if (!this.isInitialized) {
|
|
3454
|
+
throw new Error("Minecraft service not initialized");
|
|
3455
|
+
}
|
|
3456
|
+
const resp = await this.client.sendMessage("createBot", undefined, overrides ?? {});
|
|
3457
|
+
const botId = typeof resp.data?.botId === "string" ? resp.data.botId : null;
|
|
3458
|
+
if (!botId) {
|
|
3459
|
+
throw new Error("Bridge did not return botId");
|
|
3460
|
+
}
|
|
3461
|
+
this.session = new Session(botId);
|
|
3462
|
+
return this.session;
|
|
3463
|
+
}
|
|
3464
|
+
async destroyBot(botId) {
|
|
3465
|
+
if (!this.isInitialized)
|
|
3466
|
+
return;
|
|
3467
|
+
await this.client.sendMessage("destroyBot", botId, {});
|
|
3468
|
+
if (this.session?.botId === botId) {
|
|
3469
|
+
this.session = null;
|
|
3470
|
+
}
|
|
3471
|
+
}
|
|
3472
|
+
async ensureBot() {
|
|
3473
|
+
if (this.session)
|
|
3474
|
+
return this.session;
|
|
3475
|
+
return await this.createBot();
|
|
3476
|
+
}
|
|
3477
|
+
async chat(message) {
|
|
3478
|
+
const session = await this.ensureBot();
|
|
3479
|
+
await this.client.sendMessage("chat", session.botId, { message });
|
|
3480
|
+
}
|
|
3481
|
+
async request(type, data) {
|
|
3482
|
+
const session = await this.ensureBot();
|
|
3483
|
+
const resp = await this.client.sendMessage(type, session.botId, data);
|
|
3484
|
+
return resp.data ?? {};
|
|
3485
|
+
}
|
|
3486
|
+
async getWorldState() {
|
|
3487
|
+
if (!this.session) {
|
|
3488
|
+
return { connected: false };
|
|
3489
|
+
}
|
|
3490
|
+
const resp = await this.client.sendMessage("getState", this.session.botId, {});
|
|
3491
|
+
return minecraftWorldStateSchema.parse(resp.data ?? { connected: false });
|
|
3492
|
+
}
|
|
3493
|
+
async waitForReady(maxAttempts = 20, delayMs = 500) {
|
|
3494
|
+
for (let i = 0;i < maxAttempts; i++) {
|
|
3495
|
+
try {
|
|
3496
|
+
if (await this.client.health())
|
|
3497
|
+
return;
|
|
3498
|
+
} catch {}
|
|
3499
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
3500
|
+
}
|
|
3501
|
+
throw new Error("Mineflayer bridge server did not become ready");
|
|
3502
|
+
}
|
|
3503
|
+
}
|
|
3504
|
+
|
|
3505
|
+
// src/actions/attack.ts
|
|
3506
|
+
function parseEntityId(text) {
|
|
3507
|
+
const trimmed = text.trim();
|
|
3508
|
+
if (!trimmed)
|
|
3509
|
+
return null;
|
|
3510
|
+
const id = Number(trimmed);
|
|
3511
|
+
return Number.isFinite(id) ? id : null;
|
|
3512
|
+
}
|
|
3513
|
+
var minecraftAttackAction = {
|
|
3514
|
+
name: "MC_ATTACK",
|
|
3515
|
+
similes: ["MINECRAFT_ATTACK", "HIT_ENTITY"],
|
|
3516
|
+
description: "Attack an entity by numeric entityId (from MC_WORLD_STATE.nearbyEntities).",
|
|
3517
|
+
validate: async (runtime, message) => {
|
|
3518
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3519
|
+
return Boolean(service) && parseEntityId(message.content.text ?? "") !== null;
|
|
3520
|
+
},
|
|
3521
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
3522
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3523
|
+
if (!service)
|
|
3524
|
+
return { text: "Minecraft service is not available", success: false };
|
|
3525
|
+
const entityId = parseEntityId(message.content.text ?? "");
|
|
3526
|
+
if (entityId === null)
|
|
3527
|
+
return { text: "Missing entityId", success: false };
|
|
3528
|
+
try {
|
|
3529
|
+
await service.request("attack", { entityId });
|
|
3530
|
+
const content = {
|
|
3531
|
+
text: `Attacked entity ${entityId}.`,
|
|
3532
|
+
actions: ["MC_ATTACK"],
|
|
3533
|
+
source: message.content.source
|
|
3534
|
+
};
|
|
3535
|
+
await callback?.(content);
|
|
3536
|
+
return { text: content.text ?? "", success: true };
|
|
3537
|
+
} catch (err) {
|
|
3538
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3539
|
+
const content = {
|
|
3540
|
+
text: `Failed to attack: ${msg}`,
|
|
3541
|
+
actions: ["MC_ATTACK"],
|
|
3542
|
+
source: message.content.source
|
|
3543
|
+
};
|
|
3544
|
+
await callback?.(content);
|
|
3545
|
+
return { text: content.text ?? "", success: false };
|
|
3546
|
+
}
|
|
3547
|
+
}
|
|
3548
|
+
};
|
|
3549
|
+
// src/actions/chat.ts
|
|
3550
|
+
var minecraftChatAction = {
|
|
3551
|
+
name: "MC_CHAT",
|
|
3552
|
+
similes: ["MINECRAFT_CHAT", "SAY_IN_MINECRAFT", "CHAT"],
|
|
3553
|
+
description: "Send a chat message in Minecraft as the bot",
|
|
3554
|
+
validate: async (runtime, message) => {
|
|
3555
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3556
|
+
return Boolean(service) && (message.content.text ?? "").trim().length > 0;
|
|
3557
|
+
},
|
|
3558
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
3559
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3560
|
+
if (!service) {
|
|
3561
|
+
return { text: "Minecraft service is not available", success: false };
|
|
3562
|
+
}
|
|
3563
|
+
const text = (message.content.text ?? "").trim();
|
|
3564
|
+
if (!text)
|
|
3565
|
+
return { text: "No chat message provided", success: false };
|
|
3566
|
+
try {
|
|
3567
|
+
await service.chat(text);
|
|
3568
|
+
const content = {
|
|
3569
|
+
text: `Sent Minecraft chat: ${text}`,
|
|
3570
|
+
actions: ["MC_CHAT"],
|
|
3571
|
+
source: message.content.source
|
|
3572
|
+
};
|
|
3573
|
+
await callback?.(content);
|
|
3574
|
+
return {
|
|
3575
|
+
text: content.text ?? "",
|
|
3576
|
+
success: true,
|
|
3577
|
+
values: { sent: true }
|
|
3578
|
+
};
|
|
3579
|
+
} catch (err) {
|
|
3580
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3581
|
+
const content = {
|
|
3582
|
+
text: `Failed to send Minecraft chat: ${msg}`,
|
|
3583
|
+
actions: ["MC_CHAT"],
|
|
3584
|
+
source: message.content.source
|
|
3585
|
+
};
|
|
3586
|
+
await callback?.(content);
|
|
3587
|
+
return { text: content.text ?? "", success: false };
|
|
3588
|
+
}
|
|
3589
|
+
}
|
|
3590
|
+
};
|
|
3591
|
+
// src/actions/connect.ts
|
|
3592
|
+
import { z as z3 } from "zod";
|
|
3593
|
+
var connectOverridesSchema = z3.object({
|
|
3594
|
+
host: z3.string().optional(),
|
|
3595
|
+
port: z3.number().int().positive().optional(),
|
|
3596
|
+
username: z3.string().optional(),
|
|
3597
|
+
auth: z3.enum(["offline", "microsoft"]).optional(),
|
|
3598
|
+
version: z3.string().optional()
|
|
3599
|
+
}).passthrough();
|
|
3600
|
+
function parseOverrides(text) {
|
|
3601
|
+
const trimmed = text.trim();
|
|
3602
|
+
if (!trimmed.startsWith("{") || !trimmed.endsWith("}"))
|
|
3603
|
+
return {};
|
|
3604
|
+
try {
|
|
3605
|
+
const parsed = JSON.parse(trimmed);
|
|
3606
|
+
const validated = connectOverridesSchema.parse(parsed);
|
|
3607
|
+
const out = {};
|
|
3608
|
+
if (typeof validated.host === "string")
|
|
3609
|
+
out.host = validated.host;
|
|
3610
|
+
if (typeof validated.port === "number")
|
|
3611
|
+
out.port = validated.port;
|
|
3612
|
+
if (typeof validated.username === "string")
|
|
3613
|
+
out.username = validated.username;
|
|
3614
|
+
if (typeof validated.auth === "string")
|
|
3615
|
+
out.auth = validated.auth;
|
|
3616
|
+
if (typeof validated.version === "string")
|
|
3617
|
+
out.version = validated.version;
|
|
3618
|
+
return out;
|
|
3619
|
+
} catch {
|
|
3620
|
+
return {};
|
|
3621
|
+
}
|
|
3622
|
+
}
|
|
3623
|
+
var minecraftConnectAction = {
|
|
3624
|
+
name: "MC_CONNECT",
|
|
3625
|
+
similes: ["MINECRAFT_CONNECT", "JOIN_SERVER", "CONNECT_TO_MINECRAFT"],
|
|
3626
|
+
description: "Connect the Mineflayer bot to a Minecraft server",
|
|
3627
|
+
validate: async (runtime) => {
|
|
3628
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3629
|
+
return Boolean(service);
|
|
3630
|
+
},
|
|
3631
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
3632
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3633
|
+
if (!service) {
|
|
3634
|
+
return { text: "Minecraft service is not available", success: false };
|
|
3635
|
+
}
|
|
3636
|
+
try {
|
|
3637
|
+
const overrides = parseOverrides(message.content.text ?? "");
|
|
3638
|
+
const session = await service.createBot(overrides);
|
|
3639
|
+
const content = {
|
|
3640
|
+
text: `Connected Minecraft bot (botId=${session.botId}).`,
|
|
3641
|
+
actions: ["MC_CONNECT"],
|
|
3642
|
+
source: message.content.source
|
|
3643
|
+
};
|
|
3644
|
+
await callback?.(content);
|
|
3645
|
+
return {
|
|
3646
|
+
text: content.text ?? "",
|
|
3647
|
+
success: true,
|
|
3648
|
+
data: { botId: session.botId },
|
|
3649
|
+
values: { connected: true }
|
|
3650
|
+
};
|
|
3651
|
+
} catch (err) {
|
|
3652
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3653
|
+
const content = {
|
|
3654
|
+
text: `Failed to connect Minecraft bot: ${msg}`,
|
|
3655
|
+
actions: ["MC_CONNECT"],
|
|
3656
|
+
source: message.content.source
|
|
3657
|
+
};
|
|
3658
|
+
await callback?.(content);
|
|
3659
|
+
return {
|
|
3660
|
+
text: content.text ?? "",
|
|
3661
|
+
success: false,
|
|
3662
|
+
data: { error: msg },
|
|
3663
|
+
values: { connected: false }
|
|
3664
|
+
};
|
|
3665
|
+
}
|
|
3666
|
+
}
|
|
3667
|
+
};
|
|
3668
|
+
// src/actions/control.ts
|
|
3669
|
+
import { z as z4 } from "zod";
|
|
3670
|
+
var controlSchema = z4.object({
|
|
3671
|
+
control: z4.string(),
|
|
3672
|
+
state: z4.boolean(),
|
|
3673
|
+
durationMs: z4.number().int().positive().optional()
|
|
3674
|
+
});
|
|
3675
|
+
function parseControl(text) {
|
|
3676
|
+
const trimmed = text.trim();
|
|
3677
|
+
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
3678
|
+
try {
|
|
3679
|
+
const parsed = JSON.parse(trimmed);
|
|
3680
|
+
return controlSchema.parse(parsed);
|
|
3681
|
+
} catch {
|
|
3682
|
+
return null;
|
|
3683
|
+
}
|
|
3684
|
+
}
|
|
3685
|
+
const m = trimmed.match(/^(\S+)\s+(true|false)(?:\s+(\d+))?$/i);
|
|
3686
|
+
if (!m)
|
|
3687
|
+
return null;
|
|
3688
|
+
const control = m[1];
|
|
3689
|
+
const state = m[2].toLowerCase() === "true";
|
|
3690
|
+
const durationMs = m[3] ? Number(m[3]) : undefined;
|
|
3691
|
+
if (durationMs !== undefined && !Number.isFinite(durationMs))
|
|
3692
|
+
return null;
|
|
3693
|
+
return durationMs ? { control, state, durationMs } : { control, state };
|
|
3694
|
+
}
|
|
3695
|
+
var minecraftControlAction = {
|
|
3696
|
+
name: "MC_CONTROL",
|
|
3697
|
+
similes: ["MINECRAFT_CONTROL", "SET_CONTROL_STATE"],
|
|
3698
|
+
description: "Set a control state (e.g. forward/back/left/right/jump/sprint/sneak). Provide JSON {control,state,durationMs?} or 'forward true 1000'.",
|
|
3699
|
+
validate: async (runtime, message) => {
|
|
3700
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3701
|
+
return Boolean(service) && Boolean(parseControl(message.content.text ?? ""));
|
|
3702
|
+
},
|
|
3703
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
3704
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3705
|
+
if (!service)
|
|
3706
|
+
return { text: "Minecraft service is not available", success: false };
|
|
3707
|
+
const req = parseControl(message.content.text ?? "");
|
|
3708
|
+
if (!req)
|
|
3709
|
+
return { text: "Missing control command", success: false };
|
|
3710
|
+
try {
|
|
3711
|
+
await service.request("control", {
|
|
3712
|
+
control: req.control,
|
|
3713
|
+
state: req.state,
|
|
3714
|
+
...typeof req.durationMs === "number" ? { durationMs: req.durationMs } : {}
|
|
3715
|
+
});
|
|
3716
|
+
const content = {
|
|
3717
|
+
text: `Set control ${req.control}=${String(req.state)}${req.durationMs ? ` for ${req.durationMs}ms` : ""}.`,
|
|
3718
|
+
actions: ["MC_CONTROL"],
|
|
3719
|
+
source: message.content.source
|
|
3720
|
+
};
|
|
3721
|
+
await callback?.(content);
|
|
3722
|
+
return { text: content.text ?? "", success: true };
|
|
3723
|
+
} catch (err) {
|
|
3724
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3725
|
+
const content = {
|
|
3726
|
+
text: `Failed to set control: ${msg}`,
|
|
3727
|
+
actions: ["MC_CONTROL"],
|
|
3728
|
+
source: message.content.source
|
|
3729
|
+
};
|
|
3730
|
+
await callback?.(content);
|
|
3731
|
+
return { text: content.text ?? "", success: false };
|
|
3732
|
+
}
|
|
3733
|
+
}
|
|
3734
|
+
};
|
|
3735
|
+
// src/actions/utils.ts
|
|
3736
|
+
import { z as z5 } from "zod";
|
|
3737
|
+
var vec3Schema = z5.object({ x: z5.number(), y: z5.number(), z: z5.number() });
|
|
3738
|
+
function extractVec3(text) {
|
|
3739
|
+
const trimmed = text.trim();
|
|
3740
|
+
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
3741
|
+
try {
|
|
3742
|
+
const parsed = JSON.parse(trimmed);
|
|
3743
|
+
const v = vec3Schema.parse(parsed);
|
|
3744
|
+
return v;
|
|
3745
|
+
} catch {}
|
|
3746
|
+
}
|
|
3747
|
+
const m = trimmed.match(/(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)/);
|
|
3748
|
+
if (!m)
|
|
3749
|
+
return null;
|
|
3750
|
+
const x = Number(m[1]);
|
|
3751
|
+
const y = Number(m[2]);
|
|
3752
|
+
const z6 = Number(m[3]);
|
|
3753
|
+
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z6))
|
|
3754
|
+
return null;
|
|
3755
|
+
return { x, y, z: z6 };
|
|
3756
|
+
}
|
|
3757
|
+
|
|
3758
|
+
// src/actions/dig.ts
|
|
3759
|
+
var minecraftDigAction = {
|
|
3760
|
+
name: "MC_DIG",
|
|
3761
|
+
similes: ["MINECRAFT_DIG", "MINE_BLOCK", "BREAK_BLOCK"],
|
|
3762
|
+
description: `Dig/break the block at (x y z). Provide coordinates like '10 64 -20' or JSON {"x":10,"y":64,"z":-20}.`,
|
|
3763
|
+
validate: async (runtime, message) => {
|
|
3764
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3765
|
+
return Boolean(service) && Boolean(extractVec3(message.content.text ?? ""));
|
|
3766
|
+
},
|
|
3767
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
3768
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3769
|
+
if (!service)
|
|
3770
|
+
return { text: "Minecraft service is not available", success: false };
|
|
3771
|
+
const vec = extractVec3(message.content.text ?? "");
|
|
3772
|
+
if (!vec)
|
|
3773
|
+
return { text: "Missing coordinates (x y z)", success: false };
|
|
3774
|
+
try {
|
|
3775
|
+
const data = await service.request("dig", {
|
|
3776
|
+
x: vec.x,
|
|
3777
|
+
y: vec.y,
|
|
3778
|
+
z: vec.z
|
|
3779
|
+
});
|
|
3780
|
+
const blockName = typeof data.blockName === "string" ? data.blockName : "block";
|
|
3781
|
+
const content = {
|
|
3782
|
+
text: `Dug ${blockName} at (${vec.x}, ${vec.y}, ${vec.z}).`,
|
|
3783
|
+
actions: ["MC_DIG"],
|
|
3784
|
+
source: message.content.source
|
|
3785
|
+
};
|
|
3786
|
+
await callback?.(content);
|
|
3787
|
+
return { text: content.text ?? "", success: true };
|
|
3788
|
+
} catch (err) {
|
|
3789
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3790
|
+
const content = {
|
|
3791
|
+
text: `Failed to dig: ${msg}`,
|
|
3792
|
+
actions: ["MC_DIG"],
|
|
3793
|
+
source: message.content.source
|
|
3794
|
+
};
|
|
3795
|
+
await callback?.(content);
|
|
3796
|
+
return { text: content.text ?? "", success: false };
|
|
3797
|
+
}
|
|
3798
|
+
}
|
|
3799
|
+
};
|
|
3800
|
+
// src/actions/disconnect.ts
|
|
3801
|
+
var minecraftDisconnectAction = {
|
|
3802
|
+
name: "MC_DISCONNECT",
|
|
3803
|
+
similes: ["MINECRAFT_DISCONNECT", "LEAVE_SERVER", "QUIT_MINECRAFT"],
|
|
3804
|
+
description: "Disconnect the Mineflayer bot from the Minecraft server",
|
|
3805
|
+
validate: async (runtime) => {
|
|
3806
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3807
|
+
return Boolean(service?.getCurrentSession());
|
|
3808
|
+
},
|
|
3809
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
3810
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3811
|
+
if (!service) {
|
|
3812
|
+
return { text: "Minecraft service is not available", success: false };
|
|
3813
|
+
}
|
|
3814
|
+
const session = service.getCurrentSession();
|
|
3815
|
+
if (!session) {
|
|
3816
|
+
return { text: "No Minecraft bot is connected", success: false };
|
|
3817
|
+
}
|
|
3818
|
+
try {
|
|
3819
|
+
await service.destroyBot(session.botId);
|
|
3820
|
+
const content = {
|
|
3821
|
+
text: "Disconnected Minecraft bot.",
|
|
3822
|
+
actions: ["MC_DISCONNECT"],
|
|
3823
|
+
source: message.content.source
|
|
3824
|
+
};
|
|
3825
|
+
await callback?.(content);
|
|
3826
|
+
return {
|
|
3827
|
+
text: content.text ?? "",
|
|
3828
|
+
success: true,
|
|
3829
|
+
values: { connected: false }
|
|
3830
|
+
};
|
|
3831
|
+
} catch (err) {
|
|
3832
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3833
|
+
const content = {
|
|
3834
|
+
text: `Failed to disconnect Minecraft bot: ${msg}`,
|
|
3835
|
+
actions: ["MC_DISCONNECT"],
|
|
3836
|
+
source: message.content.source
|
|
3837
|
+
};
|
|
3838
|
+
await callback?.(content);
|
|
3839
|
+
return { text: content.text ?? "", success: false };
|
|
3840
|
+
}
|
|
3841
|
+
}
|
|
3842
|
+
};
|
|
3843
|
+
// src/actions/goto.ts
|
|
3844
|
+
var minecraftGotoAction = {
|
|
3845
|
+
name: "MC_GOTO",
|
|
3846
|
+
similes: ["MINECRAFT_GOTO", "WALK_TO", "MOVE_TO_COORDS"],
|
|
3847
|
+
description: `Pathfind to a target (x y z). Provide coordinates like '10 64 -20' or JSON {"x":10,"y":64,"z":-20}.`,
|
|
3848
|
+
validate: async (runtime, message) => {
|
|
3849
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3850
|
+
return Boolean(service) && Boolean(extractVec3(message.content.text ?? ""));
|
|
3851
|
+
},
|
|
3852
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
3853
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3854
|
+
if (!service)
|
|
3855
|
+
return { text: "Minecraft service is not available", success: false };
|
|
3856
|
+
const vec = extractVec3(message.content.text ?? "");
|
|
3857
|
+
if (!vec)
|
|
3858
|
+
return { text: "Missing coordinates (x y z)", success: false };
|
|
3859
|
+
try {
|
|
3860
|
+
await service.request("goto", { x: vec.x, y: vec.y, z: vec.z });
|
|
3861
|
+
const content = {
|
|
3862
|
+
text: `Moving to (${vec.x}, ${vec.y}, ${vec.z}).`,
|
|
3863
|
+
actions: ["MC_GOTO"],
|
|
3864
|
+
source: message.content.source
|
|
3865
|
+
};
|
|
3866
|
+
await callback?.(content);
|
|
3867
|
+
return { text: content.text ?? "", success: true };
|
|
3868
|
+
} catch (err) {
|
|
3869
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3870
|
+
const content = {
|
|
3871
|
+
text: `Failed to pathfind: ${msg}`,
|
|
3872
|
+
actions: ["MC_GOTO"],
|
|
3873
|
+
source: message.content.source
|
|
3874
|
+
};
|
|
3875
|
+
await callback?.(content);
|
|
3876
|
+
return { text: content.text ?? "", success: false };
|
|
3877
|
+
}
|
|
3878
|
+
}
|
|
3879
|
+
};
|
|
3880
|
+
// src/actions/look.ts
|
|
3881
|
+
import { z as z6 } from "zod";
|
|
3882
|
+
var lookSchema = z6.object({ yaw: z6.number(), pitch: z6.number() });
|
|
3883
|
+
function parseLook(text) {
|
|
3884
|
+
const trimmed = text.trim();
|
|
3885
|
+
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
3886
|
+
try {
|
|
3887
|
+
const parsed = JSON.parse(trimmed);
|
|
3888
|
+
return lookSchema.parse(parsed);
|
|
3889
|
+
} catch {
|
|
3890
|
+
return null;
|
|
3891
|
+
}
|
|
3892
|
+
}
|
|
3893
|
+
const m = trimmed.match(/(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)/);
|
|
3894
|
+
if (!m)
|
|
3895
|
+
return null;
|
|
3896
|
+
const yaw = Number(m[1]);
|
|
3897
|
+
const pitch = Number(m[2]);
|
|
3898
|
+
if (!Number.isFinite(yaw) || !Number.isFinite(pitch))
|
|
3899
|
+
return null;
|
|
3900
|
+
return { yaw, pitch };
|
|
3901
|
+
}
|
|
3902
|
+
var minecraftLookAction = {
|
|
3903
|
+
name: "MC_LOOK",
|
|
3904
|
+
similes: ["MINECRAFT_LOOK", "TURN_HEAD"],
|
|
3905
|
+
description: "Look to yaw/pitch (radians). Provide 'yaw pitch' or JSON {yaw,pitch}.",
|
|
3906
|
+
validate: async (runtime, message) => {
|
|
3907
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3908
|
+
return Boolean(service) && Boolean(parseLook(message.content.text ?? ""));
|
|
3909
|
+
},
|
|
3910
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
3911
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3912
|
+
if (!service)
|
|
3913
|
+
return { text: "Minecraft service is not available", success: false };
|
|
3914
|
+
const req = parseLook(message.content.text ?? "");
|
|
3915
|
+
if (!req)
|
|
3916
|
+
return { text: "Missing yaw/pitch", success: false };
|
|
3917
|
+
try {
|
|
3918
|
+
await service.request("look", { yaw: req.yaw, pitch: req.pitch });
|
|
3919
|
+
const content = {
|
|
3920
|
+
text: "Adjusted view.",
|
|
3921
|
+
actions: ["MC_LOOK"],
|
|
3922
|
+
source: message.content.source
|
|
3923
|
+
};
|
|
3924
|
+
await callback?.(content);
|
|
3925
|
+
return { text: content.text ?? "", success: true };
|
|
3926
|
+
} catch (err) {
|
|
3927
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3928
|
+
const content = {
|
|
3929
|
+
text: `Failed to look: ${msg}`,
|
|
3930
|
+
actions: ["MC_LOOK"],
|
|
3931
|
+
source: message.content.source
|
|
3932
|
+
};
|
|
3933
|
+
await callback?.(content);
|
|
3934
|
+
return { text: content.text ?? "", success: false };
|
|
3935
|
+
}
|
|
3936
|
+
}
|
|
3937
|
+
};
|
|
3938
|
+
// src/actions/place.ts
|
|
3939
|
+
import { z as z7 } from "zod";
|
|
3940
|
+
var placeSchema = z7.object({
|
|
3941
|
+
x: z7.number(),
|
|
3942
|
+
y: z7.number(),
|
|
3943
|
+
z: z7.number(),
|
|
3944
|
+
face: z7.enum(["up", "down", "north", "south", "east", "west"])
|
|
3945
|
+
});
|
|
3946
|
+
function parsePlace(text) {
|
|
3947
|
+
const trimmed = text.trim();
|
|
3948
|
+
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
3949
|
+
try {
|
|
3950
|
+
const parsed = JSON.parse(trimmed);
|
|
3951
|
+
const v = placeSchema.parse(parsed);
|
|
3952
|
+
return v;
|
|
3953
|
+
} catch {
|
|
3954
|
+
return null;
|
|
3955
|
+
}
|
|
3956
|
+
}
|
|
3957
|
+
const m = trimmed.match(/(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(up|down|north|south|east|west)\b/i);
|
|
3958
|
+
if (!m)
|
|
3959
|
+
return null;
|
|
3960
|
+
const x = Number(m[1]);
|
|
3961
|
+
const y = Number(m[2]);
|
|
3962
|
+
const zVal = Number(m[3]);
|
|
3963
|
+
const face = m[4].toLowerCase();
|
|
3964
|
+
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(zVal))
|
|
3965
|
+
return null;
|
|
3966
|
+
return { x, y, z: zVal, face };
|
|
3967
|
+
}
|
|
3968
|
+
var minecraftPlaceAction = {
|
|
3969
|
+
name: "MC_PLACE",
|
|
3970
|
+
similes: ["MINECRAFT_PLACE", "PLACE_BLOCK"],
|
|
3971
|
+
description: "Place the currently-held block onto a reference block face. Provide 'x y z face' (face=up/down/north/south/east/west) or JSON {x,y,z,face}.",
|
|
3972
|
+
validate: async (runtime, message) => {
|
|
3973
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3974
|
+
return Boolean(service) && Boolean(parsePlace(message.content.text ?? ""));
|
|
3975
|
+
},
|
|
3976
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
3977
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
3978
|
+
if (!service)
|
|
3979
|
+
return { text: "Minecraft service is not available", success: false };
|
|
3980
|
+
const req = parsePlace(message.content.text ?? "");
|
|
3981
|
+
if (!req)
|
|
3982
|
+
return { text: "Missing placement target (x y z face)", success: false };
|
|
3983
|
+
try {
|
|
3984
|
+
await service.request("place", {
|
|
3985
|
+
x: req.x,
|
|
3986
|
+
y: req.y,
|
|
3987
|
+
z: req.z,
|
|
3988
|
+
face: req.face
|
|
3989
|
+
});
|
|
3990
|
+
const content = {
|
|
3991
|
+
text: `Placed block at (${req.x}, ${req.y}, ${req.z}) face=${req.face}.`,
|
|
3992
|
+
actions: ["MC_PLACE"],
|
|
3993
|
+
source: message.content.source
|
|
3994
|
+
};
|
|
3995
|
+
await callback?.(content);
|
|
3996
|
+
return { text: content.text ?? "", success: true };
|
|
3997
|
+
} catch (err) {
|
|
3998
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3999
|
+
const content = {
|
|
4000
|
+
text: `Failed to place: ${msg}`,
|
|
4001
|
+
actions: ["MC_PLACE"],
|
|
4002
|
+
source: message.content.source
|
|
4003
|
+
};
|
|
4004
|
+
await callback?.(content);
|
|
4005
|
+
return { text: content.text ?? "", success: false };
|
|
4006
|
+
}
|
|
4007
|
+
}
|
|
4008
|
+
};
|
|
4009
|
+
// src/actions/scan.ts
|
|
4010
|
+
import { z as z8 } from "zod";
|
|
4011
|
+
var scanSchema = z8.object({
|
|
4012
|
+
blocks: z8.array(z8.string()).optional(),
|
|
4013
|
+
radius: z8.number().int().positive().optional(),
|
|
4014
|
+
maxResults: z8.number().int().positive().optional()
|
|
4015
|
+
}).passthrough();
|
|
4016
|
+
function parseScan(text) {
|
|
4017
|
+
const trimmed = text.trim();
|
|
4018
|
+
if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) {
|
|
4019
|
+
return {};
|
|
4020
|
+
}
|
|
4021
|
+
try {
|
|
4022
|
+
const parsed = JSON.parse(trimmed);
|
|
4023
|
+
const validated = scanSchema.parse({
|
|
4024
|
+
blocks: Array.isArray(parsed.blocks) ? parsed.blocks.filter((b) => typeof b === "string") : undefined,
|
|
4025
|
+
radius: typeof parsed.radius === "number" ? parsed.radius : undefined,
|
|
4026
|
+
maxResults: typeof parsed.maxResults === "number" ? parsed.maxResults : undefined
|
|
4027
|
+
});
|
|
4028
|
+
return {
|
|
4029
|
+
blocks: validated.blocks,
|
|
4030
|
+
radius: validated.radius,
|
|
4031
|
+
maxResults: validated.maxResults
|
|
4032
|
+
};
|
|
4033
|
+
} catch {
|
|
4034
|
+
return {};
|
|
4035
|
+
}
|
|
4036
|
+
}
|
|
4037
|
+
var minecraftScanAction = {
|
|
4038
|
+
name: "MC_SCAN",
|
|
4039
|
+
similes: ["MINECRAFT_SCAN", "FIND_BLOCKS", "SCAN_BLOCKS"],
|
|
4040
|
+
description: 'Scan nearby blocks. Optional JSON input: {"blocks":["oak_log"],"radius":16,"maxResults":32}. If omitted, scans for any non-air blocks.',
|
|
4041
|
+
validate: async (runtime) => {
|
|
4042
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
4043
|
+
return Boolean(service);
|
|
4044
|
+
},
|
|
4045
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
4046
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
4047
|
+
if (!service)
|
|
4048
|
+
return { text: "Minecraft service is not available", success: false };
|
|
4049
|
+
try {
|
|
4050
|
+
const params = parseScan(message.content.text ?? "");
|
|
4051
|
+
const data = await service.request("scan", {
|
|
4052
|
+
...params.blocks ? { blocks: params.blocks } : {},
|
|
4053
|
+
...typeof params.radius === "number" ? { radius: params.radius } : {},
|
|
4054
|
+
...typeof params.maxResults === "number" ? { maxResults: params.maxResults } : {}
|
|
4055
|
+
});
|
|
4056
|
+
const blocks = Array.isArray(data.blocks) ? data.blocks : [];
|
|
4057
|
+
const content = {
|
|
4058
|
+
text: `Scan found ${blocks.length} blocks.`,
|
|
4059
|
+
actions: ["MC_SCAN"],
|
|
4060
|
+
source: message.content.source
|
|
4061
|
+
};
|
|
4062
|
+
await callback?.(content);
|
|
4063
|
+
return {
|
|
4064
|
+
text: content.text ?? "",
|
|
4065
|
+
success: true,
|
|
4066
|
+
data,
|
|
4067
|
+
values: { count: blocks.length }
|
|
4068
|
+
};
|
|
4069
|
+
} catch (err) {
|
|
4070
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
4071
|
+
const content = {
|
|
4072
|
+
text: `Scan failed: ${msg}`,
|
|
4073
|
+
actions: ["MC_SCAN"],
|
|
4074
|
+
source: message.content.source
|
|
4075
|
+
};
|
|
4076
|
+
await callback?.(content);
|
|
4077
|
+
return { text: content.text ?? "", success: false };
|
|
4078
|
+
}
|
|
4079
|
+
}
|
|
4080
|
+
};
|
|
4081
|
+
// src/actions/stop.ts
|
|
4082
|
+
var minecraftStopAction = {
|
|
4083
|
+
name: "MC_STOP",
|
|
4084
|
+
similes: ["MINECRAFT_STOP", "STOP_PATHFINDER", "STOP_MOVING"],
|
|
4085
|
+
description: "Stop pathfinding / movement goals.",
|
|
4086
|
+
validate: async (runtime) => {
|
|
4087
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
4088
|
+
return Boolean(service);
|
|
4089
|
+
},
|
|
4090
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
4091
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
4092
|
+
if (!service)
|
|
4093
|
+
return { text: "Minecraft service is not available", success: false };
|
|
4094
|
+
try {
|
|
4095
|
+
await service.request("stop", {});
|
|
4096
|
+
const content = {
|
|
4097
|
+
text: "Stopped movement.",
|
|
4098
|
+
actions: ["MC_STOP"],
|
|
4099
|
+
source: message.content.source
|
|
4100
|
+
};
|
|
4101
|
+
await callback?.(content);
|
|
4102
|
+
return { text: content.text ?? "", success: true };
|
|
4103
|
+
} catch (err) {
|
|
4104
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
4105
|
+
const content = {
|
|
4106
|
+
text: `Failed to stop: ${msg}`,
|
|
4107
|
+
actions: ["MC_STOP"],
|
|
4108
|
+
source: message.content.source
|
|
4109
|
+
};
|
|
4110
|
+
await callback?.(content);
|
|
4111
|
+
return { text: content.text ?? "", success: false };
|
|
4112
|
+
}
|
|
4113
|
+
}
|
|
4114
|
+
};
|
|
4115
|
+
// src/services/waypoints-service.ts
|
|
4116
|
+
import { ChannelType, MemoryType, Service as Service2, stringToUuid } from "@elizaos/core";
|
|
4117
|
+
var WAYPOINTS_SERVICE_TYPE = "minecraft_waypoints";
|
|
4118
|
+
|
|
4119
|
+
class WaypointsService extends Service2 {
|
|
4120
|
+
static serviceType = WAYPOINTS_SERVICE_TYPE;
|
|
4121
|
+
capabilityDescription = "Minecraft waypoint storage and navigation helpers";
|
|
4122
|
+
waypoints = new Map;
|
|
4123
|
+
waypointsRoomId;
|
|
4124
|
+
waypointsWorldId;
|
|
4125
|
+
constructor(runtime) {
|
|
4126
|
+
super(runtime);
|
|
4127
|
+
if (!runtime) {
|
|
4128
|
+
throw new Error("WaypointsService requires a runtime");
|
|
4129
|
+
}
|
|
4130
|
+
this.runtime = runtime;
|
|
4131
|
+
this.waypointsWorldId = stringToUuid("00000000-0000-0000-0000-00000000a001");
|
|
4132
|
+
this.waypointsRoomId = stringToUuid(`minecraft-waypoints:${runtime.agentId}`);
|
|
4133
|
+
}
|
|
4134
|
+
static async start(runtime) {
|
|
4135
|
+
const service = new WaypointsService(runtime);
|
|
4136
|
+
await service.initialize();
|
|
4137
|
+
return service;
|
|
4138
|
+
}
|
|
4139
|
+
async stop() {}
|
|
4140
|
+
async initialize() {
|
|
4141
|
+
if (this.runtime.ensureWorldExists) {
|
|
4142
|
+
await this.runtime.ensureWorldExists({
|
|
4143
|
+
id: this.waypointsWorldId,
|
|
4144
|
+
name: "Minecraft Waypoints",
|
|
4145
|
+
agentId: this.runtime.agentId,
|
|
4146
|
+
messageServerId: stringToUuid("00000000-0000-0000-0000-000000000000"),
|
|
4147
|
+
metadata: {
|
|
4148
|
+
type: "minecraft",
|
|
4149
|
+
description: "Persistent waypoint storage"
|
|
4150
|
+
}
|
|
4151
|
+
});
|
|
4152
|
+
}
|
|
4153
|
+
if (this.runtime.ensureRoomExists) {
|
|
4154
|
+
await this.runtime.ensureRoomExists({
|
|
4155
|
+
id: this.waypointsRoomId,
|
|
4156
|
+
name: "Minecraft Waypoints",
|
|
4157
|
+
worldId: this.waypointsWorldId,
|
|
4158
|
+
source: "plugin-minecraft",
|
|
4159
|
+
type: ChannelType.SELF,
|
|
4160
|
+
metadata: {
|
|
4161
|
+
type: "minecraft",
|
|
4162
|
+
description: "Persistent waypoint storage"
|
|
4163
|
+
}
|
|
4164
|
+
});
|
|
4165
|
+
}
|
|
4166
|
+
if (this.runtime.ensureParticipantInRoom) {
|
|
4167
|
+
await this.runtime.ensureParticipantInRoom(this.runtime.agentId, this.waypointsRoomId);
|
|
4168
|
+
}
|
|
4169
|
+
const memories = await this.runtime.getMemories({
|
|
4170
|
+
roomId: this.waypointsRoomId,
|
|
4171
|
+
count: 500,
|
|
4172
|
+
tableName: "memories"
|
|
4173
|
+
});
|
|
4174
|
+
for (const m of memories) {
|
|
4175
|
+
const md = m.metadata;
|
|
4176
|
+
if (!md || md.type !== MemoryType.CUSTOM)
|
|
4177
|
+
continue;
|
|
4178
|
+
const cmd = md;
|
|
4179
|
+
if (cmd.waypointType !== "minecraft_waypoint")
|
|
4180
|
+
continue;
|
|
4181
|
+
if (typeof cmd.waypointName !== "string")
|
|
4182
|
+
continue;
|
|
4183
|
+
if (typeof cmd.x !== "number" || typeof cmd.y !== "number" || typeof cmd.z !== "number")
|
|
4184
|
+
continue;
|
|
4185
|
+
const key = cmd.waypointName.trim().toLowerCase();
|
|
4186
|
+
const createdAt = typeof m.createdAt === "number" ? new Date(m.createdAt) : new Date;
|
|
4187
|
+
const id = m.id ?? stringToUuid(`mc-waypoint:${this.runtime.agentId}:${key}`);
|
|
4188
|
+
this.waypoints.set(key, {
|
|
4189
|
+
id,
|
|
4190
|
+
name: cmd.waypointName,
|
|
4191
|
+
x: cmd.x,
|
|
4192
|
+
y: cmd.y,
|
|
4193
|
+
z: cmd.z,
|
|
4194
|
+
createdAt
|
|
4195
|
+
});
|
|
4196
|
+
}
|
|
4197
|
+
}
|
|
4198
|
+
waypointIdForKey(key) {
|
|
4199
|
+
return stringToUuid(`mc-waypoint:${this.runtime.agentId}:${key}`);
|
|
4200
|
+
}
|
|
4201
|
+
buildWaypointMemory(_key, wp) {
|
|
4202
|
+
const createdAt = Date.now();
|
|
4203
|
+
const content = {
|
|
4204
|
+
text: `Waypoint "${wp.name}" at (${wp.x}, ${wp.y}, ${wp.z})`,
|
|
4205
|
+
source: "plugin-minecraft"
|
|
4206
|
+
};
|
|
4207
|
+
const metadata = {
|
|
4208
|
+
type: MemoryType.CUSTOM,
|
|
4209
|
+
scope: "private",
|
|
4210
|
+
waypointType: "minecraft_waypoint",
|
|
4211
|
+
waypointName: wp.name,
|
|
4212
|
+
x: wp.x,
|
|
4213
|
+
y: wp.y,
|
|
4214
|
+
z: wp.z,
|
|
4215
|
+
tags: ["minecraft", "waypoint"],
|
|
4216
|
+
timestamp: createdAt
|
|
4217
|
+
};
|
|
4218
|
+
return {
|
|
4219
|
+
id: wp.id,
|
|
4220
|
+
entityId: this.runtime.agentId,
|
|
4221
|
+
agentId: this.runtime.agentId,
|
|
4222
|
+
roomId: this.waypointsRoomId,
|
|
4223
|
+
worldId: this.waypointsWorldId,
|
|
4224
|
+
createdAt,
|
|
4225
|
+
content,
|
|
4226
|
+
metadata,
|
|
4227
|
+
unique: true
|
|
4228
|
+
};
|
|
4229
|
+
}
|
|
4230
|
+
async setWaypoint(name, x, y, z9) {
|
|
4231
|
+
const key = name.trim().toLowerCase();
|
|
4232
|
+
const wp = {
|
|
4233
|
+
id: this.waypointIdForKey(key),
|
|
4234
|
+
name: name.trim(),
|
|
4235
|
+
x,
|
|
4236
|
+
y,
|
|
4237
|
+
z: z9,
|
|
4238
|
+
createdAt: new Date
|
|
4239
|
+
};
|
|
4240
|
+
this.waypoints.set(key, wp);
|
|
4241
|
+
const memory = this.buildWaypointMemory(key, wp);
|
|
4242
|
+
const existing = await this.runtime.getMemories({
|
|
4243
|
+
roomId: this.waypointsRoomId,
|
|
4244
|
+
count: 1,
|
|
4245
|
+
tableName: "memories"
|
|
4246
|
+
});
|
|
4247
|
+
if (existing.some((m) => m.id === wp.id)) {
|
|
4248
|
+
await this.runtime.updateMemory({
|
|
4249
|
+
id: wp.id,
|
|
4250
|
+
content: memory.content,
|
|
4251
|
+
metadata: memory.metadata
|
|
4252
|
+
});
|
|
4253
|
+
} else {
|
|
4254
|
+
await this.runtime.createMemory(memory, "memories", true);
|
|
4255
|
+
}
|
|
4256
|
+
return wp;
|
|
4257
|
+
}
|
|
4258
|
+
async deleteWaypoint(name) {
|
|
4259
|
+
const key = name.trim().toLowerCase();
|
|
4260
|
+
const wp = this.waypoints.get(key);
|
|
4261
|
+
const deleted = this.waypoints.delete(key);
|
|
4262
|
+
if (wp) {
|
|
4263
|
+
await this.runtime.deleteMemory(wp.id);
|
|
4264
|
+
}
|
|
4265
|
+
return deleted;
|
|
4266
|
+
}
|
|
4267
|
+
getWaypoint(name) {
|
|
4268
|
+
const key = name.trim().toLowerCase();
|
|
4269
|
+
return this.waypoints.get(key) ?? null;
|
|
4270
|
+
}
|
|
4271
|
+
listWaypoints() {
|
|
4272
|
+
return Array.from(this.waypoints.values()).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
|
|
4273
|
+
}
|
|
4274
|
+
}
|
|
4275
|
+
|
|
4276
|
+
// src/actions/waypoints.ts
|
|
4277
|
+
function parseName(text) {
|
|
4278
|
+
const name = text.trim();
|
|
4279
|
+
return name.length > 0 ? name : null;
|
|
4280
|
+
}
|
|
4281
|
+
var minecraftWaypointSetAction = {
|
|
4282
|
+
name: "MC_WAYPOINT_SET",
|
|
4283
|
+
similes: ["MINECRAFT_WAYPOINT_SET", "SET_WAYPOINT", "SAVE_WAYPOINT"],
|
|
4284
|
+
description: "Save the bot's current position as a named waypoint (message text is the name).",
|
|
4285
|
+
validate: async (runtime, message) => {
|
|
4286
|
+
return Boolean(runtime.getService(WAYPOINTS_SERVICE_TYPE)) && Boolean(parseName(message.content.text ?? ""));
|
|
4287
|
+
},
|
|
4288
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
4289
|
+
const waypoints = runtime.getService(WAYPOINTS_SERVICE_TYPE);
|
|
4290
|
+
const mc = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
4291
|
+
const name = parseName(message.content.text ?? "");
|
|
4292
|
+
if (!waypoints || !mc)
|
|
4293
|
+
return {
|
|
4294
|
+
text: "Waypoint or Minecraft service not available",
|
|
4295
|
+
success: false
|
|
4296
|
+
};
|
|
4297
|
+
if (!name)
|
|
4298
|
+
return { text: "Missing waypoint name", success: false };
|
|
4299
|
+
const ws = await mc.getWorldState();
|
|
4300
|
+
const pos = ws.position;
|
|
4301
|
+
if (!pos)
|
|
4302
|
+
return {
|
|
4303
|
+
text: "No position available (is the bot connected?)",
|
|
4304
|
+
success: false
|
|
4305
|
+
};
|
|
4306
|
+
const wp = await waypoints.setWaypoint(name, pos.x, pos.y, pos.z);
|
|
4307
|
+
const content = {
|
|
4308
|
+
text: `Saved waypoint "${wp.name}" at (${wp.x.toFixed(1)}, ${wp.y.toFixed(1)}, ${wp.z.toFixed(1)}).`,
|
|
4309
|
+
actions: ["MC_WAYPOINT_SET"],
|
|
4310
|
+
source: message.content.source
|
|
4311
|
+
};
|
|
4312
|
+
await callback?.(content);
|
|
4313
|
+
return {
|
|
4314
|
+
text: content.text ?? "",
|
|
4315
|
+
success: true,
|
|
4316
|
+
data: {
|
|
4317
|
+
name: wp.name,
|
|
4318
|
+
x: wp.x,
|
|
4319
|
+
y: wp.y,
|
|
4320
|
+
z: wp.z,
|
|
4321
|
+
createdAt: wp.createdAt.toISOString()
|
|
4322
|
+
}
|
|
4323
|
+
};
|
|
4324
|
+
}
|
|
4325
|
+
};
|
|
4326
|
+
var minecraftWaypointDeleteAction = {
|
|
4327
|
+
name: "MC_WAYPOINT_DELETE",
|
|
4328
|
+
similes: ["MINECRAFT_WAYPOINT_DELETE", "DELETE_WAYPOINT", "REMOVE_WAYPOINT"],
|
|
4329
|
+
description: "Delete a named waypoint (message text is the name).",
|
|
4330
|
+
validate: async (runtime, message) => {
|
|
4331
|
+
return Boolean(runtime.getService(WAYPOINTS_SERVICE_TYPE)) && Boolean(parseName(message.content.text ?? ""));
|
|
4332
|
+
},
|
|
4333
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
4334
|
+
const waypoints = runtime.getService(WAYPOINTS_SERVICE_TYPE);
|
|
4335
|
+
const name = parseName(message.content.text ?? "");
|
|
4336
|
+
if (!waypoints)
|
|
4337
|
+
return { text: "Waypoints service not available", success: false };
|
|
4338
|
+
if (!name)
|
|
4339
|
+
return { text: "Missing waypoint name", success: false };
|
|
4340
|
+
const deleted = await waypoints.deleteWaypoint(name);
|
|
4341
|
+
const content = {
|
|
4342
|
+
text: deleted ? `Deleted waypoint "${name}".` : `No waypoint named "${name}".`,
|
|
4343
|
+
actions: ["MC_WAYPOINT_DELETE"],
|
|
4344
|
+
source: message.content.source
|
|
4345
|
+
};
|
|
4346
|
+
await callback?.(content);
|
|
4347
|
+
return { text: content.text ?? "", success: deleted, values: { deleted } };
|
|
4348
|
+
}
|
|
4349
|
+
};
|
|
4350
|
+
var minecraftWaypointListAction = {
|
|
4351
|
+
name: "MC_WAYPOINT_LIST",
|
|
4352
|
+
similes: ["MINECRAFT_WAYPOINT_LIST", "LIST_WAYPOINTS", "SHOW_WAYPOINTS"],
|
|
4353
|
+
description: "List saved waypoints.",
|
|
4354
|
+
validate: async (runtime) => {
|
|
4355
|
+
return Boolean(runtime.getService(WAYPOINTS_SERVICE_TYPE));
|
|
4356
|
+
},
|
|
4357
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
4358
|
+
const waypoints = runtime.getService(WAYPOINTS_SERVICE_TYPE);
|
|
4359
|
+
if (!waypoints)
|
|
4360
|
+
return { text: "Waypoints service not available", success: false };
|
|
4361
|
+
const list = waypoints.listWaypoints();
|
|
4362
|
+
const lines = list.map((w) => `- ${w.name}: (${w.x.toFixed(1)}, ${w.y.toFixed(1)}, ${w.z.toFixed(1)})`);
|
|
4363
|
+
const content = {
|
|
4364
|
+
text: list.length ? `Waypoints:
|
|
4365
|
+
${lines.join(`
|
|
4366
|
+
`)}` : "No waypoints saved.",
|
|
4367
|
+
actions: ["MC_WAYPOINT_LIST"],
|
|
4368
|
+
source: message.content.source
|
|
4369
|
+
};
|
|
4370
|
+
await callback?.(content);
|
|
4371
|
+
return {
|
|
4372
|
+
text: content.text ?? "",
|
|
4373
|
+
success: true,
|
|
4374
|
+
data: {
|
|
4375
|
+
waypoints: list.map((w) => ({
|
|
4376
|
+
name: w.name,
|
|
4377
|
+
x: w.x,
|
|
4378
|
+
y: w.y,
|
|
4379
|
+
z: w.z,
|
|
4380
|
+
createdAt: w.createdAt.toISOString()
|
|
4381
|
+
}))
|
|
4382
|
+
}
|
|
4383
|
+
};
|
|
4384
|
+
}
|
|
4385
|
+
};
|
|
4386
|
+
var minecraftWaypointGotoAction = {
|
|
4387
|
+
name: "MC_WAYPOINT_GOTO",
|
|
4388
|
+
similes: ["MINECRAFT_WAYPOINT_GOTO", "GOTO_WAYPOINT", "NAVIGATE_WAYPOINT"],
|
|
4389
|
+
description: "Pathfind to a named waypoint (message text is the name).",
|
|
4390
|
+
validate: async (runtime, message) => {
|
|
4391
|
+
return Boolean(runtime.getService(WAYPOINTS_SERVICE_TYPE)) && Boolean(runtime.getService(MINECRAFT_SERVICE_TYPE)) && Boolean(parseName(message.content.text ?? ""));
|
|
4392
|
+
},
|
|
4393
|
+
handler: async (runtime, message, _state, _options, callback) => {
|
|
4394
|
+
const waypoints = runtime.getService(WAYPOINTS_SERVICE_TYPE);
|
|
4395
|
+
const mc = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
4396
|
+
const name = parseName(message.content.text ?? "");
|
|
4397
|
+
if (!waypoints || !mc)
|
|
4398
|
+
return {
|
|
4399
|
+
text: "Waypoint or Minecraft service not available",
|
|
4400
|
+
success: false
|
|
4401
|
+
};
|
|
4402
|
+
if (!name)
|
|
4403
|
+
return { text: "Missing waypoint name", success: false };
|
|
4404
|
+
const wp = waypoints.getWaypoint(name);
|
|
4405
|
+
if (!wp) {
|
|
4406
|
+
const content2 = {
|
|
4407
|
+
text: `No waypoint named "${name}".`,
|
|
4408
|
+
actions: ["MC_WAYPOINT_GOTO"],
|
|
4409
|
+
source: message.content.source
|
|
4410
|
+
};
|
|
4411
|
+
await callback?.(content2);
|
|
4412
|
+
return { text: content2.text ?? "", success: false };
|
|
4413
|
+
}
|
|
4414
|
+
await mc.request("goto", { x: wp.x, y: wp.y, z: wp.z });
|
|
4415
|
+
const content = {
|
|
4416
|
+
text: `Navigating to waypoint "${wp.name}" at (${wp.x.toFixed(1)}, ${wp.y.toFixed(1)}, ${wp.z.toFixed(1)}).`,
|
|
4417
|
+
actions: ["MC_WAYPOINT_GOTO"],
|
|
4418
|
+
source: message.content.source
|
|
4419
|
+
};
|
|
4420
|
+
await callback?.(content);
|
|
4421
|
+
return { text: content.text ?? "", success: true };
|
|
4422
|
+
}
|
|
4423
|
+
};
|
|
4424
|
+
// src/providers/vision.ts
|
|
4425
|
+
var minecraftVisionProvider = {
|
|
4426
|
+
name: "MC_VISION",
|
|
4427
|
+
description: "Semantic environment context: biome, what I'm looking at, key nearby blocks (logs/ores), nearby entities",
|
|
4428
|
+
get: async (runtime, _message, _state) => {
|
|
4429
|
+
const mc = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
4430
|
+
if (!mc) {
|
|
4431
|
+
return {
|
|
4432
|
+
text: "Minecraft service not available",
|
|
4433
|
+
values: { connected: false },
|
|
4434
|
+
data: {}
|
|
4435
|
+
};
|
|
4436
|
+
}
|
|
4437
|
+
const ws = await mc.getWorldState();
|
|
4438
|
+
if (!ws.connected) {
|
|
4439
|
+
return {
|
|
4440
|
+
text: "Minecraft bot not connected",
|
|
4441
|
+
values: { connected: false },
|
|
4442
|
+
data: {}
|
|
4443
|
+
};
|
|
4444
|
+
}
|
|
4445
|
+
const scan = await mc.request("scan", {
|
|
4446
|
+
blocks: [
|
|
4447
|
+
"oak_log",
|
|
4448
|
+
"spruce_log",
|
|
4449
|
+
"birch_log",
|
|
4450
|
+
"jungle_log",
|
|
4451
|
+
"acacia_log",
|
|
4452
|
+
"dark_oak_log",
|
|
4453
|
+
"stone",
|
|
4454
|
+
"coal_ore",
|
|
4455
|
+
"iron_ore"
|
|
4456
|
+
],
|
|
4457
|
+
radius: 16,
|
|
4458
|
+
maxResults: 24
|
|
4459
|
+
});
|
|
4460
|
+
const blocks = Array.isArray(scan.blocks) ? scan.blocks : [];
|
|
4461
|
+
const pos = ws.position ? `(${ws.position.x.toFixed(1)}, ${ws.position.y.toFixed(1)}, ${ws.position.z.toFixed(1)})` : "(unknown)";
|
|
4462
|
+
const biomeName = ws.biome && typeof ws.biome === "object" && "name" in ws.biome && typeof ws.biome.name === "string" ? ws.biome.name : null;
|
|
4463
|
+
const lookingAt = ws.lookingAt;
|
|
4464
|
+
const laName = lookingAt && typeof lookingAt.name === "string" ? lookingAt.name : null;
|
|
4465
|
+
const laPos = lookingAt?.position ? {
|
|
4466
|
+
x: typeof lookingAt.position.x === "number" ? lookingAt.position.x : null,
|
|
4467
|
+
y: typeof lookingAt.position.y === "number" ? lookingAt.position.y : null,
|
|
4468
|
+
z: typeof lookingAt.position.z === "number" ? lookingAt.position.z : null
|
|
4469
|
+
} : null;
|
|
4470
|
+
const lookingText = laName && laPos && laPos.x !== null && laPos.y !== null && laPos.z !== null ? `Looking at: ${laName} at (${laPos.x}, ${laPos.y}, ${laPos.z})` : "Looking at: (unknown)";
|
|
4471
|
+
const entityCount = Array.isArray(ws.nearbyEntities) ? ws.nearbyEntities.length : 0;
|
|
4472
|
+
return {
|
|
4473
|
+
text: `Biome: ${biomeName ?? "unknown"}
|
|
4474
|
+
Position: ${pos}
|
|
4475
|
+
${lookingText}
|
|
4476
|
+
NearbyEntities: ${entityCount}
|
|
4477
|
+
NearbyBlocksFound: ${blocks.length}`,
|
|
4478
|
+
values: {
|
|
4479
|
+
connected: true,
|
|
4480
|
+
biome: biomeName ?? null,
|
|
4481
|
+
entityCount,
|
|
4482
|
+
blocksFound: blocks.length
|
|
4483
|
+
},
|
|
4484
|
+
data: {
|
|
4485
|
+
biome: ws.biome ?? null,
|
|
4486
|
+
position: ws.position ?? null,
|
|
4487
|
+
lookingAt: ws.lookingAt ?? null,
|
|
4488
|
+
nearbyEntities: ws.nearbyEntities ?? [],
|
|
4489
|
+
nearbyBlocks: blocks
|
|
4490
|
+
}
|
|
4491
|
+
};
|
|
4492
|
+
}
|
|
4493
|
+
};
|
|
4494
|
+
// src/providers/waypoints.ts
|
|
4495
|
+
var minecraftWaypointsProvider = {
|
|
4496
|
+
name: "MC_WAYPOINTS",
|
|
4497
|
+
description: "Saved Minecraft waypoints (names and coordinates)",
|
|
4498
|
+
get: async (runtime, _message, _state) => {
|
|
4499
|
+
const service = runtime.getService(WAYPOINTS_SERVICE_TYPE);
|
|
4500
|
+
if (!service) {
|
|
4501
|
+
return {
|
|
4502
|
+
text: "Waypoints service not available",
|
|
4503
|
+
values: { count: 0 },
|
|
4504
|
+
data: { waypoints: [] }
|
|
4505
|
+
};
|
|
4506
|
+
}
|
|
4507
|
+
const list = service.listWaypoints();
|
|
4508
|
+
const lines = list.map((w) => `- ${w.name}: (${w.x.toFixed(1)}, ${w.y.toFixed(1)}, ${w.z.toFixed(1)})`);
|
|
4509
|
+
return {
|
|
4510
|
+
text: list.length ? `Waypoints:
|
|
4511
|
+
${lines.join(`
|
|
4512
|
+
`)}` : "No waypoints saved.",
|
|
4513
|
+
values: { count: list.length },
|
|
4514
|
+
data: {
|
|
4515
|
+
waypoints: list.map((w) => ({
|
|
4516
|
+
name: w.name,
|
|
4517
|
+
x: w.x,
|
|
4518
|
+
y: w.y,
|
|
4519
|
+
z: w.z,
|
|
4520
|
+
createdAt: w.createdAt.toISOString()
|
|
4521
|
+
}))
|
|
4522
|
+
}
|
|
4523
|
+
};
|
|
4524
|
+
}
|
|
4525
|
+
};
|
|
4526
|
+
// src/providers/world-state.ts
|
|
4527
|
+
import { logger as logger4 } from "@elizaos/core";
|
|
4528
|
+
var minecraftWorldStateProvider = {
|
|
4529
|
+
name: "MC_WORLD_STATE",
|
|
4530
|
+
description: "Minecraft world state: position, health, inventory, nearby entities",
|
|
4531
|
+
get: async (runtime, _message, _state) => {
|
|
4532
|
+
const service = runtime.getService(MINECRAFT_SERVICE_TYPE);
|
|
4533
|
+
if (!service) {
|
|
4534
|
+
return {
|
|
4535
|
+
text: "Minecraft service is not available",
|
|
4536
|
+
values: { connected: false },
|
|
4537
|
+
data: {}
|
|
4538
|
+
};
|
|
4539
|
+
}
|
|
4540
|
+
try {
|
|
4541
|
+
const state = await service.getWorldState();
|
|
4542
|
+
if (!state.connected) {
|
|
4543
|
+
return {
|
|
4544
|
+
text: "Minecraft bot is not connected. Use MC_CONNECT to join a server.",
|
|
4545
|
+
values: { connected: false },
|
|
4546
|
+
data: {}
|
|
4547
|
+
};
|
|
4548
|
+
}
|
|
4549
|
+
const pos = state.position ? `(${state.position.x.toFixed(1)}, ${state.position.y.toFixed(1)}, ${state.position.z.toFixed(1)})` : "(unknown)";
|
|
4550
|
+
const invCount = Array.isArray(state.inventory) ? state.inventory.length : 0;
|
|
4551
|
+
const entCount = Array.isArray(state.nearbyEntities) ? state.nearbyEntities.length : 0;
|
|
4552
|
+
return {
|
|
4553
|
+
text: `Minecraft: hp=${state.health ?? "?"} food=${state.food ?? "?"} pos=${pos} invItems=${invCount} nearbyEntities=${entCount}`,
|
|
4554
|
+
values: {
|
|
4555
|
+
connected: true,
|
|
4556
|
+
health: state.health ?? null,
|
|
4557
|
+
food: state.food ?? null,
|
|
4558
|
+
x: state.position?.x ?? null,
|
|
4559
|
+
y: state.position?.y ?? null,
|
|
4560
|
+
z: state.position?.z ?? null,
|
|
4561
|
+
inventoryCount: invCount,
|
|
4562
|
+
nearbyEntitiesCount: entCount
|
|
4563
|
+
},
|
|
4564
|
+
data: state
|
|
4565
|
+
};
|
|
4566
|
+
} catch (err) {
|
|
4567
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
4568
|
+
logger4.error(`[Minecraft] Error getting world state: ${msg}`);
|
|
4569
|
+
return {
|
|
4570
|
+
text: "Error getting Minecraft world state",
|
|
4571
|
+
values: { connected: false, error: true },
|
|
4572
|
+
data: {}
|
|
4573
|
+
};
|
|
4574
|
+
}
|
|
4575
|
+
}
|
|
4576
|
+
};
|
|
4577
|
+
// src/index.ts
|
|
4578
|
+
var configSchema = z9.object({
|
|
4579
|
+
MC_SERVER_PORT: z9.string().optional().default("3457"),
|
|
4580
|
+
MC_HOST: z9.string().optional().default("127.0.0.1"),
|
|
4581
|
+
MC_PORT: z9.string().optional().default("25565"),
|
|
4582
|
+
MC_USERNAME: z9.string().optional(),
|
|
4583
|
+
MC_AUTH: z9.string().optional().default("offline"),
|
|
4584
|
+
MC_VERSION: z9.string().optional()
|
|
4585
|
+
});
|
|
4586
|
+
var minecraftStateProvider = minecraftWorldStateProvider;
|
|
4587
|
+
var minecraftPlugin = {
|
|
4588
|
+
name: "plugin-minecraft",
|
|
4589
|
+
description: "Minecraft automation plugin (Mineflayer bridge)",
|
|
4590
|
+
config: {
|
|
4591
|
+
MC_SERVER_PORT: process.env.MC_SERVER_PORT ?? "3457",
|
|
4592
|
+
MC_HOST: process.env.MC_HOST ?? "127.0.0.1",
|
|
4593
|
+
MC_PORT: process.env.MC_PORT ?? "25565",
|
|
4594
|
+
MC_USERNAME: process.env.MC_USERNAME ?? null,
|
|
4595
|
+
MC_AUTH: process.env.MC_AUTH ?? "offline",
|
|
4596
|
+
MC_VERSION: process.env.MC_VERSION ?? null
|
|
4597
|
+
},
|
|
4598
|
+
async init(config, _runtime) {
|
|
4599
|
+
logger5.info("Initializing Minecraft plugin");
|
|
4600
|
+
const validatedConfig = await configSchema.parseAsync(config);
|
|
4601
|
+
for (const [key, value] of Object.entries(validatedConfig)) {
|
|
4602
|
+
if (value !== undefined && value !== null) {
|
|
4603
|
+
process.env[key] = String(value);
|
|
4604
|
+
}
|
|
4605
|
+
}
|
|
4606
|
+
logger5.info("Minecraft plugin initialized");
|
|
4607
|
+
},
|
|
4608
|
+
services: [MinecraftService, WaypointsService],
|
|
4609
|
+
actions: [
|
|
4610
|
+
minecraftConnectAction,
|
|
4611
|
+
minecraftDisconnectAction,
|
|
4612
|
+
minecraftChatAction,
|
|
4613
|
+
minecraftGotoAction,
|
|
4614
|
+
minecraftStopAction,
|
|
4615
|
+
minecraftLookAction,
|
|
4616
|
+
minecraftControlAction,
|
|
4617
|
+
minecraftDigAction,
|
|
4618
|
+
minecraftPlaceAction,
|
|
4619
|
+
minecraftAttackAction,
|
|
4620
|
+
minecraftScanAction,
|
|
4621
|
+
minecraftWaypointSetAction,
|
|
4622
|
+
minecraftWaypointListAction,
|
|
4623
|
+
minecraftWaypointGotoAction,
|
|
4624
|
+
minecraftWaypointDeleteAction
|
|
4625
|
+
],
|
|
4626
|
+
providers: [
|
|
4627
|
+
minecraftStateProvider,
|
|
4628
|
+
minecraftWaypointsProvider,
|
|
4629
|
+
minecraftVisionProvider
|
|
4630
|
+
]
|
|
4631
|
+
};
|
|
4632
|
+
var src_default = minecraftPlugin;
|
|
4633
|
+
export {
|
|
4634
|
+
minecraftWorldStateSchema,
|
|
4635
|
+
minecraftWorldStateProvider,
|
|
4636
|
+
minecraftWaypointsProvider,
|
|
4637
|
+
minecraftWaypointSetAction,
|
|
4638
|
+
minecraftWaypointListAction,
|
|
4639
|
+
minecraftWaypointGotoAction,
|
|
4640
|
+
minecraftWaypointDeleteAction,
|
|
4641
|
+
minecraftVisionProvider,
|
|
4642
|
+
minecraftStopAction,
|
|
4643
|
+
minecraftScanAction,
|
|
4644
|
+
minecraftPlugin,
|
|
4645
|
+
minecraftPlaceAction,
|
|
4646
|
+
minecraftLookAction,
|
|
4647
|
+
minecraftGotoAction,
|
|
4648
|
+
minecraftDisconnectAction,
|
|
4649
|
+
minecraftDigAction,
|
|
4650
|
+
minecraftControlAction,
|
|
4651
|
+
minecraftConnectAction,
|
|
4652
|
+
minecraftChatAction,
|
|
4653
|
+
minecraftAttackAction,
|
|
4654
|
+
src_default as default,
|
|
4655
|
+
WaypointsService,
|
|
4656
|
+
WAYPOINTS_SERVICE_TYPE,
|
|
4657
|
+
Session,
|
|
4658
|
+
MinecraftWebSocketClient,
|
|
4659
|
+
MinecraftService,
|
|
4660
|
+
MinecraftProcessManager,
|
|
4661
|
+
MINECRAFT_SERVICE_TYPE
|
|
4662
|
+
};
|
|
4663
|
+
|
|
4664
|
+
//# debugId=BB7F89CAAD33745264756E2164756E21
|