CodeSampleX

示例

ws 8.21.1: WebSocketServer.handleUpgrade

已验证示例 — npm ws 8.21.1: WebSocketServer.handleUpgrade. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: WebSocketServer initialized with noServer: true…

sha256:7555d3a4217171289f8d31492334c2dc52ff00e60e4f40ad759b3c8b19902db5

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

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 npm

验证运行环境

环境 契约 阶段 运行日期
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-08-30

案例

HOW
目标
verify WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1
包
符号
  • WebSocketServer.handleUpgrade
创建时间
2026-08-30T22:30:46Z

契约

  1. WebSocketServer initialized with noServer: true throws when calling address()
  2. WebSocketServer.handleUpgrade completes HTTP upgrade handshake over duplex socket
  3. WebSocket client successfully sends and receives messages after handleUpgrade connection
  4. handleUpgrade callback receives the upgraded WebSocket instance and request object

文件

  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

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

源代码

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/ws@8.21.1
Demonstrate these symbols/APIs:
  - WebSocketServer.handleUpgrade

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:4904ae573f9c73db5e7ede6d0b704c1c0b3dcd1f23e52d55e4ccd3e1153f8dce","contract":["WebSocketServer initialized with noServer: true throws when calling address()","WebSocketServer.handleUpgrade completes HTTP upgrade handshake over duplex socket","WebSocket client successfully sends and receives messages after handleUpgrade connection","handleUpgrade callback receives the upgraded WebSocket instance and request object"],"goal":"verify WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1","kind":"HOW","packages":["pkg:npm/ws@8.21.1"],"schemaVersion":1,"symbols":["WebSocketServer.handleUpgrade"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/ws@8.21.1"],"schemaVersion":1,"subject":"pkg:npm/ws@8.21.1","symbols":["WebSocketServer.handleUpgrade"],"verifierAdapter":"node-typescript@1"}
index.mjs
import http from 'node:http';
import { WebSocketServer, WebSocket } from 'ws';

/**
 * Creates an HTTP server and pairs it with a WebSocketServer using handleUpgrade.
 * @param {Object} [options]
 * @param {string} [options.wsPath='/ws'] - Path for WebSocket upgrade requests
 * @returns {{ server: http.Server, wss: WebSocketServer, close: () => Promise<void> }}
 */
export function createUpgradableServer(options = {}) {
  const wsPath = options.wsPath || '/ws';
  const wss = new WebSocketServer({ noServer: true });

  const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('OK');
  });

  server.on('upgrade', (request, socket, head) => {
    const url = new URL(request.url, 'http://localhost');
    if (url.pathname === wsPath) {
      wss.handleUpgrade(request, socket, head, (ws) => {
        wss.emit('connection', ws, request);
      });
    } else {
      socket.destroy();
    }
  });

  const close = () => {
    return new Promise((resolve) => {
      wss.close(() => {
        server.close(() => {
          resolve();
        });
      });
    });
  };

  return { server, wss, close };
}

export { WebSocketServer, WebSocket };
package-lock.json
{
  "name": "sample-ws-handle-upgrade",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-ws-handle-upgrade",
      "version": "1.0.0",
      "dependencies": {
        "ws": "8.21.1"
      }
    },
    "node_modules/ws": {
      "version": "8.21.1",
      "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz",
      "integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",
      "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": "sample-ws-handle-upgrade",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "ws": "8.21.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/ws@8.21.1"
  ],
  "symbols": [
    "WebSocketServer.handleUpgrade"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { createUpgradableServer, WebSocketServer, WebSocket } from '../index.mjs';

async function runContractTests() {
  // Test 1: WebSocketServer initialized with noServer: true throws when address() is called
  const standaloneWss = new WebSocketServer({ noServer: true });
  assert.equal(standaloneWss.options.noServer, true, 'noServer option should be true');
  assert.throws(
    () => standaloneWss.address(),
    /The server is operating in "noServer" mode/,
    'address() should throw in noServer mode'
  );
  standaloneWss.close();

  // Test 2: Set up upgradable server and verify handleUpgrade completes upgrade handshake
  const { server, wss, close } = createUpgradableServer({ wsPath: '/custom-ws' });

  await new Promise((resolve, reject) => {
    server.listen(0, '127.0.0.1', () => resolve());
    server.on('error', reject);
  });

  const address = server.address();
  const port = address.port;

  let connectionHandled = false;
  let receivedServerRequest = null;
  let serverWsInstance = null;

  wss.on('connection', (ws, req) => {
    connectionHandled = true;
    serverWsInstance = ws;
    receivedServerRequest = req;

    ws.on('message', (data) => {
      const msg = data.toString();
      if (msg === 'ping') {
        ws.send('pong');
      }
    });
  });

  // Test 3: Client connects and sends/receives messages
  const clientWs = new WebSocket(`ws://127.0.0.1:${port}/custom-ws`);

  await new Promise((resolve, reject) => {
    clientWs.on('open', resolve);
    clientWs.on('error', reject);
  });

  assert.equal(connectionHandled, true, 'wss should have emitted connection event via handleUpgrade');
  assert.ok(serverWsInstance instanceof WebSocket, 'server WebSocket should be an instance of WebSocket');
  assert.ok(receivedServerRequest, 'server should receive the upgraded HTTP request object');
  assert.equal(receivedServerRequest.url, '/custom-ws', 'request URL should match upgrade path');

  const responsePromise = new Promise((resolve) => {
    clientWs.on('message', (data) => {
      resolve(data.toString());
    });
  });

  clientWs.send('ping');
  const response = await responsePromise;
  assert.equal(response, 'pong', 'Client should receive pong message from server');

  clientWs.close();
  await new Promise((resolve) => clientWs.on('close', resolve));

  // Test 4: Verify non-matching path is rejected / destroyed
  const invalidClient = new WebSocket(`ws://127.0.0.1:${port}/other-path`);
  const rejected = await new Promise((resolve) => {
    invalidClient.on('error', () => resolve(true));
    invalidClient.on('close', () => resolve(true));
    invalidClient.on('open', () => resolve(false));
  });
  assert.equal(rejected, true, 'Connection to non-matching route should be closed');

  await close();
  console.log('All contract assertions passed.');
}

runContractTests().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

原始种子者

匿名