-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsuperwstest.mjs
465 lines (409 loc) · 13.1 KB
/
superwstest.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import util from 'util';
import WebSocket from 'ws';
import https from 'https';
import { Server, Socket } from 'net';
import BlockingQueue from './BlockingQueue.mjs';
// supertest is an optional dependency
const stRequest = (() => {
try {
const m = require('supertest');
return m.default || m;
} catch (e) {
return fallbackSTRequest;
}
})();
// es6 with top-level await:
//const stRequest = await import('supertest').then((m) => m.default, () => fallbackSTRequest);
// fallback to an error when supertest methods are used
function fallbackSTRequest() {
return new Proxy(
{},
{
get(o, prop) {
if (Object.prototype.hasOwnProperty.call(o, prop)) {
return o[prop];
}
throw new Error(
`request().${prop} is unavailable (supertest dependency not found).\n` +
'Run `npm install --save-dev supertest` to access these methods from superwstest',
);
},
},
);
}
function normaliseBinary(v) {
return new Uint8Array(v);
}
function compareBinary(a, b) {
return Buffer.from(a.buffer, a.byteOffset, a.byteLength).equals(b);
}
function stringifyBinary(v) {
const hex = Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString('hex');
const spacedHex = hex.replace(/(..)(?!$)/g, '$1 ');
return `[${spacedHex}]`;
}
function msgText({ data, isBinary }) {
if (isBinary) {
throw new Error('Expected text message, got binary');
}
return String(data);
}
function msgJson(msg) {
return JSON.parse(msgText(msg));
}
function msgBinary({ data, isBinary }) {
if (!isBinary) {
throw new Error('Expected binary message, got text');
}
return normaliseBinary(data);
}
function sendWithError(ws, msg, options) {
// https://github.com/websockets/ws/pull/1532
return new Promise((resolve, reject) => {
ws.send(msg, options, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
}).catch(async (err) => {
if (err.message && err.message.includes('WebSocket is not open')) {
const { code, data } = await ws.closed;
throw new Error(`Cannot send message; connection closed with ${code} "${data}"`);
}
});
}
function stringify(v) {
if (typeof v === 'function') {
return v.expectedMessage || 'matching function';
}
if (v instanceof Uint8Array) {
return stringifyBinary(v);
}
return JSON.stringify(v);
}
const wsMethods = {
send: (ws, msg, options) => sendWithError(ws, msg, options),
sendText: (ws, msg) => sendWithError(ws, String(msg)),
sendJson: (ws, msg) => sendWithError(ws, JSON.stringify(msg)),
sendBinary: (ws, msg) =>
sendWithError(ws, normaliseBinary(msg), {
binary: true,
}),
wait: (ws, ms) => new Promise((resolve) => setTimeout(resolve, ms)),
exec: async (ws, fn) => fn(ws),
expectMessage: async (ws, conversion, check = undefined, options = undefined) => {
const opts = { ...ws.defaultExpectOptions, ...options };
const received = await Promise.race([
ws.messages.pop(opts.timeout).catch((e) => {
throw new Error(`Expected message ${stringify(check)}, but got ${e}`);
}),
ws.closed.then(({ code, data }) => {
throw new Error(
`Expected message ${stringify(check)}, but connection closed: ${code} "${data}"`,
);
}),
]).then(conversion);
if (check === undefined) {
return;
}
if (typeof check === 'function') {
const result = check(received);
if (result === false) {
throw new Error(`Expected message ${stringify(check)}, got ${stringify(received)}`);
}
} else if (!util.isDeepStrictEqual(received, check)) {
throw new Error(`Expected message ${stringify(check)}, got ${stringify(received)}`);
}
},
expectText: (ws, expected, options) => {
let check;
if (expected instanceof RegExp) {
check = (value) => expected.test(value);
check.expectedMessage = `matching ${expected}`;
} else {
check = expected;
}
return wsMethods.expectMessage(ws, msgText, check, options);
},
expectJson: (ws, check, options) => wsMethods.expectMessage(ws, msgJson, check, options),
expectBinary: (ws, expected, options) => {
let check;
if (typeof expected === 'function') {
check = expected;
} else if (expected) {
const norm = normaliseBinary(expected);
check = (value) => compareBinary(value, norm);
check.expectedMessage = stringify(norm);
}
return wsMethods.expectMessage(ws, msgBinary, check, options);
},
close: (ws, code, message) => ws.close(code, message),
expectClosed: async (ws, expectedCode = null, expectedMessage = null) => {
const { code, data } = await ws.closed;
if (expectedCode !== null && code !== expectedCode) {
throw new Error(`Expected close code ${expectedCode}, got ${code} "${data}"`);
}
if (expectedMessage !== null && String(data) !== expectedMessage) {
throw new Error(`Expected close message "${expectedMessage}", got ${code} "${data}"`);
}
},
expectUpgrade: async (ws, check) => {
const request = await ws.upgrade;
const result = check(request);
if (result === false) {
throw new Error(
`Expected Upgrade matching assertion, got: status ${
request.statusCode
} headers ${JSON.stringify(request.headers)}`,
);
}
},
};
function reportConnectionShouldFail(ws) {
ws.close();
throw new Error('Expected connection failure, but succeeded');
}
function checkConnectionError(error, expectedCode) {
if (!expectedCode) {
return;
}
let expected = expectedCode;
if (typeof expectedCode === 'number') {
expected = `Unexpected server response: ${expectedCode}`;
}
const actual = error.message;
if (actual !== expected) {
throw new Error(`Expected connection failure with message "${expected}", got "${actual}"`);
}
}
function isOpen(ws) {
return ws.readyState === WebSocket.CONNECTING || ws.readyState === WebSocket.OPEN;
}
function closeAndRethrow(ws) {
return (e) => {
if (isOpen(ws)) {
ws.close();
}
throw e;
};
}
function findExistingHeader(headers, header) {
const lc = header.toLowerCase();
return Object.keys(headers).find((h) => h.toLowerCase() === lc) || lc;
}
const PRECONNECT_FN_ERROR = () => {
throw new Error('WebSocket has already been established; cannot change configuration');
};
function wsRequest(config, url, protocols, options) {
if (typeof protocols === 'object' && protocols !== null && !Array.isArray(protocols)) {
/* eslint-disable no-param-reassign */ // function overload
options = protocols;
protocols = [];
/* eslint-enable no-param-reassign */
}
const opts = { ...options, headers: { ...(options || {}).headers } };
const initPromise = (resolve, reject) => {
const ws = new WebSocket(url, protocols, opts);
config.clientSockets.add(ws);
const originalClose = ws.close.bind(ws);
ws.close = (...args) => {
originalClose(...args);
config.clientSockets.delete(ws);
};
Object.assign(ws, config);
ws.messages = new BlockingQueue();
const errors = new BlockingQueue();
const closed = new BlockingQueue();
const upgrade = new BlockingQueue();
ws.closed = closed.pop();
ws.firstError = errors.pop().then((e) => {
throw e;
});
ws.upgrade = upgrade.pop();
ws.on('message', (data, isBinary) => {
if (isBinary !== undefined) {
// ws 8.x
ws.messages.push({ data, isBinary });
} else if (typeof data === 'string') {
// ws 7.x
ws.messages.push({
data: Buffer.from(data, 'utf8'),
isBinary: false,
});
} else {
ws.messages.push({ data, isBinary: true });
}
});
ws.on('error', reject);
ws.on('close', (code, data) => {
config.clientSockets.delete(ws);
closed.push({ code, data });
});
ws.on('open', () => {
ws.removeListener('error', reject);
ws.on('error', (err) => errors.push(err));
resolve(ws);
});
ws.on('upgrade', (request) => {
upgrade.push(request);
});
};
// Initial Promise.resolve() gives us a tick to populate connection info (i.e. set(...))
let chain = Promise.resolve().then(() => new Promise(initPromise));
const preconnectFns = {
set(header, value) {
if (typeof header === 'object') {
Object.entries(header).forEach(([h, v]) => preconnectFns.set(h, v));
} else {
opts.headers[findExistingHeader(opts.headers, header)] = value;
}
return chain;
},
unset(header) {
delete opts.headers[findExistingHeader(opts.headers, header)];
return chain;
},
};
Object.assign(chain, preconnectFns);
/* eslint-disable no-param-reassign */ // purpose of function
function removePreConnectionFunctions(promise) {
delete promise.expectConnectionError;
Object.keys(preconnectFns).forEach((k) => {
promise[k] = PRECONNECT_FN_ERROR;
});
}
/* eslint-enable no-param-reassign */
const methods = {};
function wrapPromise(promise) {
return Object.assign(promise, methods);
}
const thenDo =
(fn) =>
(...args) => {
chain = chain.then((ws) =>
Promise.race([fn(ws, ...args), ws.firstError])
.catch(closeAndRethrow(ws))
.then(() => ws),
);
removePreConnectionFunctions(chain);
return wrapPromise(chain);
};
Object.keys(wsMethods).forEach((method) => {
methods[method] = thenDo(wsMethods[method]);
});
chain.expectConnectionError = (expectedCode = null) => {
chain = chain.then(reportConnectionShouldFail, (error) =>
checkConnectionError(error, expectedCode),
);
removePreConnectionFunctions(chain);
return chain;
};
return wrapPromise(chain);
}
async function performShutdown(sockets, shutdownDelay) {
const awaiting = [...sockets];
if (shutdownDelay > 0 && awaiting.length > 0) {
const expire = Date.now() + shutdownDelay;
while (Date.now() < expire && awaiting.some((s) => sockets.has(s))) {
/* eslint-disable-next-line no-await-in-loop */ // polling
await new Promise((r) => setTimeout(r, 0));
}
}
[...sockets].forEach((s) => {
if (s instanceof Socket) {
s.end();
} else if (s.close) {
s.close(); // WebSocketServer
}
});
}
const serverTestConfigs = new WeakMap();
function registerShutdown(server, shutdownDelay) {
let testConfig = serverTestConfigs.get(server);
if (testConfig) {
testConfig.shutdownDelay = Math.max(testConfig.shutdownDelay, shutdownDelay);
return;
}
testConfig = { shutdownDelay };
serverTestConfigs.set(server, testConfig);
const serverSockets = new Set();
server.on('connection', (s) => {
serverSockets.add(s);
s.on('close', () => serverSockets.delete(s));
});
const originalClose = server.close.bind(server);
/* eslint-disable-next-line no-param-reassign */ // ensure clean shutdown
server.close = (callback) => {
if (server.address()) {
performShutdown(serverSockets, testConfig.shutdownDelay);
testConfig.shutdownDelay = 0;
originalClose(callback);
} else if (callback) {
callback();
}
};
}
const REGEXP_HTTP = /^http/;
function getProtocol(server) {
if (!(server instanceof Server)) {
// could be WebSocketServer
server = (server.options || {}).server || server;
}
return server instanceof https.Server ? 'https' : 'http';
}
function getHostname(address) {
if (typeof address === 'string') {
return address;
}
const { family } = address;
// check for Node 18.0-18.3 (numeric) and Node <18.0 / >=18.4 (string) APIs for address.family
if (family === 6 || family === 'IPv6') {
return `[${address.address}]`;
}
return address.address;
}
function getHttpBase(server) {
if (typeof server === 'string') {
return server;
}
const address = server.address();
if (!address) {
// see https://github.com/visionmedia/supertest/issues/566
throw new Error(
'Server must be listening:\n' +
"beforeEach((done) => server.listen(0, 'localhost', done));\n" +
'afterEach((done) => server.close(done));\n' +
'\n' +
"supertest's request(app) syntax is not supported (find out more: https://github.com/davidje13/superwstest#why-isnt-requestapp-supported)",
);
}
return `${getProtocol(server)}://${getHostname(address)}:${address.port}`;
}
function makeScopedRequest() {
const clientSockets = new Set();
const request = (server, { shutdownDelay = 0, defaultExpectOptions = {} } = {}) => {
const httpBase = getHttpBase(server);
if (typeof server !== 'string') {
registerShutdown(server, shutdownDelay);
}
const wsConfig = { defaultExpectOptions, clientSockets };
const obj = stRequest(httpBase);
obj.ws = (path, ...args) =>
wsRequest(wsConfig, httpBase.replace(REGEXP_HTTP, 'ws') + path, ...args);
return obj;
};
request.closeAll = () => {
const remaining = [...clientSockets].filter(isOpen);
clientSockets.clear();
remaining.forEach((ws) => ws.close());
return remaining.length;
};
request.scoped = () => makeScopedRequest();
return request;
}
const request = makeScopedRequest();
// temporary backwards-compatibility for CommonJS require('superwstest').default
request.default = request;
export default request;