CodeSampleX

샘플

@hono/node-server 2.0.12: RequestError

검증된 샘플 — npm @hono/node-server 2.0.12: RequestError. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: RequestError is an instance of Error with…

sha256:ff6de9f6cb646b2c17b508b20571201874ce398a21854ec20028cfc22deba17d

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
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-06

케이스

HOW
목표
verify @hono/node-server.RequestError in pkg:npm/%40hono/node-server@2.0.12
패키지
심벌
  • @hono/node-server.RequestError
환경
node 22.23.2
생성일
2026-09-06T11:26:56Z

컨트랙트

  1. RequestError is an instance of Error with name RequestError and preserves message and options cause
  2. getRequestListener passes a RequestError with message Missing host header to custom errorHandler when host header is missing
  3. getRequestListener passes a RequestError with message Invalid host header to custom errorHandler when host header contains invalid characters
  4. serve handles RequestError with default HTTP 400 Bad Request response when no custom errorHandler is provided

파일

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

소스 아티팩트 내려받기 (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 @hono/node-server.RequestError in pkg:npm/%40hono/node-server@2.0.12
Kind: HOW

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

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:73eadadb40ee2536416677f63e468f79315e1290f3f152643cbb126dc4f4d6f4","contract":["RequestError is an instance of Error with name RequestError and preserves message and options cause","getRequestListener passes a RequestError with message Missing host header to custom errorHandler when host header is missing","getRequestListener passes a RequestError with message Invalid host header to custom errorHandler when host header contains invalid characters","serve handles RequestError with default HTTP 400 Bad Request response when no custom errorHandler is provided"],"goal":"verify @hono/node-server.RequestError in pkg:npm/%40hono/node-server@2.0.12","kind":"HOW","packages":["pkg:npm/%40hono/node-server@2.0.12"],"schemaVersion":1,"symbols":["@hono/node-server.RequestError"]},"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/%40hono/node-server@2.0.12"],"schemaVersion":1,"subject":"pkg:npm/%40hono/node-server@2.0.12","symbols":["@hono/node-server.RequestError"],"verifierAdapter":"node-typescript@1"}
index.js
const {
  RequestError,
  serve,
  createAdaptorServer,
  getRequestListener,
} = require("@hono/node-server");

/**
 * Creates a RequestError with the specified message and optional cause.
 * @param {string} message - Error description.
 * @param {{ cause?: unknown }} [options] - Error options including cause.
 * @returns {RequestError} Instance of RequestError.
 */
function createRequestError(message, options) {
  return new RequestError(message, options);
}

/**
 * Creates a request listener with custom error handling.
 * @param {Function} fetchHandler - Fetch request handler.
 * @param {Function} [errorHandler] - Error handler for RequestError and other errors.
 * @param {Object} [options={}] - Additional options.
 * @returns {Function} Node.js request listener.
 */
function createListenerWithErrorHandling(fetchHandler, errorHandler, options = {}) {
  return getRequestListener(fetchHandler, {
    ...options,
    errorHandler,
  });
}

/**
 * Starts a server with default error handling.
 * @param {Function} fetchHandler - Fetch request handler.
 * @param {Object} [options={}] - Server options.
 * @returns {import("node:http").Server} Active server.
 */
function startServer(fetchHandler, options = {}) {
  return serve({
    fetch: fetchHandler,
    port: options.port !== undefined ? options.port : 0,
    ...options,
  });
}

module.exports = {
  RequestError,
  serve,
  createAdaptorServer,
  getRequestListener,
  createRequestError,
  createListenerWithErrorHandling,
  startServer,
};
package-lock.json
{
  "name": "verify-hono-node-server-requesterror",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "verify-hono-node-server-requesterror",
      "version": "1.0.0",
      "dependencies": {
        "@hono/node-server": "2.0.12"
      }
    },
    "node_modules/@hono/node-server": {
      "version": "2.0.12",
      "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.0.12.tgz",
      "integrity": "sha512-eWpQYr67tqJLeaSUl0Q+TquuYfUdTibpOJlUMV2FfUP7+KqCC5TufnwnlXL6mobZBJbGAYRd7ZvEBDCbLInjhg==",
      "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": "verify-hono-node-server-requesterror",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for @hono/node-server RequestError",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "@hono/node-server": "2.0.12"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @hono/node-server.RequestError in pkg:npm/%40hono/node-server@2.0.12",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40hono/node-server@2.0.12"
  ],
  "symbols": [
    "@hono/node-server.RequestError"
  ]
}
test/contract.cjs
const assert = require("node:assert/strict");
const http = require("node:http");
const net = require("node:net");
const {
  RequestError,
  serve,
  getRequestListener,
  createRequestError,
  createListenerWithErrorHandling,
  startServer,
} = require("../index.js");

