CodeSampleX

Sample

ws 8.21.3: WebSocketServer

Verified sample for npm ws 8.21.3: WebSocketServer. The contract ran on node 22 · linux alpine/x64 · docker and passed: assert WebSocketServer initializes…

sha256:b63c15525b0b1789e9035f51fb518f460758705c779648dd279ac6ee99f5a1fc

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 npm

Verification-run environments

Environment Contract Stages Run
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-23
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-07

Case

HOW
Goal
verify ws.WebSocketServer in pkg:npm/ws@8.21.3
Packages
Symbols
  • ws.WebSocketServer
Created
2026-08-23T06:05:22Z

Contract

  1. assert WebSocketServer initializes with port and host
  2. assert WebSocketServer emits connection event with socket and incoming request
  3. assert WebSocketServer tracks active clients in clients Set and removes on disconnect
  4. assert WebSocketServer broadcasts messages to multiple connected clients
  5. assert WebSocketServer closes cleanly and emits close event

Files

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

Download the source artifact (tar.gz)

Source

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 ws.WebSocketServer in pkg:npm/ws@8.21.3
Kind: HOW

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

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:42637672fd8bc0e232a8257eac9423bc17372a231178775f2495719fa748d7b7","contract":["assert WebSocketServer initializes with port and host","assert WebSocketServer emits connection event with socket and incoming request","assert WebSocketServer tracks active clients in clients Set and removes on disconnect","assert WebSocketServer broadcasts messages to multiple connected clients","assert WebSocketServer closes cleanly and emits close event"],"goal":"verify ws.WebSocketServer in pkg:npm/ws@8.21.3","kind":"HOW","packages":["pkg:npm/ws@8.21.3"],"schemaVersion":1,"symbols":["ws.WebSocketServer"]},"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.3"],"schemaVersion":1,"subject":"pkg:npm/ws@8.21.3","symbols":["ws.WebSocketServer"],"verifierAdapter":"node-typescript@1"}
index.mjs
import WebSocket, { WebSocketServer } from 'ws';

/**
 * Creates and starts a WebSocketServer instance.
 * @param {import('ws').ServerOptions} [options]
 * @param {Function} [callback]
 * @returns {WebSocketServer}
 */
export function createWebSocketServer(options = {}, callback) {
  return new WebSocketServer(options, callback);
}

/**
 * Broadcasts a message to all connected clients on a WebSocketServer.
 * @param {WebSocketServer} server
 * @param {any} data
 * @param {object} [options]
 */
export function broadcast(server, data, options) {
  for (const client of server.clients) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data, options);
    }
  }
}

export { WebSocket, WebSocketServer };
package-lock.json
{
  "name": "sample-ws-websocketserver",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-ws-websocketserver",
      "version": "1.0.0",
      "dependencies": {
        "ws": "8.21.3"
      }
    },
    "node_modules/ws": {
      "version": "8.21.3",
      "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
      "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
      "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-websocketserver",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "ws": "8.21.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify ws.WebSocketServer in pkg:npm/ws@8.21.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/ws@8.21.3"
  ],
  "symbols": [
    "ws.WebSocketServer"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { createWebSocketServer, broadcast, WebSocket, WebSocketServer } from '../index.mjs';

// 1. assert WebSocketServer initializes with port and host
{
  const wss = createWebSocketServer({ host: '127.0.0.1', port: 0 });
  await new Promise((resolve) => wss.on('listening', resolve));
  const address = wss.address();
  assert.strictEqual(typeof address, 'object');
  assert.strictEqual(address.address, '127.0.0.1');
  assert.ok(address.port > 0);
  await new Promise((resolve) => wss.close(resolve));
}

// 2. assert WebSocketServer emits connection event with socket and incoming request
{
  const wss = createWebSocketServer({ host: '127.0.0.1', port: 0 });
  await new Promise((resolve) => wss.on('listening', resolve));
  const port = wss.address().port;

  let serverReqUrl = null;
  let serverWs = null;
  wss.on('connection', (ws, req) => {
    serverWs = ws;
    serverReqUrl = req.url;
  });

  const client = new WebSocket(`ws://127.0.0.1:${port}/test-path?param=val`);
  await new Promise((resolve, reject) => {
    client.on('open', resolve);
    client.on('error', reject);
  });

  assert.ok(serverWs !== null);
  assert.strictEqual(serverWs.readyState, WebSocket.OPEN);
  assert.strictEqual(serverReqUrl, '/test-path?param=val');

  client.close();
  await new Promise((r) => client.on('close', r));
  await new Promise((r) => wss.close(r));
}

// 3. assert WebSocketServer tracks active clients in clients Set and removes on disconnect
{
  const wss = createWebSocketServer({ host: '127.0.0.1', port: 0 });
  await new Promise((resolve) => wss.on('listening', resolve));
  const port = wss.address().port;

  assert.strictEqual(wss.clients.size, 0);

  const client1 = new WebSocket(`ws://127.0.0.1:${port}`);
  await new Promise((r) => client1.on('open', r));
  assert.strictEqual(wss.clients.size, 1);

  const client2 = new WebSocket(`ws://127.0.0.1:${port}`);
  await new Promise((r) => client2.on('open', r));
  assert.strictEqual(wss.clients.size, 2);

  client1.close();
  await new Promise((r) => client1.on('close', r));
  await new Promise((r) => setTimeout(r, 50));
  assert.strictEqual(wss.clients.size, 1);

  client2.close();
  await new Promise((r) => client2.on('close', r));
  await new Promise((r) => setTimeout(r, 50));
  assert.strictEqual(wss.clients.size, 0);

  await new Promise((r) => wss.close(r));
}

// 4. assert WebSocketServer broadcasts messages to multiple connected clients
{
  const wss = createWebSocketServer({ host: '127.0.0.1', port: 0 });
  await new Promise((resolve) => wss.on('listening', resolve));
  const port = wss.address().port;

  const client1 = new WebSocket(`ws://127.0.0.1:${port}`);
  const client2 = new WebSocket(`ws://127.0.0.1:${port}`);

  await Promise.all([
    new Promise((r) => client1.on('open', r)),
    new Promise((r) => client2.on('open', r))
  ]);

  const msgPromise1 = new Promise((resolve) => client1.on('message', (d) => resolve(d.toString('utf8'))));
  const msgPromise2 = new Promise((resolve) => client2.on('message', (d) => resolve(d.toString('utf8'))));

  broadcast(wss, 'broadcast payload');

  const [res1, res2] = await Promise.all([msgPromise1, msgPromise2]);
  assert.strictEqual(res1, 'broadcast payload');
  assert.strictEqual(res2, 'broadcast payload');

  client1.close();
  client2.close();
  await Promise.all([
    new Promise((r) => client1.on('close', r)),
    new Promise((r) => client2.on('close', r))
  ]);
  await new Promise((r) => wss.close(r));
}

// 5. assert WebSocketServer closes cleanly and emits close event
{
  const wss = createWebSocketServer({ host: '127.0.0.1', port: 0 });
  await new Promise((resolve) => wss.on('listening', resolve));

  let closeEventFired = false;
  wss.on('close', () => {
    closeEventFired = true;
  });

  await new Promise((resolve) => wss.close(resolve));
  assert.strictEqual(closeEventFired, true);
}

console.log('Contract tests passed successfully.');

Origin Seeder

anonymous