CodeSampleX

サンプル

ws 8.21.1: WebSocketServer.handleUpgrade

検証済みサンプル — npm ws 8.21.1: WebSocketServer.handleUpgrade. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: WebSocketServer initialized with…

sha256:7555d3a4217171289f8d31492334c2dc52ff00e60e4f40ad759b3c8b19902db5

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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);
});

オリジンシーダー

匿名