샘플
hono 4.13.7: validator
검증된 샘플 — npm hono 4.13.7: validator. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: validator is exported as a middleware factory function from…
sha256:855b012a8bd0802de872ed834bd38431043423d8db33962546e4e96487616b10
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 1
- 빌드한 서명 키
- 1
선언된 환경
linux 24 · ubuntu · glibc 2.39 x64 npm
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| 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/validator in pkg:npm/hono@4.13.7
- 패키지
- 심벌
-
- hono/validator
- 생성일
- 2026-09-06T04:35:43Z
컨트랙트
- validator is exported as a middleware factory function from hono/validator
- validator validates and sanitizes JSON request body, providing validated data via c.req.valid('json')
- validator validates and transforms query parameters, providing validated data via c.req.valid('query')
- validator validates path parameters and short-circuits with custom error response when validation fails
- validator validates custom request headers, returning 401 when required header is missing or invalid
파일
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
소스
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/validator in pkg:npm/hono@4.13.7
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/hono@4.13.7
Demonstrate these symbols/APIs:
- hono/validator
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.
{"case":{"caseId":"case:sha256:e536335a6e11781a97e592a66e83b5a0935807127c04092a91591c8a867fad2a","contract":["validator is exported as a middleware factory function from hono/validator","validator validates and sanitizes JSON request body, providing validated data via c.req.valid('json')","validator validates and transforms query parameters, providing validated data via c.req.valid('query')","validator validates path parameters and short-circuits with custom error response when validation fails","validator validates custom request headers, returning 401 when required header is missing or invalid"],"goal":"verify hono/validator in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["hono/validator"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.7","symbols":["hono/validator"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-hono-validator",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-hono-validator",
"version": "1.0.0",
"dependencies": {
"hono": "4.13.7"
}
},
"node_modules/hono": {
"version": "4.13.7",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.13.7.tgz",
"integrity": "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ==",
"license": "MIT",
"engines": {
"node": ">=16.9.0"
}
}
}
}
{
"name": "sample-hono-validator",
"version": "1.0.0",
"private": true,
"description": "Clean-room verification for hono/validator in pkg:npm/hono@4.13.7",
"type": "module",
"dependencies": {
"hono": "4.13.7"
}
}
{
"schemaVersion": 1,
"goal": "verify hono/validator in pkg:npm/hono@4.13.7",
"kind": "HOW",
"packages": [
"pkg:npm/hono@4.13.7"
],
"symbols": [
"hono/validator"
]
}
import { Hono } from 'hono';
import { validator } from 'hono/validator';
/**
* Creates and configures a Hono application demonstrating hono/validator.
* @returns {Hono} Configured Hono application instance.
*/
export function createApp() {
const app = new Hono();
// Validate and sanitize JSON body for POST /api/posts
app.post(
'/api/posts',
validator('json', (value, c) => {
const title = value && typeof value.title === 'string' ? value.title.trim() : null;
const count = Number(value?.count);
if (!title || Number.isNaN(count) || count < 0) {
return c.json({ error: 'Invalid title or count' }, 400);
}
return { title, count };
}),
(c) => {
const validData = c.req.valid('json');
return c.json({ success: true, data: validData });
}
);
// Validate and transform query parameters for GET /api/search
app.get(
'/api/search',
validator('query', (value, c) => {
const limit = Number(value.limit);
const page = Number(value.page);
if (Number.isNaN(limit) || Number.isNaN(page) || limit <= 0 || page <= 0) {
return c.json({ error: 'Invalid query parameters' }, 400);
}
return { limit, page };
}),
(c) => {
const validQuery = c.req.valid('query');
return c.json({ limit: validQuery.limit, page: validQuery.page });
}
);
// Validate path parameter for GET /api/items/:id
app.get(
'/api/items/:id',
validator('param', (value, c) => {
const id = Number(value.id);
if (Number.isNaN(id) || id <= 0) {
return c.json({ error: 'Invalid numeric ID' }, 400);
}
return { id };
}),
(c) => {
const { id } = c.req.valid('param');
return c.json({ itemId: id });
}
);
// Validate custom request headers for GET /api/protected
app.get(
'/api/protected',
validator('header', (value, c) => {
const apiKey = value['x-api-key'];
if (!apiKey || apiKey !== 'secret-key-123') {
return c.text('Unauthorized Header', 401);
}
return { apiKey };
}),
(c) => {
const { apiKey } = c.req.valid('header');
return c.json({ authorized: true, apiKey });
}
);
return app;
}
export { validator };
import assert from 'node:assert/strict';
import { createApp, validator } from '../src/index.mjs';
import { validator as rawValidator } from 'hono/validator';
async function runContractTests() {
// 1. validator is exported as a middleware factory function from hono/validator
assert.equal(typeof validator, 'function', 'validator must be exported as a function');
assert.equal(typeof rawValidator, 'function', 'hono/validator must export validator function');
const mw = validator('json', (value) => value);
assert.equal(typeof mw, 'function', 'validator factory must return a middleware function');
const app = createApp();
// 2. validator validates and sanitizes JSON request body, providing validated data via c.req.valid('json')
{
const validRes = await app.request('http://localhost/api/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: ' Clean Code ', count: 5 })
});
assert.equal(validRes.status, 200, 'Valid JSON request should return 200');
const validData = await validRes.json();
assert.deepEqual(validData, { success: true, data: { title: 'Clean Code', count: 5 } });
const invalidRes = await app.request('http://localhost/api/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: '', count: -1 })
});
assert.equal(invalidRes.status, 400, 'Invalid JSON request should return 400');
const invalidData = await invalidRes.json();
assert.deepEqual(invalidData, { error: 'Invalid title or count' });
}
// 3. validator validates and transforms query parameters, providing validated data via c.req.valid('query')
{
const validRes = await app.request('http://localhost/api/search?limit=10&page=2');
assert.equal(validRes.status, 200, 'Valid query should return 200');
const validData = await validRes.json();
assert.deepEqual(validData, { limit: 10, page: 2 });
const invalidRes = await app.request('http://localhost/api/search?limit=abc&page=2');
assert.equal(invalidRes.status, 400, 'Invalid query should return 400');
const invalidData = await invalidRes.json();
assert.deepEqual(invalidData, { error: 'Invalid query parameters' });
}
// 4. validator validates path parameters and short-circuits with custom error response when validation fails
{
const validRes = await app.request('http://localhost/api/items/123');
assert.equal(validRes.status, 200, 'Valid param should return 200');
const validData = await validRes.json();
assert.deepEqual(validData, { itemId: 123 });
const invalidRes = await app.request('http://localhost/api/items/invalid-id');
assert.equal(invalidRes.status, 400, 'Invalid param should return 400');
const invalidData = await invalidRes.json();
assert.deepEqual(invalidData, { error: 'Invalid numeric ID' });
}
// 5. validator validates custom request headers, returning 401 when required header is missing or invalid
{
const validRes = await app.request('http://localhost/api/protected', {
headers: { 'x-api-key': 'secret-key-123' }
});
assert.equal(validRes.status, 200, 'Valid header should return 200');
const validData = await validRes.json();
assert.deepEqual(validData, { authorized: true, apiKey: 'secret-key-123' });
const invalidRes = await app.request('http://localhost/api/protected', {
headers: { 'x-api-key': 'wrong-key' }
});
assert.equal(invalidRes.status, 401, 'Invalid header should return 401');
const text = await invalidRes.text();
assert.equal(text, 'Unauthorized Header');
const missingRes = await app.request('http://localhost/api/protected');
assert.equal(missingRes.status, 401, 'Missing header should return 401');
}
console.log('All contracts for hono/validator in pkg:npm/hono@4.13.7 passed.');
}
await runContractTests();
오리진 시더
익명