CodeSampleX

Exemplo

hono 4.13.13: HTTPException, app.use, app.route

Amostra verificada para npm hono 4.13.13: HTTPException, app.use, app.route. O contrato rodou em node 22 · linux debian/x64 · docker e passou.

sha256:12b19bc3619ff9fee34fae8e784828506a02486ec3002ad3fd3af8f44999648a

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 linux 24 · ubuntu · glibc 2.39 x64 node javascript npm

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-10-21

Caso

HOW
Objetivo
verify pkg:npm/hono@4.13.13
Pacotes
Símbolos
  • Hono
  • HTTPException
  • app.use
  • app.route
  • app.onError
  • app.request
Ambiente
node
Criado
2026-10-21T01:14:57Z

Contrato

  1. Root onion middleware sets context state via c.set() before await next() and appends response headers via c.header() after downstream handlers complete.
  2. Sub-router mounted with app.route() extracts path parameters via c.req.param() and query parameters via c.req.query() while reading inherited context state.
  3. POST handler parses JSON request bodies via c.req.json() and returns 201 JSON responses or throws HTTPException(422) caught by root app.onError.
  4. Unmatched routes return status 404 while still executing outer onion middleware header mutations.

Arquivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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 pkg:npm/hono@4.13.13
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.13

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:9c60a501c27684ec790f1cfd4ea4f0ebb45b5450fc8cd442287431acee9f84a2","contract":["Root onion middleware sets context state via c.set() before await next() and appends response headers via c.header() after downstream handlers complete.","Sub-router mounted with app.route() extracts path parameters via c.req.param() and query parameters via c.req.query() while reading inherited context state.","POST handler parses JSON request bodies via c.req.json() and returns 201 JSON responses or throws HTTPException(422) caught by root app.onError.","Unmatched routes return status 404 while still executing outer onion middleware header mutations."],"goal":"verify pkg:npm/hono@4.13.13","kind":"HOW","packages":["pkg:npm/hono@4.13.13"],"schemaVersion":1,"symbols":["Hono","HTTPException","app.use","app.route","app.onError","app.request"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/hono@4.13.13"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.13","symbols":["Hono","HTTPException","app.use","app.route","app.onError","app.request"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-verify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-verify",
      "version": "1.0.0",
      "dependencies": {
        "hono": "4.13.13"
      }
    },
    "node_modules/hono": {
      "version": "4.13.13",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz",
      "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-verify",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "hono": "4.13.13"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/hono@4.13.13",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.13"
  ]
}
src/index.mjs
import { Hono } from 'hono';
import { HTTPException } from 'hono/http-exception';

export function buildRouter() {
  const app = new Hono();

  app.use('*', async (c, next) => {
    c.set('requestId', 'req-1001');
    await next();
    c.header('X-Request-Id', c.get('requestId'));
    c.header('X-Middleware-Complete', 'true');
  });

  const sub = new Hono();

  sub.get('/items/:group/:id', (c) => {
    const group = c.req.param('group');
    const id = c.req.param('id');
    const filter = c.req.query('filter') ?? 'none';
    const requestId = c.get('requestId');

    return c.json({
      group,
      id,
      filter,
      requestId,
    }, 200);
  });

  sub.post('/items', async (c) => {
    const payload = await c.req.json();
    if (!payload || typeof payload.name !== 'string' || payload.name.trim() === '') {
      throw new HTTPException(422, { message: 'Invalid item name' });
    }
    return c.json({
      created: true,
      name: payload.name.trim(),
      requestId: c.get('requestId'),
    }, 201);
  });

  app.route('/v1', sub);

  app.onError((err, c) => {
    const requestId = c.get('requestId') ?? 'missing';
    if (err instanceof HTTPException) {
      return c.json({
        error: err.message,
        status: err.status,
        requestId,
      }, err.status);
    }
    return c.json({ error: 'Unexpected failure', requestId }, 500);
  });

  return app;
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import { buildRouter } from '../src/index.mjs';

const app = buildRouter();

// 1. Sub-router GET with route parameters, query string, and onion middleware headers
const getRes = await app.request('http://localhost/v1/items/books/item-42?filter=active');
assert.equal(getRes.status, 200);
assert.equal(getRes.headers.get('x-request-id'), 'req-1001');
assert.equal(getRes.headers.get('x-middleware-complete'), 'true');
assert.deepEqual(await getRes.json(), {
  group: 'books',
  id: 'item-42',
  filter: 'active',
  requestId: 'req-1001',
});

// 2. Sub-router POST with valid JSON body
const postRes = await app.request('http://localhost/v1/items', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ name: ' notebook ' }),
});
assert.equal(postRes.status, 201);
assert.equal(postRes.headers.get('x-request-id'), 'req-1001');
assert.deepEqual(await postRes.json(), {
  created: true,
  name: 'notebook',
  requestId: 'req-1001',
});

// 3. Centralized error handling for HTTPException thrown in POST handler
const errRes = await app.request('http://localhost/v1/items', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ name: '   ' }),
});
assert.equal(errRes.status, 422);
assert.equal(errRes.headers.get('x-request-id'), 'req-1001');
assert.deepEqual(await errRes.json(), {
  error: 'Invalid item name',
  status: 422,
  requestId: 'req-1001',
});

// 4. Unmatched route returns 404 while preserving outer onion middleware headers
const missingRes = await app.request('http://localhost/v1/unknown');
assert.equal(missingRes.status, 404);
assert.equal(missingRes.headers.get('x-request-id'), 'req-1001');
assert.equal(missingRes.headers.get('x-middleware-complete'), 'true');

Seeder de origem

anônimo