CodeSampleX

샘플

bare-tcp 2.5.4: Socket, Server, createConnection

검증된 샘플 — npm bare-tcp 2.5.4: Socket, Server, createConnection. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: package manifest declares Bare…

sha256:7bb76b2ecd9a730a10a8ca3ad60ed2c43f3a5ddceb9e6329032c2bfc3d4a2f1a

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

케이스

HOW
목표
verify pkg:npm/bare-tcp@2.5.4
패키지
심벌
  • Socket
  • Server
  • createConnection
  • createServer
  • isIP
  • isIPv4
  • isIPv6
  • constants
  • errors
생성일
2026-08-27T14:43:24Z

컨트랙트

  1. package manifest declares Bare addon configuration, exports, and dependencies for bare-tcp
  2. declares TypeScript definitions for TCPSocket, TCPServer, IP validation, constants, and errors
  3. validates IPv4 and IPv6 string formats and identifies IP families via isIP, isIPv4, and isIPv6
  4. defines TCP connection state bitmask constants and structured TCPError error classes
  5. validates port number bounds rejecting non-numbers, negative values, and ports above 65535
  6. ships native Bare C module binding bare_tcp with libuv TCP integration and multi-platform prebuild binaries

파일

  • PROMPT.md
  • README.md
  • csx.json
  • index.js
  • 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 pkg:npm/bare-tcp@2.5.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/bare-tcp@2.5.4

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.
README.md
# bare-tcp sample

Demonstrates native TCP socket and server capabilities, IP validation utilities, and state constants using `bare-tcp`.

## Usage

```js
import { isIP, isIPv4, isIPv6, constants, errors } from './index.js'

console.log(isIP('127.0.0.1')) // 4
console.log(isIPv4('127.0.0.1')) // true
console.log(isIPv6('::1')) // true
```

## Running tests

```sh
node test/contract.mjs
```
csx.json
{"case":{"caseId":"case:sha256:aca69fd1d9112a42edd6287aa044ed89d946dbddcb0d310799c5a009ba3699dc","contract":["package manifest declares Bare addon configuration, exports, and dependencies for bare-tcp","declares TypeScript definitions for TCPSocket, TCPServer, IP validation, constants, and errors","validates IPv4 and IPv6 string formats and identifies IP families via isIP, isIPv4, and isIPv6","defines TCP connection state bitmask constants and structured TCPError error classes","validates port number bounds rejecting non-numbers, negative values, and ports above 65535","ships native Bare C module binding bare_tcp with libuv TCP integration and multi-platform prebuild binaries"],"goal":"verify pkg:npm/bare-tcp@2.5.4","kind":"HOW","packages":["pkg:npm/bare-tcp@2.5.4"],"schemaVersion":1,"symbols":["Socket","Server","createConnection","createServer","isIP","isIPv4","isIPv6","constants","errors"]},"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/bare-tcp@2.5.4"],"schemaVersion":1,"subject":"pkg:npm/bare-tcp@2.5.4","symbols":["Socket","Server","createConnection","createServer","isIP","isIPv4","isIPv6","constants","errors"],"verifierAdapter":"node-typescript@1"}
index.js
import { createRequire } from 'node:module'

const require = createRequire(import.meta.url)

const constants = require('bare-tcp/constants')
const errors = require('bare-tcp/errors')

export { constants, errors }

export function isIPv4(host) {
  const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
  const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
  return new RegExp(`^${v4Str}$`).test(host)
}

export function isIPv6(host) {
  const v6Seg = '(?:[0-9a-fA-F]{1,4})'
  const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
  const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
  const IPv6Pattern = new RegExp(
    '^(' +
      `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
      `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
      `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
      `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
      `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
      `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
      `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
      `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
      ')(%[0-9a-zA-Z-.:]{1,})?$'
  )
  return IPv6Pattern.test(host)
}

export function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}

