Пример
ws 8.18.0: Prove that WebSocketServer in noServer mode requires an explicit callback to emit the connection event and enforces mutually exclusive server binding options
Проверенный пример — npm ws 8.18.0: Prove that WebSocketServer in noServer mode requires an explicit callback to emit the connection event and enforces…
sha256:1bbc5ebf0baf145241c54a6e82f53217d1dc077a446e9f041f9fb300dbcdd268
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 3
- Ключи подписи, собравшие его
- 3
Заявленная среда
node linux x64 node node npm
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-17 |
| node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-18 |
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-09-08 |
Кейс
HOW- Цель
- Prove that WebSocketServer in noServer mode requires an explicit callback to emit the connection event and enforces mutually exclusive server binding options
- Пакеты
- Символы
-
- WebSocketServer
- WebSocketServer.prototype.handleUpgrade
- WebSocketServer.prototype.shouldHandle
- Окружение
- node
- Создан
- 2026-08-17T14:58:06Z
Контракт
- WebSocketServer.prototype.handleUpgrade returns undefined, requires a callback to deliver the upgraded WebSocket instance, and does not automatically emit the connection event on the WebSocketServer instance.
- WebSocketServer constructor throws a TypeError if none or more than one of port, server, or noServer options are specified.
- WebSocketServer in noServer mode tracks connected sockets in wss.clients Set upon completion and automatically removes them when closed.
- WebSocketServer.prototype.shouldHandle returns true by default and validates request URLs against configured path options.
Файлы
- NOTES.md
- csx.json
- package-lock.json
- package.json
- test/contract.mjs
Исходный код
An initial query to `search_known_solution` for `ws` returned existing samples covering `WebSocket.Server` custom upgrade response headers via the `headers` event (`sha256:5f1c789102dfbea125a68fc2917dbc83d9878ae5092f3b71c085dd77db5e2e41`) and distinguishing `ws` EventEmitter / Buffer payloads from native WHATWG WebSocket (`sha256:1a1d36a350a9eb2dcd345ed3b5163cee5cc2ec75783de4b1c90f8d313b012ee7`).
This sample pins `ws` at version 8.18.0.
### Observed Behavior
1. **Option Exclusivity**:
The `WebSocketServer` constructor strictly enforces that exactly one of `port`, `server`, or `noServer` is specified. Specifying none (e.g. `new WebSocketServer({})`) or multiple options (e.g. `{ noServer: true, port: 8080 }`) immediately throws `TypeError: One and only one of the "port", "server", or "noServer" options must be specified`.
2. **Manual Upgrade Lifecycle (`handleUpgrade`)**:
When integrating `ws` into an existing HTTP server via `{ noServer: true }`, invoking `wss.handleUpgrade(request, socket, head, callback)` returns `undefined`. The 4th argument `callback` is required; omitting it causes an unhandled `TypeError: cb is not a function` upon handshake completion.
3. **Failure in Connection Event Emission**:
A common mistake is expecting `wss.handleUpgrade()` to automatically emit the `connection` event on the `WebSocketServer` instance. In reality, `handleUpgrade` completes the WebSocket handshake and delivers the initialized `WebSocket` instance solely to the provided callback `(ws, request)`. If the callback does not explicitly call `wss.emit('connection', ws, request)`, registered server-level connection handlers will never be invoked, failing silently without throwing an error.
4. **Client Tracking**:
Even in `noServer` mode with default `clientTracking: true`, `wss.clients` is an instance of `Set` that contains the upgraded socket once handshake completes and removes it automatically when the socket closes.
{"case":{"believed":"Calling handleUpgrade on a WebSocketServer created with noServer: true automatically emits the connection event on the server instance.","caseId":"case:sha256:96f18a75456ccb67fc0a883e59f222589174abae7c5665dadfa1340e1658089c","contract":["WebSocketServer.prototype.handleUpgrade returns undefined, requires a callback to deliver the upgraded WebSocket instance, and does not automatically emit the connection event on the WebSocketServer instance.","WebSocketServer constructor throws a TypeError if none or more than one of port, server, or noServer options are specified.","WebSocketServer in noServer mode tracks connected sockets in wss.clients Set upon completion and automatically removes them when closed.","WebSocketServer.prototype.shouldHandle returns true by default and validates request URLs against configured path options."],"goal":"Prove that WebSocketServer in noServer mode requires an explicit callback to emit the connection event and enforces mutually exclusive server binding options","kind":"HOW","packages":["pkg:npm/ws@8.18.0"],"schemaVersion":1,"symbols":["WebSocketServer","WebSocketServer.prototype.handleUpgrade","WebSocketServer.prototype.shouldHandle"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/ws@8.18.0"],"schemaVersion":1,"symbols":["WebSocketServer","WebSocketServer.prototype.handleUpgrade","WebSocketServer.prototype.shouldHandle"],"verifierAdapter":"node-typescript@1"}
{
"name": "npm-ws-api",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "npm-ws-api",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"ws": "8.18.0"
}
},
"node_modules/ws": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz",
"integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
{
"name": "npm-ws-api",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"ws": "8.18.0"
}
}
import assert from 'node:assert/strict';
import http from 'node:http';
import { WebSocketServer, WebSocket } from 'ws';
// 1. WebSocketServer constructor enforces mutual exclusivity between port, server, and noServer
assert.throws(
() => new WebSocketServer({}),
{
name: 'TypeError',
message: 'One and only one of the "port", "server", or "noServer" options must be specified'
}
);
assert.throws(
() => new WebSocketServer({ noServer: true, port: 8080 }),
{
name: 'TypeError',
message: 'One and only one of the "port", "server", or "noServer" options must be specified'
}
);
assert.throws(
() => new WebSocketServer({ noServer: true, server: {} }),
{
name: 'TypeError',
message: 'One and only one of the "port", "server", or "noServer" options must be specified'
}
);
// 2. WebSocketServer.prototype.shouldHandle path validation
const wssFiltered = new WebSocketServer({ noServer: true, path: '/ws/chat' });
assert.strictEqual(wssFiltered.shouldHandle({ url: '/ws/chat' }), true);
assert.strictEqual(wssFiltered.shouldHandle({ url: '/ws/chat?room=general' }), true);
assert.strictEqual(wssFiltered.shouldHandle({ url: '/ws/other' }), false);
const wss = new WebSocketServer({ noServer: true });
assert.strictEqual(wss.shouldHandle({ url: '/any/arbitrary/path' }), true);
assert.strictEqual(wss.clients instanceof Set, true);
assert.strictEqual(wss.clients.size, 0);
// 3. handleUpgrade integration on HTTP server
let connectionFired = false;
let serverReceivedWs = null;
wss.on('connection', (socket, request) => {
connectionFired = true;
serverReceivedWs = socket;
socket.send('ready');
});
const server = http.createServer();
server.on('upgrade', (request, socket, head) => {
const returnValue = wss.handleUpgrade(request, socket, head, (upgradedWs, req) => {
// ws has completed handshake and is open, but connection event is NOT emitted automatically
assert.strictEqual(connectionFired, false, 'handleUpgrade must not emit connection event automatically');
assert.strictEqual(upgradedWs.readyState, WebSocket.OPEN);
assert.strictEqual(wss.clients.has(upgradedWs), true);
assert.strictEqual(wss.clients.size, 1);
// Explicit manual emission is required to trigger wss.on('connection') listeners
wss.emit('connection', upgradedWs, req);
assert.strictEqual(connectionFired, true);
});
// handleUpgrade returns undefined (not a Promise, not a WebSocket instance)
assert.strictEqual(returnValue, undefined);
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const port = server.address().port;
// 4. Verify client interaction and clientTracking cleanup
await new Promise((resolve, reject) => {
const client = new WebSocket(`ws://127.0.0.1:${port}/test`);
client.on('error', reject);
client.on('message', (data) => {
try {
assert.strictEqual(data.toString('utf8'), 'ready');
client.close();
} catch (err) {
reject(err);
}
});
client.on('close', () => {
setTimeout(() => {
try {
assert.strictEqual(wss.clients.size, 0);
assert.strictEqual(wss.clients.has(serverReceivedWs), false);
resolve();
} catch (err) {
reject(err);
}
}, 50);
});
});
await new Promise((resolve) => server.close(resolve));
wss.close();
wssFiltered.close();