CodeSampleX

Пример

hono 4.13.23

Проверенный пример — npm hono 4.13.23. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: Outer app.use middleware sets request context via…

sha256:e3b4ada04e4c2d0f29893444be4b5a418914c228fc54e382e0acb9f3218188db

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-11-28

Кейс

HOW
Цель
verify pkg:npm/hono@4.13.23
Пакеты
Окружение
node 22.23.2
Создан
2026-11-28T03:51:09Z

Контракт

  1. Outer app.use middleware sets request context via c.set() before await next() and appends the x-handled-trace response header via c.header() after downstream handlers finish.
  2. Sub-router mounted via app.basePath('/api').route('/items', router) reads path parameters via c.req.param(), query parameters via c.req.query(), and inherited middleware state via c.get().
  3. POST /api/items validates JSON bodies with hono/validator validator('json', ...), returning 201 with c.req.valid('json') on valid input and 400 on invalid input.
  4. Throwing HTTPException from hono/http-exception (409 on duplicate id, 404 on missing item) is handled by app.onError with JSON error payloads and preserved middleware headers.
  5. Unmatched routes invoke custom app.notFound returning 404 JSON while still running outer middleware post-processing.

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/app.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/hono@4.13.23
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.23
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:fcd3d9cf5dfa6c09b9c584b55af7ff88b61a8ce150fb27252b61b157d87094e7","constraints":{"executionContext":"node"},"contract":["Outer app.use middleware sets request context via c.set() before await next() and appends the x-handled-trace response header via c.header() after downstream handlers finish.","Sub-router mounted via app.basePath('/api').route('/items', router) reads path parameters via c.req.param(), query parameters via c.req.query(), and inherited middleware state via c.get().","POST /api/items validates JSON bodies with hono/validator validator('json', ...), returning 201 with c.req.valid('json') on valid input and 400 on invalid input.","Throwing HTTPException from hono/http-exception (409 on duplicate id, 404 on missing item) is handled by app.onError with JSON error payloads and preserved middleware headers.","Unmatched routes invoke custom app.notFound returning 404 JSON while still running outer middleware post-processing."],"goal":"verify pkg:npm/hono@4.13.23","kind":"HOW","packages":["pkg:npm/hono@4.13.23"],"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/hono@4.13.23"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.23","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "hono-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "hono-sample",
      "version": "1.0.0",
      "dependencies": {
        "hono": "4.13.23"
      }
    },
    "node_modules/hono": {
      "version": "4.13.23",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.23.tgz",
      "integrity": "sha512-OS90dj7dcsftEEWCOef8jRbnHE5lbrOq0hNRqjSyPsOnaGZvvfof1KS05hQNb4kUOCfDq1mG3PmHoX37DMnHQg==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "hono-sample",
  "version": "1.0.0",
  "private": true,
  "description": "Minimal CJS verification sample for hono@4.13.23",
  "main": "src/app.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "hono": "4.13.23"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/hono@4.13.23",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.23"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/app.js
'use strict';

const { Hono } = require('hono');
const { HTTPException } = require('hono/http-exception');
const { validator } = require('hono/validator');

function createApp() {
  const store = new Map([
    ['item-1', { id: 'item-1', name: 'Widget', count: 3 }],
  ]);

  const app = new Hono();

  // Outer middleware: set context state before next() and attach response header after next()
  app.use('*', async (c, next) => {
    const traceId = c.req.header('x-trace-id') || 'default-trace';
    c.set('traceId', traceId);
    await next();
    c.header('x-handled-trace', c.get('traceId'));
  });

  const itemsRouter = new Hono();

  itemsRouter.get('/:id', (c) => {
    const id = c.req.param('id');
    const item = store.get(id);
    if (!item) {
      throw new HTTPException(404, { message: `Item not found: ${id}` });
    }
    const includeMeta = c.req.query('meta') === '1';
    const body = includeMeta
      ? { ...item, traceId: c.get('traceId') }
      : item;
    return c.json(body, 200);
  });

  itemsRouter.post(
    '/',
    validator('json', (value, c) => {
      if (
        !value ||
        typeof value !== 'object' ||
        typeof value.id !== 'string' ||
        value.id.trim() === '' ||
        typeof value.name !== 'string' ||
        value.name.trim() === '' ||
        typeof value.count !== 'number' ||
        !Number.isInteger(value.count) ||
        value.count < 0
      ) {
        return c.json({ error: 'invalid_payload' }, 400);
      }
      return {
        id: value.id.trim(),
        name: value.name.trim(),
        count: value.count,
      };
    }),
    (c) => {
      const payload = c.req.valid('json');
      if (store.has(payload.id)) {
        throw new HTTPException(409, { message: 'Duplicate item id' });
      }
      store.set(payload.id, payload);
      return c.json({ created: payload, traceId: c.get('traceId') }, 201);
    }
  );

  const api = app.basePath('/api');
  api.route('/items', itemsRouter);

  app.onError((err, c) => {
    if (err instanceof HTTPException) {
      return c.json(
        { error: err.message, status: err.status, traceId: c.get('traceId') },
        err.status
      );
    }
    return c.json({ error: 'internal_error', status: 500 }, 500);
  });

  app.notFound((c) => {
    return c.json({ error: 'not_found', path: c.req.path }, 404);
  });

  return app;
}

module.exports = { createApp };
test/contract.js
'use strict';

const assert = require('node:assert/strict');
const { createApp } = require('../src/app.js');

async function main() {
  const app = createApp();

  // 1. GET existing item with path param, query param, and middleware context/header propagation
  {
    const res = await app.request('http://localhost/api/items/item-1?meta=1', {
      headers: { 'x-trace-id': 'trace-alpha' },
    });
    assert.equal(res.status, 200);
    assert.equal(res.headers.get('x-handled-trace'), 'trace-alpha');
    const body = await res.json();
    assert.deepEqual(body, {
      id: 'item-1',
      name: 'Widget',
      count: 3,
      traceId: 'trace-alpha',
    });
  }

  // 2. POST valid JSON passes validator('json') and returns 201 with created item
  {
    const res = await app.request('http://localhost/api/items', {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        'x-trace-id': 'trace-create',
      },
      body: JSON.stringify({ id: 'item-2', name: 'Gadget', count: 5 }),
    });
    assert.equal(res.status, 201);
    assert.equal(res.headers.get('x-handled-trace'), 'trace-create');
    const body = await res.json();
    assert.deepEqual(body, {
      created: { id: 'item-2', name: 'Gadget', count: 5 },
      traceId: 'trace-create',
    });
  }

  // 3. POST invalid JSON payload is rejected by validator('json') with 400
  {
    const res = await app.request('http://localhost/api/items', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ id: 'item-3', name: 'Bad', count: -1 }),
    });
    assert.equal(res.status, 400);
    assert.equal(res.headers.get('x-handled-trace'), 'default-trace');
    const body = await res.json();
    assert.deepEqual(body, { error: 'invalid_payload' });
  }

  // 4. POST duplicate id throws HTTPException(409) handled by app.onError
  {
    const res = await app.request('http://localhost/api/items', {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        'x-trace-id': 'trace-dup',
      },
      body: JSON.stringify({ id: 'item-2', name: 'Gadget', count: 5 }),
    });
    assert.equal(res.status, 409);
    assert.equal(res.headers.get('x-handled-trace'), 'trace-dup');
    const body = await res.json();
    assert.deepEqual(body, {
      error: 'Duplicate item id',
      status: 409,
      traceId: 'trace-dup',
    });
  }

  // 5. GET unknown item id throws HTTPException(404) handled by app.onError
  {
    const res = await app.request('http://localhost/api/items/missing-id', {
      headers: { 'x-trace-id': 'trace-missing' },
    });
    assert.equal(res.status, 404);
    assert.equal(res.headers.get('x-handled-trace'), 'trace-missing');
    const body = await res.json();
    assert.deepEqual(body, {
      error: 'Item not found: missing-id',
      status: 404,
      traceId: 'trace-missing',
    });
  }

  // 6. Unmatched route invokes custom app.notFound while preserving outer middleware header
  {
    const res = await app.request('http://localhost/unknown/path', {
      headers: { 'x-trace-id': 'trace-404' },
    });
    assert.equal(res.status, 404);
    assert.equal(res.headers.get('x-handled-trace'), 'trace-404');
    const body = await res.json();
    assert.deepEqual(body, { error: 'not_found', path: '/unknown/path' });
  }

  console.log('hono@4.13.23 contract checks passed');
}

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

Исходный сидер

аноним