/**
 * Sends a raw HTTP request over TCP socket and returns response string.
 * @param {number} port - Target server port.
 * @param {string} rawHttp - Raw HTTP request bytes.
 * @returns {Promise<string>}
 */
function sendRawRequest(port, rawHttp) {
  return new Promise((resolve, reject) => {
    const client = net.createConnection({ port, host: "127.0.0.1" }, () => {
      client.write(rawHttp);
    });
    let data = "";
    client.on("data", (chunk) => {
      data += chunk.toString();
    });
    client.on("end", () => {
      resolve(data);
    });
    client.on("error", reject);
  });
}

async function runContractTests() {
  // Contract 1: RequestError is an instance of Error with name RequestError and preserves message and options cause
  {
    const causeErr = new Error("underlying connection fault");
    const err = createRequestError("request validation failed", { cause: causeErr });

    assert.ok(err instanceof Error, "RequestError must be an instance of Error");
    assert.ok(err instanceof RequestError, "err must be an instance of RequestError");
    assert.strictEqual(err.name, "RequestError", "Error name must be RequestError");
    assert.strictEqual(err.message, "request validation failed", "Error message must match");
    assert.strictEqual(err.cause, causeErr, "Error cause must match provided cause");
  }

  // Contract 2: getRequestListener passes a RequestError with message Missing host header to custom errorHandler when host header is missing
  {
    let capturedError = null;
    const listener = createListenerWithErrorHandling(
      () => new Response("ok", { status: 200 }),
      (err) => {
        capturedError = err;
        return new Response("Handled: " + err.message, {
          status: 400,
          headers: { "X-Error-Type": err.name },
        });
      }
    );

    const server = http.createServer(listener);
    await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
    const port = server.address().port;

    const response = await sendRawRequest(port, "GET / HTTP/1.0\r\nConnection: close\r\n\r\n");

    assert.ok(response.startsWith("HTTP/1.1 400 Bad Request"), "Response status must be 400");
    assert.ok(response.includes("X-Error-Type: RequestError"), "Header must reflect RequestError");
    assert.ok(response.includes("Handled: Missing host header"), "Body must reflect Missing host header");
    assert.ok(capturedError instanceof RequestError, "Captured error must be instance of RequestError");
    assert.strictEqual(capturedError.name, "RequestError");
    assert.strictEqual(capturedError.message, "Missing host header");

    await new Promise((resolve) => server.close(resolve));
  }

  // Contract 3: getRequestListener passes a RequestError with message Invalid host header to custom errorHandler when host header contains invalid characters
  {
    let capturedError = null;
    const listener = createListenerWithErrorHandling(
      () => new Response("ok", { status: 200 }),
      (err) => {
        capturedError = err;
        return new Response("Handled: " + err.message, {
          status: 400,
          headers: { "X-Error-Type": err.name },
        });
      }
    );

    const server = http.createServer(listener);
    await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
    const port = server.address().port;

    const response = await sendRawRequest(
      port,
      "GET / HTTP/1.1\r\nHost: inv@lid_host\r\nConnection: close\r\n\r\n"
    );

    assert.ok(response.startsWith("HTTP/1.1 400 Bad Request"), "Response status must be 400");
    assert.ok(response.includes("X-Error-Type: RequestError"), "Header must reflect RequestError");
    assert.ok(response.includes("Handled: Invalid host header"), "Body must reflect Invalid host header");
    assert.ok(capturedError instanceof RequestError, "Captured error must be instance of RequestError");
    assert.strictEqual(capturedError.name, "RequestError");
    assert.strictEqual(capturedError.message, "Invalid host header");

    await new Promise((resolve) => server.close(resolve));
  }

  // Contract 4: serve handles RequestError with default HTTP 400 Bad Request response when no custom errorHandler is provided
  {
    const server = startServer(() => new Response("ok-healthy", { status: 200 }));

    await new Promise((resolve) => server.on("listening", resolve));
    const port = server.address().port;

    const badRes = await sendRawRequest(port, "GET / HTTP/1.0\r\nConnection: close\r\n\r\n");
    assert.ok(badRes.startsWith("HTTP/1.1 400 Bad Request"), "Should return default 400 Bad Request");

    const goodRes = await sendRawRequest(
      port,
      "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"
    );
    assert.ok(goodRes.startsWith("HTTP/1.1 200 OK"), "Valid request should return 200 OK");
    assert.ok(goodRes.includes("ok-healthy"), "Body should match expected handler output");

    await new Promise((resolve) => server.close(resolve));
  }

  console.log("All @hono/node-server.RequestError contract tests passed successfully.");
}

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

오리진 시더

익명