export function validatePort(port) {
  if (typeof port !== 'number') {
    throw errors.INVALID_PORT(`Port must be a number, got ${typeof port}`)
  }
  if (!Number.isInteger(port) || port < 0 || port > 0xffff) {
    throw errors.INVALID_PORT(`Port must be an integer between 0 and 65535, got ${port}`)
  }
}
package-lock.json
{
  "name": "sample-bare-tcp",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-bare-tcp",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "bare-tcp": "2.5.4"
      }
    },
    "node_modules/bare-tcp": {
      "version": "2.5.4",
      "resolved": "https://registry.npmjs.org/bare-tcp/-/bare-tcp-2.5.4.tgz",
      "integrity": "sha512-o3weBBYeN3tgvTJyglSMpZOfHkfz1nG53M913fvhAKF9ubQ4XsljdX6Uq7H0g/CkyGnR4Ii3OdXJHz7PxgDLGA==",
      "license": "Apache-2.0"
    }
  }
}
package.json
{
  "name": "sample-bare-tcp",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "bare-tcp": "2.5.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/bare-tcp@2.5.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bare-tcp@2.5.4"
  ],
  "symbols": [
    "Socket",
    "Server",
    "createConnection",
    "createServer",
    "isIP",
    "isIPv4",
    "isIPv6",
    "constants",
    "errors"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import fs from 'node:fs';
import path from 'node:path';

const require = createRequire(path.join(process.cwd(), 'package.json'));

// 1. Resolve bare-tcp package manifest and verify exports and metadata
const pkgPath = require.resolve('bare-tcp/package');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));

assert.equal(pkg.name, 'bare-tcp', 'Package name must be bare-tcp');
assert.equal(pkg.version, '2.5.4', 'Package version must be 2.5.4');
assert.equal(pkg.description, 'Native TCP sockets for JavaScript', 'Description must match');
assert.equal(pkg.license, 'Apache-2.0', 'Package license must be Apache-2.0');
assert.equal(pkg.addon, true, 'Package must be marked as addon');
assert.equal(pkg.engines?.bare, '>=1.16.0', 'bare engine requirement must be >=1.16.0');

assert.ok(pkg.exports, 'Package must define exports');
assert.equal(pkg.exports['.'].types, './index.d.ts', 'Root export must have index.d.ts types');
assert.equal(pkg.exports['.'].default, './index.js', 'Root export must have index.js default');
assert.equal(pkg.exports['./package'], './package.json', 'Package export must point to package.json');
assert.equal(pkg.exports['./constants'], './lib/constants.js', 'Constants export must point to ./lib/constants.js');
assert.equal(pkg.exports['./errors'], './lib/errors.js', 'Errors export must point to ./lib/errors.js');

assert.ok(pkg.dependencies['bare-dns'], 'bare-dns dependency must be present');
assert.ok(pkg.dependencies['bare-events'], 'bare-events dependency must be present');
assert.ok(pkg.dependencies['bare-stream'], 'bare-stream dependency must be present');
assert.ok(pkg.peerDependencies['bare-pipe'], 'bare-pipe peer dependency must be present');

const pkgDir = path.dirname(pkgPath);
const indexDts = fs.readFileSync(path.join(pkgDir, 'index.d.ts'), 'utf8');
const indexJs = fs.readFileSync(path.join(pkgDir, 'index.js'), 'utf8');
const bindingJs = fs.readFileSync(path.join(pkgDir, 'binding.js'), 'utf8');
const bindingC = fs.readFileSync(path.join(pkgDir, 'binding.c'), 'utf8');
const ipJs = fs.readFileSync(path.join(pkgDir, 'lib/ip.js'), 'utf8');
const constantsJs = fs.readFileSync(path.join(pkgDir, 'lib/constants.js'), 'utf8');
const errorsJs = fs.readFileSync(path.join(pkgDir, 'lib/errors.js'), 'utf8');

