CodeSampleX

Ejemplo

undici 7.30.2

Muestra verificada para npm undici 7.30.2. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó: undici.request executes GET with query…

sha256:35f0e0331b9610fbfa1d4a9adbc2d01d7a96d9d05c96e9e1b28599e05eb9957f

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-11-30

Caso

HOW
Objetivo
verify pkg:npm/undici@7.30.2
Paquetes
Entorno
node 22.23.2
Creado
2026-11-30T00:16:38Z

Contrato

  1. undici.request executes GET with query parameters and headers and POST with JSON body against localhost and parses JSON via body.json()
  2. undici.stream streams chunked HTTP response data through a custom Writable factory
  3. undici.Pool and undici.Client dispatch HTTP requests against localhost and mark closed after close()
  4. undici.MockAgent with disableNetConnect intercepts mocked undici.request and undici.fetch calls, rejects unmocked requests with UND_MOCK_ERR_MOCK_NOT_MATCHED, and enforces assertNoPendingInterceptors()
  5. undici.RetryAgent retries a transient 503 GET response to 200, closes the wrapped MockAgent on RetryAgent.close() (subsequent close rejects with UND_ERR_DESTROYED), and undici.request rejects with AbortError on an aborted AbortController.signal

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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@7.30.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/undici@7.30.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:2d20e0313191b6a1ea38848f69d63c70162ed455ab1f6a3c34337432b54c97c3","constraints":{"executionContext":"node"},"contract":["undici.request executes GET with query parameters and headers and POST with JSON body against localhost and parses JSON via body.json()","undici.stream streams chunked HTTP response data through a custom Writable factory","undici.Pool and undici.Client dispatch HTTP requests against localhost and mark closed after close()","undici.MockAgent with disableNetConnect intercepts mocked undici.request and undici.fetch calls, rejects unmocked requests with UND_MOCK_ERR_MOCK_NOT_MATCHED, and enforces assertNoPendingInterceptors()","undici.RetryAgent retries a transient 503 GET response to 200, closes the wrapped MockAgent on RetryAgent.close() (subsequent close rejects with UND_ERR_DESTROYED), and undici.request rejects with AbortError on an aborted AbortController.signal"],"goal":"verify pkg:npm/undici@7.30.2","kind":"HOW","packages":["pkg:npm/undici@7.30.2"],"schemaVersion":1},"contractCommand":["node","test/contract.cjs"],"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@7.30.2"],"schemaVersion":1,"subject":"pkg:npm/undici@7.30.2","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",
      "license": "MIT-0",
      "dependencies": {
        "undici": "7.30.2"
      }
    },
    "node_modules/undici": {
      "version": "7.30.2",
      "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz",
      "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==",
      "license": "MIT",
      "engines": {
        "node": ">=20.18.1"
      }
    }
  }
}
package.json
{
  "name": "undici-sample",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "undici": "7.30.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/undici@7.30.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/undici@7.30.2"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.cjs
'use strict';

const { Writable } = require('node:stream');
const {
  Client,
  MockAgent,
  Pool,
  RetryAgent,
  fetch,
  request,
  stream,
} = require('undici');

async function requestJson(url, options = {}) {
  const { body, headers, ...rest } = options;
  const reqHeaders = { ...headers };
  let serializedBody;

  if (body !== undefined) {
    serializedBody = JSON.stringify(body);
    if (!reqHeaders['content-type']) {
      reqHeaders['content-type'] = 'application/json';
    }
  }

  const res = await request(url, {
    ...rest,
    headers: reqHeaders,
    body: serializedBody,
  });

  const data = await res.body.json();
  return {
    statusCode: res.statusCode,
    headers: res.headers,
    data,
  };
}

async function streamText(url, options = {}) {
  const chunks = [];
  let responseStatus = 0;
  let responseHeaders = {};

  await stream(url, options, ({ statusCode, headers }) => {
    responseStatus = statusCode;
    responseHeaders = headers;
    return new Writable({
      write(chunk, _encoding, callback) {
        chunks.push(Buffer.from(chunk));
        callback();
      },
    });
  });

  return {
    statusCode: responseStatus,
    headers: responseHeaders,
    text: Buffer.concat(chunks).toString('utf8'),
  };
}

function createMockSession(origin) {
  const agent = new MockAgent();
  agent.disableNetConnect();
  const pool = agent.get(origin);
  return { agent, pool };
}

function createRetryingDispatcher(dispatcher, retryOptions) {
  return new RetryAgent(dispatcher, retryOptions);
}

module.exports = {
  Client,
  MockAgent,
  Pool,
  RetryAgent,
  createMockSession,
  createRetryingDispatcher,
  fetch,
  request,
  requestJson,
  streamText,
};
test/contract.cjs
'use strict';

const assert = require('node:assert/strict');
const http = require('node:http');
const {
  Client,
  Pool,
  createMockSession,
  createRetryingDispatcher,
  fetch,
  request,
  requestJson,
  streamText,
} = require('../src/index.cjs');

function startLocalServer() {
  return new Promise((resolve, reject) => {
    const server = http.createServer((req, res) => {
      const parsed = new URL(req.url, 'http://localhost');

      if (req.method === 'GET' && parsed.pathname === '/echo') {
        res.writeHead(200, {
          'content-type': 'application/json',
          'x-mode': 'echo',
        });
        res.end(JSON.stringify({
          query: Object.fromEntries(parsed.searchParams.entries()),
          header: req.headers['x-trace'] || null,
        }));
        return;
      }

      if (req.method === 'POST' && parsed.pathname === '/items') {
        const chunks = [];
        req.on('data', (chunk) => chunks.push(chunk));
        req.on('end', () => {
          const payload = JSON.parse(Buffer.concat(chunks).toString('utf8'));
          res.writeHead(201, { 'content-type': 'application/json' });
          res.end(JSON.stringify({
            created: true,
            item: payload,
            contentType: req.headers['content-type'],
          }));
        });
        return;
      }

      if (req.method === 'GET' && parsed.pathname === '/stream') {
        res.writeHead(200, { 'content-type': 'text/plain' });
        res.write('chunk-1:');
        res.write('chunk-2:');
        res.end('chunk-3');
        return;
      }

      res.writeHead(404, { 'content-type': 'application/json' });
      res.end(JSON.stringify({ error: 'not-found' }));
    });

    server.on('error', reject);
    server.listen(0, 'localhost', () => {
      const address = server.address();
      resolve({
        server,
        origin: `http://localhost:${address.port}`,
      });
    });
  });
}

function stopLocalServer(server) {
  return new Promise((resolve, reject) => {
    server.close((err) => (err ? reject(err) : resolve()));
  });
}

async function testRequestAndStream(origin) {
  const getRes = await requestJson(`${origin}/echo`, {
    method: 'GET',
    query: { filter: 'active', limit: '5' },
    headers: { 'x-trace': 'req-1' },
  });
  assert.equal(getRes.statusCode, 200);
  assert.equal(getRes.headers['x-mode'], 'echo');
  assert.deepEqual(getRes.data, {
    query: { filter: 'active', limit: '5' },
    header: 'req-1',
  });

  const postRes = await requestJson(`${origin}/items`, {
    method: 'POST',
    body: { name: 'widget', count: 3 },
  });
  assert.equal(postRes.statusCode, 201);
  assert.equal(postRes.data.created, true);
  assert.deepEqual(postRes.data.item, { name: 'widget', count: 3 });
  assert.equal(postRes.data.contentType, 'application/json');

  const streamed = await streamText(`${origin}/stream`, { method: 'GET' });
  assert.equal(streamed.statusCode, 200);
  assert.equal(streamed.text, 'chunk-1:chunk-2:chunk-3');
}

async function testPoolAndClient(origin) {
  const pool = new Pool(origin, { connections: 2 });
  try {
    const res = await pool.request({
      path: '/echo?source=pool',
      method: 'GET',
    });
    assert.equal(res.statusCode, 200);
    const body = await res.body.json();
    assert.equal(body.query.source, 'pool');
  } finally {
    await pool.close();
  }
  assert.equal(pool.closed, true);

  const client = new Client(origin);
  try {
    const res = await client.request({
      path: '/echo?source=client',
      method: 'GET',
    });
    assert.equal(res.statusCode, 200);
    const body = await res.body.json();
    assert.equal(body.query.source, 'client');
  } finally {
    await client.close();
  }
  assert.equal(client.closed, true);
}

async function testMockAgentAndFetch() {
  const { agent, pool } = createMockSession('http://example.com');
  try {
    pool
      .intercept({
        path: '/api/status',
        method: 'GET',
        headers: { 'x-client': 'test' },
      })
      .reply(200, { ok: true, via: 'request' }, {
        headers: { 'content-type': 'application/json' },
      });

    pool
      .intercept({
        path: '/api/fetch',
        method: 'POST',
      })
      .reply(201, { ok: true, via: 'fetch' }, {
        headers: { 'content-type': 'application/json' },
      });

    const reqRes = await requestJson('http://example.com/api/status', {
      method: 'GET',
      headers: { 'x-client': 'test' },
      dispatcher: agent,
    });
    assert.equal(reqRes.statusCode, 200);
    assert.deepEqual(reqRes.data, { ok: true, via: 'request' });

    const fetchRes = await fetch('http://example.com/api/fetch', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ ping: 1 }),
      dispatcher: agent,
    });
    assert.equal(fetchRes.status, 201);
    assert.deepEqual(await fetchRes.json(), { ok: true, via: 'fetch' });

    await assert.rejects(
      () => request('http://example.com/unmocked', { dispatcher: agent }),
      (err) => err && err.code === 'UND_MOCK_ERR_MOCK_NOT_MATCHED',
    );

    agent.assertNoPendingInterceptors();

    pool.intercept({ path: '/never-called', method: 'GET' }).reply(200, 'ok');
    assert.throws(() => agent.assertNoPendingInterceptors());
  } finally {
    await agent.close();
  }
}

