CodeSampleX

샘플

undici 6.28.0

검증된 샘플 — npm undici 6.28.0. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: undici.request executes HTTP requests with headers, query, JSON…

sha256:a669aa4644ea98a4f66dffa9d8028c10e1c603081a78347a7f77b3da0c403d38

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

케이스

HOW
목표
verify pkg:npm/undici@6.28.0
패키지
환경
node 22.23.2
생성일
2026-08-20T06:13:31Z

컨트랙트

  1. undici.request executes HTTP requests with headers, query, JSON payloads, and body parsing methods
  2. undici.MockAgent intercepts HTTP client dispatches with mock status codes, custom headers, and structured response payloads offline
  3. undici.Client and undici.Pool manage dedicated and pooled connections with custom dispatch options and lifecycle management
  4. undici abort handling terminates in-flight requests using AbortController signals

파일

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

소스 아티팩트 내려받기 (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/undici@6.28.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/undici@6.28.0
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:a1b517e738fd47bd2524c440707930b1dac81e29825255ce047ad598fa722af4","constraints":{"executionContext":"node"},"contract":["undici.request executes HTTP requests with headers, query, JSON payloads, and body parsing methods","undici.MockAgent intercepts HTTP client dispatches with mock status codes, custom headers, and structured response payloads offline","undici.Client and undici.Pool manage dedicated and pooled connections with custom dispatch options and lifecycle management","undici abort handling terminates in-flight requests using AbortController signals"],"goal":"verify pkg:npm/undici@6.28.0","kind":"HOW","packages":["pkg:npm/undici@6.28.0"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"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/undici@6.28.0"],"schemaVersion":1,"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "undici-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "undici-sample",
      "version": "1.0.0",
      "dependencies": {
        "undici": "6.28.0"
      }
    },
    "node_modules/undici": {
      "version": "6.28.0",
      "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz",
      "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==",
      "license": "MIT",
      "engines": {
        "node": ">=18.17"
      }
    }
  }
}
package.json
{
  "name": "undici-sample",
  "version": "1.0.0",
  "dependencies": {
    "undici": "6.28.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/undici@6.28.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/undici@6.28.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const undici = require('undici');

/**
 * Executes an HTTP request using undici.request.
 *
 * @param {string | URL} url - Target URL.
 * @param {import('undici').RequestOptions} [options] - Request options.
 * @returns {Promise<import('undici').Dispatcher.ResponseData>}
 */
async function sendRequest(url, options) {
  return undici.request(url, options);
}

/**
 * Creates and configures an offline MockAgent for intercepting requests.
 *
 * @param {string | URL} origin - Base origin to intercept.
 * @returns {{ agent: import('undici').MockAgent, pool: import('undici').MockPool | import('undici').MockClient }}
 */
function createMockEnvironment(origin) {
  const agent = new undici.MockAgent();
  agent.disableNetConnect();
  const pool = agent.get(origin);
  return { agent, pool };
}

/**
 * Creates an undici connection Pool for managing multiple requests to an origin.
 *
 * @param {string | URL} origin - Target origin.
 * @param {import('undici').Pool.Options} [options] - Pool configuration options.
 * @returns {import('undici').Pool}
 */
function createPool(origin, options) {
  return new undici.Pool(origin, options);
}

/**
 * Creates an undici Client for managing a single connection to an origin.
 *
 * @param {string | URL} origin - Target origin.
 * @param {import('undici').Client.Options} [options] - Client configuration options.
 * @returns {import('undici').Client}
 */
function createClient(origin, options) {
  return new undici.Client(origin, options);
}

module.exports = {
  sendRequest,
  createMockEnvironment,
  createPool,
  createClient,
  undici,
};
test/contract.js
const assert = require('node:assert/strict');
const {
  sendRequest,
  createMockEnvironment,
  createPool,
  createClient,
  undici,
} = require('../src/index.js');

async function runContracts() {
  // Contract 1: undici.request executes HTTP requests with headers, query, JSON payloads, and body parsing methods
  {
    const { agent, pool } = createMockEnvironment('http://localhost:8080');
    undici.setGlobalDispatcher(agent);

    // Mock GET endpoint
    pool.intercept({
      path: '/api/resource?filter=active',
      method: 'GET',
      headers: {
        'x-custom-header': 'test-val',
      },
    }).reply(200, { id: 'item-101', status: 'active' }, {
      headers: { 'content-type': 'application/json' },
    });

    // Mock POST endpoint
    pool.intercept({
      path: '/api/resource',
      method: 'POST',
      body: JSON.stringify({ name: 'new-item' }),
    }).reply(201, { id: 'item-102', created: true }, {
      headers: { 'content-type': 'application/json' },
    });

    // Test GET request
    const getResponse = await sendRequest('http://localhost:8080/api/resource?filter=active', {
      method: 'GET',
      headers: { 'x-custom-header': 'test-val' },
    });
    assert.strictEqual(getResponse.statusCode, 200, 'GET status code should be 200');
    assert.strictEqual(getResponse.headers['content-type'], 'application/json');
    const getData = await getResponse.body.json();
    assert.deepStrictEqual(getData, { id: 'item-101', status: 'active' });

    // Test POST request
    const postResponse = await sendRequest('http://localhost:8080/api/resource', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ name: 'new-item' }),
    });
    assert.strictEqual(postResponse.statusCode, 201, 'POST status code should be 201');
    const postData = await postResponse.body.json();
    assert.deepStrictEqual(postData, { id: 'item-102', created: true });

    await agent.close();
  }

  // Contract 2: undici.MockAgent intercepts HTTP client dispatches with mock status codes, custom headers, and structured response payloads offline
  {
    const { agent, pool } = createMockEnvironment('http://localhost:8080');

    pool.intercept({
      path: '/text-data',
      method: 'GET',
    }).reply(200, 'sample text payload', {
      headers: {
        'content-type': 'text/plain',
        'x-server-version': '1.0.0',
      },
    });

    pool.intercept({
      path: '/not-found',
      method: 'GET',
    }).reply(404, { error: 'Not Found' }, {
      headers: { 'content-type': 'application/json' },
    });

    // Request text payload using explicit dispatcher
    const textRes = await undici.request('http://localhost:8080/text-data', {
      dispatcher: agent,
    });
    assert.strictEqual(textRes.statusCode, 200);
    assert.strictEqual(textRes.headers['content-type'], 'text/plain');
    assert.strictEqual(textRes.headers['x-server-version'], '1.0.0');
    const textContent = await textRes.body.text();
    assert.strictEqual(textContent, 'sample text payload');

    // Request 404
    const notFoundRes = await undici.request('http://localhost:8080/not-found', {
      dispatcher: agent,
    });
    assert.strictEqual(notFoundRes.statusCode, 404);
    const errorData = await notFoundRes.body.json();
    assert.deepStrictEqual(errorData, { error: 'Not Found' });

    await agent.close();
  }

  // Contract 3: undici.Client and undici.Pool manage dedicated and pooled connections with custom dispatch options and lifecycle management
  {
    const { agent } = createMockEnvironment('http://localhost:8080');

    const pool = createPool('http://localhost:8080', {
      factory: () => agent.get('http://localhost:8080'),
    });
    assert.strictEqual(pool.closed, false, 'Pool should initially be open');
    assert.strictEqual(pool.destroyed, false, 'Pool should not be destroyed');
    await pool.close();
    assert.strictEqual(pool.closed, true, 'Pool should be closed after close()');

    const client = createClient('http://localhost:8080', {
      factory: () => agent.get('http://localhost:8080'),
    });
    assert.strictEqual(client.closed, false, 'Client should initially be open');
    assert.strictEqual(client.destroyed, false, 'Client should not be destroyed');
    await client.close();
    assert.strictEqual(client.closed, true, 'Client should be closed after close()');

    await agent.close();
  }

  // Contract 4: undici abort handling terminates in-flight requests using AbortController signals
  {
    const { agent, pool } = createMockEnvironment('http://localhost:8080');

    pool.intercept({
      path: '/delayed-endpoint',
      method: 'GET',
    }).reply(200, 'delayed response').delay(1000);

    const controller = new AbortController();
    setTimeout(() => {
      controller.abort();
    }, 20);

    await assert.rejects(
      async () => {
        await undici.request('http://localhost:8080/delayed-endpoint', {
          dispatcher: agent,
          signal: controller.signal,
        });
      },
      (err) => {
        assert.ok(
          err.name === 'AbortError' ||
          err.name === 'RequestAbortedError' ||
          err.code === 'UND_ERR_ABORTED' ||
          controller.signal.aborted,
          'Error should indicate aborted request'
        );
        return true;
      },
      'Request should be aborted when AbortSignal fires'
    );

    await agent.close();
  }

  console.log('All pkg:npm/undici@6.28.0 contracts passed successfully.');
}

runContracts().catch((err) => {
  console.error(err);
  process.exit(1);
});

오리진 시더

익명