CodeSampleX

샘플

agent-base 6.0.2

검증된 샘플 — npm agent-base 6.0.2. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: createAgent wraps a synchronous or Promise-returning socket…

sha256:7d9c98b1bce5270d1c28e2027527bba91cb005c10b587d35fb2daee5e7cc403f

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-21

케이스

HOW
목표
verify pkg:npm/agent-base@6.0.2
패키지
환경
node 22.23.2
생성일
2026-08-21T04:38:57Z

컨트랙트

  1. createAgent wraps a synchronous or Promise-returning socket callback into an http.Agent compatible instance
  2. Agent routes HTTP requests through custom sockets created by async callbacks
  3. Agent supports 3-argument legacy style callback (req, opts, cb) with error and socket resolution
  4. Agent delegates request handling when the callback returns another http.Agent instance
  5. Agent emits ETIMEOUT on the request when the callback does not produce a socket within the specified timeout
  6. Agent defaultPort and protocol getters dynamically reflect secureEndpoint state unless explicitly overridden

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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/agent-base@6.0.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/agent-base@6.0.2
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:b4dbc685ccfcab69af22e2e984049ada7c9bedbe5e277f46e370034d68ce13b9","constraints":{"executionContext":"node"},"contract":["createAgent wraps a synchronous or Promise-returning socket callback into an http.Agent compatible instance","Agent routes HTTP requests through custom sockets created by async callbacks","Agent supports 3-argument legacy style callback (req, opts, cb) with error and socket resolution","Agent delegates request handling when the callback returns another http.Agent instance","Agent emits ETIMEOUT on the request when the callback does not produce a socket within the specified timeout","Agent defaultPort and protocol getters dynamically reflect secureEndpoint state unless explicitly overridden"],"goal":"verify pkg:npm/agent-base@6.0.2","kind":"HOW","packages":["pkg:npm/agent-base@6.0.2"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/agent-base@6.0.2"],"schemaVersion":1,"subject":"pkg:npm/agent-base@6.0.2","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-agent-base",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-agent-base",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "agent-base": "6.0.2"
      }
    },
    "node_modules/agent-base": {
      "version": "6.0.2",
      "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
      "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
      "license": "MIT",
      "dependencies": {
        "debug": "4"
      },
      "engines": {
        "node": ">= 6.0.0"
      }
    },
    "node_modules/debug": {
      "version": "4.4.3",
      "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
      "license": "MIT",
      "dependencies": {
        "ms": "^2.1.3"
      },
      "engines": {
        "node": ">=6.0"
      },
      "peerDependenciesMeta": {
        "supports-color": {
          "optional": true
        }
      }
    },
    "node_modules/ms": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
      "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-agent-base",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of agent-base",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "agent-base": "6.0.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/agent-base@6.0.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/agent-base@6.0.2"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const createAgent = require('agent-base');
const { Agent } = createAgent;

/**
 * Creates a custom HTTP/HTTPS agent from a socket-producing callback.
 *
 * @param {Function} callback - Function(req, opts) returning a Duplex stream or Promise<Duplex>
 * @param {Object} [options] - Agent options such as timeout
 * @returns {Agent} Agent instance
 */
function createCustomAgent(callback, options) {
  return createAgent(callback, options);
}

/**
 * Custom agent class extending agent-base Agent with configurable default ports/protocols.
 */
class ConfigurableAgent extends Agent {
  constructor(callback, options = {}) {
    super(callback, options);
    if (options.defaultPort) {
      this.defaultPort = options.defaultPort;
    }
    if (options.protocol) {
      this.protocol = options.protocol;
    }
  }
}

module.exports = {
  createAgent,
  Agent,
  createCustomAgent,
  ConfigurableAgent
};
test/contract.mjs
import assert from 'node:assert';
import http from 'node:http';
import net from 'node:net';
import { Duplex } from 'node:stream';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  createAgent,
  Agent,
  createCustomAgent,
  ConfigurableAgent
} = require('../src/index.js');

