CodeSampleX

Exemplo

@hono/node-server 2.1.0: getRequestListener

Amostra verificada para npm @hono/node-server 2.1.0: getRequestListener. O contrato rodou em node 22 · linux debian/x64 · docker e passou.

sha256:96735db421392dad18b51640f9a0061b1938524da0e9a7ace5b344e3c469c54a

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-09-04

Caso

HOW
Objetivo
verify @hono/node-server.getRequestListener in pkg:npm/%40hono/node-server@2.1.0
Pacotes
Símbolos
  • @hono/node-server.getRequestListener
Ambiente
node 22.23.2
Criado
2026-09-04T12:19:50Z

Contrato

  1. @hono/node-server exports getRequestListener function
  2. getRequestListener returns a request listener callback for Node http.Server
  3. getRequestListener passes web-standard Request and env with incoming/outgoing to fetch handler
  4. getRequestListener handles GET requests and sends status, headers, and text body
  5. getRequestListener handles POST requests with JSON payload
  6. getRequestListener supports custom errorHandler option for caught errors
  7. getRequestListener supports overrideGlobalObjects option

Arquivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 @hono/node-server.getRequestListener in pkg:npm/%40hono/node-server@2.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40hono/node-server@2.1.0
Demonstrate these symbols/APIs:
  - @hono/node-server.getRequestListener

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:badd108e414a4603a267ac5acfffd9d6425a10c300bf0b6c84407abae59a279f","contract":["@hono/node-server exports getRequestListener function","getRequestListener returns a request listener callback for Node http.Server","getRequestListener passes web-standard Request and env with incoming/outgoing to fetch handler","getRequestListener handles GET requests and sends status, headers, and text body","getRequestListener handles POST requests with JSON payload","getRequestListener supports custom errorHandler option for caught errors","getRequestListener supports overrideGlobalObjects option"],"goal":"verify @hono/node-server.getRequestListener in pkg:npm/%40hono/node-server@2.1.0","kind":"HOW","packages":["pkg:npm/%40hono/node-server@2.1.0"],"schemaVersion":1,"symbols":["@hono/node-server.getRequestListener"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40hono/node-server@2.1.0"],"schemaVersion":1,"subject":"pkg:npm/%40hono/node-server@2.1.0","symbols":["@hono/node-server.getRequestListener"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-node-server-getrequestlistener",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-node-server-getrequestlistener",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@hono/node-server": "2.1.0"
      }
    },
    "node_modules/@hono/node-server": {
      "version": "2.1.0",
      "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.0.tgz",
      "integrity": "sha512-XovyyCCnBzW+zKu+z/zq8hwNs4KOR5rEMAOxo2f40Q5xoOI37IMm6MIg2COOUtUApo0i6850MTBKH2u4QLGIqg==",
      "license": "MIT",
      "engines": {
        "node": ">=20"
      },
      "peerDependencies": {
        "hono": "^4"
      }
    },
    "node_modules/hono": {
      "version": "4.13.5",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.5.tgz",
      "integrity": "sha512-O6+/eCYRkzzzy0rPWwKLiGBR1nFuUPZynnwjxN1MBA62NNqbT0wQEzQyK2gSO5yDIDB336sXQleAhOHrzlYyKw==",
      "license": "MIT",
      "peer": true,
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-node-server-getrequestlistener",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "dependencies": {
    "@hono/node-server": "2.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @hono/node-server.getRequestListener in pkg:npm/%40hono/node-server@2.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40hono/node-server@2.1.0"
  ],
  "symbols": [
    "@hono/node-server.getRequestListener"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import http from 'node:http';
import { getRequestListener } from '@hono/node-server';

// Contract 1: @hono/node-server exports getRequestListener function
{
  assert.strictEqual(typeof getRequestListener, 'function');
}

// Contract 2: getRequestListener returns a request listener callback for Node http.Server
// Contract 3: getRequestListener passes web-standard Request and env with incoming/outgoing to fetch handler
// Contract 4: getRequestListener handles GET requests and sends status, headers, and text body
// Contract 5: getRequestListener handles POST requests with JSON payload
{
  let envReceived = null;
  const listener = getRequestListener(async (req, env) => {
    envReceived = env;
    const url = new URL(req.url);

    if (url.pathname === '/hello' && req.method === 'GET') {
      return new Response('Hello from getRequestListener!', {
        status: 200,
        headers: {
          'content-type': 'text/plain; charset=utf-8',
          'x-custom-header': 'test-val',
        },
      });
    }

    if (url.pathname === '/echo-json' && req.method === 'POST') {
      const data = await req.json();
      return new Response(JSON.stringify({ received: data, method: req.method }), {
        status: 201,
        headers: { 'content-type': 'application/json' },
      });
    }

    return new Response('Not Found', { status: 404 });
  });

  assert.strictEqual(typeof listener, 'function');

  const server = http.createServer(listener);

  await new Promise((resolve) => {
    server.listen(0, '127.0.0.1', resolve);
  });

  const address = server.address();
  assert.ok(address && typeof address === 'object');
  assert.strictEqual(typeof address.port, 'number');
  assert.strictEqual(address.address, '127.0.0.1');

  const baseUrl = `http://127.0.0.1:${address.port}`;

  try {
    // GET request
    const getRes = await fetch(`${baseUrl}/hello`);
    assert.strictEqual(getRes.status, 200);
    assert.strictEqual(getRes.headers.get('content-type'), 'text/plain; charset=utf-8');
    assert.strictEqual(getRes.headers.get('x-custom-header'), 'test-val');
    const getText = await getRes.text();
    assert.strictEqual(getText, 'Hello from getRequestListener!');

    // Check env passed to fetch handler
    assert.ok(envReceived);
    assert.ok(envReceived.incoming instanceof http.IncomingMessage);
    assert.ok(envReceived.outgoing instanceof http.ServerResponse);

    // POST request
    const postPayload = { symbol: '@hono/node-server.getRequestListener', verified: true };
    const postRes = await fetch(`${baseUrl}/echo-json`, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(postPayload),
    });
    assert.strictEqual(postRes.status, 201);
    assert.strictEqual(postRes.headers.get('content-type'), 'application/json');
    const postData = await postRes.json();
    assert.deepStrictEqual(postData, {
      received: postPayload,
      method: 'POST',
    });

    // 404 check
    const missingRes = await fetch(`${baseUrl}/not-exists`);
    assert.strictEqual(missingRes.status, 404);
  } finally {
    await new Promise((resolve, reject) => {
      server.close((err) => (err ? reject(err) : resolve()));
    });
  }
  assert.strictEqual(server.listening, false);
}

