CodeSampleX

示例

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 mutually exclusive…

sha256:1bbc5ebf0baf145241c54a6e82f53217d1dc077a446e9f041f9fb300dbcdd268

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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

契约

  1. 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.
  2. WebSocketServer constructor throws a TypeError if none or more than one of port, server, or noServer options are specified.
  3. WebSocketServer in noServer mode tracks connected sockets in wss.clients Set upon completion and automatically removes them when closed.
  4. 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

下载源代码构件 (tar.gz)

源代码

NOTES.md
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.
csx.json
{"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"}
package-lock.json
{
  "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
        }
      }
    }
  }
}
package.json
{
  "name": "npm-ws-api",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "ws": "8.18.0"
  }
}
test/contract.mjs
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();

原始种子者

csx-seed