async function runContract() {
  const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain', 'X-Path': req.url });
    res.end(`echo:${req.url}`);
  });

  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  const port = server.address().port;

  try {
    // 1. createAgent wraps a synchronous or Promise-returning socket callback into an http.Agent compatible instance
    const syncAgent = createAgent((req, opts) => {
      return net.connect(opts.port, opts.host);
    });
    assert.strictEqual(typeof syncAgent.addRequest, 'function', 'Agent must implement addRequest');
    assert(syncAgent instanceof Agent, 'Agent must be an instance of Agent');

    // 2. Agent routes HTTP requests through custom sockets created by async callbacks
    let asyncConnected = false;
    const asyncAgent = createCustomAgent(async (req, opts) => {
      await new Promise((r) => setTimeout(r, 10));
      asyncConnected = true;
      return net.connect(opts.port, opts.host);
    });

    const res1 = await new Promise((resolve, reject) => {
      const req = http.get(
        {
          host: '127.0.0.1',
          port: port,
          path: '/test-async',
          agent: asyncAgent
        },
        (res) => {
          let body = '';
          res.on('data', (chunk) => (body += chunk));
          res.on('end', () => resolve({ status: res.statusCode, body }));
        }
      );
      req.on('error', reject);
    });
    assert.strictEqual(asyncConnected, true, 'Async callback must be executed');
    assert.strictEqual(res1.status, 200, 'Response status must be 200');
    assert.strictEqual(res1.body, 'echo:/test-async', 'Response body must match');

    // 3. Agent supports 3-argument legacy style callback (req, opts, cb) with error and socket resolution
    let legacyCalled = false;
    const legacyAgent = createAgent((req, opts, cb) => {
      legacyCalled = true;
      const sock = net.connect(opts.port, opts.host, () => {
        cb(null, sock);
      });
      sock.on('error', cb);
    });

    const res2 = await new Promise((resolve, reject) => {
      const req = http.get(
        {
          host: '127.0.0.1',
          port: port,
          path: '/test-legacy',
          agent: legacyAgent
        },
        (res) => {
          let body = '';
          res.on('data', (chunk) => (body += chunk));
          res.on('end', () => resolve({ status: res.statusCode, body }));
        }
      );
      req.on('error', reject);
    });
    assert.strictEqual(legacyCalled, true, 'Legacy callback must be called');
    assert.strictEqual(res2.status, 200, 'Legacy response status must be 200');
    assert.strictEqual(res2.body, 'echo:/test-legacy', 'Legacy response body must match');

    // 4. Agent delegates request handling when the callback returns another http.Agent instance
    const standardAgent = new http.Agent();
    const delegatingAgent = createAgent((req, opts) => {
      return standardAgent;
    });

    const res3 = await new Promise((resolve, reject) => {
      const req = http.get(
        {
          host: '127.0.0.1',
          port: port,
          path: '/test-delegate',
          agent: delegatingAgent
        },
        (res) => {
          let body = '';
          res.on('data', (chunk) => (body += chunk));
          res.on('end', () => resolve({ status: res.statusCode, body }));
        }
      );
      req.on('error', reject);
    });
    assert.strictEqual(res3.status, 200, 'Delegated agent response status must be 200');
    assert.strictEqual(res3.body, 'echo:/test-delegate', 'Delegated agent response body must match');
    standardAgent.destroy();

    // 5. Agent emits ETIMEOUT on the request when the callback does not produce a socket within the specified timeout
    let timerId;
    const timeoutAgent = createAgent(
      () =>
        new Promise((resolve) => {
          timerId = setTimeout(() => {
            const dummy = new Duplex({
              read() {},
              write(chunk, enc, cb) {
                cb();
              }
            });
            resolve(dummy);
          }, 150);
        }),
      { timeout: 20 }
    );

    const timeoutError = await new Promise((resolve) => {
      const req = http.get(
        {
          host: '127.0.0.1',
          port: port,
          path: '/test-timeout',
          agent: timeoutAgent
        },
        () => {}
      );
      req.on('error', (err) => resolve(err));
    });
    clearTimeout(timerId);
    assert(timeoutError, 'Request must emit an error on timeout');
    assert.strictEqual(timeoutError.code, 'ETIMEOUT', 'Error code must be ETIMEOUT');

    // 6. Agent defaultPort and protocol getters dynamically reflect secureEndpoint state unless explicitly overridden
    const defaultAgent = new Agent();
    assert.strictEqual(defaultAgent.defaultPort, 80, 'Default port should be 80 for standard endpoint');
    assert.strictEqual(defaultAgent.protocol, 'http:', 'Default protocol should be http:');

    const customAgentInstance = new ConfigurableAgent(() => {}, {
      defaultPort: 8080,
      protocol: 'custom:'
    });
    assert.strictEqual(customAgentInstance.defaultPort, 8080, 'Configured defaultPort must match');
    assert.strictEqual(customAgentInstance.protocol, 'custom:', 'Configured protocol must match');

    console.log('Contract tests passed successfully.');
  } finally {
    server.close();
  }
}

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

오리진 시더

익명