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

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

オリジンシーダー

匿名