flashcards-codex-bridge 0.0.0-stage → 0.1.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 +41 -2
- package/bin.mjs +2 -0
- package/dist/bin.mjs +3882 -0
- package/package.json +32 -4
package/dist/bin.mjs
ADDED
|
@@ -0,0 +1,3882 @@
|
|
|
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
|
+
function __accessProp(key) {
|
|
8
|
+
return this[key];
|
|
9
|
+
}
|
|
10
|
+
var __toESMCache_node;
|
|
11
|
+
var __toESMCache_esm;
|
|
12
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
13
|
+
var canCache = mod != null && typeof mod === "object";
|
|
14
|
+
if (canCache) {
|
|
15
|
+
var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
|
|
16
|
+
var cached = cache.get(mod);
|
|
17
|
+
if (cached)
|
|
18
|
+
return cached;
|
|
19
|
+
}
|
|
20
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
21
|
+
const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
22
|
+
if (mod && typeof mod === "object" || typeof mod === "function") {
|
|
23
|
+
for (let key of __getOwnPropNames(mod))
|
|
24
|
+
if (!__hasOwnProp.call(to, key))
|
|
25
|
+
__defProp(to, key, {
|
|
26
|
+
get: __accessProp.bind(mod, key),
|
|
27
|
+
enumerable: true
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
if (canCache)
|
|
31
|
+
cache.set(mod, to);
|
|
32
|
+
return to;
|
|
33
|
+
};
|
|
34
|
+
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
35
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
36
|
+
|
|
37
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/constants.js
|
|
38
|
+
var require_constants = __commonJS(function(exports, module) {
|
|
39
|
+
var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
|
|
40
|
+
var hasBlob = typeof Blob !== "undefined";
|
|
41
|
+
if (hasBlob)
|
|
42
|
+
BINARY_TYPES.push("blob");
|
|
43
|
+
module.exports = {
|
|
44
|
+
BINARY_TYPES,
|
|
45
|
+
CLOSE_TIMEOUT: 30000,
|
|
46
|
+
EMPTY_BUFFER: Buffer.alloc(0),
|
|
47
|
+
GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
|
|
48
|
+
hasBlob,
|
|
49
|
+
kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
|
|
50
|
+
kListener: Symbol("kListener"),
|
|
51
|
+
kStatusCode: Symbol("status-code"),
|
|
52
|
+
kWebSocket: Symbol("websocket"),
|
|
53
|
+
NOOP: () => {}
|
|
54
|
+
};
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/buffer-util.js
|
|
58
|
+
var require_buffer_util = __commonJS(function(exports, module) {
|
|
59
|
+
var { EMPTY_BUFFER } = require_constants();
|
|
60
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
61
|
+
function concat(list, totalLength) {
|
|
62
|
+
if (list.length === 0)
|
|
63
|
+
return EMPTY_BUFFER;
|
|
64
|
+
if (list.length === 1)
|
|
65
|
+
return list[0];
|
|
66
|
+
const target = Buffer.allocUnsafe(totalLength);
|
|
67
|
+
let offset = 0;
|
|
68
|
+
for (let i = 0;i < list.length; i++) {
|
|
69
|
+
const buf = list[i];
|
|
70
|
+
target.set(buf, offset);
|
|
71
|
+
offset += buf.length;
|
|
72
|
+
}
|
|
73
|
+
if (offset < totalLength) {
|
|
74
|
+
return new FastBuffer(target.buffer, target.byteOffset, offset);
|
|
75
|
+
}
|
|
76
|
+
return target;
|
|
77
|
+
}
|
|
78
|
+
function _mask(source, mask, output, offset, length) {
|
|
79
|
+
for (let i = 0;i < length; i++) {
|
|
80
|
+
output[offset + i] = source[i] ^ mask[i & 3];
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function _unmask(buffer, mask) {
|
|
84
|
+
for (let i = 0;i < buffer.length; i++) {
|
|
85
|
+
buffer[i] ^= mask[i & 3];
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function toArrayBuffer(buf) {
|
|
89
|
+
if (buf.length === buf.buffer.byteLength) {
|
|
90
|
+
return buf.buffer;
|
|
91
|
+
}
|
|
92
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
|
|
93
|
+
}
|
|
94
|
+
function toBuffer(data) {
|
|
95
|
+
toBuffer.readOnly = true;
|
|
96
|
+
if (Buffer.isBuffer(data))
|
|
97
|
+
return data;
|
|
98
|
+
let buf;
|
|
99
|
+
if (data instanceof ArrayBuffer) {
|
|
100
|
+
buf = new FastBuffer(data);
|
|
101
|
+
} else if (ArrayBuffer.isView(data)) {
|
|
102
|
+
buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
|
|
103
|
+
} else {
|
|
104
|
+
buf = Buffer.from(data);
|
|
105
|
+
toBuffer.readOnly = false;
|
|
106
|
+
}
|
|
107
|
+
return buf;
|
|
108
|
+
}
|
|
109
|
+
module.exports = {
|
|
110
|
+
concat,
|
|
111
|
+
mask: _mask,
|
|
112
|
+
toArrayBuffer,
|
|
113
|
+
toBuffer,
|
|
114
|
+
unmask: _unmask
|
|
115
|
+
};
|
|
116
|
+
if (!process.env.WS_NO_BUFFER_UTIL) {
|
|
117
|
+
try {
|
|
118
|
+
const bufferUtil = __require("bufferutil");
|
|
119
|
+
module.exports.mask = function(source, mask2, output, offset, length) {
|
|
120
|
+
if (length < 48)
|
|
121
|
+
_mask(source, mask2, output, offset, length);
|
|
122
|
+
else
|
|
123
|
+
bufferUtil.mask(source, mask2, output, offset, length);
|
|
124
|
+
};
|
|
125
|
+
module.exports.unmask = function(buffer, mask) {
|
|
126
|
+
if (buffer.length < 32)
|
|
127
|
+
_unmask(buffer, mask);
|
|
128
|
+
else
|
|
129
|
+
bufferUtil.unmask(buffer, mask);
|
|
130
|
+
};
|
|
131
|
+
} catch (e) {}
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/limiter.js
|
|
136
|
+
var require_limiter = __commonJS(function(exports, module) {
|
|
137
|
+
var kDone = Symbol("kDone");
|
|
138
|
+
var kRun = Symbol("kRun");
|
|
139
|
+
|
|
140
|
+
class Limiter {
|
|
141
|
+
constructor(concurrency) {
|
|
142
|
+
this[kDone] = () => {
|
|
143
|
+
this.pending--;
|
|
144
|
+
this[kRun]();
|
|
145
|
+
};
|
|
146
|
+
this.concurrency = concurrency || Infinity;
|
|
147
|
+
this.jobs = [];
|
|
148
|
+
this.pending = 0;
|
|
149
|
+
}
|
|
150
|
+
add(job) {
|
|
151
|
+
this.jobs.push(job);
|
|
152
|
+
this[kRun]();
|
|
153
|
+
}
|
|
154
|
+
[kRun]() {
|
|
155
|
+
if (this.pending === this.concurrency)
|
|
156
|
+
return;
|
|
157
|
+
if (this.jobs.length) {
|
|
158
|
+
const job = this.jobs.shift();
|
|
159
|
+
this.pending++;
|
|
160
|
+
job(this[kDone]);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
module.exports = Limiter;
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/permessage-deflate.js
|
|
168
|
+
var require_permessage_deflate = __commonJS(function(exports, module) {
|
|
169
|
+
var zlib = __require("zlib");
|
|
170
|
+
var bufferUtil = require_buffer_util();
|
|
171
|
+
var Limiter = require_limiter();
|
|
172
|
+
var { kStatusCode } = require_constants();
|
|
173
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
174
|
+
var TRAILER = Buffer.from([0, 0, 255, 255]);
|
|
175
|
+
var kPerMessageDeflate = Symbol("permessage-deflate");
|
|
176
|
+
var kTotalLength = Symbol("total-length");
|
|
177
|
+
var kCallback = Symbol("callback");
|
|
178
|
+
var kBuffers = Symbol("buffers");
|
|
179
|
+
var kError = Symbol("error");
|
|
180
|
+
var zlibLimiter;
|
|
181
|
+
|
|
182
|
+
class PerMessageDeflate {
|
|
183
|
+
constructor(options) {
|
|
184
|
+
this._options = options || {};
|
|
185
|
+
this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024;
|
|
186
|
+
this._maxPayload = this._options.maxPayload | 0;
|
|
187
|
+
this._isServer = !!this._options.isServer;
|
|
188
|
+
this._deflate = null;
|
|
189
|
+
this._inflate = null;
|
|
190
|
+
this.params = null;
|
|
191
|
+
if (!zlibLimiter) {
|
|
192
|
+
const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10;
|
|
193
|
+
zlibLimiter = new Limiter(concurrency);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
static get extensionName() {
|
|
197
|
+
return "permessage-deflate";
|
|
198
|
+
}
|
|
199
|
+
offer() {
|
|
200
|
+
const params = {};
|
|
201
|
+
if (this._options.serverNoContextTakeover) {
|
|
202
|
+
params.server_no_context_takeover = true;
|
|
203
|
+
}
|
|
204
|
+
if (this._options.clientNoContextTakeover) {
|
|
205
|
+
params.client_no_context_takeover = true;
|
|
206
|
+
}
|
|
207
|
+
if (this._options.serverMaxWindowBits) {
|
|
208
|
+
params.server_max_window_bits = this._options.serverMaxWindowBits;
|
|
209
|
+
}
|
|
210
|
+
if (this._options.clientMaxWindowBits) {
|
|
211
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
212
|
+
} else if (this._options.clientMaxWindowBits == null) {
|
|
213
|
+
params.client_max_window_bits = true;
|
|
214
|
+
}
|
|
215
|
+
return params;
|
|
216
|
+
}
|
|
217
|
+
accept(configurations) {
|
|
218
|
+
configurations = this.normalizeParams(configurations);
|
|
219
|
+
this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
|
|
220
|
+
return this.params;
|
|
221
|
+
}
|
|
222
|
+
cleanup() {
|
|
223
|
+
if (this._inflate) {
|
|
224
|
+
this._inflate.close();
|
|
225
|
+
this._inflate = null;
|
|
226
|
+
}
|
|
227
|
+
if (this._deflate) {
|
|
228
|
+
const callback = this._deflate[kCallback];
|
|
229
|
+
this._deflate.close();
|
|
230
|
+
this._deflate = null;
|
|
231
|
+
if (callback) {
|
|
232
|
+
callback(new Error("The deflate stream was closed while data was being processed"));
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
acceptAsServer(offers) {
|
|
237
|
+
const opts = this._options;
|
|
238
|
+
const accepted = offers.find((params) => {
|
|
239
|
+
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" && (typeof params.client_max_window_bits === "number" ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)) {
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
242
|
+
return true;
|
|
243
|
+
});
|
|
244
|
+
if (!accepted) {
|
|
245
|
+
throw new Error("None of the extension offers can be accepted");
|
|
246
|
+
}
|
|
247
|
+
if (opts.serverNoContextTakeover) {
|
|
248
|
+
accepted.server_no_context_takeover = true;
|
|
249
|
+
}
|
|
250
|
+
if (opts.clientNoContextTakeover) {
|
|
251
|
+
accepted.client_no_context_takeover = true;
|
|
252
|
+
}
|
|
253
|
+
if (typeof opts.serverMaxWindowBits === "number") {
|
|
254
|
+
accepted.server_max_window_bits = opts.serverMaxWindowBits;
|
|
255
|
+
}
|
|
256
|
+
if (typeof opts.clientMaxWindowBits === "number") {
|
|
257
|
+
accepted.client_max_window_bits = opts.clientMaxWindowBits;
|
|
258
|
+
} else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
|
|
259
|
+
delete accepted.client_max_window_bits;
|
|
260
|
+
}
|
|
261
|
+
return accepted;
|
|
262
|
+
}
|
|
263
|
+
acceptAsClient(response) {
|
|
264
|
+
const params = response[0];
|
|
265
|
+
if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
|
|
266
|
+
throw new Error('Unexpected parameter "client_no_context_takeover"');
|
|
267
|
+
}
|
|
268
|
+
if (!params.client_max_window_bits) {
|
|
269
|
+
if (typeof this._options.clientMaxWindowBits === "number") {
|
|
270
|
+
params.client_max_window_bits = this._options.clientMaxWindowBits;
|
|
271
|
+
}
|
|
272
|
+
} else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
|
|
273
|
+
throw new Error('Unexpected or invalid parameter "client_max_window_bits"');
|
|
274
|
+
}
|
|
275
|
+
return params;
|
|
276
|
+
}
|
|
277
|
+
normalizeParams(configurations) {
|
|
278
|
+
configurations.forEach((params) => {
|
|
279
|
+
Object.keys(params).forEach((key) => {
|
|
280
|
+
let value = params[key];
|
|
281
|
+
if (value.length > 1) {
|
|
282
|
+
throw new Error(`Parameter "${key}" must have only a single value`);
|
|
283
|
+
}
|
|
284
|
+
value = value[0];
|
|
285
|
+
if (key === "client_max_window_bits") {
|
|
286
|
+
if (value !== true) {
|
|
287
|
+
const num = +value;
|
|
288
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
289
|
+
throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
|
|
290
|
+
}
|
|
291
|
+
value = num;
|
|
292
|
+
} else if (!this._isServer) {
|
|
293
|
+
throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
|
|
294
|
+
}
|
|
295
|
+
} else if (key === "server_max_window_bits") {
|
|
296
|
+
const num = +value;
|
|
297
|
+
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
298
|
+
throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
|
|
299
|
+
}
|
|
300
|
+
value = num;
|
|
301
|
+
} else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
|
|
302
|
+
if (value !== true) {
|
|
303
|
+
throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
|
|
304
|
+
}
|
|
305
|
+
} else {
|
|
306
|
+
throw new Error(`Unknown parameter "${key}"`);
|
|
307
|
+
}
|
|
308
|
+
params[key] = value;
|
|
309
|
+
});
|
|
310
|
+
});
|
|
311
|
+
return configurations;
|
|
312
|
+
}
|
|
313
|
+
decompress(data, fin, callback) {
|
|
314
|
+
zlibLimiter.add((done) => {
|
|
315
|
+
this._decompress(data, fin, (err, result) => {
|
|
316
|
+
done();
|
|
317
|
+
callback(err, result);
|
|
318
|
+
});
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
compress(data, fin, callback) {
|
|
322
|
+
zlibLimiter.add((done) => {
|
|
323
|
+
this._compress(data, fin, (err, result) => {
|
|
324
|
+
done();
|
|
325
|
+
callback(err, result);
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
_decompress(data, fin, callback) {
|
|
330
|
+
const endpoint = this._isServer ? "client" : "server";
|
|
331
|
+
if (!this._inflate) {
|
|
332
|
+
const key = `${endpoint}_max_window_bits`;
|
|
333
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
334
|
+
this._inflate = zlib.createInflateRaw({
|
|
335
|
+
...this._options.zlibInflateOptions,
|
|
336
|
+
windowBits
|
|
337
|
+
});
|
|
338
|
+
this._inflate[kPerMessageDeflate] = this;
|
|
339
|
+
this._inflate[kTotalLength] = 0;
|
|
340
|
+
this._inflate[kBuffers] = [];
|
|
341
|
+
this._inflate.on("error", inflateOnError);
|
|
342
|
+
this._inflate.on("data", inflateOnData);
|
|
343
|
+
}
|
|
344
|
+
this._inflate[kCallback] = callback;
|
|
345
|
+
this._inflate.write(data);
|
|
346
|
+
if (fin)
|
|
347
|
+
this._inflate.write(TRAILER);
|
|
348
|
+
this._inflate.flush(() => {
|
|
349
|
+
const err = this._inflate[kError];
|
|
350
|
+
if (err) {
|
|
351
|
+
this._inflate.close();
|
|
352
|
+
this._inflate = null;
|
|
353
|
+
callback(err);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
const data = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
|
|
357
|
+
if (this._inflate._readableState.endEmitted) {
|
|
358
|
+
this._inflate.close();
|
|
359
|
+
this._inflate = null;
|
|
360
|
+
} else {
|
|
361
|
+
this._inflate[kTotalLength] = 0;
|
|
362
|
+
this._inflate[kBuffers] = [];
|
|
363
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
364
|
+
this._inflate.reset();
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
callback(null, data);
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
_compress(data, fin, callback) {
|
|
371
|
+
const endpoint = this._isServer ? "server" : "client";
|
|
372
|
+
if (!this._deflate) {
|
|
373
|
+
const key = `${endpoint}_max_window_bits`;
|
|
374
|
+
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
|
|
375
|
+
this._deflate = zlib.createDeflateRaw({
|
|
376
|
+
...this._options.zlibDeflateOptions,
|
|
377
|
+
windowBits
|
|
378
|
+
});
|
|
379
|
+
this._deflate[kTotalLength] = 0;
|
|
380
|
+
this._deflate[kBuffers] = [];
|
|
381
|
+
this._deflate.on("data", deflateOnData);
|
|
382
|
+
}
|
|
383
|
+
this._deflate[kCallback] = callback;
|
|
384
|
+
this._deflate.write(data);
|
|
385
|
+
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
|
|
386
|
+
if (!this._deflate) {
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
let data = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
|
|
390
|
+
if (fin) {
|
|
391
|
+
data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
|
|
392
|
+
}
|
|
393
|
+
this._deflate[kCallback] = null;
|
|
394
|
+
this._deflate[kTotalLength] = 0;
|
|
395
|
+
this._deflate[kBuffers] = [];
|
|
396
|
+
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
|
|
397
|
+
this._deflate.reset();
|
|
398
|
+
}
|
|
399
|
+
callback(null, data);
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
module.exports = PerMessageDeflate;
|
|
404
|
+
function deflateOnData(chunk) {
|
|
405
|
+
this[kBuffers].push(chunk);
|
|
406
|
+
this[kTotalLength] += chunk.length;
|
|
407
|
+
}
|
|
408
|
+
function inflateOnData(chunk) {
|
|
409
|
+
this[kTotalLength] += chunk.length;
|
|
410
|
+
if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
|
|
411
|
+
this[kBuffers].push(chunk);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
this[kError] = new RangeError("Max payload size exceeded");
|
|
415
|
+
this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
|
|
416
|
+
this[kError][kStatusCode] = 1009;
|
|
417
|
+
this.removeListener("data", inflateOnData);
|
|
418
|
+
this.reset();
|
|
419
|
+
}
|
|
420
|
+
function inflateOnError(err) {
|
|
421
|
+
this[kPerMessageDeflate]._inflate = null;
|
|
422
|
+
if (this[kError]) {
|
|
423
|
+
this[kCallback](this[kError]);
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
err[kStatusCode] = 1007;
|
|
427
|
+
this[kCallback](err);
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/validation.js
|
|
432
|
+
var require_validation = __commonJS(function(exports, module) {
|
|
433
|
+
var { isUtf8 } = __require("buffer");
|
|
434
|
+
var { hasBlob } = require_constants();
|
|
435
|
+
var tokenChars = [
|
|
436
|
+
0,
|
|
437
|
+
0,
|
|
438
|
+
0,
|
|
439
|
+
0,
|
|
440
|
+
0,
|
|
441
|
+
0,
|
|
442
|
+
0,
|
|
443
|
+
0,
|
|
444
|
+
0,
|
|
445
|
+
0,
|
|
446
|
+
0,
|
|
447
|
+
0,
|
|
448
|
+
0,
|
|
449
|
+
0,
|
|
450
|
+
0,
|
|
451
|
+
0,
|
|
452
|
+
0,
|
|
453
|
+
0,
|
|
454
|
+
0,
|
|
455
|
+
0,
|
|
456
|
+
0,
|
|
457
|
+
0,
|
|
458
|
+
0,
|
|
459
|
+
0,
|
|
460
|
+
0,
|
|
461
|
+
0,
|
|
462
|
+
0,
|
|
463
|
+
0,
|
|
464
|
+
0,
|
|
465
|
+
0,
|
|
466
|
+
0,
|
|
467
|
+
0,
|
|
468
|
+
0,
|
|
469
|
+
1,
|
|
470
|
+
0,
|
|
471
|
+
1,
|
|
472
|
+
1,
|
|
473
|
+
1,
|
|
474
|
+
1,
|
|
475
|
+
1,
|
|
476
|
+
0,
|
|
477
|
+
0,
|
|
478
|
+
1,
|
|
479
|
+
1,
|
|
480
|
+
0,
|
|
481
|
+
1,
|
|
482
|
+
1,
|
|
483
|
+
0,
|
|
484
|
+
1,
|
|
485
|
+
1,
|
|
486
|
+
1,
|
|
487
|
+
1,
|
|
488
|
+
1,
|
|
489
|
+
1,
|
|
490
|
+
1,
|
|
491
|
+
1,
|
|
492
|
+
1,
|
|
493
|
+
1,
|
|
494
|
+
0,
|
|
495
|
+
0,
|
|
496
|
+
0,
|
|
497
|
+
0,
|
|
498
|
+
0,
|
|
499
|
+
0,
|
|
500
|
+
0,
|
|
501
|
+
1,
|
|
502
|
+
1,
|
|
503
|
+
1,
|
|
504
|
+
1,
|
|
505
|
+
1,
|
|
506
|
+
1,
|
|
507
|
+
1,
|
|
508
|
+
1,
|
|
509
|
+
1,
|
|
510
|
+
1,
|
|
511
|
+
1,
|
|
512
|
+
1,
|
|
513
|
+
1,
|
|
514
|
+
1,
|
|
515
|
+
1,
|
|
516
|
+
1,
|
|
517
|
+
1,
|
|
518
|
+
1,
|
|
519
|
+
1,
|
|
520
|
+
1,
|
|
521
|
+
1,
|
|
522
|
+
1,
|
|
523
|
+
1,
|
|
524
|
+
1,
|
|
525
|
+
1,
|
|
526
|
+
1,
|
|
527
|
+
0,
|
|
528
|
+
0,
|
|
529
|
+
0,
|
|
530
|
+
1,
|
|
531
|
+
1,
|
|
532
|
+
1,
|
|
533
|
+
1,
|
|
534
|
+
1,
|
|
535
|
+
1,
|
|
536
|
+
1,
|
|
537
|
+
1,
|
|
538
|
+
1,
|
|
539
|
+
1,
|
|
540
|
+
1,
|
|
541
|
+
1,
|
|
542
|
+
1,
|
|
543
|
+
1,
|
|
544
|
+
1,
|
|
545
|
+
1,
|
|
546
|
+
1,
|
|
547
|
+
1,
|
|
548
|
+
1,
|
|
549
|
+
1,
|
|
550
|
+
1,
|
|
551
|
+
1,
|
|
552
|
+
1,
|
|
553
|
+
1,
|
|
554
|
+
1,
|
|
555
|
+
1,
|
|
556
|
+
1,
|
|
557
|
+
1,
|
|
558
|
+
1,
|
|
559
|
+
0,
|
|
560
|
+
1,
|
|
561
|
+
0,
|
|
562
|
+
1,
|
|
563
|
+
0
|
|
564
|
+
];
|
|
565
|
+
function isValidStatusCode(code) {
|
|
566
|
+
return code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3000 && code <= 4999;
|
|
567
|
+
}
|
|
568
|
+
function _isValidUTF8(buf) {
|
|
569
|
+
const len = buf.length;
|
|
570
|
+
let i = 0;
|
|
571
|
+
while (i < len) {
|
|
572
|
+
if ((buf[i] & 128) === 0) {
|
|
573
|
+
i++;
|
|
574
|
+
} else if ((buf[i] & 224) === 192) {
|
|
575
|
+
if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
|
|
576
|
+
return false;
|
|
577
|
+
}
|
|
578
|
+
i += 2;
|
|
579
|
+
} else if ((buf[i] & 240) === 224) {
|
|
580
|
+
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) {
|
|
581
|
+
return false;
|
|
582
|
+
}
|
|
583
|
+
i += 3;
|
|
584
|
+
} else if ((buf[i] & 248) === 240) {
|
|
585
|
+
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) {
|
|
586
|
+
return false;
|
|
587
|
+
}
|
|
588
|
+
i += 4;
|
|
589
|
+
} else {
|
|
590
|
+
return false;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return true;
|
|
594
|
+
}
|
|
595
|
+
function isBlob(value) {
|
|
596
|
+
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");
|
|
597
|
+
}
|
|
598
|
+
module.exports = {
|
|
599
|
+
isBlob,
|
|
600
|
+
isValidStatusCode,
|
|
601
|
+
isValidUTF8: _isValidUTF8,
|
|
602
|
+
tokenChars
|
|
603
|
+
};
|
|
604
|
+
if (isUtf8) {
|
|
605
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
606
|
+
return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
|
|
607
|
+
};
|
|
608
|
+
} else if (!process.env.WS_NO_UTF_8_VALIDATE) {
|
|
609
|
+
try {
|
|
610
|
+
const isValidUTF8 = __require("utf-8-validate");
|
|
611
|
+
module.exports.isValidUTF8 = function(buf) {
|
|
612
|
+
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
|
|
613
|
+
};
|
|
614
|
+
} catch (e) {}
|
|
615
|
+
}
|
|
616
|
+
});
|
|
617
|
+
|
|
618
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/receiver.js
|
|
619
|
+
var require_receiver = __commonJS(function(exports, module) {
|
|
620
|
+
var { Writable } = __require("stream");
|
|
621
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
622
|
+
var {
|
|
623
|
+
BINARY_TYPES,
|
|
624
|
+
EMPTY_BUFFER,
|
|
625
|
+
kStatusCode,
|
|
626
|
+
kWebSocket
|
|
627
|
+
} = require_constants();
|
|
628
|
+
var { concat, toArrayBuffer, unmask } = require_buffer_util();
|
|
629
|
+
var { isValidStatusCode, isValidUTF8 } = require_validation();
|
|
630
|
+
var FastBuffer = Buffer[Symbol.species];
|
|
631
|
+
var GET_INFO = 0;
|
|
632
|
+
var GET_PAYLOAD_LENGTH_16 = 1;
|
|
633
|
+
var GET_PAYLOAD_LENGTH_64 = 2;
|
|
634
|
+
var GET_MASK = 3;
|
|
635
|
+
var GET_DATA = 4;
|
|
636
|
+
var INFLATING = 5;
|
|
637
|
+
var DEFER_EVENT = 6;
|
|
638
|
+
|
|
639
|
+
class Receiver extends Writable {
|
|
640
|
+
constructor(options = {}) {
|
|
641
|
+
super();
|
|
642
|
+
this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true;
|
|
643
|
+
this._binaryType = options.binaryType || BINARY_TYPES[0];
|
|
644
|
+
this._extensions = options.extensions || {};
|
|
645
|
+
this._isServer = !!options.isServer;
|
|
646
|
+
this._maxBufferedChunks = options.maxBufferedChunks | 0;
|
|
647
|
+
this._maxFragments = options.maxFragments | 0;
|
|
648
|
+
this._maxPayload = options.maxPayload | 0;
|
|
649
|
+
this._skipUTF8Validation = !!options.skipUTF8Validation;
|
|
650
|
+
this[kWebSocket] = undefined;
|
|
651
|
+
this._bufferedBytes = 0;
|
|
652
|
+
this._buffers = [];
|
|
653
|
+
this._compressed = false;
|
|
654
|
+
this._payloadLength = 0;
|
|
655
|
+
this._mask = undefined;
|
|
656
|
+
this._fragmented = 0;
|
|
657
|
+
this._masked = false;
|
|
658
|
+
this._fin = false;
|
|
659
|
+
this._opcode = 0;
|
|
660
|
+
this._totalPayloadLength = 0;
|
|
661
|
+
this._messageLength = 0;
|
|
662
|
+
this._numFragments = 0;
|
|
663
|
+
this._fragments = [];
|
|
664
|
+
this._errored = false;
|
|
665
|
+
this._loop = false;
|
|
666
|
+
this._state = GET_INFO;
|
|
667
|
+
}
|
|
668
|
+
_write(chunk, encoding, cb) {
|
|
669
|
+
if (this._opcode === 8 && this._state == GET_INFO)
|
|
670
|
+
return cb();
|
|
671
|
+
if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
|
|
672
|
+
cb(this.createError(RangeError, "Too many buffered chunks", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
this._bufferedBytes += chunk.length;
|
|
676
|
+
this._buffers.push(chunk);
|
|
677
|
+
this.startLoop(cb);
|
|
678
|
+
}
|
|
679
|
+
consume(n) {
|
|
680
|
+
this._bufferedBytes -= n;
|
|
681
|
+
if (n === this._buffers[0].length)
|
|
682
|
+
return this._buffers.shift();
|
|
683
|
+
if (n < this._buffers[0].length) {
|
|
684
|
+
const buf = this._buffers[0];
|
|
685
|
+
this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
|
|
686
|
+
return new FastBuffer(buf.buffer, buf.byteOffset, n);
|
|
687
|
+
}
|
|
688
|
+
const dst = Buffer.allocUnsafe(n);
|
|
689
|
+
do {
|
|
690
|
+
const buf = this._buffers[0];
|
|
691
|
+
const offset = dst.length - n;
|
|
692
|
+
if (n >= buf.length) {
|
|
693
|
+
dst.set(this._buffers.shift(), offset);
|
|
694
|
+
} else {
|
|
695
|
+
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
|
|
696
|
+
this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
|
|
697
|
+
}
|
|
698
|
+
n -= buf.length;
|
|
699
|
+
} while (n > 0);
|
|
700
|
+
return dst;
|
|
701
|
+
}
|
|
702
|
+
startLoop(cb) {
|
|
703
|
+
this._loop = true;
|
|
704
|
+
do {
|
|
705
|
+
switch (this._state) {
|
|
706
|
+
case GET_INFO:
|
|
707
|
+
this.getInfo(cb);
|
|
708
|
+
break;
|
|
709
|
+
case GET_PAYLOAD_LENGTH_16:
|
|
710
|
+
this.getPayloadLength16(cb);
|
|
711
|
+
break;
|
|
712
|
+
case GET_PAYLOAD_LENGTH_64:
|
|
713
|
+
this.getPayloadLength64(cb);
|
|
714
|
+
break;
|
|
715
|
+
case GET_MASK:
|
|
716
|
+
this.getMask();
|
|
717
|
+
break;
|
|
718
|
+
case GET_DATA:
|
|
719
|
+
this.getData(cb);
|
|
720
|
+
break;
|
|
721
|
+
case INFLATING:
|
|
722
|
+
case DEFER_EVENT:
|
|
723
|
+
this._loop = false;
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
} while (this._loop);
|
|
727
|
+
if (!this._errored)
|
|
728
|
+
cb();
|
|
729
|
+
}
|
|
730
|
+
getInfo(cb) {
|
|
731
|
+
if (this._bufferedBytes < 2) {
|
|
732
|
+
this._loop = false;
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
const buf = this.consume(2);
|
|
736
|
+
if ((buf[0] & 48) !== 0) {
|
|
737
|
+
const error = this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3");
|
|
738
|
+
cb(error);
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
const compressed = (buf[0] & 64) === 64;
|
|
742
|
+
if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
|
|
743
|
+
const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
|
|
744
|
+
cb(error);
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
this._fin = (buf[0] & 128) === 128;
|
|
748
|
+
this._opcode = buf[0] & 15;
|
|
749
|
+
this._payloadLength = buf[1] & 127;
|
|
750
|
+
if (this._opcode === 0) {
|
|
751
|
+
if (compressed) {
|
|
752
|
+
const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
|
|
753
|
+
cb(error);
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
if (!this._fragmented) {
|
|
757
|
+
const error = this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE");
|
|
758
|
+
cb(error);
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
this._opcode = this._fragmented;
|
|
762
|
+
} else if (this._opcode === 1 || this._opcode === 2) {
|
|
763
|
+
if (this._fragmented) {
|
|
764
|
+
const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
|
|
765
|
+
cb(error);
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
this._compressed = compressed;
|
|
769
|
+
} else if (this._opcode > 7 && this._opcode < 11) {
|
|
770
|
+
if (!this._fin) {
|
|
771
|
+
const error = this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN");
|
|
772
|
+
cb(error);
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
if (compressed) {
|
|
776
|
+
const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
|
|
777
|
+
cb(error);
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
|
|
781
|
+
const error = this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");
|
|
782
|
+
cb(error);
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
} else {
|
|
786
|
+
const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
|
|
787
|
+
cb(error);
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
if (!this._fin && !this._fragmented)
|
|
791
|
+
this._fragmented = this._opcode;
|
|
792
|
+
this._masked = (buf[1] & 128) === 128;
|
|
793
|
+
if (this._isServer) {
|
|
794
|
+
if (!this._masked) {
|
|
795
|
+
const error = this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK");
|
|
796
|
+
cb(error);
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
} else if (this._masked) {
|
|
800
|
+
const error = this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK");
|
|
801
|
+
cb(error);
|
|
802
|
+
return;
|
|
803
|
+
}
|
|
804
|
+
if (this._payloadLength === 126)
|
|
805
|
+
this._state = GET_PAYLOAD_LENGTH_16;
|
|
806
|
+
else if (this._payloadLength === 127)
|
|
807
|
+
this._state = GET_PAYLOAD_LENGTH_64;
|
|
808
|
+
else
|
|
809
|
+
this.haveLength(cb);
|
|
810
|
+
}
|
|
811
|
+
getPayloadLength16(cb) {
|
|
812
|
+
if (this._bufferedBytes < 2) {
|
|
813
|
+
this._loop = false;
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
this._payloadLength = this.consume(2).readUInt16BE(0);
|
|
817
|
+
this.haveLength(cb);
|
|
818
|
+
}
|
|
819
|
+
getPayloadLength64(cb) {
|
|
820
|
+
if (this._bufferedBytes < 8) {
|
|
821
|
+
this._loop = false;
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
const buf = this.consume(8);
|
|
825
|
+
const num = buf.readUInt32BE(0);
|
|
826
|
+
if (num > Math.pow(2, 53 - 32) - 1) {
|
|
827
|
+
const error = this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");
|
|
828
|
+
cb(error);
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
|
|
832
|
+
this.haveLength(cb);
|
|
833
|
+
}
|
|
834
|
+
haveLength(cb) {
|
|
835
|
+
if (this._payloadLength && this._opcode < 8) {
|
|
836
|
+
this._totalPayloadLength += this._payloadLength;
|
|
837
|
+
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
|
|
838
|
+
const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
|
|
839
|
+
cb(error);
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
if (this._masked)
|
|
844
|
+
this._state = GET_MASK;
|
|
845
|
+
else
|
|
846
|
+
this._state = GET_DATA;
|
|
847
|
+
}
|
|
848
|
+
getMask() {
|
|
849
|
+
if (this._bufferedBytes < 4) {
|
|
850
|
+
this._loop = false;
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
this._mask = this.consume(4);
|
|
854
|
+
this._state = GET_DATA;
|
|
855
|
+
}
|
|
856
|
+
getData(cb) {
|
|
857
|
+
let data = EMPTY_BUFFER;
|
|
858
|
+
if (this._payloadLength) {
|
|
859
|
+
if (this._bufferedBytes < this._payloadLength) {
|
|
860
|
+
this._loop = false;
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
data = this.consume(this._payloadLength);
|
|
864
|
+
if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
|
|
865
|
+
unmask(data, this._mask);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
if (this._opcode > 7) {
|
|
869
|
+
this.controlMessage(data, cb);
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
|
|
873
|
+
const error = this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS");
|
|
874
|
+
cb(error);
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
if (this._compressed) {
|
|
878
|
+
this._state = INFLATING;
|
|
879
|
+
this.decompress(data, cb);
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
if (data.length) {
|
|
883
|
+
this._messageLength = this._totalPayloadLength;
|
|
884
|
+
this._fragments.push(data);
|
|
885
|
+
}
|
|
886
|
+
this.dataMessage(cb);
|
|
887
|
+
}
|
|
888
|
+
decompress(data, cb) {
|
|
889
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
890
|
+
perMessageDeflate.decompress(data, this._fin, (err, buf) => {
|
|
891
|
+
if (err)
|
|
892
|
+
return cb(err);
|
|
893
|
+
if (buf.length) {
|
|
894
|
+
this._messageLength += buf.length;
|
|
895
|
+
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
|
|
896
|
+
const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
|
|
897
|
+
cb(error);
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
this._fragments.push(buf);
|
|
901
|
+
}
|
|
902
|
+
this.dataMessage(cb);
|
|
903
|
+
if (this._state === GET_INFO)
|
|
904
|
+
this.startLoop(cb);
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
dataMessage(cb) {
|
|
908
|
+
if (!this._fin) {
|
|
909
|
+
this._state = GET_INFO;
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
912
|
+
const messageLength = this._messageLength;
|
|
913
|
+
const fragments = this._fragments;
|
|
914
|
+
this._totalPayloadLength = 0;
|
|
915
|
+
this._messageLength = 0;
|
|
916
|
+
this._fragmented = 0;
|
|
917
|
+
this._numFragments = 0;
|
|
918
|
+
this._fragments = [];
|
|
919
|
+
if (this._opcode === 2) {
|
|
920
|
+
let data;
|
|
921
|
+
if (this._binaryType === "nodebuffer") {
|
|
922
|
+
data = concat(fragments, messageLength);
|
|
923
|
+
} else if (this._binaryType === "arraybuffer") {
|
|
924
|
+
data = toArrayBuffer(concat(fragments, messageLength));
|
|
925
|
+
} else if (this._binaryType === "blob") {
|
|
926
|
+
data = new Blob(fragments);
|
|
927
|
+
} else {
|
|
928
|
+
data = fragments;
|
|
929
|
+
}
|
|
930
|
+
if (this._allowSynchronousEvents) {
|
|
931
|
+
this.emit("message", data, true);
|
|
932
|
+
this._state = GET_INFO;
|
|
933
|
+
} else {
|
|
934
|
+
this._state = DEFER_EVENT;
|
|
935
|
+
setImmediate(() => {
|
|
936
|
+
this.emit("message", data, true);
|
|
937
|
+
this._state = GET_INFO;
|
|
938
|
+
this.startLoop(cb);
|
|
939
|
+
});
|
|
940
|
+
}
|
|
941
|
+
} else {
|
|
942
|
+
const buf = concat(fragments, messageLength);
|
|
943
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
944
|
+
const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
|
|
945
|
+
cb(error);
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
if (this._state === INFLATING || this._allowSynchronousEvents) {
|
|
949
|
+
this.emit("message", buf, false);
|
|
950
|
+
this._state = GET_INFO;
|
|
951
|
+
} else {
|
|
952
|
+
this._state = DEFER_EVENT;
|
|
953
|
+
setImmediate(() => {
|
|
954
|
+
this.emit("message", buf, false);
|
|
955
|
+
this._state = GET_INFO;
|
|
956
|
+
this.startLoop(cb);
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
controlMessage(data, cb) {
|
|
962
|
+
if (this._opcode === 8) {
|
|
963
|
+
if (data.length === 0) {
|
|
964
|
+
this._loop = false;
|
|
965
|
+
this.emit("conclude", 1005, EMPTY_BUFFER);
|
|
966
|
+
this.end();
|
|
967
|
+
} else {
|
|
968
|
+
const code = data.readUInt16BE(0);
|
|
969
|
+
if (!isValidStatusCode(code)) {
|
|
970
|
+
const error = this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE");
|
|
971
|
+
cb(error);
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
|
|
975
|
+
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
|
|
976
|
+
const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
|
|
977
|
+
cb(error);
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
this._loop = false;
|
|
981
|
+
this.emit("conclude", code, buf);
|
|
982
|
+
this.end();
|
|
983
|
+
}
|
|
984
|
+
this._state = GET_INFO;
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
if (this._allowSynchronousEvents) {
|
|
988
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
989
|
+
this._state = GET_INFO;
|
|
990
|
+
} else {
|
|
991
|
+
this._state = DEFER_EVENT;
|
|
992
|
+
setImmediate(() => {
|
|
993
|
+
this.emit(this._opcode === 9 ? "ping" : "pong", data);
|
|
994
|
+
this._state = GET_INFO;
|
|
995
|
+
this.startLoop(cb);
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
createError(ErrorCtor, message, prefix, statusCode, errorCode) {
|
|
1000
|
+
this._loop = false;
|
|
1001
|
+
this._errored = true;
|
|
1002
|
+
const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
|
|
1003
|
+
Error.captureStackTrace(err, this.createError);
|
|
1004
|
+
err.code = errorCode;
|
|
1005
|
+
err[kStatusCode] = statusCode;
|
|
1006
|
+
return err;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
module.exports = Receiver;
|
|
1010
|
+
});
|
|
1011
|
+
|
|
1012
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/sender.js
|
|
1013
|
+
var require_sender = __commonJS(function(exports, module) {
|
|
1014
|
+
var { Duplex } = __require("stream");
|
|
1015
|
+
var { randomFillSync } = __require("crypto");
|
|
1016
|
+
var {
|
|
1017
|
+
types: { isUint8Array }
|
|
1018
|
+
} = __require("util");
|
|
1019
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
1020
|
+
var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
|
|
1021
|
+
var { isBlob, isValidStatusCode } = require_validation();
|
|
1022
|
+
var { mask: applyMask, toBuffer } = require_buffer_util();
|
|
1023
|
+
var kByteLength = Symbol("kByteLength");
|
|
1024
|
+
var maskBuffer = Buffer.alloc(4);
|
|
1025
|
+
var RANDOM_POOL_SIZE = 8 * 1024;
|
|
1026
|
+
var randomPool;
|
|
1027
|
+
var randomPoolPointer = RANDOM_POOL_SIZE;
|
|
1028
|
+
var DEFAULT = 0;
|
|
1029
|
+
var DEFLATING = 1;
|
|
1030
|
+
var GET_BLOB_DATA = 2;
|
|
1031
|
+
|
|
1032
|
+
class Sender {
|
|
1033
|
+
constructor(socket, extensions, generateMask) {
|
|
1034
|
+
this._extensions = extensions || {};
|
|
1035
|
+
if (generateMask) {
|
|
1036
|
+
this._generateMask = generateMask;
|
|
1037
|
+
this._maskBuffer = Buffer.alloc(4);
|
|
1038
|
+
}
|
|
1039
|
+
this._socket = socket;
|
|
1040
|
+
this._firstFragment = true;
|
|
1041
|
+
this._compress = false;
|
|
1042
|
+
this._bufferedBytes = 0;
|
|
1043
|
+
this._queue = [];
|
|
1044
|
+
this._state = DEFAULT;
|
|
1045
|
+
this.onerror = NOOP;
|
|
1046
|
+
this[kWebSocket] = undefined;
|
|
1047
|
+
}
|
|
1048
|
+
static frame(data, options) {
|
|
1049
|
+
let mask;
|
|
1050
|
+
let merge = false;
|
|
1051
|
+
let offset = 2;
|
|
1052
|
+
let skipMasking = false;
|
|
1053
|
+
if (options.mask) {
|
|
1054
|
+
mask = options.maskBuffer || maskBuffer;
|
|
1055
|
+
if (options.generateMask) {
|
|
1056
|
+
options.generateMask(mask);
|
|
1057
|
+
} else {
|
|
1058
|
+
if (randomPoolPointer === RANDOM_POOL_SIZE) {
|
|
1059
|
+
if (randomPool === undefined) {
|
|
1060
|
+
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
|
|
1061
|
+
}
|
|
1062
|
+
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
|
|
1063
|
+
randomPoolPointer = 0;
|
|
1064
|
+
}
|
|
1065
|
+
mask[0] = randomPool[randomPoolPointer++];
|
|
1066
|
+
mask[1] = randomPool[randomPoolPointer++];
|
|
1067
|
+
mask[2] = randomPool[randomPoolPointer++];
|
|
1068
|
+
mask[3] = randomPool[randomPoolPointer++];
|
|
1069
|
+
}
|
|
1070
|
+
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
|
|
1071
|
+
offset = 6;
|
|
1072
|
+
}
|
|
1073
|
+
let dataLength;
|
|
1074
|
+
if (typeof data === "string") {
|
|
1075
|
+
if ((!options.mask || skipMasking) && options[kByteLength] !== undefined) {
|
|
1076
|
+
dataLength = options[kByteLength];
|
|
1077
|
+
} else {
|
|
1078
|
+
data = Buffer.from(data);
|
|
1079
|
+
dataLength = data.length;
|
|
1080
|
+
}
|
|
1081
|
+
} else {
|
|
1082
|
+
dataLength = data.length;
|
|
1083
|
+
merge = options.mask && options.readOnly && !skipMasking;
|
|
1084
|
+
}
|
|
1085
|
+
let payloadLength = dataLength;
|
|
1086
|
+
if (dataLength >= 65536) {
|
|
1087
|
+
offset += 8;
|
|
1088
|
+
payloadLength = 127;
|
|
1089
|
+
} else if (dataLength > 125) {
|
|
1090
|
+
offset += 2;
|
|
1091
|
+
payloadLength = 126;
|
|
1092
|
+
}
|
|
1093
|
+
const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
|
|
1094
|
+
target[0] = options.fin ? options.opcode | 128 : options.opcode;
|
|
1095
|
+
if (options.rsv1)
|
|
1096
|
+
target[0] |= 64;
|
|
1097
|
+
target[1] = payloadLength;
|
|
1098
|
+
if (payloadLength === 126) {
|
|
1099
|
+
target.writeUInt16BE(dataLength, 2);
|
|
1100
|
+
} else if (payloadLength === 127) {
|
|
1101
|
+
target[2] = target[3] = 0;
|
|
1102
|
+
target.writeUIntBE(dataLength, 4, 6);
|
|
1103
|
+
}
|
|
1104
|
+
if (!options.mask)
|
|
1105
|
+
return [target, data];
|
|
1106
|
+
target[1] |= 128;
|
|
1107
|
+
target[offset - 4] = mask[0];
|
|
1108
|
+
target[offset - 3] = mask[1];
|
|
1109
|
+
target[offset - 2] = mask[2];
|
|
1110
|
+
target[offset - 1] = mask[3];
|
|
1111
|
+
if (skipMasking)
|
|
1112
|
+
return [target, data];
|
|
1113
|
+
if (merge) {
|
|
1114
|
+
applyMask(data, mask, target, offset, dataLength);
|
|
1115
|
+
return [target];
|
|
1116
|
+
}
|
|
1117
|
+
applyMask(data, mask, data, 0, dataLength);
|
|
1118
|
+
return [target, data];
|
|
1119
|
+
}
|
|
1120
|
+
close(code, data, mask, cb) {
|
|
1121
|
+
let buf;
|
|
1122
|
+
if (code === undefined) {
|
|
1123
|
+
buf = EMPTY_BUFFER;
|
|
1124
|
+
} else if (typeof code !== "number" || !isValidStatusCode(code)) {
|
|
1125
|
+
throw new TypeError("First argument must be a valid error code number");
|
|
1126
|
+
} else if (data === undefined || !data.length) {
|
|
1127
|
+
buf = Buffer.allocUnsafe(2);
|
|
1128
|
+
buf.writeUInt16BE(code, 0);
|
|
1129
|
+
} else {
|
|
1130
|
+
const length = Buffer.byteLength(data);
|
|
1131
|
+
if (length > 123) {
|
|
1132
|
+
throw new RangeError("The message must not be greater than 123 bytes");
|
|
1133
|
+
}
|
|
1134
|
+
buf = Buffer.allocUnsafe(2 + length);
|
|
1135
|
+
buf.writeUInt16BE(code, 0);
|
|
1136
|
+
if (typeof data === "string") {
|
|
1137
|
+
buf.write(data, 2);
|
|
1138
|
+
} else if (isUint8Array(data)) {
|
|
1139
|
+
buf.set(data, 2);
|
|
1140
|
+
} else {
|
|
1141
|
+
throw new TypeError("Second argument must be a string or a Uint8Array");
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
const options = {
|
|
1145
|
+
[kByteLength]: buf.length,
|
|
1146
|
+
fin: true,
|
|
1147
|
+
generateMask: this._generateMask,
|
|
1148
|
+
mask,
|
|
1149
|
+
maskBuffer: this._maskBuffer,
|
|
1150
|
+
opcode: 8,
|
|
1151
|
+
readOnly: false,
|
|
1152
|
+
rsv1: false
|
|
1153
|
+
};
|
|
1154
|
+
if (this._state !== DEFAULT) {
|
|
1155
|
+
this.enqueue([this.dispatch, buf, false, options, cb]);
|
|
1156
|
+
} else {
|
|
1157
|
+
this.sendFrame(Sender.frame(buf, options), cb);
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
ping(data, mask, cb) {
|
|
1161
|
+
let byteLength;
|
|
1162
|
+
let readOnly;
|
|
1163
|
+
if (typeof data === "string") {
|
|
1164
|
+
byteLength = Buffer.byteLength(data);
|
|
1165
|
+
readOnly = false;
|
|
1166
|
+
} else if (isBlob(data)) {
|
|
1167
|
+
byteLength = data.size;
|
|
1168
|
+
readOnly = false;
|
|
1169
|
+
} else {
|
|
1170
|
+
data = toBuffer(data);
|
|
1171
|
+
byteLength = data.length;
|
|
1172
|
+
readOnly = toBuffer.readOnly;
|
|
1173
|
+
}
|
|
1174
|
+
if (byteLength > 125) {
|
|
1175
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1176
|
+
}
|
|
1177
|
+
const options = {
|
|
1178
|
+
[kByteLength]: byteLength,
|
|
1179
|
+
fin: true,
|
|
1180
|
+
generateMask: this._generateMask,
|
|
1181
|
+
mask,
|
|
1182
|
+
maskBuffer: this._maskBuffer,
|
|
1183
|
+
opcode: 9,
|
|
1184
|
+
readOnly,
|
|
1185
|
+
rsv1: false
|
|
1186
|
+
};
|
|
1187
|
+
if (isBlob(data)) {
|
|
1188
|
+
if (this._state !== DEFAULT) {
|
|
1189
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1190
|
+
} else {
|
|
1191
|
+
this.getBlobData(data, false, options, cb);
|
|
1192
|
+
}
|
|
1193
|
+
} else if (this._state !== DEFAULT) {
|
|
1194
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1195
|
+
} else {
|
|
1196
|
+
this.sendFrame(Sender.frame(data, options), cb);
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
pong(data, mask, cb) {
|
|
1200
|
+
let byteLength;
|
|
1201
|
+
let readOnly;
|
|
1202
|
+
if (typeof data === "string") {
|
|
1203
|
+
byteLength = Buffer.byteLength(data);
|
|
1204
|
+
readOnly = false;
|
|
1205
|
+
} else if (isBlob(data)) {
|
|
1206
|
+
byteLength = data.size;
|
|
1207
|
+
readOnly = false;
|
|
1208
|
+
} else {
|
|
1209
|
+
data = toBuffer(data);
|
|
1210
|
+
byteLength = data.length;
|
|
1211
|
+
readOnly = toBuffer.readOnly;
|
|
1212
|
+
}
|
|
1213
|
+
if (byteLength > 125) {
|
|
1214
|
+
throw new RangeError("The data size must not be greater than 125 bytes");
|
|
1215
|
+
}
|
|
1216
|
+
const options = {
|
|
1217
|
+
[kByteLength]: byteLength,
|
|
1218
|
+
fin: true,
|
|
1219
|
+
generateMask: this._generateMask,
|
|
1220
|
+
mask,
|
|
1221
|
+
maskBuffer: this._maskBuffer,
|
|
1222
|
+
opcode: 10,
|
|
1223
|
+
readOnly,
|
|
1224
|
+
rsv1: false
|
|
1225
|
+
};
|
|
1226
|
+
if (isBlob(data)) {
|
|
1227
|
+
if (this._state !== DEFAULT) {
|
|
1228
|
+
this.enqueue([this.getBlobData, data, false, options, cb]);
|
|
1229
|
+
} else {
|
|
1230
|
+
this.getBlobData(data, false, options, cb);
|
|
1231
|
+
}
|
|
1232
|
+
} else if (this._state !== DEFAULT) {
|
|
1233
|
+
this.enqueue([this.dispatch, data, false, options, cb]);
|
|
1234
|
+
} else {
|
|
1235
|
+
this.sendFrame(Sender.frame(data, options), cb);
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
send(data, options, cb) {
|
|
1239
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
1240
|
+
let opcode = options.binary ? 2 : 1;
|
|
1241
|
+
let rsv1 = options.compress;
|
|
1242
|
+
let byteLength;
|
|
1243
|
+
let readOnly;
|
|
1244
|
+
if (typeof data === "string") {
|
|
1245
|
+
byteLength = Buffer.byteLength(data);
|
|
1246
|
+
readOnly = false;
|
|
1247
|
+
} else if (isBlob(data)) {
|
|
1248
|
+
byteLength = data.size;
|
|
1249
|
+
readOnly = false;
|
|
1250
|
+
} else {
|
|
1251
|
+
data = toBuffer(data);
|
|
1252
|
+
byteLength = data.length;
|
|
1253
|
+
readOnly = toBuffer.readOnly;
|
|
1254
|
+
}
|
|
1255
|
+
if (this._firstFragment) {
|
|
1256
|
+
this._firstFragment = false;
|
|
1257
|
+
if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
|
|
1258
|
+
rsv1 = byteLength >= perMessageDeflate._threshold;
|
|
1259
|
+
}
|
|
1260
|
+
this._compress = rsv1;
|
|
1261
|
+
} else {
|
|
1262
|
+
rsv1 = false;
|
|
1263
|
+
opcode = 0;
|
|
1264
|
+
}
|
|
1265
|
+
if (options.fin)
|
|
1266
|
+
this._firstFragment = true;
|
|
1267
|
+
const opts = {
|
|
1268
|
+
[kByteLength]: byteLength,
|
|
1269
|
+
fin: options.fin,
|
|
1270
|
+
generateMask: this._generateMask,
|
|
1271
|
+
mask: options.mask,
|
|
1272
|
+
maskBuffer: this._maskBuffer,
|
|
1273
|
+
opcode,
|
|
1274
|
+
readOnly,
|
|
1275
|
+
rsv1
|
|
1276
|
+
};
|
|
1277
|
+
if (isBlob(data)) {
|
|
1278
|
+
if (this._state !== DEFAULT) {
|
|
1279
|
+
this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
|
|
1280
|
+
} else {
|
|
1281
|
+
this.getBlobData(data, this._compress, opts, cb);
|
|
1282
|
+
}
|
|
1283
|
+
} else if (this._state !== DEFAULT) {
|
|
1284
|
+
this.enqueue([this.dispatch, data, this._compress, opts, cb]);
|
|
1285
|
+
} else {
|
|
1286
|
+
this.dispatch(data, this._compress, opts, cb);
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
getBlobData(blob, compress, options, cb) {
|
|
1290
|
+
this._bufferedBytes += options[kByteLength];
|
|
1291
|
+
this._state = GET_BLOB_DATA;
|
|
1292
|
+
blob.arrayBuffer().then((arrayBuffer) => {
|
|
1293
|
+
if (this._socket.destroyed) {
|
|
1294
|
+
const err = new Error("The socket was closed while the blob was being read");
|
|
1295
|
+
process.nextTick(callCallbacks, this, err, cb);
|
|
1296
|
+
return;
|
|
1297
|
+
}
|
|
1298
|
+
this._bufferedBytes -= options[kByteLength];
|
|
1299
|
+
const data = toBuffer(arrayBuffer);
|
|
1300
|
+
if (!compress) {
|
|
1301
|
+
this._state = DEFAULT;
|
|
1302
|
+
this.sendFrame(Sender.frame(data, options), cb);
|
|
1303
|
+
this.dequeue();
|
|
1304
|
+
} else {
|
|
1305
|
+
this.dispatch(data, compress, options, cb);
|
|
1306
|
+
}
|
|
1307
|
+
}).catch((err) => {
|
|
1308
|
+
process.nextTick(onError, this, err, cb);
|
|
1309
|
+
});
|
|
1310
|
+
}
|
|
1311
|
+
dispatch(data, compress, options, cb) {
|
|
1312
|
+
if (!compress) {
|
|
1313
|
+
this.sendFrame(Sender.frame(data, options), cb);
|
|
1314
|
+
return;
|
|
1315
|
+
}
|
|
1316
|
+
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
|
|
1317
|
+
this._bufferedBytes += options[kByteLength];
|
|
1318
|
+
this._state = DEFLATING;
|
|
1319
|
+
perMessageDeflate.compress(data, options.fin, (_, buf) => {
|
|
1320
|
+
if (this._socket.destroyed) {
|
|
1321
|
+
const err = new Error("The socket was closed while data was being compressed");
|
|
1322
|
+
callCallbacks(this, err, cb);
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
this._bufferedBytes -= options[kByteLength];
|
|
1326
|
+
this._state = DEFAULT;
|
|
1327
|
+
options.readOnly = false;
|
|
1328
|
+
this.sendFrame(Sender.frame(buf, options), cb);
|
|
1329
|
+
this.dequeue();
|
|
1330
|
+
});
|
|
1331
|
+
}
|
|
1332
|
+
dequeue() {
|
|
1333
|
+
while (this._state === DEFAULT && this._queue.length) {
|
|
1334
|
+
const params = this._queue.shift();
|
|
1335
|
+
this._bufferedBytes -= params[3][kByteLength];
|
|
1336
|
+
Reflect.apply(params[0], this, params.slice(1));
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
enqueue(params) {
|
|
1340
|
+
this._bufferedBytes += params[3][kByteLength];
|
|
1341
|
+
this._queue.push(params);
|
|
1342
|
+
}
|
|
1343
|
+
sendFrame(list, cb) {
|
|
1344
|
+
if (list.length === 2) {
|
|
1345
|
+
this._socket.cork();
|
|
1346
|
+
this._socket.write(list[0]);
|
|
1347
|
+
this._socket.write(list[1], cb);
|
|
1348
|
+
this._socket.uncork();
|
|
1349
|
+
} else {
|
|
1350
|
+
this._socket.write(list[0], cb);
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
module.exports = Sender;
|
|
1355
|
+
function callCallbacks(sender, err, cb) {
|
|
1356
|
+
if (typeof cb === "function")
|
|
1357
|
+
cb(err);
|
|
1358
|
+
for (let i = 0;i < sender._queue.length; i++) {
|
|
1359
|
+
const params = sender._queue[i];
|
|
1360
|
+
const callback = params[params.length - 1];
|
|
1361
|
+
if (typeof callback === "function")
|
|
1362
|
+
callback(err);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
function onError(sender, err, cb) {
|
|
1366
|
+
callCallbacks(sender, err, cb);
|
|
1367
|
+
sender.onerror(err);
|
|
1368
|
+
}
|
|
1369
|
+
});
|
|
1370
|
+
|
|
1371
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/event-target.js
|
|
1372
|
+
var require_event_target = __commonJS(function(exports, module) {
|
|
1373
|
+
var { kForOnEventAttribute, kListener } = require_constants();
|
|
1374
|
+
var kCode = Symbol("kCode");
|
|
1375
|
+
var kData = Symbol("kData");
|
|
1376
|
+
var kError = Symbol("kError");
|
|
1377
|
+
var kMessage = Symbol("kMessage");
|
|
1378
|
+
var kReason = Symbol("kReason");
|
|
1379
|
+
var kTarget = Symbol("kTarget");
|
|
1380
|
+
var kType = Symbol("kType");
|
|
1381
|
+
var kWasClean = Symbol("kWasClean");
|
|
1382
|
+
|
|
1383
|
+
class Event {
|
|
1384
|
+
constructor(type) {
|
|
1385
|
+
this[kTarget] = null;
|
|
1386
|
+
this[kType] = type;
|
|
1387
|
+
}
|
|
1388
|
+
get target() {
|
|
1389
|
+
return this[kTarget];
|
|
1390
|
+
}
|
|
1391
|
+
get type() {
|
|
1392
|
+
return this[kType];
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
Object.defineProperty(Event.prototype, "target", { enumerable: true });
|
|
1396
|
+
Object.defineProperty(Event.prototype, "type", { enumerable: true });
|
|
1397
|
+
|
|
1398
|
+
class CloseEvent extends Event {
|
|
1399
|
+
constructor(type, options = {}) {
|
|
1400
|
+
super(type);
|
|
1401
|
+
this[kCode] = options.code === undefined ? 0 : options.code;
|
|
1402
|
+
this[kReason] = options.reason === undefined ? "" : options.reason;
|
|
1403
|
+
this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
|
|
1404
|
+
}
|
|
1405
|
+
get code() {
|
|
1406
|
+
return this[kCode];
|
|
1407
|
+
}
|
|
1408
|
+
get reason() {
|
|
1409
|
+
return this[kReason];
|
|
1410
|
+
}
|
|
1411
|
+
get wasClean() {
|
|
1412
|
+
return this[kWasClean];
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
|
|
1416
|
+
Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
|
|
1417
|
+
Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
|
|
1418
|
+
|
|
1419
|
+
class ErrorEvent extends Event {
|
|
1420
|
+
constructor(type, options = {}) {
|
|
1421
|
+
super(type);
|
|
1422
|
+
this[kError] = options.error === undefined ? null : options.error;
|
|
1423
|
+
this[kMessage] = options.message === undefined ? "" : options.message;
|
|
1424
|
+
}
|
|
1425
|
+
get error() {
|
|
1426
|
+
return this[kError];
|
|
1427
|
+
}
|
|
1428
|
+
get message() {
|
|
1429
|
+
return this[kMessage];
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
|
|
1433
|
+
Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
|
|
1434
|
+
|
|
1435
|
+
class MessageEvent extends Event {
|
|
1436
|
+
constructor(type, options = {}) {
|
|
1437
|
+
super(type);
|
|
1438
|
+
this[kData] = options.data === undefined ? null : options.data;
|
|
1439
|
+
}
|
|
1440
|
+
get data() {
|
|
1441
|
+
return this[kData];
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
|
|
1445
|
+
var EventTarget = {
|
|
1446
|
+
addEventListener(type, handler, options = {}) {
|
|
1447
|
+
for (const listener of this.listeners(type)) {
|
|
1448
|
+
if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
1449
|
+
return;
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
let wrapper;
|
|
1453
|
+
if (type === "message") {
|
|
1454
|
+
wrapper = function onMessage(data, isBinary) {
|
|
1455
|
+
const event = new MessageEvent("message", {
|
|
1456
|
+
data: isBinary ? data : data.toString()
|
|
1457
|
+
});
|
|
1458
|
+
event[kTarget] = this;
|
|
1459
|
+
callListener(handler, this, event);
|
|
1460
|
+
};
|
|
1461
|
+
} else if (type === "close") {
|
|
1462
|
+
wrapper = function onClose(code, message) {
|
|
1463
|
+
const event = new CloseEvent("close", {
|
|
1464
|
+
code,
|
|
1465
|
+
reason: message.toString(),
|
|
1466
|
+
wasClean: this._closeFrameReceived && this._closeFrameSent
|
|
1467
|
+
});
|
|
1468
|
+
event[kTarget] = this;
|
|
1469
|
+
callListener(handler, this, event);
|
|
1470
|
+
};
|
|
1471
|
+
} else if (type === "error") {
|
|
1472
|
+
wrapper = function onError(error) {
|
|
1473
|
+
const event = new ErrorEvent("error", {
|
|
1474
|
+
error,
|
|
1475
|
+
message: error.message
|
|
1476
|
+
});
|
|
1477
|
+
event[kTarget] = this;
|
|
1478
|
+
callListener(handler, this, event);
|
|
1479
|
+
};
|
|
1480
|
+
} else if (type === "open") {
|
|
1481
|
+
wrapper = function onOpen() {
|
|
1482
|
+
const event = new Event("open");
|
|
1483
|
+
event[kTarget] = this;
|
|
1484
|
+
callListener(handler, this, event);
|
|
1485
|
+
};
|
|
1486
|
+
} else {
|
|
1487
|
+
return;
|
|
1488
|
+
}
|
|
1489
|
+
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
|
|
1490
|
+
wrapper[kListener] = handler;
|
|
1491
|
+
if (options.once) {
|
|
1492
|
+
this.once(type, wrapper);
|
|
1493
|
+
} else {
|
|
1494
|
+
this.on(type, wrapper);
|
|
1495
|
+
}
|
|
1496
|
+
},
|
|
1497
|
+
removeEventListener(type, handler) {
|
|
1498
|
+
for (const listener of this.listeners(type)) {
|
|
1499
|
+
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
|
|
1500
|
+
this.removeListener(type, listener);
|
|
1501
|
+
break;
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
};
|
|
1506
|
+
module.exports = {
|
|
1507
|
+
CloseEvent,
|
|
1508
|
+
ErrorEvent,
|
|
1509
|
+
Event,
|
|
1510
|
+
EventTarget,
|
|
1511
|
+
MessageEvent
|
|
1512
|
+
};
|
|
1513
|
+
function callListener(listener, thisArg, event) {
|
|
1514
|
+
if (typeof listener === "object" && listener.handleEvent) {
|
|
1515
|
+
listener.handleEvent.call(listener, event);
|
|
1516
|
+
} else {
|
|
1517
|
+
listener.call(thisArg, event);
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
});
|
|
1521
|
+
|
|
1522
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/extension.js
|
|
1523
|
+
var require_extension = __commonJS(function(exports, module) {
|
|
1524
|
+
var { tokenChars } = require_validation();
|
|
1525
|
+
function push(dest, name, elem) {
|
|
1526
|
+
if (dest[name] === undefined)
|
|
1527
|
+
dest[name] = [elem];
|
|
1528
|
+
else
|
|
1529
|
+
dest[name].push(elem);
|
|
1530
|
+
}
|
|
1531
|
+
function parse(header) {
|
|
1532
|
+
const offers = Object.create(null);
|
|
1533
|
+
let params = Object.create(null);
|
|
1534
|
+
let mustUnescape = false;
|
|
1535
|
+
let isEscaping = false;
|
|
1536
|
+
let inQuotes = false;
|
|
1537
|
+
let extensionName;
|
|
1538
|
+
let paramName;
|
|
1539
|
+
let start = -1;
|
|
1540
|
+
let code = -1;
|
|
1541
|
+
let end = -1;
|
|
1542
|
+
let i = 0;
|
|
1543
|
+
for (;i < header.length; i++) {
|
|
1544
|
+
code = header.charCodeAt(i);
|
|
1545
|
+
if (extensionName === undefined) {
|
|
1546
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
1547
|
+
if (start === -1)
|
|
1548
|
+
start = i;
|
|
1549
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
1550
|
+
if (end === -1 && start !== -1)
|
|
1551
|
+
end = i;
|
|
1552
|
+
} else if (code === 59 || code === 44) {
|
|
1553
|
+
if (start === -1) {
|
|
1554
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1555
|
+
}
|
|
1556
|
+
if (end === -1)
|
|
1557
|
+
end = i;
|
|
1558
|
+
const name = header.slice(start, end);
|
|
1559
|
+
if (code === 44) {
|
|
1560
|
+
push(offers, name, params);
|
|
1561
|
+
params = Object.create(null);
|
|
1562
|
+
} else {
|
|
1563
|
+
extensionName = name;
|
|
1564
|
+
}
|
|
1565
|
+
start = end = -1;
|
|
1566
|
+
} else {
|
|
1567
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1568
|
+
}
|
|
1569
|
+
} else if (paramName === undefined) {
|
|
1570
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
1571
|
+
if (start === -1)
|
|
1572
|
+
start = i;
|
|
1573
|
+
} else if (code === 32 || code === 9) {
|
|
1574
|
+
if (end === -1 && start !== -1)
|
|
1575
|
+
end = i;
|
|
1576
|
+
} else if (code === 59 || code === 44) {
|
|
1577
|
+
if (start === -1) {
|
|
1578
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1579
|
+
}
|
|
1580
|
+
if (end === -1)
|
|
1581
|
+
end = i;
|
|
1582
|
+
push(params, header.slice(start, end), true);
|
|
1583
|
+
if (code === 44) {
|
|
1584
|
+
push(offers, extensionName, params);
|
|
1585
|
+
params = Object.create(null);
|
|
1586
|
+
extensionName = undefined;
|
|
1587
|
+
}
|
|
1588
|
+
start = end = -1;
|
|
1589
|
+
} else if (code === 61 && start !== -1 && end === -1) {
|
|
1590
|
+
paramName = header.slice(start, i);
|
|
1591
|
+
start = end = -1;
|
|
1592
|
+
} else {
|
|
1593
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1594
|
+
}
|
|
1595
|
+
} else {
|
|
1596
|
+
if (isEscaping) {
|
|
1597
|
+
if (tokenChars[code] !== 1) {
|
|
1598
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1599
|
+
}
|
|
1600
|
+
if (start === -1)
|
|
1601
|
+
start = i;
|
|
1602
|
+
else if (!mustUnescape)
|
|
1603
|
+
mustUnescape = true;
|
|
1604
|
+
isEscaping = false;
|
|
1605
|
+
} else if (inQuotes) {
|
|
1606
|
+
if (tokenChars[code] === 1) {
|
|
1607
|
+
if (start === -1)
|
|
1608
|
+
start = i;
|
|
1609
|
+
} else if (code === 34 && start !== -1) {
|
|
1610
|
+
inQuotes = false;
|
|
1611
|
+
end = i;
|
|
1612
|
+
} else if (code === 92) {
|
|
1613
|
+
isEscaping = true;
|
|
1614
|
+
} else {
|
|
1615
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1616
|
+
}
|
|
1617
|
+
} else if (code === 34 && header.charCodeAt(i - 1) === 61) {
|
|
1618
|
+
inQuotes = true;
|
|
1619
|
+
} else if (end === -1 && tokenChars[code] === 1) {
|
|
1620
|
+
if (start === -1)
|
|
1621
|
+
start = i;
|
|
1622
|
+
} else if (start !== -1 && (code === 32 || code === 9)) {
|
|
1623
|
+
if (end === -1)
|
|
1624
|
+
end = i;
|
|
1625
|
+
} else if (code === 59 || code === 44) {
|
|
1626
|
+
if (start === -1) {
|
|
1627
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1628
|
+
}
|
|
1629
|
+
if (end === -1)
|
|
1630
|
+
end = i;
|
|
1631
|
+
let value = header.slice(start, end);
|
|
1632
|
+
if (mustUnescape) {
|
|
1633
|
+
value = value.replace(/\\/g, "");
|
|
1634
|
+
mustUnescape = false;
|
|
1635
|
+
}
|
|
1636
|
+
push(params, paramName, value);
|
|
1637
|
+
if (code === 44) {
|
|
1638
|
+
push(offers, extensionName, params);
|
|
1639
|
+
params = Object.create(null);
|
|
1640
|
+
extensionName = undefined;
|
|
1641
|
+
}
|
|
1642
|
+
paramName = undefined;
|
|
1643
|
+
start = end = -1;
|
|
1644
|
+
} else {
|
|
1645
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
if (start === -1 || inQuotes || code === 32 || code === 9) {
|
|
1650
|
+
throw new SyntaxError("Unexpected end of input");
|
|
1651
|
+
}
|
|
1652
|
+
if (end === -1)
|
|
1653
|
+
end = i;
|
|
1654
|
+
const token = header.slice(start, end);
|
|
1655
|
+
if (extensionName === undefined) {
|
|
1656
|
+
push(offers, token, params);
|
|
1657
|
+
} else {
|
|
1658
|
+
if (paramName === undefined) {
|
|
1659
|
+
push(params, token, true);
|
|
1660
|
+
} else if (mustUnescape) {
|
|
1661
|
+
push(params, paramName, token.replace(/\\/g, ""));
|
|
1662
|
+
} else {
|
|
1663
|
+
push(params, paramName, token);
|
|
1664
|
+
}
|
|
1665
|
+
push(offers, extensionName, params);
|
|
1666
|
+
}
|
|
1667
|
+
return offers;
|
|
1668
|
+
}
|
|
1669
|
+
function format(extensions) {
|
|
1670
|
+
return Object.keys(extensions).map((extension) => {
|
|
1671
|
+
let configurations = extensions[extension];
|
|
1672
|
+
if (!Array.isArray(configurations))
|
|
1673
|
+
configurations = [configurations];
|
|
1674
|
+
return configurations.map((params) => {
|
|
1675
|
+
return [extension].concat(Object.keys(params).map((k) => {
|
|
1676
|
+
let values = params[k];
|
|
1677
|
+
if (!Array.isArray(values))
|
|
1678
|
+
values = [values];
|
|
1679
|
+
return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
|
|
1680
|
+
})).join("; ");
|
|
1681
|
+
}).join(", ");
|
|
1682
|
+
}).join(", ");
|
|
1683
|
+
}
|
|
1684
|
+
module.exports = { format, parse };
|
|
1685
|
+
});
|
|
1686
|
+
|
|
1687
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/websocket.js
|
|
1688
|
+
var require_websocket = __commonJS(function(exports, module) {
|
|
1689
|
+
var EventEmitter = __require("events");
|
|
1690
|
+
var https = __require("https");
|
|
1691
|
+
var http = __require("http");
|
|
1692
|
+
var net = __require("net");
|
|
1693
|
+
var tls = __require("tls");
|
|
1694
|
+
var { randomBytes, createHash } = __require("crypto");
|
|
1695
|
+
var { Duplex, Readable } = __require("stream");
|
|
1696
|
+
var { URL: URL2 } = __require("url");
|
|
1697
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
1698
|
+
var Receiver = require_receiver();
|
|
1699
|
+
var Sender = require_sender();
|
|
1700
|
+
var { isBlob } = require_validation();
|
|
1701
|
+
var {
|
|
1702
|
+
BINARY_TYPES,
|
|
1703
|
+
CLOSE_TIMEOUT,
|
|
1704
|
+
EMPTY_BUFFER,
|
|
1705
|
+
GUID,
|
|
1706
|
+
kForOnEventAttribute,
|
|
1707
|
+
kListener,
|
|
1708
|
+
kStatusCode,
|
|
1709
|
+
kWebSocket,
|
|
1710
|
+
NOOP
|
|
1711
|
+
} = require_constants();
|
|
1712
|
+
var {
|
|
1713
|
+
EventTarget: { addEventListener, removeEventListener }
|
|
1714
|
+
} = require_event_target();
|
|
1715
|
+
var { format, parse } = require_extension();
|
|
1716
|
+
var { toBuffer } = require_buffer_util();
|
|
1717
|
+
var kAborted = Symbol("kAborted");
|
|
1718
|
+
var protocolVersions = [8, 13];
|
|
1719
|
+
var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
|
|
1720
|
+
var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
|
|
1721
|
+
|
|
1722
|
+
class WebSocket extends EventEmitter {
|
|
1723
|
+
constructor(address, protocols, options) {
|
|
1724
|
+
super();
|
|
1725
|
+
this._binaryType = BINARY_TYPES[0];
|
|
1726
|
+
this._closeCode = 1006;
|
|
1727
|
+
this._closeFrameReceived = false;
|
|
1728
|
+
this._closeFrameSent = false;
|
|
1729
|
+
this._closeMessage = EMPTY_BUFFER;
|
|
1730
|
+
this._closeTimer = null;
|
|
1731
|
+
this._errorEmitted = false;
|
|
1732
|
+
this._extensions = {};
|
|
1733
|
+
this._paused = false;
|
|
1734
|
+
this._protocol = "";
|
|
1735
|
+
this._readyState = WebSocket.CONNECTING;
|
|
1736
|
+
this._receiver = null;
|
|
1737
|
+
this._sender = null;
|
|
1738
|
+
this._socket = null;
|
|
1739
|
+
if (address !== null) {
|
|
1740
|
+
this._bufferedAmount = 0;
|
|
1741
|
+
this._isServer = false;
|
|
1742
|
+
this._redirects = 0;
|
|
1743
|
+
if (protocols === undefined) {
|
|
1744
|
+
if (!options || options.protocols === undefined) {
|
|
1745
|
+
protocols = [];
|
|
1746
|
+
} else if (Array.isArray(options.protocols)) {
|
|
1747
|
+
protocols = options.protocols;
|
|
1748
|
+
} else {
|
|
1749
|
+
protocols = [options.protocols];
|
|
1750
|
+
}
|
|
1751
|
+
} else if (!Array.isArray(protocols)) {
|
|
1752
|
+
if (typeof protocols === "object" && protocols !== null) {
|
|
1753
|
+
options = protocols;
|
|
1754
|
+
if (options.protocols === undefined) {
|
|
1755
|
+
protocols = [];
|
|
1756
|
+
} else if (Array.isArray(options.protocols)) {
|
|
1757
|
+
protocols = options.protocols;
|
|
1758
|
+
} else {
|
|
1759
|
+
protocols = [options.protocols];
|
|
1760
|
+
}
|
|
1761
|
+
} else {
|
|
1762
|
+
protocols = [protocols];
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
initAsClient(this, address, protocols, options);
|
|
1766
|
+
} else {
|
|
1767
|
+
this._autoPong = options.autoPong;
|
|
1768
|
+
this._closeTimeout = options.closeTimeout;
|
|
1769
|
+
this._isServer = true;
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
get binaryType() {
|
|
1773
|
+
return this._binaryType;
|
|
1774
|
+
}
|
|
1775
|
+
set binaryType(type) {
|
|
1776
|
+
if (!BINARY_TYPES.includes(type))
|
|
1777
|
+
return;
|
|
1778
|
+
this._binaryType = type;
|
|
1779
|
+
if (this._receiver)
|
|
1780
|
+
this._receiver._binaryType = type;
|
|
1781
|
+
}
|
|
1782
|
+
get bufferedAmount() {
|
|
1783
|
+
if (!this._socket)
|
|
1784
|
+
return this._bufferedAmount;
|
|
1785
|
+
return this._socket._writableState.length + this._sender._bufferedBytes;
|
|
1786
|
+
}
|
|
1787
|
+
get extensions() {
|
|
1788
|
+
return Object.keys(this._extensions).join();
|
|
1789
|
+
}
|
|
1790
|
+
get isPaused() {
|
|
1791
|
+
return this._paused;
|
|
1792
|
+
}
|
|
1793
|
+
get onclose() {
|
|
1794
|
+
return null;
|
|
1795
|
+
}
|
|
1796
|
+
get onerror() {
|
|
1797
|
+
return null;
|
|
1798
|
+
}
|
|
1799
|
+
get onopen() {
|
|
1800
|
+
return null;
|
|
1801
|
+
}
|
|
1802
|
+
get onmessage() {
|
|
1803
|
+
return null;
|
|
1804
|
+
}
|
|
1805
|
+
get protocol() {
|
|
1806
|
+
return this._protocol;
|
|
1807
|
+
}
|
|
1808
|
+
get readyState() {
|
|
1809
|
+
return this._readyState;
|
|
1810
|
+
}
|
|
1811
|
+
get url() {
|
|
1812
|
+
return this._url;
|
|
1813
|
+
}
|
|
1814
|
+
setSocket(socket, head, options) {
|
|
1815
|
+
const receiver = new Receiver({
|
|
1816
|
+
allowSynchronousEvents: options.allowSynchronousEvents,
|
|
1817
|
+
binaryType: this.binaryType,
|
|
1818
|
+
extensions: this._extensions,
|
|
1819
|
+
isServer: this._isServer,
|
|
1820
|
+
maxBufferedChunks: options.maxBufferedChunks,
|
|
1821
|
+
maxFragments: options.maxFragments,
|
|
1822
|
+
maxPayload: options.maxPayload,
|
|
1823
|
+
skipUTF8Validation: options.skipUTF8Validation
|
|
1824
|
+
});
|
|
1825
|
+
const sender = new Sender(socket, this._extensions, options.generateMask);
|
|
1826
|
+
this._receiver = receiver;
|
|
1827
|
+
this._sender = sender;
|
|
1828
|
+
this._socket = socket;
|
|
1829
|
+
receiver[kWebSocket] = this;
|
|
1830
|
+
sender[kWebSocket] = this;
|
|
1831
|
+
socket[kWebSocket] = this;
|
|
1832
|
+
receiver.on("conclude", receiverOnConclude);
|
|
1833
|
+
receiver.on("drain", receiverOnDrain);
|
|
1834
|
+
receiver.on("error", receiverOnError);
|
|
1835
|
+
receiver.on("message", receiverOnMessage);
|
|
1836
|
+
receiver.on("ping", receiverOnPing);
|
|
1837
|
+
receiver.on("pong", receiverOnPong);
|
|
1838
|
+
sender.onerror = senderOnError;
|
|
1839
|
+
if (socket.setTimeout)
|
|
1840
|
+
socket.setTimeout(0);
|
|
1841
|
+
if (socket.setNoDelay)
|
|
1842
|
+
socket.setNoDelay();
|
|
1843
|
+
if (head.length > 0)
|
|
1844
|
+
socket.unshift(head);
|
|
1845
|
+
socket.on("close", socketOnClose);
|
|
1846
|
+
socket.on("data", socketOnData);
|
|
1847
|
+
socket.on("end", socketOnEnd);
|
|
1848
|
+
socket.on("error", socketOnError);
|
|
1849
|
+
this._readyState = WebSocket.OPEN;
|
|
1850
|
+
this.emit("open");
|
|
1851
|
+
}
|
|
1852
|
+
emitClose() {
|
|
1853
|
+
if (!this._socket) {
|
|
1854
|
+
this._readyState = WebSocket.CLOSED;
|
|
1855
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
1856
|
+
return;
|
|
1857
|
+
}
|
|
1858
|
+
if (this._extensions[PerMessageDeflate.extensionName]) {
|
|
1859
|
+
this._extensions[PerMessageDeflate.extensionName].cleanup();
|
|
1860
|
+
}
|
|
1861
|
+
this._receiver.removeAllListeners();
|
|
1862
|
+
this._readyState = WebSocket.CLOSED;
|
|
1863
|
+
this.emit("close", this._closeCode, this._closeMessage);
|
|
1864
|
+
}
|
|
1865
|
+
close(code, data) {
|
|
1866
|
+
if (this.readyState === WebSocket.CLOSED)
|
|
1867
|
+
return;
|
|
1868
|
+
if (this.readyState === WebSocket.CONNECTING) {
|
|
1869
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
1870
|
+
abortHandshake(this, this._req, msg);
|
|
1871
|
+
return;
|
|
1872
|
+
}
|
|
1873
|
+
if (this.readyState === WebSocket.CLOSING) {
|
|
1874
|
+
if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
|
|
1875
|
+
this._socket.end();
|
|
1876
|
+
}
|
|
1877
|
+
return;
|
|
1878
|
+
}
|
|
1879
|
+
this._sender.close(code, data, !this._isServer, (err) => {
|
|
1880
|
+
if (err)
|
|
1881
|
+
return;
|
|
1882
|
+
this._closeFrameSent = true;
|
|
1883
|
+
if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
|
|
1884
|
+
this._socket.end();
|
|
1885
|
+
}
|
|
1886
|
+
});
|
|
1887
|
+
this._readyState = WebSocket.CLOSING;
|
|
1888
|
+
setCloseTimer(this);
|
|
1889
|
+
}
|
|
1890
|
+
pause() {
|
|
1891
|
+
if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
|
|
1892
|
+
return;
|
|
1893
|
+
}
|
|
1894
|
+
this._paused = true;
|
|
1895
|
+
this._socket.pause();
|
|
1896
|
+
}
|
|
1897
|
+
ping(data, mask, cb) {
|
|
1898
|
+
if (this.readyState === WebSocket.CONNECTING) {
|
|
1899
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
1900
|
+
}
|
|
1901
|
+
if (typeof data === "function") {
|
|
1902
|
+
cb = data;
|
|
1903
|
+
data = mask = undefined;
|
|
1904
|
+
} else if (typeof mask === "function") {
|
|
1905
|
+
cb = mask;
|
|
1906
|
+
mask = undefined;
|
|
1907
|
+
}
|
|
1908
|
+
if (typeof data === "number")
|
|
1909
|
+
data = data.toString();
|
|
1910
|
+
if (this.readyState !== WebSocket.OPEN) {
|
|
1911
|
+
sendAfterClose(this, data, cb);
|
|
1912
|
+
return;
|
|
1913
|
+
}
|
|
1914
|
+
if (mask === undefined)
|
|
1915
|
+
mask = !this._isServer;
|
|
1916
|
+
this._sender.ping(data || EMPTY_BUFFER, mask, cb);
|
|
1917
|
+
}
|
|
1918
|
+
pong(data, mask, cb) {
|
|
1919
|
+
if (this.readyState === WebSocket.CONNECTING) {
|
|
1920
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
1921
|
+
}
|
|
1922
|
+
if (typeof data === "function") {
|
|
1923
|
+
cb = data;
|
|
1924
|
+
data = mask = undefined;
|
|
1925
|
+
} else if (typeof mask === "function") {
|
|
1926
|
+
cb = mask;
|
|
1927
|
+
mask = undefined;
|
|
1928
|
+
}
|
|
1929
|
+
if (typeof data === "number")
|
|
1930
|
+
data = data.toString();
|
|
1931
|
+
if (this.readyState !== WebSocket.OPEN) {
|
|
1932
|
+
sendAfterClose(this, data, cb);
|
|
1933
|
+
return;
|
|
1934
|
+
}
|
|
1935
|
+
if (mask === undefined)
|
|
1936
|
+
mask = !this._isServer;
|
|
1937
|
+
this._sender.pong(data || EMPTY_BUFFER, mask, cb);
|
|
1938
|
+
}
|
|
1939
|
+
resume() {
|
|
1940
|
+
if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
|
|
1941
|
+
return;
|
|
1942
|
+
}
|
|
1943
|
+
this._paused = false;
|
|
1944
|
+
if (!this._receiver._writableState.needDrain)
|
|
1945
|
+
this._socket.resume();
|
|
1946
|
+
}
|
|
1947
|
+
send(data, options, cb) {
|
|
1948
|
+
if (this.readyState === WebSocket.CONNECTING) {
|
|
1949
|
+
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
|
|
1950
|
+
}
|
|
1951
|
+
if (typeof options === "function") {
|
|
1952
|
+
cb = options;
|
|
1953
|
+
options = {};
|
|
1954
|
+
}
|
|
1955
|
+
if (typeof data === "number")
|
|
1956
|
+
data = data.toString();
|
|
1957
|
+
if (this.readyState !== WebSocket.OPEN) {
|
|
1958
|
+
sendAfterClose(this, data, cb);
|
|
1959
|
+
return;
|
|
1960
|
+
}
|
|
1961
|
+
const opts = {
|
|
1962
|
+
binary: typeof data !== "string",
|
|
1963
|
+
mask: !this._isServer,
|
|
1964
|
+
compress: true,
|
|
1965
|
+
fin: true,
|
|
1966
|
+
...options
|
|
1967
|
+
};
|
|
1968
|
+
if (!this._extensions[PerMessageDeflate.extensionName]) {
|
|
1969
|
+
opts.compress = false;
|
|
1970
|
+
}
|
|
1971
|
+
this._sender.send(data || EMPTY_BUFFER, opts, cb);
|
|
1972
|
+
}
|
|
1973
|
+
terminate() {
|
|
1974
|
+
if (this.readyState === WebSocket.CLOSED)
|
|
1975
|
+
return;
|
|
1976
|
+
if (this.readyState === WebSocket.CONNECTING) {
|
|
1977
|
+
const msg = "WebSocket was closed before the connection was established";
|
|
1978
|
+
abortHandshake(this, this._req, msg);
|
|
1979
|
+
return;
|
|
1980
|
+
}
|
|
1981
|
+
if (this._socket) {
|
|
1982
|
+
this._readyState = WebSocket.CLOSING;
|
|
1983
|
+
this._socket.destroy();
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
Object.defineProperty(WebSocket, "CONNECTING", {
|
|
1988
|
+
enumerable: true,
|
|
1989
|
+
value: readyStates.indexOf("CONNECTING")
|
|
1990
|
+
});
|
|
1991
|
+
Object.defineProperty(WebSocket.prototype, "CONNECTING", {
|
|
1992
|
+
enumerable: true,
|
|
1993
|
+
value: readyStates.indexOf("CONNECTING")
|
|
1994
|
+
});
|
|
1995
|
+
Object.defineProperty(WebSocket, "OPEN", {
|
|
1996
|
+
enumerable: true,
|
|
1997
|
+
value: readyStates.indexOf("OPEN")
|
|
1998
|
+
});
|
|
1999
|
+
Object.defineProperty(WebSocket.prototype, "OPEN", {
|
|
2000
|
+
enumerable: true,
|
|
2001
|
+
value: readyStates.indexOf("OPEN")
|
|
2002
|
+
});
|
|
2003
|
+
Object.defineProperty(WebSocket, "CLOSING", {
|
|
2004
|
+
enumerable: true,
|
|
2005
|
+
value: readyStates.indexOf("CLOSING")
|
|
2006
|
+
});
|
|
2007
|
+
Object.defineProperty(WebSocket.prototype, "CLOSING", {
|
|
2008
|
+
enumerable: true,
|
|
2009
|
+
value: readyStates.indexOf("CLOSING")
|
|
2010
|
+
});
|
|
2011
|
+
Object.defineProperty(WebSocket, "CLOSED", {
|
|
2012
|
+
enumerable: true,
|
|
2013
|
+
value: readyStates.indexOf("CLOSED")
|
|
2014
|
+
});
|
|
2015
|
+
Object.defineProperty(WebSocket.prototype, "CLOSED", {
|
|
2016
|
+
enumerable: true,
|
|
2017
|
+
value: readyStates.indexOf("CLOSED")
|
|
2018
|
+
});
|
|
2019
|
+
[
|
|
2020
|
+
"binaryType",
|
|
2021
|
+
"bufferedAmount",
|
|
2022
|
+
"extensions",
|
|
2023
|
+
"isPaused",
|
|
2024
|
+
"protocol",
|
|
2025
|
+
"readyState",
|
|
2026
|
+
"url"
|
|
2027
|
+
].forEach((property) => {
|
|
2028
|
+
Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
|
|
2029
|
+
});
|
|
2030
|
+
["open", "error", "close", "message"].forEach((method) => {
|
|
2031
|
+
Object.defineProperty(WebSocket.prototype, `on${method}`, {
|
|
2032
|
+
enumerable: true,
|
|
2033
|
+
get() {
|
|
2034
|
+
for (const listener of this.listeners(method)) {
|
|
2035
|
+
if (listener[kForOnEventAttribute])
|
|
2036
|
+
return listener[kListener];
|
|
2037
|
+
}
|
|
2038
|
+
return null;
|
|
2039
|
+
},
|
|
2040
|
+
set(handler) {
|
|
2041
|
+
for (const listener of this.listeners(method)) {
|
|
2042
|
+
if (listener[kForOnEventAttribute]) {
|
|
2043
|
+
this.removeListener(method, listener);
|
|
2044
|
+
break;
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
if (typeof handler !== "function")
|
|
2048
|
+
return;
|
|
2049
|
+
this.addEventListener(method, handler, {
|
|
2050
|
+
[kForOnEventAttribute]: true
|
|
2051
|
+
});
|
|
2052
|
+
}
|
|
2053
|
+
});
|
|
2054
|
+
});
|
|
2055
|
+
WebSocket.prototype.addEventListener = addEventListener;
|
|
2056
|
+
WebSocket.prototype.removeEventListener = removeEventListener;
|
|
2057
|
+
module.exports = WebSocket;
|
|
2058
|
+
function initAsClient(websocket, address, protocols, options) {
|
|
2059
|
+
const opts = {
|
|
2060
|
+
allowSynchronousEvents: true,
|
|
2061
|
+
autoPong: true,
|
|
2062
|
+
closeTimeout: CLOSE_TIMEOUT,
|
|
2063
|
+
protocolVersion: protocolVersions[1],
|
|
2064
|
+
maxBufferedChunks: 256 * 1024,
|
|
2065
|
+
maxFragments: 16 * 1024,
|
|
2066
|
+
maxPayload: 100 * 1024 * 1024,
|
|
2067
|
+
skipUTF8Validation: false,
|
|
2068
|
+
perMessageDeflate: true,
|
|
2069
|
+
followRedirects: false,
|
|
2070
|
+
maxRedirects: 10,
|
|
2071
|
+
...options,
|
|
2072
|
+
socketPath: undefined,
|
|
2073
|
+
hostname: undefined,
|
|
2074
|
+
protocol: undefined,
|
|
2075
|
+
protocols: undefined,
|
|
2076
|
+
timeout: undefined,
|
|
2077
|
+
method: "GET",
|
|
2078
|
+
host: undefined,
|
|
2079
|
+
path: undefined,
|
|
2080
|
+
port: undefined
|
|
2081
|
+
};
|
|
2082
|
+
websocket._autoPong = opts.autoPong;
|
|
2083
|
+
websocket._closeTimeout = opts.closeTimeout;
|
|
2084
|
+
if (!protocolVersions.includes(opts.protocolVersion)) {
|
|
2085
|
+
throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(", ")})`);
|
|
2086
|
+
}
|
|
2087
|
+
let parsedUrl;
|
|
2088
|
+
if (address instanceof URL2) {
|
|
2089
|
+
parsedUrl = address;
|
|
2090
|
+
} else {
|
|
2091
|
+
try {
|
|
2092
|
+
parsedUrl = new URL2(address);
|
|
2093
|
+
} catch {
|
|
2094
|
+
throw new SyntaxError(`Invalid URL: ${address}`);
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
2097
|
+
if (parsedUrl.protocol === "http:") {
|
|
2098
|
+
parsedUrl.protocol = "ws:";
|
|
2099
|
+
} else if (parsedUrl.protocol === "https:") {
|
|
2100
|
+
parsedUrl.protocol = "wss:";
|
|
2101
|
+
}
|
|
2102
|
+
websocket._url = parsedUrl.href;
|
|
2103
|
+
const isSecure = parsedUrl.protocol === "wss:";
|
|
2104
|
+
const isIpcUrl = parsedUrl.protocol === "ws+unix:";
|
|
2105
|
+
let invalidUrlMessage;
|
|
2106
|
+
if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
|
|
2107
|
+
invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", ` + '"http:", "https:", or "ws+unix:"';
|
|
2108
|
+
} else if (isIpcUrl && !parsedUrl.pathname) {
|
|
2109
|
+
invalidUrlMessage = "The URL's pathname is empty";
|
|
2110
|
+
} else if (parsedUrl.hash) {
|
|
2111
|
+
invalidUrlMessage = "The URL contains a fragment identifier";
|
|
2112
|
+
}
|
|
2113
|
+
if (invalidUrlMessage) {
|
|
2114
|
+
const err = new SyntaxError(invalidUrlMessage);
|
|
2115
|
+
if (websocket._redirects === 0) {
|
|
2116
|
+
throw err;
|
|
2117
|
+
} else {
|
|
2118
|
+
emitErrorAndClose(websocket, err);
|
|
2119
|
+
return;
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
const defaultPort = isSecure ? 443 : 80;
|
|
2123
|
+
const key = randomBytes(16).toString("base64");
|
|
2124
|
+
const request3 = isSecure ? https.request : http.request;
|
|
2125
|
+
const protocolSet = new Set;
|
|
2126
|
+
let perMessageDeflate;
|
|
2127
|
+
opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
|
|
2128
|
+
opts.defaultPort = opts.defaultPort || defaultPort;
|
|
2129
|
+
opts.port = parsedUrl.port || defaultPort;
|
|
2130
|
+
opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
|
|
2131
|
+
opts.headers = {
|
|
2132
|
+
...opts.headers,
|
|
2133
|
+
"Sec-WebSocket-Version": opts.protocolVersion,
|
|
2134
|
+
"Sec-WebSocket-Key": key,
|
|
2135
|
+
Connection: "Upgrade",
|
|
2136
|
+
Upgrade: "websocket"
|
|
2137
|
+
};
|
|
2138
|
+
opts.path = parsedUrl.pathname + parsedUrl.search;
|
|
2139
|
+
opts.timeout = opts.handshakeTimeout;
|
|
2140
|
+
if (opts.perMessageDeflate) {
|
|
2141
|
+
perMessageDeflate = new PerMessageDeflate({
|
|
2142
|
+
...opts.perMessageDeflate,
|
|
2143
|
+
isServer: false,
|
|
2144
|
+
maxPayload: opts.maxPayload
|
|
2145
|
+
});
|
|
2146
|
+
opts.headers["Sec-WebSocket-Extensions"] = format({
|
|
2147
|
+
[PerMessageDeflate.extensionName]: perMessageDeflate.offer()
|
|
2148
|
+
});
|
|
2149
|
+
}
|
|
2150
|
+
if (protocols.length) {
|
|
2151
|
+
for (const protocol of protocols) {
|
|
2152
|
+
if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
|
|
2153
|
+
throw new SyntaxError("An invalid or duplicated subprotocol was specified");
|
|
2154
|
+
}
|
|
2155
|
+
protocolSet.add(protocol);
|
|
2156
|
+
}
|
|
2157
|
+
opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
|
|
2158
|
+
}
|
|
2159
|
+
if (opts.origin) {
|
|
2160
|
+
if (opts.protocolVersion < 13) {
|
|
2161
|
+
opts.headers["Sec-WebSocket-Origin"] = opts.origin;
|
|
2162
|
+
} else {
|
|
2163
|
+
opts.headers.Origin = opts.origin;
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
if (parsedUrl.username || parsedUrl.password) {
|
|
2167
|
+
opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
|
|
2168
|
+
}
|
|
2169
|
+
if (isIpcUrl) {
|
|
2170
|
+
const parts = opts.path.split(":");
|
|
2171
|
+
opts.socketPath = parts[0];
|
|
2172
|
+
opts.path = parts[1];
|
|
2173
|
+
}
|
|
2174
|
+
let req;
|
|
2175
|
+
if (opts.followRedirects) {
|
|
2176
|
+
if (websocket._redirects === 0) {
|
|
2177
|
+
websocket._originalIpc = isIpcUrl;
|
|
2178
|
+
websocket._originalSecure = isSecure;
|
|
2179
|
+
websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
|
|
2180
|
+
const headers = options && options.headers;
|
|
2181
|
+
options = { ...options, headers: {} };
|
|
2182
|
+
if (headers) {
|
|
2183
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
2184
|
+
options.headers[key.toLowerCase()] = value;
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
} else if (websocket.listenerCount("redirect") === 0) {
|
|
2188
|
+
const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
|
|
2189
|
+
if (!isSameHost || websocket._originalSecure && !isSecure) {
|
|
2190
|
+
delete opts.headers.authorization;
|
|
2191
|
+
delete opts.headers.cookie;
|
|
2192
|
+
if (!isSameHost)
|
|
2193
|
+
delete opts.headers.host;
|
|
2194
|
+
opts.auth = undefined;
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
if (opts.auth && !options.headers.authorization) {
|
|
2198
|
+
options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
|
|
2199
|
+
}
|
|
2200
|
+
req = websocket._req = request3(opts);
|
|
2201
|
+
if (websocket._redirects) {
|
|
2202
|
+
websocket.emit("redirect", websocket.url, req);
|
|
2203
|
+
}
|
|
2204
|
+
} else {
|
|
2205
|
+
req = websocket._req = request3(opts);
|
|
2206
|
+
}
|
|
2207
|
+
if (opts.timeout) {
|
|
2208
|
+
req.on("timeout", () => {
|
|
2209
|
+
abortHandshake(websocket, req, "Opening handshake has timed out");
|
|
2210
|
+
});
|
|
2211
|
+
}
|
|
2212
|
+
req.on("error", (err) => {
|
|
2213
|
+
if (req === null || req[kAborted])
|
|
2214
|
+
return;
|
|
2215
|
+
req = websocket._req = null;
|
|
2216
|
+
emitErrorAndClose(websocket, err);
|
|
2217
|
+
});
|
|
2218
|
+
req.on("response", (res) => {
|
|
2219
|
+
const location = res.headers.location;
|
|
2220
|
+
const statusCode = res.statusCode;
|
|
2221
|
+
if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
|
|
2222
|
+
if (++websocket._redirects > opts.maxRedirects) {
|
|
2223
|
+
abortHandshake(websocket, req, "Maximum redirects exceeded");
|
|
2224
|
+
return;
|
|
2225
|
+
}
|
|
2226
|
+
req.abort();
|
|
2227
|
+
let addr;
|
|
2228
|
+
try {
|
|
2229
|
+
addr = new URL2(location, address);
|
|
2230
|
+
} catch (e) {
|
|
2231
|
+
const err = new SyntaxError(`Invalid URL: ${location}`);
|
|
2232
|
+
emitErrorAndClose(websocket, err);
|
|
2233
|
+
return;
|
|
2234
|
+
}
|
|
2235
|
+
initAsClient(websocket, addr, protocols, options);
|
|
2236
|
+
} else if (!websocket.emit("unexpected-response", req, res)) {
|
|
2237
|
+
abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
|
|
2238
|
+
}
|
|
2239
|
+
});
|
|
2240
|
+
req.on("upgrade", (res, socket, head) => {
|
|
2241
|
+
websocket.emit("upgrade", res);
|
|
2242
|
+
if (websocket.readyState !== WebSocket.CONNECTING)
|
|
2243
|
+
return;
|
|
2244
|
+
req = websocket._req = null;
|
|
2245
|
+
const upgrade = res.headers.upgrade;
|
|
2246
|
+
if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
|
|
2247
|
+
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
2248
|
+
return;
|
|
2249
|
+
}
|
|
2250
|
+
const digest = createHash("sha1").update(key + GUID).digest("base64");
|
|
2251
|
+
if (res.headers["sec-websocket-accept"] !== digest) {
|
|
2252
|
+
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
2253
|
+
return;
|
|
2254
|
+
}
|
|
2255
|
+
const serverProt = res.headers["sec-websocket-protocol"];
|
|
2256
|
+
let protError;
|
|
2257
|
+
if (serverProt !== undefined) {
|
|
2258
|
+
if (!protocolSet.size) {
|
|
2259
|
+
protError = "Server sent a subprotocol but none was requested";
|
|
2260
|
+
} else if (!protocolSet.has(serverProt)) {
|
|
2261
|
+
protError = "Server sent an invalid subprotocol";
|
|
2262
|
+
}
|
|
2263
|
+
} else if (protocolSet.size) {
|
|
2264
|
+
protError = "Server sent no subprotocol";
|
|
2265
|
+
}
|
|
2266
|
+
if (protError) {
|
|
2267
|
+
abortHandshake(websocket, socket, protError);
|
|
2268
|
+
return;
|
|
2269
|
+
}
|
|
2270
|
+
if (serverProt)
|
|
2271
|
+
websocket._protocol = serverProt;
|
|
2272
|
+
const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
|
|
2273
|
+
if (secWebSocketExtensions !== undefined) {
|
|
2274
|
+
if (!perMessageDeflate) {
|
|
2275
|
+
const message = "Server sent a Sec-WebSocket-Extensions header but no extension " + "was requested";
|
|
2276
|
+
abortHandshake(websocket, socket, message);
|
|
2277
|
+
return;
|
|
2278
|
+
}
|
|
2279
|
+
let extensions;
|
|
2280
|
+
try {
|
|
2281
|
+
extensions = parse(secWebSocketExtensions);
|
|
2282
|
+
} catch (err) {
|
|
2283
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
2284
|
+
abortHandshake(websocket, socket, message);
|
|
2285
|
+
return;
|
|
2286
|
+
}
|
|
2287
|
+
const extensionNames = Object.keys(extensions);
|
|
2288
|
+
if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
|
|
2289
|
+
const message = "Server indicated an extension that was not requested";
|
|
2290
|
+
abortHandshake(websocket, socket, message);
|
|
2291
|
+
return;
|
|
2292
|
+
}
|
|
2293
|
+
try {
|
|
2294
|
+
perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
|
|
2295
|
+
} catch (err) {
|
|
2296
|
+
const message = "Invalid Sec-WebSocket-Extensions header";
|
|
2297
|
+
abortHandshake(websocket, socket, message);
|
|
2298
|
+
return;
|
|
2299
|
+
}
|
|
2300
|
+
websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
|
|
2301
|
+
}
|
|
2302
|
+
websocket.setSocket(socket, head, {
|
|
2303
|
+
allowSynchronousEvents: opts.allowSynchronousEvents,
|
|
2304
|
+
generateMask: opts.generateMask,
|
|
2305
|
+
maxBufferedChunks: opts.maxBufferedChunks,
|
|
2306
|
+
maxFragments: opts.maxFragments,
|
|
2307
|
+
maxPayload: opts.maxPayload,
|
|
2308
|
+
skipUTF8Validation: opts.skipUTF8Validation
|
|
2309
|
+
});
|
|
2310
|
+
});
|
|
2311
|
+
if (opts.finishRequest) {
|
|
2312
|
+
opts.finishRequest(req, websocket);
|
|
2313
|
+
} else {
|
|
2314
|
+
req.end();
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
function emitErrorAndClose(websocket, err) {
|
|
2318
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2319
|
+
websocket._errorEmitted = true;
|
|
2320
|
+
websocket.emit("error", err);
|
|
2321
|
+
websocket.emitClose();
|
|
2322
|
+
}
|
|
2323
|
+
function netConnect(options) {
|
|
2324
|
+
options.path = options.socketPath;
|
|
2325
|
+
return net.connect(options);
|
|
2326
|
+
}
|
|
2327
|
+
function tlsConnect(options) {
|
|
2328
|
+
options.path = undefined;
|
|
2329
|
+
if (!options.servername && options.servername !== "") {
|
|
2330
|
+
options.servername = net.isIP(options.host) ? "" : options.host;
|
|
2331
|
+
}
|
|
2332
|
+
return tls.connect(options);
|
|
2333
|
+
}
|
|
2334
|
+
function abortHandshake(websocket, stream, message) {
|
|
2335
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2336
|
+
const err = new Error(message);
|
|
2337
|
+
Error.captureStackTrace(err, abortHandshake);
|
|
2338
|
+
if (stream.setHeader) {
|
|
2339
|
+
stream[kAborted] = true;
|
|
2340
|
+
stream.abort();
|
|
2341
|
+
if (stream.socket && !stream.socket.destroyed) {
|
|
2342
|
+
stream.socket.destroy();
|
|
2343
|
+
}
|
|
2344
|
+
process.nextTick(emitErrorAndClose, websocket, err);
|
|
2345
|
+
} else {
|
|
2346
|
+
stream.destroy(err);
|
|
2347
|
+
stream.once("error", websocket.emit.bind(websocket, "error"));
|
|
2348
|
+
stream.once("close", websocket.emitClose.bind(websocket));
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
2351
|
+
function sendAfterClose(websocket, data, cb) {
|
|
2352
|
+
if (data) {
|
|
2353
|
+
const length = isBlob(data) ? data.size : toBuffer(data).length;
|
|
2354
|
+
if (websocket._socket)
|
|
2355
|
+
websocket._sender._bufferedBytes += length;
|
|
2356
|
+
else
|
|
2357
|
+
websocket._bufferedAmount += length;
|
|
2358
|
+
}
|
|
2359
|
+
if (cb) {
|
|
2360
|
+
const err = new Error(`WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})`);
|
|
2361
|
+
process.nextTick(cb, err);
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
function receiverOnConclude(code, reason) {
|
|
2365
|
+
const websocket = this[kWebSocket];
|
|
2366
|
+
websocket._closeFrameReceived = true;
|
|
2367
|
+
websocket._closeMessage = reason;
|
|
2368
|
+
websocket._closeCode = code;
|
|
2369
|
+
if (websocket._socket[kWebSocket] === undefined)
|
|
2370
|
+
return;
|
|
2371
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
2372
|
+
process.nextTick(resume, websocket._socket);
|
|
2373
|
+
if (code === 1005)
|
|
2374
|
+
websocket.close();
|
|
2375
|
+
else
|
|
2376
|
+
websocket.close(code, reason);
|
|
2377
|
+
}
|
|
2378
|
+
function receiverOnDrain() {
|
|
2379
|
+
const websocket = this[kWebSocket];
|
|
2380
|
+
if (!websocket.isPaused)
|
|
2381
|
+
websocket._socket.resume();
|
|
2382
|
+
}
|
|
2383
|
+
function receiverOnError(err) {
|
|
2384
|
+
const websocket = this[kWebSocket];
|
|
2385
|
+
if (websocket._socket[kWebSocket] !== undefined) {
|
|
2386
|
+
websocket._socket.removeListener("data", socketOnData);
|
|
2387
|
+
process.nextTick(resume, websocket._socket);
|
|
2388
|
+
websocket.close(err[kStatusCode]);
|
|
2389
|
+
}
|
|
2390
|
+
if (!websocket._errorEmitted) {
|
|
2391
|
+
websocket._errorEmitted = true;
|
|
2392
|
+
websocket.emit("error", err);
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
function receiverOnFinish() {
|
|
2396
|
+
this[kWebSocket].emitClose();
|
|
2397
|
+
}
|
|
2398
|
+
function receiverOnMessage(data, isBinary) {
|
|
2399
|
+
this[kWebSocket].emit("message", data, isBinary);
|
|
2400
|
+
}
|
|
2401
|
+
function receiverOnPing(data) {
|
|
2402
|
+
const websocket = this[kWebSocket];
|
|
2403
|
+
if (websocket._autoPong)
|
|
2404
|
+
websocket.pong(data, !this._isServer, NOOP);
|
|
2405
|
+
websocket.emit("ping", data);
|
|
2406
|
+
}
|
|
2407
|
+
function receiverOnPong(data) {
|
|
2408
|
+
this[kWebSocket].emit("pong", data);
|
|
2409
|
+
}
|
|
2410
|
+
function resume(stream) {
|
|
2411
|
+
stream.resume();
|
|
2412
|
+
}
|
|
2413
|
+
function senderOnError(err) {
|
|
2414
|
+
const websocket = this[kWebSocket];
|
|
2415
|
+
if (websocket.readyState === WebSocket.CLOSED)
|
|
2416
|
+
return;
|
|
2417
|
+
if (websocket.readyState === WebSocket.OPEN) {
|
|
2418
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2419
|
+
setCloseTimer(websocket);
|
|
2420
|
+
}
|
|
2421
|
+
this._socket.end();
|
|
2422
|
+
if (!websocket._errorEmitted) {
|
|
2423
|
+
websocket._errorEmitted = true;
|
|
2424
|
+
websocket.emit("error", err);
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
function setCloseTimer(websocket) {
|
|
2428
|
+
websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
|
|
2429
|
+
}
|
|
2430
|
+
function socketOnClose() {
|
|
2431
|
+
const websocket = this[kWebSocket];
|
|
2432
|
+
this.removeListener("close", socketOnClose);
|
|
2433
|
+
this.removeListener("data", socketOnData);
|
|
2434
|
+
this.removeListener("end", socketOnEnd);
|
|
2435
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2436
|
+
if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
|
|
2437
|
+
const chunk = this.read(this._readableState.length);
|
|
2438
|
+
websocket._receiver.write(chunk);
|
|
2439
|
+
}
|
|
2440
|
+
websocket._receiver.end();
|
|
2441
|
+
this[kWebSocket] = undefined;
|
|
2442
|
+
clearTimeout(websocket._closeTimer);
|
|
2443
|
+
if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
|
|
2444
|
+
websocket.emitClose();
|
|
2445
|
+
} else {
|
|
2446
|
+
websocket._receiver.on("error", receiverOnFinish);
|
|
2447
|
+
websocket._receiver.on("finish", receiverOnFinish);
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
function socketOnData(chunk) {
|
|
2451
|
+
if (!this[kWebSocket]._receiver.write(chunk)) {
|
|
2452
|
+
this.pause();
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
function socketOnEnd() {
|
|
2456
|
+
const websocket = this[kWebSocket];
|
|
2457
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2458
|
+
websocket._receiver.end();
|
|
2459
|
+
this.end();
|
|
2460
|
+
}
|
|
2461
|
+
function socketOnError() {
|
|
2462
|
+
const websocket = this[kWebSocket];
|
|
2463
|
+
this.removeListener("error", socketOnError);
|
|
2464
|
+
this.on("error", NOOP);
|
|
2465
|
+
if (websocket) {
|
|
2466
|
+
websocket._readyState = WebSocket.CLOSING;
|
|
2467
|
+
this.destroy();
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
});
|
|
2471
|
+
|
|
2472
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/stream.js
|
|
2473
|
+
var require_stream = __commonJS(function(exports, module) {
|
|
2474
|
+
var WebSocket = require_websocket();
|
|
2475
|
+
var { Duplex } = __require("stream");
|
|
2476
|
+
function emitClose(stream) {
|
|
2477
|
+
stream.emit("close");
|
|
2478
|
+
}
|
|
2479
|
+
function duplexOnEnd() {
|
|
2480
|
+
if (!this.destroyed && this._writableState.finished) {
|
|
2481
|
+
this.destroy();
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
function duplexOnError(err) {
|
|
2485
|
+
this.removeListener("error", duplexOnError);
|
|
2486
|
+
this.destroy();
|
|
2487
|
+
if (this.listenerCount("error") === 0) {
|
|
2488
|
+
this.emit("error", err);
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
function createWebSocketStream(ws, options) {
|
|
2492
|
+
let terminateOnDestroy = true;
|
|
2493
|
+
const duplex = new Duplex({
|
|
2494
|
+
...options,
|
|
2495
|
+
autoDestroy: false,
|
|
2496
|
+
emitClose: false,
|
|
2497
|
+
objectMode: false,
|
|
2498
|
+
writableObjectMode: false
|
|
2499
|
+
});
|
|
2500
|
+
ws.on("message", function message(msg, isBinary) {
|
|
2501
|
+
const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
|
|
2502
|
+
if (!duplex.push(data))
|
|
2503
|
+
ws.pause();
|
|
2504
|
+
});
|
|
2505
|
+
ws.once("error", function error(err) {
|
|
2506
|
+
if (duplex.destroyed)
|
|
2507
|
+
return;
|
|
2508
|
+
terminateOnDestroy = false;
|
|
2509
|
+
duplex.destroy(err);
|
|
2510
|
+
});
|
|
2511
|
+
ws.once("close", function close() {
|
|
2512
|
+
if (duplex.destroyed)
|
|
2513
|
+
return;
|
|
2514
|
+
duplex.push(null);
|
|
2515
|
+
});
|
|
2516
|
+
duplex._destroy = function(err, callback) {
|
|
2517
|
+
if (ws.readyState === ws.CLOSED) {
|
|
2518
|
+
callback(err);
|
|
2519
|
+
process.nextTick(emitClose, duplex);
|
|
2520
|
+
return;
|
|
2521
|
+
}
|
|
2522
|
+
let called = false;
|
|
2523
|
+
ws.once("error", function error(err) {
|
|
2524
|
+
called = true;
|
|
2525
|
+
callback(err);
|
|
2526
|
+
});
|
|
2527
|
+
ws.once("close", function close() {
|
|
2528
|
+
if (!called)
|
|
2529
|
+
callback(err);
|
|
2530
|
+
process.nextTick(emitClose, duplex);
|
|
2531
|
+
});
|
|
2532
|
+
if (terminateOnDestroy)
|
|
2533
|
+
ws.terminate();
|
|
2534
|
+
};
|
|
2535
|
+
duplex._final = function(callback) {
|
|
2536
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
2537
|
+
ws.once("open", function open() {
|
|
2538
|
+
duplex._final(callback);
|
|
2539
|
+
});
|
|
2540
|
+
return;
|
|
2541
|
+
}
|
|
2542
|
+
if (ws._socket === null)
|
|
2543
|
+
return;
|
|
2544
|
+
if (ws._socket._writableState.finished) {
|
|
2545
|
+
callback();
|
|
2546
|
+
if (duplex._readableState.endEmitted)
|
|
2547
|
+
duplex.destroy();
|
|
2548
|
+
} else {
|
|
2549
|
+
ws._socket.once("finish", function finish() {
|
|
2550
|
+
callback();
|
|
2551
|
+
});
|
|
2552
|
+
ws.close();
|
|
2553
|
+
}
|
|
2554
|
+
};
|
|
2555
|
+
duplex._read = function() {
|
|
2556
|
+
if (ws.isPaused)
|
|
2557
|
+
ws.resume();
|
|
2558
|
+
};
|
|
2559
|
+
duplex._write = function(chunk, encoding, callback) {
|
|
2560
|
+
if (ws.readyState === ws.CONNECTING) {
|
|
2561
|
+
ws.once("open", function open() {
|
|
2562
|
+
duplex._write(chunk, encoding, callback);
|
|
2563
|
+
});
|
|
2564
|
+
return;
|
|
2565
|
+
}
|
|
2566
|
+
ws.send(chunk, callback);
|
|
2567
|
+
};
|
|
2568
|
+
duplex.on("end", duplexOnEnd);
|
|
2569
|
+
duplex.on("error", duplexOnError);
|
|
2570
|
+
return duplex;
|
|
2571
|
+
}
|
|
2572
|
+
module.exports = createWebSocketStream;
|
|
2573
|
+
});
|
|
2574
|
+
|
|
2575
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/subprotocol.js
|
|
2576
|
+
var require_subprotocol = __commonJS(function(exports, module) {
|
|
2577
|
+
var { tokenChars } = require_validation();
|
|
2578
|
+
function parse(header) {
|
|
2579
|
+
const protocols = new Set;
|
|
2580
|
+
let start = -1;
|
|
2581
|
+
let end = -1;
|
|
2582
|
+
let i = 0;
|
|
2583
|
+
for (i;i < header.length; i++) {
|
|
2584
|
+
const code = header.charCodeAt(i);
|
|
2585
|
+
if (end === -1 && tokenChars[code] === 1) {
|
|
2586
|
+
if (start === -1)
|
|
2587
|
+
start = i;
|
|
2588
|
+
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
2589
|
+
if (end === -1 && start !== -1)
|
|
2590
|
+
end = i;
|
|
2591
|
+
} else if (code === 44) {
|
|
2592
|
+
if (start === -1) {
|
|
2593
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2594
|
+
}
|
|
2595
|
+
if (end === -1)
|
|
2596
|
+
end = i;
|
|
2597
|
+
const protocol = header.slice(start, end);
|
|
2598
|
+
if (protocols.has(protocol)) {
|
|
2599
|
+
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
|
|
2600
|
+
}
|
|
2601
|
+
protocols.add(protocol);
|
|
2602
|
+
start = end = -1;
|
|
2603
|
+
} else {
|
|
2604
|
+
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
2605
|
+
}
|
|
2606
|
+
}
|
|
2607
|
+
if (start === -1 || end !== -1) {
|
|
2608
|
+
throw new SyntaxError("Unexpected end of input");
|
|
2609
|
+
}
|
|
2610
|
+
const protocol = header.slice(start, i);
|
|
2611
|
+
if (protocols.has(protocol)) {
|
|
2612
|
+
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
|
|
2613
|
+
}
|
|
2614
|
+
protocols.add(protocol);
|
|
2615
|
+
return protocols;
|
|
2616
|
+
}
|
|
2617
|
+
module.exports = { parse };
|
|
2618
|
+
});
|
|
2619
|
+
|
|
2620
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/lib/websocket-server.js
|
|
2621
|
+
var require_websocket_server = __commonJS(function(exports, module) {
|
|
2622
|
+
var EventEmitter = __require("events");
|
|
2623
|
+
var http = __require("http");
|
|
2624
|
+
var { Duplex } = __require("stream");
|
|
2625
|
+
var { createHash } = __require("crypto");
|
|
2626
|
+
var extension = require_extension();
|
|
2627
|
+
var PerMessageDeflate = require_permessage_deflate();
|
|
2628
|
+
var subprotocol = require_subprotocol();
|
|
2629
|
+
var WebSocket = require_websocket();
|
|
2630
|
+
var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
|
|
2631
|
+
var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
|
|
2632
|
+
var RUNNING = 0;
|
|
2633
|
+
var CLOSING = 1;
|
|
2634
|
+
var CLOSED = 2;
|
|
2635
|
+
|
|
2636
|
+
class WebSocketServer extends EventEmitter {
|
|
2637
|
+
constructor(options, callback) {
|
|
2638
|
+
super();
|
|
2639
|
+
options = {
|
|
2640
|
+
allowSynchronousEvents: true,
|
|
2641
|
+
autoPong: true,
|
|
2642
|
+
maxBufferedChunks: 256 * 1024,
|
|
2643
|
+
maxFragments: 16 * 1024,
|
|
2644
|
+
maxPayload: 100 * 1024 * 1024,
|
|
2645
|
+
skipUTF8Validation: false,
|
|
2646
|
+
perMessageDeflate: false,
|
|
2647
|
+
handleProtocols: null,
|
|
2648
|
+
clientTracking: true,
|
|
2649
|
+
closeTimeout: CLOSE_TIMEOUT,
|
|
2650
|
+
verifyClient: null,
|
|
2651
|
+
noServer: false,
|
|
2652
|
+
backlog: null,
|
|
2653
|
+
server: null,
|
|
2654
|
+
host: null,
|
|
2655
|
+
path: null,
|
|
2656
|
+
port: null,
|
|
2657
|
+
WebSocket,
|
|
2658
|
+
...options
|
|
2659
|
+
};
|
|
2660
|
+
if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
|
|
2661
|
+
throw new TypeError('One and only one of the "port", "server", or "noServer" options ' + "must be specified");
|
|
2662
|
+
}
|
|
2663
|
+
if (options.port != null) {
|
|
2664
|
+
this._server = http.createServer((req, res) => {
|
|
2665
|
+
const body = http.STATUS_CODES[426];
|
|
2666
|
+
res.writeHead(426, {
|
|
2667
|
+
"Content-Length": body.length,
|
|
2668
|
+
"Content-Type": "text/plain"
|
|
2669
|
+
});
|
|
2670
|
+
res.end(body);
|
|
2671
|
+
});
|
|
2672
|
+
this._server.listen(options.port, options.host, options.backlog, callback);
|
|
2673
|
+
} else if (options.server) {
|
|
2674
|
+
this._server = options.server;
|
|
2675
|
+
}
|
|
2676
|
+
if (this._server) {
|
|
2677
|
+
const emitConnection = this.emit.bind(this, "connection");
|
|
2678
|
+
this._removeListeners = addListeners(this._server, {
|
|
2679
|
+
listening: this.emit.bind(this, "listening"),
|
|
2680
|
+
error: this.emit.bind(this, "error"),
|
|
2681
|
+
upgrade: (req, socket, head) => {
|
|
2682
|
+
this.handleUpgrade(req, socket, head, emitConnection);
|
|
2683
|
+
}
|
|
2684
|
+
});
|
|
2685
|
+
}
|
|
2686
|
+
if (options.perMessageDeflate === true)
|
|
2687
|
+
options.perMessageDeflate = {};
|
|
2688
|
+
if (options.clientTracking) {
|
|
2689
|
+
this.clients = new Set;
|
|
2690
|
+
this._shouldEmitClose = false;
|
|
2691
|
+
}
|
|
2692
|
+
this.options = options;
|
|
2693
|
+
this._state = RUNNING;
|
|
2694
|
+
}
|
|
2695
|
+
address() {
|
|
2696
|
+
if (this.options.noServer) {
|
|
2697
|
+
throw new Error('The server is operating in "noServer" mode');
|
|
2698
|
+
}
|
|
2699
|
+
if (!this._server)
|
|
2700
|
+
return null;
|
|
2701
|
+
return this._server.address();
|
|
2702
|
+
}
|
|
2703
|
+
close(cb) {
|
|
2704
|
+
if (this._state === CLOSED) {
|
|
2705
|
+
if (cb) {
|
|
2706
|
+
this.once("close", () => {
|
|
2707
|
+
cb(new Error("The server is not running"));
|
|
2708
|
+
});
|
|
2709
|
+
}
|
|
2710
|
+
process.nextTick(emitClose, this);
|
|
2711
|
+
return;
|
|
2712
|
+
}
|
|
2713
|
+
if (cb)
|
|
2714
|
+
this.once("close", cb);
|
|
2715
|
+
if (this._state === CLOSING)
|
|
2716
|
+
return;
|
|
2717
|
+
this._state = CLOSING;
|
|
2718
|
+
if (this.options.noServer || this.options.server) {
|
|
2719
|
+
if (this._server) {
|
|
2720
|
+
this._removeListeners();
|
|
2721
|
+
this._removeListeners = this._server = null;
|
|
2722
|
+
}
|
|
2723
|
+
if (this.clients) {
|
|
2724
|
+
if (!this.clients.size) {
|
|
2725
|
+
process.nextTick(emitClose, this);
|
|
2726
|
+
} else {
|
|
2727
|
+
this._shouldEmitClose = true;
|
|
2728
|
+
}
|
|
2729
|
+
} else {
|
|
2730
|
+
process.nextTick(emitClose, this);
|
|
2731
|
+
}
|
|
2732
|
+
} else {
|
|
2733
|
+
const server = this._server;
|
|
2734
|
+
this._removeListeners();
|
|
2735
|
+
this._removeListeners = this._server = null;
|
|
2736
|
+
server.close(() => {
|
|
2737
|
+
emitClose(this);
|
|
2738
|
+
});
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
shouldHandle(req) {
|
|
2742
|
+
if (this.options.path) {
|
|
2743
|
+
const index = req.url.indexOf("?");
|
|
2744
|
+
const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
|
|
2745
|
+
if (pathname !== this.options.path)
|
|
2746
|
+
return false;
|
|
2747
|
+
}
|
|
2748
|
+
return true;
|
|
2749
|
+
}
|
|
2750
|
+
handleUpgrade(req, socket, head, cb) {
|
|
2751
|
+
socket.on("error", socketOnError);
|
|
2752
|
+
const key = req.headers["sec-websocket-key"];
|
|
2753
|
+
const upgrade = req.headers.upgrade;
|
|
2754
|
+
const version = +req.headers["sec-websocket-version"];
|
|
2755
|
+
if (req.method !== "GET") {
|
|
2756
|
+
const message = "Invalid HTTP method";
|
|
2757
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
|
|
2758
|
+
return;
|
|
2759
|
+
}
|
|
2760
|
+
if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
|
|
2761
|
+
const message = "Invalid Upgrade header";
|
|
2762
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
2763
|
+
return;
|
|
2764
|
+
}
|
|
2765
|
+
if (key === undefined || !keyRegex.test(key)) {
|
|
2766
|
+
const message = "Missing or invalid Sec-WebSocket-Key header";
|
|
2767
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
2768
|
+
return;
|
|
2769
|
+
}
|
|
2770
|
+
if (version !== 13 && version !== 8) {
|
|
2771
|
+
const message = "Missing or invalid Sec-WebSocket-Version header";
|
|
2772
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
|
|
2773
|
+
"Sec-WebSocket-Version": "13, 8"
|
|
2774
|
+
});
|
|
2775
|
+
return;
|
|
2776
|
+
}
|
|
2777
|
+
if (!this.shouldHandle(req)) {
|
|
2778
|
+
abortHandshake(socket, 400);
|
|
2779
|
+
return;
|
|
2780
|
+
}
|
|
2781
|
+
const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
|
|
2782
|
+
let protocols = new Set;
|
|
2783
|
+
if (secWebSocketProtocol !== undefined) {
|
|
2784
|
+
try {
|
|
2785
|
+
protocols = subprotocol.parse(secWebSocketProtocol);
|
|
2786
|
+
} catch (err) {
|
|
2787
|
+
const message = "Invalid Sec-WebSocket-Protocol header";
|
|
2788
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
2789
|
+
return;
|
|
2790
|
+
}
|
|
2791
|
+
}
|
|
2792
|
+
const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
|
|
2793
|
+
const extensions = {};
|
|
2794
|
+
if (this.options.perMessageDeflate && secWebSocketExtensions !== undefined) {
|
|
2795
|
+
const perMessageDeflate = new PerMessageDeflate({
|
|
2796
|
+
...this.options.perMessageDeflate,
|
|
2797
|
+
isServer: true,
|
|
2798
|
+
maxPayload: this.options.maxPayload
|
|
2799
|
+
});
|
|
2800
|
+
try {
|
|
2801
|
+
const offers = extension.parse(secWebSocketExtensions);
|
|
2802
|
+
if (offers[PerMessageDeflate.extensionName]) {
|
|
2803
|
+
perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
|
|
2804
|
+
extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
|
|
2805
|
+
}
|
|
2806
|
+
} catch (err) {
|
|
2807
|
+
const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
|
|
2808
|
+
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
2809
|
+
return;
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
if (this.options.verifyClient) {
|
|
2813
|
+
const info = {
|
|
2814
|
+
origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
|
|
2815
|
+
secure: !!(req.socket.authorized || req.socket.encrypted),
|
|
2816
|
+
req
|
|
2817
|
+
};
|
|
2818
|
+
if (this.options.verifyClient.length === 2) {
|
|
2819
|
+
this.options.verifyClient(info, (verified, code, message, headers) => {
|
|
2820
|
+
if (!verified) {
|
|
2821
|
+
return abortHandshake(socket, code || 401, message, headers);
|
|
2822
|
+
}
|
|
2823
|
+
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
|
|
2824
|
+
});
|
|
2825
|
+
return;
|
|
2826
|
+
}
|
|
2827
|
+
if (!this.options.verifyClient(info))
|
|
2828
|
+
return abortHandshake(socket, 401);
|
|
2829
|
+
}
|
|
2830
|
+
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
|
|
2831
|
+
}
|
|
2832
|
+
completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
|
|
2833
|
+
if (!socket.readable || !socket.writable)
|
|
2834
|
+
return socket.destroy();
|
|
2835
|
+
if (socket[kWebSocket]) {
|
|
2836
|
+
throw new Error("server.handleUpgrade() was called more than once with the same " + "socket, possibly due to a misconfiguration");
|
|
2837
|
+
}
|
|
2838
|
+
if (this._state > RUNNING)
|
|
2839
|
+
return abortHandshake(socket, 503);
|
|
2840
|
+
const digest = createHash("sha1").update(key + GUID).digest("base64");
|
|
2841
|
+
const headers = [
|
|
2842
|
+
"HTTP/1.1 101 Switching Protocols",
|
|
2843
|
+
"Upgrade: websocket",
|
|
2844
|
+
"Connection: Upgrade",
|
|
2845
|
+
`Sec-WebSocket-Accept: ${digest}`
|
|
2846
|
+
];
|
|
2847
|
+
const ws = new this.options.WebSocket(null, undefined, this.options);
|
|
2848
|
+
if (protocols.size) {
|
|
2849
|
+
const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
|
|
2850
|
+
if (protocol) {
|
|
2851
|
+
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
|
|
2852
|
+
ws._protocol = protocol;
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
if (extensions[PerMessageDeflate.extensionName]) {
|
|
2856
|
+
const params = extensions[PerMessageDeflate.extensionName].params;
|
|
2857
|
+
const value = extension.format({
|
|
2858
|
+
[PerMessageDeflate.extensionName]: [params]
|
|
2859
|
+
});
|
|
2860
|
+
headers.push(`Sec-WebSocket-Extensions: ${value}`);
|
|
2861
|
+
ws._extensions = extensions;
|
|
2862
|
+
}
|
|
2863
|
+
this.emit("headers", headers, req);
|
|
2864
|
+
socket.write(headers.concat(`\r
|
|
2865
|
+
`).join(`\r
|
|
2866
|
+
`));
|
|
2867
|
+
socket.removeListener("error", socketOnError);
|
|
2868
|
+
ws.setSocket(socket, head, {
|
|
2869
|
+
allowSynchronousEvents: this.options.allowSynchronousEvents,
|
|
2870
|
+
maxBufferedChunks: this.options.maxBufferedChunks,
|
|
2871
|
+
maxFragments: this.options.maxFragments,
|
|
2872
|
+
maxPayload: this.options.maxPayload,
|
|
2873
|
+
skipUTF8Validation: this.options.skipUTF8Validation
|
|
2874
|
+
});
|
|
2875
|
+
if (this.clients) {
|
|
2876
|
+
this.clients.add(ws);
|
|
2877
|
+
ws.on("close", () => {
|
|
2878
|
+
this.clients.delete(ws);
|
|
2879
|
+
if (this._shouldEmitClose && !this.clients.size) {
|
|
2880
|
+
process.nextTick(emitClose, this);
|
|
2881
|
+
}
|
|
2882
|
+
});
|
|
2883
|
+
}
|
|
2884
|
+
cb(ws, req);
|
|
2885
|
+
}
|
|
2886
|
+
}
|
|
2887
|
+
module.exports = WebSocketServer;
|
|
2888
|
+
function addListeners(server, map) {
|
|
2889
|
+
for (const event of Object.keys(map))
|
|
2890
|
+
server.on(event, map[event]);
|
|
2891
|
+
return function removeListeners() {
|
|
2892
|
+
for (const event of Object.keys(map)) {
|
|
2893
|
+
server.removeListener(event, map[event]);
|
|
2894
|
+
}
|
|
2895
|
+
};
|
|
2896
|
+
}
|
|
2897
|
+
function emitClose(server) {
|
|
2898
|
+
server._state = CLOSED;
|
|
2899
|
+
server.emit("close");
|
|
2900
|
+
}
|
|
2901
|
+
function socketOnError() {
|
|
2902
|
+
this.destroy();
|
|
2903
|
+
}
|
|
2904
|
+
function abortHandshake(socket, code, message, headers) {
|
|
2905
|
+
message = message || http.STATUS_CODES[code];
|
|
2906
|
+
headers = {
|
|
2907
|
+
Connection: "close",
|
|
2908
|
+
"Content-Type": "text/html",
|
|
2909
|
+
"Content-Length": Buffer.byteLength(message),
|
|
2910
|
+
...headers
|
|
2911
|
+
};
|
|
2912
|
+
socket.once("finish", socket.destroy);
|
|
2913
|
+
socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
|
|
2914
|
+
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join(`\r
|
|
2915
|
+
`) + `\r
|
|
2916
|
+
\r
|
|
2917
|
+
` + message);
|
|
2918
|
+
}
|
|
2919
|
+
function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
|
|
2920
|
+
if (server.listenerCount("wsClientError")) {
|
|
2921
|
+
const err = new Error(message);
|
|
2922
|
+
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
|
|
2923
|
+
server.emit("wsClientError", err, socket, req);
|
|
2924
|
+
} else {
|
|
2925
|
+
abortHandshake(socket, code, message, headers);
|
|
2926
|
+
}
|
|
2927
|
+
}
|
|
2928
|
+
});
|
|
2929
|
+
|
|
2930
|
+
// ../flashcards/src/chat/demo-instructions.md
|
|
2931
|
+
var demo_instructions_default = `# Demo tutor: English for a German-speaking beginner
|
|
2932
|
+
|
|
2933
|
+
You are the tutor in a notes and flashcards app. The learner speaks German and learns English at level A1. The learner reads, listens and answers questions in the notes; only you write, with the note tools. Never ask a question back, never offer options, never ask for confirmation.
|
|
2934
|
+
|
|
2935
|
+
## What a turn carries
|
|
2936
|
+
|
|
2937
|
+
- \`<open-note id="…" title="…" />\`: the note open beside the chat. With a skill button and no selection it comes as \`<note id="…" title="…">\` with the note's markdown inside.
|
|
2938
|
+
- \`<selection from="title">\`: text the learner selected, usually in the open note.
|
|
2939
|
+
- \`<skill>\`: sent by the buttons "Write notes" and "Write flashcards". Where the skill says something else (commands, \`fcc\`, level tags, card counts, asking the user), these instructions win.
|
|
2940
|
+
- The learner's typed text, usually German.
|
|
2941
|
+
|
|
2942
|
+
## When you write
|
|
2943
|
+
|
|
2944
|
+
1. "Nur im Chat", "nichts ändern" or the like: no write, whatever else the turn holds.
|
|
2945
|
+
2. A question ("Warum …?", "Wie heißt …?", "Was bedeutet …?"): answer in the chat only, also when a selection is attached.
|
|
2946
|
+
3. You write only when the learner asks in words for a note, cards, a question, an exercise or a change, or presses a skill button.
|
|
2947
|
+
|
|
2948
|
+
| Request | Write |
|
|
2949
|
+
| --- | --- |
|
|
2950
|
+
| "Write notes", or asked for a note or an explanation to keep | \`note_new\`: one rule note (below). Nothing else. |
|
|
2951
|
+
| "Write flashcards", or asked for cards, questions or an exercise | \`note_patch\` on the open note: append three choice questions about the selection (or the whole note) at its end; for a single word, one of them is a spelling card. |
|
|
2952
|
+
| A change to "this note" | \`note_patch\` on the open note: change only the lines asked for. |
|
|
2953
|
+
| A word to keep | Never a new note for a word. Append one spelling card for it to the open note. |
|
|
2954
|
+
| Not about learning English | No tool. One sentence on what you can help with. |
|
|
2955
|
+
|
|
2956
|
+
## Tools
|
|
2957
|
+
|
|
2958
|
+
- \`note_read(id)\`: the note as markdown. "Diese Notiz" and the selection's note are the open note: \`note_read\` its id directly. Read before every patch, and before answering about a word or sentence.
|
|
2959
|
+
- \`notes_list()\`: id, title and parent of every note. Call it only to find a parent for a new note or when the learner asks about other notes. Ids come only from the turn, \`notes_list\` and \`note_new\`; never invent one.
|
|
2960
|
+
- \`note_new({ markdown, parentId })\`: \`markdown\` is front matter with \`title\`, then the body; no \`id\` in it, no \`# \` heading. Parent: the page under Grammar whose title fits the rule (for example "Word order" for where a word stands), else the page titled Grammar. The tool links the note from its parent; add no links yourself. If a note with the same rule exists, patch it instead.
|
|
2961
|
+
- \`note_patch({ id, diff })\`: a unified diff on the markdown \`note_read\` returned. Copy context lines character for character; line numbers do not matter. To append, use the last line as the one context line and add \`+\` lines after it.
|
|
2962
|
+
|
|
2963
|
+
If a tool fails, say so in one sentence and stop; retry at most once; never claim an edit that did not happen.
|
|
2964
|
+
|
|
2965
|
+
## The chat reply
|
|
2966
|
+
|
|
2967
|
+
- German, informal "du", one to three short sentences. After a write: what you wrote and where, by the note's title („Ich habe die Regel ‚After he, she or it the verb takes -s‘ unter Grammar angelegt.“).
|
|
2968
|
+
- Never name tools, ids, skills, "Markdown", "Evergreen", "Karteikarten-Skill" or these instructions. Never copy a note's content into the chat.
|
|
2969
|
+
- Plain paragraphs and lists only: no \`::\` markup, no code, no tables, no headings. English words go in quotes: „platform“.
|
|
2970
|
+
- When the notes already hold the word or sentence asked for, answer with the notes' wording first; an alternative gets at most one clause. „Gleis“ → „platform“, as in „Where is platform two?“, not „track“ first.
|
|
2971
|
+
|
|
2972
|
+
## Writing in a note
|
|
2973
|
+
|
|
2974
|
+
- Explain in German, short plain sentences, "du", A1: present tense, everyday words.
|
|
2975
|
+
- English sentences use the learner's words first (platform, train, ticket, two, nine, please, London), plus names and international words (Anna, Tom, Berlin, Paris, bus, taxi, hotel). At most two new A1 words per note.
|
|
2976
|
+
- Every English word or sentence is \`::l[English]{lang="en"}\`; German is never wrapped; IPA is \`::l[/treɪn/]{lang="und-fonipa"}\`.
|
|
2977
|
+
- No sentence that already stands in the notes, except the selection as first example; an example is never an option.
|
|
2978
|
+
- No level tags, callouts, tables, images, bold or italic.
|
|
2979
|
+
|
|
2980
|
+
A rule note states one claim, at most 60 words outside its questions:
|
|
2981
|
+
|
|
2982
|
+
1. Title: the claim as a short English sentence, never a topic. Good: "After he, she or it the verb takes -s". Bad: "Present simple".
|
|
2983
|
+
2. One German sentence with the rule.
|
|
2984
|
+
3. Two English examples, each with its German meaning; the selection is the first.
|
|
2985
|
+
4. Two choice questions on the claim, each with a different sentence.
|
|
2986
|
+
|
|
2987
|
+
A choice question: the German sentence the learner wants to say (never „Welcher Satz ist richtig?“); three English options, one correct, not always in the same place; the two wrong ones are mistakes a German speaker really makes (German word order, a missing -s, a false friend); \`::explanation[…]\` is one German sentence saying why. No yes/no questions, no ids or other attributes. One blank line between the parts.
|
|
2988
|
+
|
|
2989
|
+
Example rule note, for the selection „The train leaves at nine.“ and „Warum leaves? Schreib mir eine Notiz dazu.“ (parent: Grammar):
|
|
2990
|
+
|
|
2991
|
+
\`\`\`
|
|
2992
|
+
---
|
|
2993
|
+
title: After he, she or it the verb takes -s
|
|
2994
|
+
---
|
|
2995
|
+
|
|
2996
|
+
Nach ::l[he]{lang="en"}, ::l[she]{lang="en"} oder ::l[it]{lang="en"} bekommt das Verb ein -s.
|
|
2997
|
+
|
|
2998
|
+
- ::l[The train leaves at nine.]{lang="en"} Der Zug fährt um neun ab.
|
|
2999
|
+
- ::l[Anna works in London.]{lang="en"} Anna arbeitet in London.
|
|
3000
|
+
|
|
3001
|
+
:::sc
|
|
3002
|
+
:::question[Der Bus fährt um zehn ab.]
|
|
3003
|
+
|
|
3004
|
+
::opt[::l[The bus leave at ten.]{lang="en"}]
|
|
3005
|
+
|
|
3006
|
+
::opt[::l[The bus leaves at ten.]{lang="en"}]{.correct}
|
|
3007
|
+
|
|
3008
|
+
::opt[::l[At ten leaves the bus.]{lang="en"}]
|
|
3009
|
+
|
|
3010
|
+
::explanation[::l[The bus]{lang="en"} ist „er, sie, es“, also bekommt das Verb ein -s.]
|
|
3011
|
+
:::
|
|
3012
|
+
|
|
3013
|
+
:::sc
|
|
3014
|
+
:::question[Tom wohnt in Berlin.]
|
|
3015
|
+
|
|
3016
|
+
::opt[::l[Tom lives in Berlin.]{lang="en"}]{.correct}
|
|
3017
|
+
|
|
3018
|
+
::opt[::l[Tom live in Berlin.]{lang="en"}]
|
|
3019
|
+
|
|
3020
|
+
::opt[::l[Tom is live in Berlin.]{lang="en"}]
|
|
3021
|
+
|
|
3022
|
+
::explanation[::l[Tom]{lang="en"} ist „er“, also ::l[lives]{lang="en"} mit -s.]
|
|
3023
|
+
:::
|
|
3024
|
+
\`\`\`
|
|
3025
|
+
|
|
3026
|
+
A spelling card asks for one word from its German meaning and IPA; the answer is the English word, lowercase:
|
|
3027
|
+
|
|
3028
|
+
\`\`\`
|
|
3029
|
+
:::sa
|
|
3030
|
+
:::question[der Zug · ::l[/treɪn/]{lang="und-fonipa"}]
|
|
3031
|
+
|
|
3032
|
+
::answer[train]
|
|
3033
|
+
:::
|
|
3034
|
+
\`\`\`
|
|
3035
|
+
`;
|
|
3036
|
+
|
|
3037
|
+
// src/serve-node.ts
|
|
3038
|
+
import { spawn } from "node:child_process";
|
|
3039
|
+
import { createServer } from "node:http";
|
|
3040
|
+
|
|
3041
|
+
// ../../../../../.bun/install/cache/links/ws@8.22.0-fc9ccb3317cbe8c0/node_modules/ws/wrapper.mjs
|
|
3042
|
+
var import_stream = __toESM(require_stream(), 1);
|
|
3043
|
+
var import_extension = __toESM(require_extension(), 1);
|
|
3044
|
+
var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
|
|
3045
|
+
var import_receiver = __toESM(require_receiver(), 1);
|
|
3046
|
+
var import_sender = __toESM(require_sender(), 1);
|
|
3047
|
+
var import_subprotocol = __toESM(require_subprotocol(), 1);
|
|
3048
|
+
var import_websocket = __toESM(require_websocket(), 1);
|
|
3049
|
+
var import_websocket_server = __toESM(require_websocket_server(), 1);
|
|
3050
|
+
|
|
3051
|
+
// ../flashcards/scripts/demo-codex-bridge.ts
|
|
3052
|
+
import { spawnSync } from "node:child_process";
|
|
3053
|
+
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
3054
|
+
import { tmpdir } from "node:os";
|
|
3055
|
+
import { join, resolve } from "node:path";
|
|
3056
|
+
var DEMO_BRIDGE_PORT = 3417;
|
|
3057
|
+
var bridgeSkills = ["evergreen-notes", "write-flash-cards"];
|
|
3058
|
+
var defaultBridgeOrigins = [
|
|
3059
|
+
"https://osnovahq.com",
|
|
3060
|
+
"https://easyray-storybook.pages.dev",
|
|
3061
|
+
"http://localhost:3000",
|
|
3062
|
+
"http://127.0.0.1:3000"
|
|
3063
|
+
];
|
|
3064
|
+
var storyUrl = "https://easyray-storybook.pages.dev/?id=Apps.Flashcards.TrainStationNotes&view=story&theme=dark";
|
|
3065
|
+
function createBridgeRouter(appServer, threadParams, skill) {
|
|
3066
|
+
const bySocket = new Map;
|
|
3067
|
+
const byThread = new Map;
|
|
3068
|
+
const emit = (conversation, event) => {
|
|
3069
|
+
conversation.socket.send(JSON.stringify(event));
|
|
3070
|
+
};
|
|
3071
|
+
function receive(message) {
|
|
3072
|
+
const event = message.params;
|
|
3073
|
+
const conversation = event?.threadId ? byThread.get(event.threadId) : undefined;
|
|
3074
|
+
if (message.method === "item/tool/call" && message.id !== undefined) {
|
|
3075
|
+
const call = message.params;
|
|
3076
|
+
if (!conversation) {
|
|
3077
|
+
appServer.respond(message.id, {
|
|
3078
|
+
success: false,
|
|
3079
|
+
contentItems: [{ type: "inputText", text: "No browser connected" }]
|
|
3080
|
+
});
|
|
3081
|
+
return;
|
|
3082
|
+
}
|
|
3083
|
+
emit(conversation, {
|
|
3084
|
+
type: "tool",
|
|
3085
|
+
callId: message.id,
|
|
3086
|
+
tool: call.tool,
|
|
3087
|
+
arguments: call.arguments ?? {}
|
|
3088
|
+
});
|
|
3089
|
+
return;
|
|
3090
|
+
}
|
|
3091
|
+
if (!event || !conversation)
|
|
3092
|
+
return;
|
|
3093
|
+
if (message.method === "item/agentMessage/delta" && event.itemId && event.delta) {
|
|
3094
|
+
conversation.streamed.add(event.itemId);
|
|
3095
|
+
emit(conversation, {
|
|
3096
|
+
type: "delta",
|
|
3097
|
+
itemId: event.itemId,
|
|
3098
|
+
text: event.delta
|
|
3099
|
+
});
|
|
3100
|
+
}
|
|
3101
|
+
if (message.method === "item/completed" && event.item?.type === "agentMessage" && !conversation.streamed.delete(event.item.id) && event.item.text)
|
|
3102
|
+
emit(conversation, {
|
|
3103
|
+
type: "delta",
|
|
3104
|
+
itemId: event.item.id,
|
|
3105
|
+
text: event.item.text
|
|
3106
|
+
});
|
|
3107
|
+
if (message.method === "turn/completed" && event.turn) {
|
|
3108
|
+
conversation.turnId = "";
|
|
3109
|
+
const error = event.turn.status === "failed" ? event.turn.error?.message ?? "Turn failed" : undefined;
|
|
3110
|
+
emit(conversation, {
|
|
3111
|
+
type: "completed",
|
|
3112
|
+
error,
|
|
3113
|
+
interrupted: event.turn.status === "interrupted" || undefined
|
|
3114
|
+
});
|
|
3115
|
+
}
|
|
3116
|
+
}
|
|
3117
|
+
async function onMessage(conversation, raw) {
|
|
3118
|
+
const message = JSON.parse(raw);
|
|
3119
|
+
const threadId = await conversation.thread;
|
|
3120
|
+
if (message.type === "toolResult") {
|
|
3121
|
+
appServer.respond(message.callId, {
|
|
3122
|
+
success: message.success,
|
|
3123
|
+
contentItems: [{ type: "inputText", text: message.text }]
|
|
3124
|
+
});
|
|
3125
|
+
return;
|
|
3126
|
+
}
|
|
3127
|
+
if (message.type === "interrupt") {
|
|
3128
|
+
if (conversation.turnId)
|
|
3129
|
+
await appServer.request("turn/interrupt", {
|
|
3130
|
+
threadId,
|
|
3131
|
+
turnId: conversation.turnId
|
|
3132
|
+
});
|
|
3133
|
+
return;
|
|
3134
|
+
}
|
|
3135
|
+
if (conversation.turnId)
|
|
3136
|
+
throw new Error("A reply is still running");
|
|
3137
|
+
let text = message.text;
|
|
3138
|
+
if (message.skill) {
|
|
3139
|
+
const skillText = bridgeSkills.includes(message.skill.name) ? skill(message.skill.name) : undefined;
|
|
3140
|
+
if (skillText === undefined) {
|
|
3141
|
+
emit(conversation, {
|
|
3142
|
+
type: "error",
|
|
3143
|
+
message: `Unknown skill: ${message.skill.name}`
|
|
3144
|
+
});
|
|
3145
|
+
return;
|
|
3146
|
+
}
|
|
3147
|
+
text = [skillTurnText(message.skill.label, skillText), text].filter(Boolean).join(`
|
|
3148
|
+
|
|
3149
|
+
`);
|
|
3150
|
+
}
|
|
3151
|
+
const started = await appServer.request("turn/start", {
|
|
3152
|
+
threadId,
|
|
3153
|
+
input: [{ type: "text", text, text_elements: [] }],
|
|
3154
|
+
effort: "low"
|
|
3155
|
+
});
|
|
3156
|
+
conversation.turnId = started.turn.id;
|
|
3157
|
+
}
|
|
3158
|
+
return {
|
|
3159
|
+
open(socket) {
|
|
3160
|
+
const thread = appServer.request("thread/start", threadParams()).then((started) => started.thread.id);
|
|
3161
|
+
const conversation = {
|
|
3162
|
+
socket,
|
|
3163
|
+
thread,
|
|
3164
|
+
threadId: "",
|
|
3165
|
+
turnId: "",
|
|
3166
|
+
streamed: new Set
|
|
3167
|
+
};
|
|
3168
|
+
bySocket.set(socket, conversation);
|
|
3169
|
+
(async () => {
|
|
3170
|
+
try {
|
|
3171
|
+
const threadId = await thread;
|
|
3172
|
+
if (bySocket.get(socket) !== conversation)
|
|
3173
|
+
return;
|
|
3174
|
+
conversation.threadId = threadId;
|
|
3175
|
+
byThread.set(threadId, conversation);
|
|
3176
|
+
emit(conversation, { type: "ready" });
|
|
3177
|
+
} catch (error) {
|
|
3178
|
+
emit(conversation, { type: "error", message: String(error) });
|
|
3179
|
+
}
|
|
3180
|
+
})();
|
|
3181
|
+
},
|
|
3182
|
+
close(socket) {
|
|
3183
|
+
const conversation = bySocket.get(socket);
|
|
3184
|
+
bySocket.delete(socket);
|
|
3185
|
+
if (!conversation?.threadId)
|
|
3186
|
+
return;
|
|
3187
|
+
byThread.delete(conversation.threadId);
|
|
3188
|
+
if (conversation.turnId)
|
|
3189
|
+
appServer.request("turn/interrupt", {
|
|
3190
|
+
threadId: conversation.threadId,
|
|
3191
|
+
turnId: conversation.turnId
|
|
3192
|
+
});
|
|
3193
|
+
},
|
|
3194
|
+
message(socket, raw) {
|
|
3195
|
+
const conversation = bySocket.get(socket);
|
|
3196
|
+
if (!conversation)
|
|
3197
|
+
return;
|
|
3198
|
+
onMessage(conversation, raw).catch((error) => {
|
|
3199
|
+
emit(conversation, {
|
|
3200
|
+
type: "completed",
|
|
3201
|
+
error: error instanceof Error ? error.message : String(error)
|
|
3202
|
+
});
|
|
3203
|
+
});
|
|
3204
|
+
},
|
|
3205
|
+
receive,
|
|
3206
|
+
broadcast(event) {
|
|
3207
|
+
for (const conversation of bySocket.values())
|
|
3208
|
+
emit(conversation, event);
|
|
3209
|
+
}
|
|
3210
|
+
};
|
|
3211
|
+
}
|
|
3212
|
+
var skillTurnText = (label, skillText) => `Apply this skill for this turn (task: ${label}). Write the result into the notes with the note tools, then reply in the chat.
|
|
3213
|
+
<skill>
|
|
3214
|
+
${skillText}
|
|
3215
|
+
</skill>`;
|
|
3216
|
+
var objectSchema = (properties, required) => ({
|
|
3217
|
+
type: "object",
|
|
3218
|
+
properties,
|
|
3219
|
+
required,
|
|
3220
|
+
additionalProperties: false
|
|
3221
|
+
});
|
|
3222
|
+
var dynamicTools = [
|
|
3223
|
+
{
|
|
3224
|
+
type: "function",
|
|
3225
|
+
name: "notes_list",
|
|
3226
|
+
description: "List every note in the workspace: id, title, parentId.",
|
|
3227
|
+
inputSchema: objectSchema({}, [])
|
|
3228
|
+
},
|
|
3229
|
+
{
|
|
3230
|
+
type: "function",
|
|
3231
|
+
name: "note_read",
|
|
3232
|
+
description: "Read one note as markdown (pageMeta frontmatter with id and title, then the body).",
|
|
3233
|
+
inputSchema: objectSchema({ id: { type: "string" } }, ["id"])
|
|
3234
|
+
},
|
|
3235
|
+
{
|
|
3236
|
+
type: "function",
|
|
3237
|
+
name: "note_new",
|
|
3238
|
+
description: `Create a note from markdown: frontmatter (---
|
|
3239
|
+
title: ...
|
|
3240
|
+
---) plus body. Optional parentId nests it. Returns its id.`,
|
|
3241
|
+
inputSchema: objectSchema({ markdown: { type: "string" }, parentId: { type: "string" } }, ["markdown"])
|
|
3242
|
+
},
|
|
3243
|
+
{
|
|
3244
|
+
type: "function",
|
|
3245
|
+
name: "note_patch",
|
|
3246
|
+
description: "Apply a unified diff to the markdown that note_read returned. Context lines must match exactly; @@ line numbers are advisory.",
|
|
3247
|
+
inputSchema: objectSchema({ id: { type: "string" }, diff: { type: "string" } }, ["id", "diff"])
|
|
3248
|
+
}
|
|
3249
|
+
];
|
|
3250
|
+
function bridgeThreadParams(input) {
|
|
3251
|
+
return {
|
|
3252
|
+
cwd: input.cwd,
|
|
3253
|
+
sandbox: "read-only",
|
|
3254
|
+
approvalPolicy: "never",
|
|
3255
|
+
developerInstructions: input.instructions,
|
|
3256
|
+
dynamicTools,
|
|
3257
|
+
...input.codex
|
|
3258
|
+
};
|
|
3259
|
+
}
|
|
3260
|
+
function createCodexSession(write, threadParams, skill) {
|
|
3261
|
+
const pending = new Map;
|
|
3262
|
+
let nextId = 0;
|
|
3263
|
+
const post = (message) => {
|
|
3264
|
+
write(JSON.stringify(message) + `
|
|
3265
|
+
`);
|
|
3266
|
+
};
|
|
3267
|
+
const send = (method, params) => {
|
|
3268
|
+
const id = ++nextId;
|
|
3269
|
+
return new Promise((res, reject) => {
|
|
3270
|
+
pending.set(id, {
|
|
3271
|
+
resolve: (v) => {
|
|
3272
|
+
res(v);
|
|
3273
|
+
},
|
|
3274
|
+
reject
|
|
3275
|
+
});
|
|
3276
|
+
post({ id, method, params });
|
|
3277
|
+
});
|
|
3278
|
+
};
|
|
3279
|
+
const initialized = (async () => {
|
|
3280
|
+
await send("initialize", {
|
|
3281
|
+
clientInfo: {
|
|
3282
|
+
name: "flashcards-demo",
|
|
3283
|
+
title: "Flashcards demo chat",
|
|
3284
|
+
version: "1"
|
|
3285
|
+
},
|
|
3286
|
+
capabilities: { experimentalApi: true, requestAttestation: false }
|
|
3287
|
+
});
|
|
3288
|
+
post({ method: "initialized", params: {} });
|
|
3289
|
+
})();
|
|
3290
|
+
initialized.catch((error) => {
|
|
3291
|
+
console.error("codex start failed", error);
|
|
3292
|
+
});
|
|
3293
|
+
const router = createBridgeRouter({
|
|
3294
|
+
request: async (method, params) => {
|
|
3295
|
+
await initialized;
|
|
3296
|
+
return send(method, params);
|
|
3297
|
+
},
|
|
3298
|
+
respond: (id, result) => {
|
|
3299
|
+
post({ id, result });
|
|
3300
|
+
}
|
|
3301
|
+
}, threadParams, skill);
|
|
3302
|
+
function handle(message) {
|
|
3303
|
+
if (message.method === "item/tool/call" || message.method && message.id === undefined) {
|
|
3304
|
+
router.receive(message);
|
|
3305
|
+
return;
|
|
3306
|
+
}
|
|
3307
|
+
if (message.method && message.id !== undefined) {
|
|
3308
|
+
post({
|
|
3309
|
+
id: message.id,
|
|
3310
|
+
error: { code: -32601, message: `Unsupported: ${message.method}` }
|
|
3311
|
+
});
|
|
3312
|
+
return;
|
|
3313
|
+
}
|
|
3314
|
+
if (message.id !== undefined) {
|
|
3315
|
+
const entry = pending.get(message.id);
|
|
3316
|
+
pending.delete(message.id);
|
|
3317
|
+
if (message.error)
|
|
3318
|
+
entry?.reject(new Error(message.error.message));
|
|
3319
|
+
else
|
|
3320
|
+
entry?.resolve(message.result);
|
|
3321
|
+
}
|
|
3322
|
+
}
|
|
3323
|
+
let buffer = "";
|
|
3324
|
+
return {
|
|
3325
|
+
router,
|
|
3326
|
+
receive(chunk) {
|
|
3327
|
+
buffer += chunk;
|
|
3328
|
+
let end = buffer.indexOf(`
|
|
3329
|
+
`);
|
|
3330
|
+
while (end >= 0) {
|
|
3331
|
+
const line = buffer.slice(0, end).trim();
|
|
3332
|
+
buffer = buffer.slice(end + 1);
|
|
3333
|
+
if (line) {
|
|
3334
|
+
try {
|
|
3335
|
+
handle(JSON.parse(line));
|
|
3336
|
+
} catch (error) {
|
|
3337
|
+
console.error("bad line from codex", error);
|
|
3338
|
+
}
|
|
3339
|
+
}
|
|
3340
|
+
end = buffer.indexOf(`
|
|
3341
|
+
`);
|
|
3342
|
+
}
|
|
3343
|
+
},
|
|
3344
|
+
exited() {
|
|
3345
|
+
console.error("codex app-server exited");
|
|
3346
|
+
router.broadcast({ type: "error", message: "codex app-server exited" });
|
|
3347
|
+
}
|
|
3348
|
+
};
|
|
3349
|
+
}
|
|
3350
|
+
function routeBridgeRequest(request, options) {
|
|
3351
|
+
const origin = request.origin ?? "";
|
|
3352
|
+
if (!options.allowedOrigins.includes(origin))
|
|
3353
|
+
return {
|
|
3354
|
+
status: 403,
|
|
3355
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
3356
|
+
body: `Origin ${origin || "(none)"} is not allowed. Start the bridge with --allow-origin ${origin || "<origin>"} to allow it.`
|
|
3357
|
+
};
|
|
3358
|
+
if (request.upgrade)
|
|
3359
|
+
return { upgrade: true };
|
|
3360
|
+
return {
|
|
3361
|
+
status: 200,
|
|
3362
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
3363
|
+
body: "flashcards codex bridge"
|
|
3364
|
+
};
|
|
3365
|
+
}
|
|
3366
|
+
var bridgeUsage = `Usage: flashcards-codex-bridge [--port N] [--allow-origin URL]...
|
|
3367
|
+
--port N port on 127.0.0.1 (env FLASHCARDS_BRIDGE_PORT, default ${DEMO_BRIDGE_PORT}; the page connects to ${DEMO_BRIDGE_PORT})
|
|
3368
|
+
--allow-origin URL also accept this page origin, repeatable (env FLASHCARDS_BRIDGE_ORIGINS, comma-separated)`;
|
|
3369
|
+
function parseBridgeOptions(argv, env) {
|
|
3370
|
+
let port = env.FLASHCARDS_BRIDGE_PORT;
|
|
3371
|
+
const origins = (env.FLASHCARDS_BRIDGE_ORIGINS ?? "").split(",").map((origin) => origin.trim()).filter(Boolean);
|
|
3372
|
+
for (let index = 0;index < argv.length; index++) {
|
|
3373
|
+
const flag = argv[index];
|
|
3374
|
+
const value = argv[index + 1];
|
|
3375
|
+
if (flag === "--help" || flag === "-h")
|
|
3376
|
+
return { help: true };
|
|
3377
|
+
if ((flag === "--port" || flag === "--allow-origin") && value) {
|
|
3378
|
+
if (flag === "--port")
|
|
3379
|
+
port = value;
|
|
3380
|
+
else
|
|
3381
|
+
origins.push(value);
|
|
3382
|
+
index++;
|
|
3383
|
+
continue;
|
|
3384
|
+
}
|
|
3385
|
+
return { error: `Unknown or incomplete option: ${flag}` };
|
|
3386
|
+
}
|
|
3387
|
+
const parsedPort = port === undefined ? DEMO_BRIDGE_PORT : Number(port);
|
|
3388
|
+
if (!Number.isInteger(parsedPort) || parsedPort < 0 || parsedPort > 65535)
|
|
3389
|
+
return { error: `Not a port: ${port}` };
|
|
3390
|
+
for (const origin of origins)
|
|
3391
|
+
if (!URL.canParse(origin) || new URL(origin).origin !== origin)
|
|
3392
|
+
return {
|
|
3393
|
+
error: `Not an origin (scheme://host[:port], no path): ${origin}`
|
|
3394
|
+
};
|
|
3395
|
+
return {
|
|
3396
|
+
port: parsedPort,
|
|
3397
|
+
allowedOrigins: [...defaultBridgeOrigins, ...origins]
|
|
3398
|
+
};
|
|
3399
|
+
}
|
|
3400
|
+
var probeCodex = (args) => {
|
|
3401
|
+
const result = spawnSync("codex", args, { encoding: "utf8", timeout: 1e4 });
|
|
3402
|
+
return {
|
|
3403
|
+
error: result.error,
|
|
3404
|
+
status: result.status,
|
|
3405
|
+
stdout: result.stdout ?? "",
|
|
3406
|
+
stderr: result.stderr ?? ""
|
|
3407
|
+
};
|
|
3408
|
+
};
|
|
3409
|
+
function codexProblem(probe = probeCodex) {
|
|
3410
|
+
const version = probe(["--version"]);
|
|
3411
|
+
if (version.error || version.status !== 0)
|
|
3412
|
+
return [
|
|
3413
|
+
"Codex CLI (`codex`) is not installed or not on PATH.",
|
|
3414
|
+
"Install it: npm install -g @openai/codex (or: brew install codex)",
|
|
3415
|
+
"Then log in: codex login"
|
|
3416
|
+
].join(`
|
|
3417
|
+
`);
|
|
3418
|
+
const login = probe(["login", "status"]);
|
|
3419
|
+
if (login.status !== 0 || /not logged in/i.test(`${login.stdout}
|
|
3420
|
+
${login.stderr}`))
|
|
3421
|
+
return "Codex CLI is not authenticated. Run `codex login` and try again.";
|
|
3422
|
+
return;
|
|
3423
|
+
}
|
|
3424
|
+
var portTakenMessage = (port) => `Port ${port} on 127.0.0.1 is already in use: is another bridge running? Stop it, or pass --port N (the chat page connects to ${DEMO_BRIDGE_PORT}).`;
|
|
3425
|
+
var readyMessage = (port) => `Flashcards chat bridge ready on ws://127.0.0.1:${port}. Open ${storyUrl} and press Chat (Ctrl+C stops the bridge).`;
|
|
3426
|
+
var isPortTaken = (error) => error?.code === "EADDRINUSE";
|
|
3427
|
+
function sessionDirectory() {
|
|
3428
|
+
const directory = join(tmpdir(), "flashcards-demo-codex");
|
|
3429
|
+
mkdirSync(directory, { recursive: true });
|
|
3430
|
+
return directory;
|
|
3431
|
+
}
|
|
3432
|
+
if (false)
|
|
3433
|
+
;
|
|
3434
|
+
|
|
3435
|
+
// src/serve-node.ts
|
|
3436
|
+
function serveNode(input) {
|
|
3437
|
+
const sockets = new import_websocket_server.default({ noServer: true });
|
|
3438
|
+
const route = (request, upgrade) => routeBridgeRequest({ origin: request.headers.origin, upgrade }, input);
|
|
3439
|
+
const server = createServer((request, response) => {
|
|
3440
|
+
const answer = route(request, false);
|
|
3441
|
+
if (!answer.upgrade)
|
|
3442
|
+
response.writeHead(answer.status, answer.headers).end(answer.body);
|
|
3443
|
+
});
|
|
3444
|
+
server.on("upgrade", (request, socket, head) => {
|
|
3445
|
+
const answer = route(request, true);
|
|
3446
|
+
if (!answer.upgrade) {
|
|
3447
|
+
socket.on("error", () => socket.destroy());
|
|
3448
|
+
socket.end(`HTTP/1.1 ${answer.status} Forbidden\r
|
|
3449
|
+
Content-Type: text/plain\r
|
|
3450
|
+
Connection: close\r
|
|
3451
|
+
\r
|
|
3452
|
+
${answer.body}`);
|
|
3453
|
+
return;
|
|
3454
|
+
}
|
|
3455
|
+
sockets.handleUpgrade(request, socket, head, (ws) => {
|
|
3456
|
+
const peer = {
|
|
3457
|
+
send: (text) => {
|
|
3458
|
+
ws.send(text);
|
|
3459
|
+
}
|
|
3460
|
+
};
|
|
3461
|
+
input.router.open(peer);
|
|
3462
|
+
ws.on("message", (data) => {
|
|
3463
|
+
input.router.message(peer, String(data));
|
|
3464
|
+
});
|
|
3465
|
+
ws.on("close", () => {
|
|
3466
|
+
input.router.close(peer);
|
|
3467
|
+
});
|
|
3468
|
+
});
|
|
3469
|
+
});
|
|
3470
|
+
return new Promise((resolve, reject) => {
|
|
3471
|
+
server.once("error", reject);
|
|
3472
|
+
server.listen(input.port, "127.0.0.1", () => {
|
|
3473
|
+
server.off("error", reject);
|
|
3474
|
+
resolve(server);
|
|
3475
|
+
});
|
|
3476
|
+
});
|
|
3477
|
+
}
|
|
3478
|
+
async function startBridge(texts) {
|
|
3479
|
+
const options = parseBridgeOptions(process.argv.slice(2), process.env);
|
|
3480
|
+
if ("help" in options || "error" in options) {
|
|
3481
|
+
if ("error" in options)
|
|
3482
|
+
console.error(options.error);
|
|
3483
|
+
console.info(bridgeUsage);
|
|
3484
|
+
process.exit("error" in options ? 2 : 0);
|
|
3485
|
+
}
|
|
3486
|
+
const problem = codexProblem();
|
|
3487
|
+
if (problem) {
|
|
3488
|
+
console.error(problem);
|
|
3489
|
+
process.exit(1);
|
|
3490
|
+
}
|
|
3491
|
+
const cwd = sessionDirectory();
|
|
3492
|
+
const child = spawn("codex", ["app-server"], {
|
|
3493
|
+
cwd,
|
|
3494
|
+
stdio: ["pipe", "pipe", "inherit"]
|
|
3495
|
+
});
|
|
3496
|
+
const session = createCodexSession((line) => {
|
|
3497
|
+
child.stdin.write(line);
|
|
3498
|
+
}, () => bridgeThreadParams({ cwd, instructions: texts.instructions }), (name) => texts.skills[name]);
|
|
3499
|
+
child.stdout.setEncoding("utf8");
|
|
3500
|
+
child.stdout.on("data", (chunk) => {
|
|
3501
|
+
session.receive(chunk);
|
|
3502
|
+
});
|
|
3503
|
+
child.on("exit", () => {
|
|
3504
|
+
session.exited();
|
|
3505
|
+
process.exit(1);
|
|
3506
|
+
});
|
|
3507
|
+
try {
|
|
3508
|
+
const server = await serveNode({
|
|
3509
|
+
port: options.port,
|
|
3510
|
+
allowedOrigins: options.allowedOrigins,
|
|
3511
|
+
router: session.router
|
|
3512
|
+
});
|
|
3513
|
+
const address = server.address();
|
|
3514
|
+
console.info(readyMessage(typeof address === "object" && address ? address.port : 0));
|
|
3515
|
+
} catch (error) {
|
|
3516
|
+
console.error(isPortTaken(error) ? portTakenMessage(options.port) : error);
|
|
3517
|
+
child.kill();
|
|
3518
|
+
process.exit(1);
|
|
3519
|
+
}
|
|
3520
|
+
const stop = () => {
|
|
3521
|
+
child.kill();
|
|
3522
|
+
process.exit(0);
|
|
3523
|
+
};
|
|
3524
|
+
process.on("SIGINT", stop);
|
|
3525
|
+
process.on("SIGTERM", stop);
|
|
3526
|
+
}
|
|
3527
|
+
|
|
3528
|
+
// src/bin.ts
|
|
3529
|
+
await startBridge({ instructions: demo_instructions_default, skills: { "evergreen-notes": `---
|
|
3530
|
+
name: evergreen-notes
|
|
3531
|
+
gate: 'evergreen notes?'
|
|
3532
|
+
description: >
|
|
3533
|
+
Use when creating, editing, splitting, linking, or outlining evergreen notes
|
|
3534
|
+
in a markdown note graph outside of \`legacy\` folder
|
|
3535
|
+
---
|
|
3536
|
+
|
|
3537
|
+
# Evergreen Notes
|
|
3538
|
+
|
|
3539
|
+
Use when task = add material to the notes, or create / edit / split / link / outline notes.
|
|
3540
|
+
|
|
3541
|
+
## Goal
|
|
3542
|
+
|
|
3543
|
+
Notes that evolve, contribute, and accumulate over time across projects. Every edit should make the graph a better thinking tool for its owner, not a bigger archive.
|
|
3544
|
+
|
|
3545
|
+
## Principles (why each matters)
|
|
3546
|
+
|
|
3547
|
+
1. **Concept-oriented.** One note per concept, never per source, author, project, or topic bucket. Why: new material on a concept must land on prior thinking about it, so ideas accrete and tensions surface.
|
|
3548
|
+
2. **Atomic, with tradeoff.** One claim per note, but enough of that claim to stand alone. Too broad → subclaims hide and links get muddy. Too fragmented → the link network breaks. No litmus test; choose by reuse.
|
|
3549
|
+
3. **Titles are APIs.** A complete declarative phrase that states the claim, so other notes can reference the idea by its title alone. Questions are fine when the answer is genuinely unresolved. Noun phrases only for definitions of core terms and for outlines. Prefer positive framings ("X requires Y", not "Z fails").
|
|
3550
|
+
4. **Dense, labeled, fine-grained links.** Link inline where the relationship does work, and say what the relationship is (depends on, qualifies, contrasts, extends). Why: links record how a conclusion was reached and create paths for later surprise. Never a "Related:" pile.
|
|
3551
|
+
5. **Associative before hierarchical.** Let structure emerge from links. Outlines are speculative hubs that order notes into possible arguments; they are not taxonomies.
|
|
3552
|
+
6. **Own words, owner's voice.** Rewrite source material in the graph's language. Keep the source's claim, causal direction, and primary outcome; drop its prose. Cite inline only when provenance matters.
|
|
3553
|
+
|
|
3554
|
+
## Workflow
|
|
3555
|
+
|
|
3556
|
+
1. **Search first.** Search the graph for the incoming claim's key terms and for its candidate title. Note candidate pages, their ids, nearby concepts, local naming style, and outlines. Search is how the graph creates pressure to synthesize; read what it returns.
|
|
3557
|
+
2. **Name the claims.** Write down each distinct claim in the incoming material in one sentence each. One sentence = one candidate note. Most single-paragraph inputs carry one claim; a source passage may carry several.
|
|
3558
|
+
3. **Choose the operation per claim** (first match wins):
|
|
3559
|
+
- **Extend** — an existing note's title already states this claim (same subject, same predicate). Add the new reason, example, or consequence locally; keep the opener; smallest sufficient diff.
|
|
3560
|
+
- **Split** — an existing note's body already carries this claim but its title does not. Move the claim into a child note; leave a one-sentence bridge link in the parent; keep the parent's title and opener unless already wrong.
|
|
3561
|
+
- **Create** — the claim is distinct and would be reused by other notes. Nearby notes that state a prerequisite, mechanism, caveat, or broader frame are link targets, not owners. One note per claim; several claims → several notes, linked to each other.
|
|
3562
|
+
- **No-op** — the material restates what the graph already says, or is a platitude no future note would link to. Do not pad an existing note. Reply with the owning note's exact title (titles are the handles; "the existing note" is not one) and the sentence that covers it.
|
|
3563
|
+
Tie-break: if unsure between extend and create, ask "would another note ever link to this claim by itself?" Yes → create.
|
|
3564
|
+
4. **Write.** Title first sentence: the claim. Then the support. Links inline with their relationship. No sources section for user-pasted text.
|
|
3565
|
+
5. **Place.** Every new note goes into at least one outline; create an outline (noun-phrase title, ordered links with short annotations) if none fits. Order by "which comes first?"; nest a note under the one it explains. Extending a note does not require touching outlines.
|
|
3566
|
+
6. **Revisit boundaries.** After writing, check each touched note: does every sentence support its title? If a body now outgrows its title, retitle or split.
|
|
3567
|
+
|
|
3568
|
+
## Priorities when rules conflict
|
|
3569
|
+
|
|
3570
|
+
- Correct operation > minimal diff. A missed new note costs more than an extra edit.
|
|
3571
|
+
- Fidelity to the incoming claim > matching local wording. Do not drop the new information to make a note look tidy.
|
|
3572
|
+
- Never: two notes for one claim; invented page ids; a link whose relationship you cannot state in the sentence.
|
|
3573
|
+
|
|
3574
|
+
## Worked cases
|
|
3575
|
+
|
|
3576
|
+
Each case: graph excerpt → incoming material → tempting wrong move → right move. Titles are illustrative.
|
|
3577
|
+
|
|
3578
|
+
### 1. Prerequisite note is a link target, not the owner (create, not extend)
|
|
3579
|
+
|
|
3580
|
+
Graph: \`Player agency requires meaningful non-illusory choices\` — body says choices must differ in outcome or they are theatrical.
|
|
3581
|
+
|
|
3582
|
+
Incoming: "Direct feedback makes player choices feel consequential because the player can see what changed."
|
|
3583
|
+
|
|
3584
|
+
Tempting: append to the agency note; it is nearby and "about choices".
|
|
3585
|
+
|
|
3586
|
+
Right: **create** \`Direct feedback makes player choices feel consequential\`. The agency note states a requirement (choices must matter); the incoming claim states a mechanism (feedback makes the mattering visible). Different predicate → different note. Link: "This depends on [[agency note]] because feedback can only reveal consequences that exist."
|
|
3587
|
+
|
|
3588
|
+
Why it matters: absorbing it would hide a reusable claim inside a note whose title no other note can use to reference feedback.
|
|
3589
|
+
|
|
3590
|
+
### 2. Same claim, new support (extend, not create)
|
|
3591
|
+
|
|
3592
|
+
Graph: \`Flow requires clear goals, no distractions, direct feedback, and continuous challenge\` — body mentions the flow channel between boredom and frustration.
|
|
3593
|
+
|
|
3594
|
+
Incoming: "Continuous challenge is the fragile prerequisite: designers usually detect challenge falling behind skill only through playtest data, because their own mastery hides it."
|
|
3595
|
+
|
|
3596
|
+
Tempting: create \`Playtest data is needed to detect challenge falling behind skill\`.
|
|
3597
|
+
|
|
3598
|
+
Right: **extend** the flow note with two sentences: the fragility and the playtest reason. The incoming text explains one of the four listed prerequisites; the title already owns that claim. No outline change.
|
|
3599
|
+
|
|
3600
|
+
When it flips: if the incoming text made a claim reusable outside flow ("designer mastery hides difficulty problems in any authored experience"), that generalization would be its own note.
|
|
3601
|
+
|
|
3602
|
+
### 3. Body carries a claim the title does not state (split, not append)
|
|
3603
|
+
|
|
3604
|
+
Graph: \`Feedback loops communicate progress and reinforce player behavior\` — body: "Immediate feedback makes cause and effect legible, while delayed feedback makes it harder to tell whether an action worked."
|
|
3605
|
+
|
|
3606
|
+
Incoming: "Cause and effect is easiest to learn when feedback follows an action closely. Beyond games, delayed feedback makes people misattribute results because other events intervene before the outcome appears."
|
|
3607
|
+
|
|
3608
|
+
Tempting: append the new sentences to the feedback-loops note.
|
|
3609
|
+
|
|
3610
|
+
Right: **split**. The legibility mechanism is already embedded in the parent and the incoming text develops it as a general claim. Child: \`Immediate feedback makes cause and effect legible\` with body that keeps the new information (intervening events → misattribution). Parent keeps its title and opener and gets a bridge: "This works because [[child]]." Remove the duplicated mechanism sentence from the parent. Outline: nest the child under the parent.
|
|
3611
|
+
|
|
3612
|
+
Failure to avoid: writing the child from the parent's old sentence and dropping the misattribution mechanism the user just gave you.
|
|
3613
|
+
|
|
3614
|
+
### 4. Multi-claim source (several notes, not one summary)
|
|
3615
|
+
|
|
3616
|
+
Graph: notes on creative work and motivation.
|
|
3617
|
+
|
|
3618
|
+
Incoming passage: "(a) People persist longer with hard creative work when intermediate progress is visible. (b) Visible progress does not reduce difficulty; it converts uncertainty into felt momentum. (c) Fake progress indicators reverse the effect because trust erodes."
|
|
3619
|
+
|
|
3620
|
+
Tempting: one note titled after the passage, or one note that lists all three.
|
|
3621
|
+
|
|
3622
|
+
Right: (a) is the top-level claim → note \`Visible intermediate progress increases persistence in difficult creative work\`. (b) is its mechanism; it stays in (a)'s body unless the graph already has an uncertainty note — then link to it. (c) is a distinct reusable claim → its own note \`Fake progress indicators erode trust in tools\` if absent, otherwise link to the existing one. Two notes, both linked, both in the outline.
|
|
3623
|
+
|
|
3624
|
+
Rule of thumb: a claim gets its own note when its title would differ in subject or predicate from the top-level claim and another note could plausibly link to it alone.
|
|
3625
|
+
|
|
3626
|
+
### 5. Restatement (no-op)
|
|
3627
|
+
|
|
3628
|
+
Graph: \`Flow requires clear goals, no distractions, direct feedback, and continuous challenge\` — body already says the flow channel sits between boredom and frustration and challenge must grow with skill.
|
|
3629
|
+
|
|
3630
|
+
Incoming: "Flow happens when challenge matches skill; too easy is boring, too hard is frustrating."
|
|
3631
|
+
|
|
3632
|
+
Tempting: append a paragraph so the edit "does something".
|
|
3633
|
+
|
|
3634
|
+
Right: **no-op**. Tell the user the note already states this, quote the sentence, and offer to add only if they meant something more specific. Padding makes future readers hunt for what changed.
|
|
3635
|
+
|
|
3636
|
+
### 6. Platitude (no-op, or ask for the real claim)
|
|
3637
|
+
|
|
3638
|
+
Incoming: "Games should be fun and engaging."
|
|
3639
|
+
|
|
3640
|
+
Right: do not create a note. No future note would link to this title; it makes no claim a reader could disagree with. Reply with what a note-worthy version would need: a mechanism, a condition, or a contrast.
|
|
3641
|
+
|
|
3642
|
+
### 7. No outline exists (create the outline)
|
|
3643
|
+
|
|
3644
|
+
Graph: three atomic notes on game feel, no outline note.
|
|
3645
|
+
|
|
3646
|
+
Incoming: a fourth claim.
|
|
3647
|
+
|
|
3648
|
+
Right: create the note, then create \`Game feel outline\` (noun phrase) listing the four notes in argument order with one-line annotations. Outlines are speculative; a four-item outline is fine.
|
|
3649
|
+
|
|
3650
|
+
### 8. Contradiction with an existing note (record tension, do not overwrite)
|
|
3651
|
+
|
|
3652
|
+
Graph: \`Variable rewards maintain excitement longer than fixed rewards\`.
|
|
3653
|
+
|
|
3654
|
+
Incoming: "In a study of two puzzle games, fixed rewards produced longer sessions once players understood the economy."
|
|
3655
|
+
|
|
3656
|
+
Tempting: rewrite the existing note's claim to hedge, or ignore the new evidence.
|
|
3657
|
+
|
|
3658
|
+
Right: keep the existing title. Add the finding as a qualification inside the note ("This appears to hold only before players model the economy; [[study note or inline citation]] found the reverse afterwards."). If the qualification is itself reusable ("Once players model a reward economy, predictability beats variability"), create it as a note and link both ways. The existing title changes only when the owner decides the claim is wrong.
|
|
3659
|
+
|
|
3660
|
+
### 9. Link quality
|
|
3661
|
+
|
|
3662
|
+
Bad: bottom-of-note pile — "Related: [[A]], [[B]], [[C]]".
|
|
3663
|
+
|
|
3664
|
+
Good: inline with the relationship — "This works because [[A]]"; "unlike [[B]], which assumes …"; "[[C]] extends this to teams."
|
|
3665
|
+
|
|
3666
|
+
Test: if you cannot state the relationship in the sentence, the link is decorative. Remove it.
|
|
3667
|
+
|
|
3668
|
+
### 10. Outline shape
|
|
3669
|
+
|
|
3670
|
+
Bad: outline used as a tag bucket (every game note dumped in, unordered).
|
|
3671
|
+
|
|
3672
|
+
Good: ordered path with annotations, nested where a note explains its parent:
|
|
3673
|
+
|
|
3674
|
+
\`\`\`md
|
|
3675
|
+
# Game design outline
|
|
3676
|
+
|
|
3677
|
+
1. [[Games are systems of meaningful choices balanced between opposing forces]] — balance creates the space for decisions
|
|
3678
|
+
2. [[Player agency requires meaningful non-illusory choices]] — what makes a choice matter
|
|
3679
|
+
1. [[Direct feedback makes player choices feel consequential]] — how the player perceives that it mattered
|
|
3680
|
+
3. [[Flow requires clear goals, no distractions, direct feedback, and continuous challenge]] — the target emotional state
|
|
3681
|
+
\`\`\`
|
|
3682
|
+
|
|
3683
|
+
Andy's real outlines (e.g. \`§Note-writing systems\`) are grouped hubs with headings and nesting. Order matters; strict linearity does not.
|
|
3684
|
+
|
|
3685
|
+
## Mechanics
|
|
3686
|
+
|
|
3687
|
+
Note storage, ids, link syntax, and commands are defined by the graph's tooling skill (fcc). Follow it for how to search, read, create, and patch. This skill decides what to write.
|
|
3688
|
+
|
|
3689
|
+
NEVER COMMIT OR SYNC UNLESS EXPLICITLY ASKED IN PREVIOUS MESSAGE!
|
|
3690
|
+
`, "write-flash-cards": `---
|
|
3691
|
+
name: write-flash-cards
|
|
3692
|
+
description: Manual trigger. Iteratively create flashcards for content.
|
|
3693
|
+
---
|
|
3694
|
+
|
|
3695
|
+
# Writing Flash Cards
|
|
3696
|
+
|
|
3697
|
+
Use when task = create or extend flash cards from source material.
|
|
3698
|
+
|
|
3699
|
+
## Goal
|
|
3700
|
+
|
|
3701
|
+
A card is a recurring task for the reviewer's future self. A good card makes them retrieve, months later and without the source open, the one thing the source made worth remembering. A plausible-but-wrong card costs more than a missing one: it gets reviewed for years, trains the wrong thing, and erodes trust in the deck. When in doubt, omit and report.
|
|
3702
|
+
|
|
3703
|
+
## Two separate problems
|
|
3704
|
+
|
|
3705
|
+
1. **Targeting** — what to reinforce. Hardest part; the model cannot know what the reader already knows or cares about. Use every hint the user gives (highlights, "why", "notation", "contrast with X") and the reader's existing cards. Without hints, choose the source's own point, not its nearby trivia.
|
|
3706
|
+
2. **Construction** — how to phrase a prompt for a chosen target. Mechanical once the target is right; follow the patterns below.
|
|
3707
|
+
|
|
3708
|
+
Never let construction hide a targeting error. A beautifully phrased card about the wrong thing is still wrong.
|
|
3709
|
+
|
|
3710
|
+
## Required inputs
|
|
3711
|
+
|
|
3712
|
+
- source: note id(s), pasted passage, URL, or concept
|
|
3713
|
+
- target note id (cards are appended there)
|
|
3714
|
+
- optional hints: which angle to reinforce, reader level
|
|
3715
|
+
|
|
3716
|
+
If source or target is missing, ask. Do not invent a target.
|
|
3717
|
+
|
|
3718
|
+
## Workflow
|
|
3719
|
+
|
|
3720
|
+
1. Read source (\`fcc note read <id>\`) unless pasted. Read target. If the user pointed at specific lines or gave angle words, those are the targets; skip the selection step and go to construction.
|
|
3721
|
+
2. Read existing cards in the target. They tell you two things: **what is already covered** (retrieval targets, not wording) and **the reader's level and style** (chunk size, card types, how much context they include). New cards match that level. If there are no existing cards, assume an experienced reader: larger chunks, fewer cards.
|
|
3722
|
+
3. State in the trace, before any edit: source ids read, target id read, where the last existing card ends, list of covered targets. A run that cannot show this failed.
|
|
3723
|
+
4. **Select targets.** Write each candidate as one line: \`target — angle\` (angle ∈ fact / why / contrast / example / implication / purpose / procedure step / heads-up). Then filter with the Targeting rules. First pass on a normal source: 5–10 survivors. Short source: 2–4. Do not pad to a count.
|
|
3724
|
+
5. **Construct** one prompt per surviving target using the pattern for its material type. Default to recall (\`sa\`, cloze): the reviewer must produce the answer. Use \`sc\`/\`mc\` only when close distractors teach a boundary the bare answer would not; a pass that is mostly \`sc\` trains recognition, not memory.
|
|
3725
|
+
6. **Check** each card against the Construction checks. Fix by changing type or splitting, never by adding words. If still unstable, drop it and list it.
|
|
3726
|
+
7. Append after the last existing card (or EOF) with a minimal \`fcc note patch <id>\` unified diff. Never insert between existing cards; never rewrite existing cards unless asked.
|
|
3727
|
+
8. Run summary (below).
|
|
3728
|
+
|
|
3729
|
+
## Targeting rules
|
|
3730
|
+
|
|
3731
|
+
- **The source's point, not its neighbourhood.** Ask: if the reader forgot everything but one sentence of this passage, which sentence would the author want it to be? That is the target. Names, dates, places, and numbers are targets only when the source's point *is* the name/date/number.
|
|
3732
|
+
- **Low-entropy details are not targets.** If almost any other text on this subject would contain the same detail, and the source never returns to it, skip it.
|
|
3733
|
+
- **General over provincial.** A blog post's "we cap services at 400 lines" is an instance; the target is the rule of thumb it instantiates. Keep the instance as the example inside the prompt if it is vivid.
|
|
3734
|
+
- **Definitions are not understanding.** For a concept, a term↔definition pair is at most one card and never the only one. Add the angles that trace the concept's edges (see Conceptual patterns).
|
|
3735
|
+
- **Multiple angles on what matters.** The important idea in a passage deserves 2–4 cards from different angles (fact, why, contrast, implication). A minor idea deserves zero.
|
|
3736
|
+
- **Explanations pair with facts.** When the source gives a reason, write the reason card too; it is the hook the fact hangs on.
|
|
3737
|
+
- **Level.** Match the existing cards. Do not write "what is a for loop" for a senior engineer. If no cards exist and the source is introductory, prefer the mechanism cards over the vocabulary cards.
|
|
3738
|
+
- **Gaps are targets too.** A question the source raises but does not answer: write it with no \`::answer\` and say so in the summary. Never fabricate an answer.
|
|
3739
|
+
- **More than feels natural, but omit beats weak.** Coarse cards do not reduce what must be learned; they only make each unit harder to retrieve. Split. But a card you cannot make stable is dropped, not appended.
|
|
3740
|
+
|
|
3741
|
+
Out of scope: salience prompts ("next time I see X, ask…"), creative prompts that want a new answer each time, broad self-graded reflection.
|
|
3742
|
+
|
|
3743
|
+
## Prompt patterns by material type
|
|
3744
|
+
|
|
3745
|
+
### Simple facts
|
|
3746
|
+
|
|
3747
|
+
One detail per card; pair with a why-card when the source gives a reason.
|
|
3748
|
+
|
|
3749
|
+
- bad: \`What do you need to set up a Redis cache?\` (five things at once)
|
|
3750
|
+
- good: \`What data structure does Redis use to implement a sorted set?\` → \`skip list\`
|
|
3751
|
+
- pair: \`What performance property makes skip lists a suitable alternative to balanced BSTs in Redis sorted sets?\` → \`equivalent average-case O(log n)\`
|
|
3752
|
+
|
|
3753
|
+
Tighten any why-question with several plausible answers: \`Why does Redis use a skip list?\` admits "historical reasons"; the version above does not.
|
|
3754
|
+
|
|
3755
|
+
### Closed lists (fixed members)
|
|
3756
|
+
|
|
3757
|
+
One cloze per element, same order each time, so the list's shape is learned. Pair each element with a why/role card so the list can be regenerated from meaning.
|
|
3758
|
+
|
|
3759
|
+
\`\`\`md
|
|
3760
|
+
SOLID principles: Single Responsibility / Open-Closed / ::cloze[Liskov Substitution] / Interface Segregation / Dependency Inversion
|
|
3761
|
+
\`\`\`
|
|
3762
|
+
|
|
3763
|
+
Never one list-level card (\`Name the five SOLID principles\`).
|
|
3764
|
+
|
|
3765
|
+
### Procedures
|
|
3766
|
+
|
|
3767
|
+
Not "list the steps". Strip to the verbs, conditions, and decision points that carry information; the scaffolding is obvious from context. Cards about: branch conditions, why a step exists, heads-up timing or predictable surprises, what to check before moving on.
|
|
3768
|
+
|
|
3769
|
+
- good: \`In a Kubernetes rolling deployment, what triggers an automatic rollback?\` → \`new pods fail readiness probe within the deadline\`
|
|
3770
|
+
|
|
3771
|
+
### Concepts
|
|
3772
|
+
|
|
3773
|
+
Definition alone is parroting. Trace the edges with whichever lenses fit; these are the patterns models forget without being told:
|
|
3774
|
+
|
|
3775
|
+
| Lens | Prompt shape |
|
|
3776
|
+
| -------------------------- | ---------------------------------------------------------- |
|
|
3777
|
+
| attributes / tendencies | what is always / sometimes / never true of it |
|
|
3778
|
+
| similarities / differences | how it differs from the adjacent concept |
|
|
3779
|
+
| example → classification | \`Is <concrete case> an instance of X? Why?\` (\`sc\`/\`la\`) |
|
|
3780
|
+
| classification → example | \`Give an example of X\` / \`Give a non-example\` (\`la\`) |
|
|
3781
|
+
| parts / wholes | sub-concepts, broader category, named instances |
|
|
3782
|
+
| causes / effects | what it does, when, and why it is used |
|
|
3783
|
+
| purpose | what does X let you see / do quickly |
|
|
3784
|
+
| connection | how X relates to the idea introduced just before / after |
|
|
3785
|
+
| light application | apply the rule to a small new case (\`la\` with criteria) |
|
|
3786
|
+
|
|
3787
|
+
Avoid yes/no; convert to a cause, example, or implication.
|
|
3788
|
+
|
|
3789
|
+
### Open lists (no fixed membership)
|
|
3790
|
+
|
|
3791
|
+
Treat as tags. Cards: instance → tag (\`When a payment service must notify shipping after checkout without waiting, what integration pattern fits?\` → \`message queue\`) and tag → examples (\`Name two situations where a queue beats a direct call\`). Cloze on an open list does not work.
|
|
3792
|
+
|
|
3793
|
+
### Later passes
|
|
3794
|
+
|
|
3795
|
+
- second: procedural details, secondary facts, edge cases
|
|
3796
|
+
- third: conceptual lenses not yet used
|
|
3797
|
+
- later: cross-concept links, applications, unresolved gaps
|
|
3798
|
+
|
|
3799
|
+
Duplicate = same retrieval target, regardless of wording. Prefer contrasts and implications over re-explaining the first-pass mechanism in more words.
|
|
3800
|
+
|
|
3801
|
+
## Construction checks
|
|
3802
|
+
|
|
3803
|
+
Judge the question harder than the answer; the question is what the reviewer sees alone.
|
|
3804
|
+
|
|
3805
|
+
- **Focused** — one detail. \`What's important about database indexes?\` → \`What's the write-side cost of adding an index?\`
|
|
3806
|
+
- **Precise** — the question fixes the *shape* of the answer (a number, a mechanism, a name). \`What are some reasons to prefer an interface?\` drifts; \`What's the main structural constraint that makes interfaces preferable to abstract classes in Java?\` does not.
|
|
3807
|
+
- **Consistent** — same answer every review. If several source-grounded answers fit the stem, add the discriminating context or split.
|
|
3808
|
+
- **Tractable** — usually answerable. Add a cue that narrows without giving away: \`(example: driver in orm lib)\` good; \`(Dependency related)\` bad.
|
|
3809
|
+
- **Effortful** — retrieved, not inferred from the wording. Long questions with copied source phrasing get pattern-matched; keep stems short and in your own words.
|
|
3810
|
+
- **Stands alone** — works with the source closed. No \`in the article\`, \`according to the source\`, \`in this example\`, \`the author\`; name the domain, mechanism, or example instead.
|
|
3811
|
+
- **Answer fits the type** — \`sa\` answers are 1–3 typeable words; anything sentence-like moves to \`sc\`, cloze, or \`la\`.
|
|
3812
|
+
|
|
3813
|
+
## Card syntax
|
|
3814
|
+
|
|
3815
|
+
Outer fence \`:::sa|sc|mc|la\`; every card has \`:::question[...]\` (plain question text is dropped on import). \`::answer[...]\`, \`::opt[...]\`, \`::explanation[...]\` are one-line leaf directives. Mark correct options \`{.correct}\`; \`sc\` = exactly one, \`mc\` = one or more. No \`qid\`, \`fractionalIndex\`, \`{#id}\`, \`importance\`, \`difficulty\`. Omit \`::explanation\` when it adds nothing; omit \`::answer\` for a deliberate gap.
|
|
3816
|
+
|
|
3817
|
+
### \`sa\` — short answer
|
|
3818
|
+
|
|
3819
|
+
Grader = exact bag-of-words set match: lowercase, strip punctuation, split on spaces, word set must equal a saved answer. No stemming, no synonyms, no meaning.
|
|
3820
|
+
|
|
3821
|
+
So: answer = bare content words (\`electron flow\`, not \`flow of electrons\`); one \`::answer[...]\` per real variant (plural, synonym, abbreviation); \`answerRegexp\` when a pattern is cleaner (case-insensitive, unanchored → write \`^...$\`; overrides set match); \`{class="strict"}\` only for genuinely case/punctuation-sensitive targets. No code literals, backticks, or API names in \`sa\` answers → use \`sc\`/cloze.
|
|
3822
|
+
|
|
3823
|
+
\`\`\`md
|
|
3824
|
+
:::sa{answerRegexp="^(the )?(retrieval practices?|active recall)$"}
|
|
3825
|
+
:::question[What memory mechanism does spaced repetition exploit to slow forgetting?]
|
|
3826
|
+
|
|
3827
|
+
::answer[retrieval practice]
|
|
3828
|
+
|
|
3829
|
+
::explanation[Recalling reinforces far more than re-reading.]
|
|
3830
|
+
:::
|
|
3831
|
+
\`\`\`
|
|
3832
|
+
|
|
3833
|
+
### \`sc\` / \`mc\`
|
|
3834
|
+
|
|
3835
|
+
\`\`\`md
|
|
3836
|
+
:::sc
|
|
3837
|
+
:::question[What is the main structural reason to prefer an interface over an abstract class in Java?]
|
|
3838
|
+
|
|
3839
|
+
::opt[Interfaces are faster at runtime]
|
|
3840
|
+
::opt[A class can implement many interfaces but extend only one class]{.correct}
|
|
3841
|
+
::opt[Interfaces avoid constructors]
|
|
3842
|
+
:::
|
|
3843
|
+
\`\`\`
|
|
3844
|
+
|
|
3845
|
+
Distractors must be close to true; obvious distractors make the card a giveaway.
|
|
3846
|
+
|
|
3847
|
+
### Cloze
|
|
3848
|
+
|
|
3849
|
+
\`\`\`md
|
|
3850
|
+
On Titan, its gravity is so low that humans could fly simply by ::cloze[flapping their arms] in winged space suits.
|
|
3851
|
+
\`\`\`
|
|
3852
|
+
|
|
3853
|
+
Use for closed lists, ordered structures, and when the source wording itself is the durable cue. Cloze produces shallower memory than Q/A (extraneous words act as hints), so: delete the blank and read the sentence — if the rest implies the answer, or the blank is an abstract label rather than a concrete unit, use \`sa\`/\`sc\` or skip.
|
|
3854
|
+
|
|
3855
|
+
Mark a blank \`{.exact}\` when only one form is right and a near form is wrong (word order or an ending in a model sentence, \`::l[She ::cloze[is not tired]{.exact}.]{lang="en"}\`; a spelling): it is graded by form (exact match or \`answerRegexp\`, never by meaning) and starts at \`...\` with no first letter. A rule's \`.practice\` blanks already are. Leave meaning-level blanks unmarked so paraphrases pass. Form grading folds only case, punctuation and spaces, so a form-graded answer with ä, ö, ü or ß gets an \`answerRegexp\` that also accepts ae, oe, ue, ss (\`answerRegexp="^bin nicht m(ü|ue)de$"\`): that spelling is correct German, and "muede" was measured wrong without it.
|
|
3856
|
+
|
|
3857
|
+
### \`la\` — long answer
|
|
3858
|
+
|
|
3859
|
+
Only for application / comparison targets that no other type can hold, and only with observable criteria (\`identifies simultaneous cache misses\`, not \`shows understanding\`). Mark application prompts \`type="application"\`.
|
|
3860
|
+
|
|
3861
|
+
\`\`\`md
|
|
3862
|
+
:::la{type="application" criteria="['names the violated principle','ties it to the two independent change axes','does not merely restate the definition']"}
|
|
3863
|
+
:::question[A class parses config files and also sends alert emails. Which design principle is violated and why?]
|
|
3864
|
+
:::
|
|
3865
|
+
\`\`\`
|
|
3866
|
+
|
|
3867
|
+
Application prompts: small step beyond memorized knowledge, novel inputs, one correct mechanism, no strategy search. If they need many hidden prerequisites, write recall cards for those first.
|
|
3868
|
+
|
|
3869
|
+
## Patching
|
|
3870
|
+
|
|
3871
|
+
\`fcc note patch <id>\` takes a standard unified diff. Hunks anchor on context lines; copy them verbatim from \`fcc note read\`. Do not hand-count offsets. Never send \`*** Begin Patch\` format. Do not edit projected Markdown files directly; do not run sync or import.
|
|
3872
|
+
|
|
3873
|
+
## Run summary
|
|
3874
|
+
|
|
3875
|
+
1. Each new card as \`target — angle — type\` so the user can prune in one glance.
|
|
3876
|
+
2. Targets selected but dropped, with the reason (unstable / low-entropy / needs the source open / duplicate).
|
|
3877
|
+
3. What was left for later passes.
|
|
3878
|
+
4. Gaps written without answers.
|
|
3879
|
+
5. Weak existing cards, if any, with a proposed rewrite (not applied).
|
|
3880
|
+
|
|
3881
|
+
NEVER COMMIT OR SYNC UNLESS EXPLICITLY ASKED IN PREVIOUS MESSAGE!
|
|
3882
|
+
` } });
|