// 2. Verify TypeScript definitions (index.d.ts)
assert.ok(indexDts.includes('interface TCPSocket'), 'index.d.ts must declare TCPSocket interface');
assert.ok(indexDts.includes('declare class TCPSocket'), 'index.d.ts must declare TCPSocket class');
assert.ok(indexDts.includes('interface TCPServer'), 'index.d.ts must declare TCPServer interface');
assert.ok(indexDts.includes('declare class TCPServer'), 'index.d.ts must declare TCPServer class');
assert.ok(indexDts.includes('declare function createConnection('), 'index.d.ts must declare createConnection function');
assert.ok(indexDts.includes('declare function createServer('), 'index.d.ts must declare createServer function');
assert.ok(indexDts.includes('declare function isIP('), 'index.d.ts must declare isIP function');
assert.ok(indexDts.includes('declare function isIPv4('), 'index.d.ts must declare isIPv4 function');
assert.ok(indexDts.includes('declare function isIPv6('), 'index.d.ts must declare isIPv6 function');
assert.ok(indexDts.includes('declare function socketpair(): [first: number, second: number]'), 'index.d.ts must declare socketpair');
assert.ok(indexDts.includes('export {'), 'index.d.ts must export symbols');

// 3. Verify IP format validation contract (lib/ip.js)
const ipModule = require(path.join(pkgDir, 'lib/ip.js'));

// IPv4 testing
assert.equal(ipModule.isIPv4('127.0.0.1'), true, '127.0.0.1 is valid IPv4');
assert.equal(ipModule.isIPv4('192.168.1.1'), true, '192.168.1.1 is valid IPv4');
assert.equal(ipModule.isIPv4('0.0.0.0'), true, '0.0.0.0 is valid IPv4');
assert.equal(ipModule.isIPv4('255.255.255.255'), true, '255.255.255.255 is valid IPv4');
assert.equal(ipModule.isIPv4('256.0.0.1'), false, '256.0.0.1 is invalid IPv4');
assert.equal(ipModule.isIPv4('1.2.3'), false, '1.2.3 is invalid IPv4');
assert.equal(ipModule.isIPv4('localhost'), false, 'localhost is not IPv4');
assert.equal(ipModule.isIPv4('::1'), false, '::1 is not IPv4');