// Contract 6: getRequestListener supports custom errorHandler option for caught errors
{
  let caughtError = null;
  const listener = getRequestListener(
    async (req) => {
      const url = new URL(req.url);
      if (url.pathname === '/failing') {
        throw new Error('Planned execution failure');
      }
      return new Response('OK', { status: 200 });
    },
    {
      errorHandler: (err) => {
        caughtError = err;
        return new Response(JSON.stringify({ error: err.message }), {
          status: 500,
          headers: { 'content-type': 'application/json' },
        });
      },
    }
  );

  const server = http.createServer(listener);
  await new Promise((resolve) => {
    server.listen(0, '127.0.0.1', resolve);
  });

  const baseUrl = `http://127.0.0.1:${server.address().port}`;

  try {
    const res = await fetch(`${baseUrl}/failing`);
    assert.strictEqual(res.status, 500);
    assert.strictEqual(res.headers.get('content-type'), 'application/json');
    const body = await res.json();
    assert.deepStrictEqual(body, { error: 'Planned execution failure' });
    assert.ok(caughtError instanceof Error);
    assert.strictEqual(caughtError.message, 'Planned execution failure');
  } finally {
    await new Promise((resolve, reject) => {
      server.close((err) => (err ? reject(err) : resolve()));
    });
  }
}

// Contract 7: getRequestListener supports overrideGlobalObjects option
{
  const listenerNoOverride = getRequestListener(
    () => new Response('ok'),
    { overrideGlobalObjects: false }
  );
  assert.strictEqual(typeof listenerNoOverride, 'function');
}

console.log('All @hono/node-server getRequestListener contract tests passed.');

Seeder de origem

anônimo