async function testRetryAgentAndAbort(origin) {
  const { agent, pool } = createMockSession('http://example.com');
  const retryAgent = createRetryingDispatcher(agent, {
    maxRetries: 2,
    minTimeout: 10,
    maxTimeout: 20,
    statusCodes: [503],
  });

  try {
    pool.intercept({ path: '/flaky', method: 'GET' }).reply(503, 'unavailable');
    pool
      .intercept({ path: '/flaky', method: 'GET' })
      .reply(200, { recovered: true }, {
        headers: { 'content-type': 'application/json' },
      });

    const res = await requestJson('http://example.com/flaky', {
      method: 'GET',
      dispatcher: retryAgent,
    });
    assert.equal(res.statusCode, 200);
    assert.deepEqual(res.data, { recovered: true });
    agent.assertNoPendingInterceptors();
  } finally {
    await retryAgent.close();
  }
  await assert.rejects(
    () => agent.close(),
    (err) => err && err.code === 'UND_ERR_DESTROYED',
  );

  const controller = new AbortController();
  controller.abort();
  await assert.rejects(
    () => request(`${origin}/echo`, {
      signal: controller.signal,
    }),
    (err) => err && err.name === 'AbortError',
  );
}

async function main() {
  const { server, origin } = await startLocalServer();
  try {
    await testRequestAndStream(origin);
    await testPoolAndClient(origin);
    await testMockAgentAndFetch();
    await testRetryAgentAndAbort(origin);
  } finally {
    await stopLocalServer(server);
  }
  console.log('undici 7.30.2 contract passed');
}

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

Seeder de origen

anónimo