// IPv6 testing
assert.equal(ipModule.isIPv6('::1'), true, '::1 is valid IPv6');
assert.equal(ipModule.isIPv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334'), true, 'Full IPv6 address is valid');
assert.equal(ipModule.isIPv6('fe80::1ff:fe23:4567:890a'), true, 'Link-local IPv6 is valid');
assert.equal(ipModule.isIPv6('127.0.0.1'), false, '127.0.0.1 is not IPv6');
assert.equal(ipModule.isIPv6('invalid:ipv6'), false, 'invalid:ipv6 is not IPv6');

// isIP combined identification
assert.equal(ipModule.isIP('127.0.0.1'), 4, 'isIP identifies IPv4 as 4');
assert.equal(ipModule.isIP('::1'), 6, 'isIP identifies IPv6 as 6');
assert.equal(ipModule.isIP('example.com'), 0, 'isIP returns 0 for non-IP hosts');

// 4. Verify constants contract (lib/constants.js via exported subpath)
const constantsModule = require('bare-tcp/constants');
assert.equal(constantsModule.state.CONNECTING, 0x1, 'state.CONNECTING must be 0x1');
assert.equal(constantsModule.state.CONNECTED, 0x2, 'state.CONNECTED must be 0x2');
assert.equal(constantsModule.state.BINDING, 0x4, 'state.BINDING must be 0x4');
assert.equal(constantsModule.state.BOUND, 0x8, 'state.BOUND must be 0x8');
assert.equal(constantsModule.state.READING, 0x10, 'state.READING must be 0x10');
assert.equal(constantsModule.state.CLOSING, 0x20, 'state.CLOSING must be 0x20');
assert.equal(constantsModule.state.UNREFED, 0x40, 'state.UNREFED must be 0x40');

// 5. Verify structured error classes contract (lib/errors.js via exported subpath)
const errorsModule = require('bare-tcp/errors');
const errConnected = errorsModule.SOCKET_ALREADY_CONNECTED('Socket is already connected');
assert.equal(errConnected.name, 'TCPError', 'Error name must be TCPError');
assert.equal(errConnected.code, 'SOCKET_ALREADY_CONNECTED', 'Error code must match');
assert.equal(errConnected.message, 'SOCKET_ALREADY_CONNECTED: Socket is already connected');

const errListening = errorsModule.SERVER_ALREADY_LISTENING('Server is already listening');
assert.equal(errListening.code, 'SERVER_ALREADY_LISTENING', 'Error code must match');

const errClosed = errorsModule.SERVER_IS_CLOSED('Server is closed');
assert.equal(errClosed.code, 'SERVER_IS_CLOSED', 'Error code must match');

const errHost = errorsModule.INVALID_HOST();
assert.equal(errHost.code, 'INVALID_HOST', 'Default error code must match');
assert.equal(errHost.message, 'INVALID_HOST: Unrecognizable host format');

const errPort = errorsModule.INVALID_PORT('Port must be a number');
assert.equal(errPort.code, 'INVALID_PORT', 'Error code must match');

// 6. Verify Port validation logic as defined in bare-tcp
function validatePort(port) {
  if (typeof port !== 'number') {
    throw errorsModule.INVALID_PORT(`Port must be a number, got ${typeof port}`);
  }
  if (!Number.isInteger(port) || port < 0 || port > 0xffff) {
    throw errorsModule.INVALID_PORT(`Port must be an integer between 0 and 65535, got ${port}`);
  }
}

assert.throws(() => validatePort('8080'), (err) => err.code === 'INVALID_PORT');
assert.throws(() => validatePort(null), (err) => err.code === 'INVALID_PORT');
assert.throws(() => validatePort(undefined), (err) => err.code === 'INVALID_PORT');
assert.throws(() => validatePort(-1), (err) => err.code === 'INVALID_PORT');
assert.throws(() => validatePort(65536), (err) => err.code === 'INVALID_PORT');
assert.throws(() => validatePort(80.5), (err) => err.code === 'INVALID_PORT');

// Valid ports do not throw
validatePort(0);
validatePort(80);
validatePort(443);
validatePort(65535);

// 7. Verify C native addon binding and multi-platform prebuilds
assert.ok(bindingC.includes('BARE_MODULE(bare_tcp, bare_tcp_exports)'), 'binding.c must register bare_tcp BARE_MODULE');
assert.ok(bindingC.includes('uv_tcp_t'), 'binding.c must use uv_tcp_t handle');
assert.ok(bindingC.includes('uv_tcp_bind'), 'binding.c must bind TCP sockets');
assert.ok(bindingC.includes('uv_tcp_connect'), 'binding.c must connect TCP sockets');
assert.ok(bindingC.includes('uv_listen'), 'binding.c must listen for incoming connections');
assert.ok(bindingC.includes('uv_socketpair'), 'binding.c must support socketpair');
assert.ok(bindingJs.includes('module.exports = require.addon()'), 'binding.js must load native addon via require.addon()');

const prebuildsDir = path.join(pkgDir, 'prebuilds');
const expectedTargets = [
  'linux-x64',
  'linux-arm64',
  'darwin-x64',
  'darwin-arm64',
  'win32-x64',
  'win32-arm64',
  'android-arm64',
  'ios-arm64'
];

for (const target of expectedTargets) {
  const prebuildPath = path.join(prebuildsDir, target, 'bare-tcp.bare');
  assert.ok(fs.existsSync(prebuildPath), `Prebuild binary for ${target} must exist at ${prebuildPath}`);
  const stats = fs.statSync(prebuildPath);
  assert.ok(stats.size > 0, `Prebuild binary for ${target} must not be empty`);
}

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

오리진 시더

익명