CodeSampleX

샘플

ws 8.21.1: WebSocketServer.handleUpgrade

검증된 샘플 — npm ws 8.21.1: WebSocketServer.handleUpgrade. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: WebSocketServer initialized with noServer…

sha256:7555d3a4217171289f8d31492334c2dc52ff00e60e4f40ad759b3c8b19902db5

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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);
});

오리진 시더

익명