CodeSampleX

샘플

hono 4.13.7: etag

검증된 샘플 — npm hono 4.13.7: etag. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: createApp configures Hono application with etag middleware…

sha256:3c83c6799e1c029c5e16de993a72ae4705dfd6734d0c244cde2bd0c524431c68

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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 etag in pkg:npm/hono@4.13.7
패키지
심벌
  • etag
생성일
2026-09-06T04:11:53Z

컨트랙트

  1. createApp configures Hono application with etag middleware supporting default, weak, custom digest, and custom retained headers policies
  2. etag middleware generates strong SHA-1 ETag by default and sets ETag response header on 200 responses
  3. etag middleware returns 304 Not Modified with empty body when matching If-None-Match header is provided
  4. etag middleware returns 304 Not Modified when wildcard If-None-Match is provided
  5. etag middleware generates weak ETag prefixed with W/ when weak option is enabled
  6. etag middleware computes custom hash using provided generateDigest function
  7. etag middleware retains only specified headers on 304 responses when retainedHeaders option is provided
  8. etag middleware does not set ETag response header on POST requests

파일

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

소스 아티팩트 내려받기 (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 etag 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:
  - etag

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:7a2fd54added3163fe134d66d147daf65304adcd0b3096bade1414a73d677e9c","contract":["createApp configures Hono application with etag middleware supporting default, weak, custom digest, and custom retained headers policies","etag middleware generates strong SHA-1 ETag by default and sets ETag response header on 200 responses","etag middleware returns 304 Not Modified with empty body when matching If-None-Match header is provided","etag middleware returns 304 Not Modified when wildcard If-None-Match is provided","etag middleware generates weak ETag prefixed with W/ when weak option is enabled","etag middleware computes custom hash using provided generateDigest function","etag middleware retains only specified headers on 304 responses when retainedHeaders option is provided","etag middleware does not set ETag response header on POST requests"],"goal":"verify etag in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["etag"]},"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":["etag"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-etag",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-etag",
      "version": "1.0.0",
      "license": "MIT-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"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-etag",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for etag in hono@4.13.7",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.13.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify etag in pkg:npm/hono@4.13.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.7"
  ],
  "symbols": [
    "etag"
  ]
}
src/index.js
'use strict';

const { Hono } = require('hono');
const { etag, RETAINED_304_HEADERS } = require('hono/etag');

/**
 * Creates and configures a Hono application demonstrating etag middleware.
 *
 * @returns {Hono}
 */
function createApp() {
  const app = new Hono();

  // 1. Default ETag middleware route (strong ETag with SHA-1)
  app.use('/default/*', etag());
  app.get('/default/hello', (c) => {
    return c.text('Hello Hono ETag');
  });

  // 2. Weak ETag middleware route (prefixed with W/)
  app.use('/weak/*', etag({ weak: true }));
  app.get('/weak/hello', (c) => {
    return c.text('Weak ETag content');
  });

  // 3. Custom digest generator
  app.use(
    '/custom-digest/*',
    etag({
      generateDigest: (body) => {
        return crypto.subtle.digest({ name: 'SHA-256' }, body);
      }
    })
  );
  app.get('/custom-digest/hello', (c) => {
    return c.text('Custom digest content');
  });

  // 4. Custom retained headers on 304 responses
  app.use(
    '/retained/*',
    etag({
      retainedHeaders: ['etag', 'x-custom-cache']
    })
  );
  app.get('/retained/hello', (c) => {
    c.header('X-Custom-Cache', 'custom-hit');
    c.header('X-Ignored-Header', 'should-be-dropped');
    return c.text('Retained headers content');
  });

  // 5. POST endpoint where ETag is not automatically generated
  app.use('/api/*', etag());
  app.post('/api/data', (c) => {
    return c.text('Created', 201);
  });

  return app;
}

module.exports = {
  createApp,
  Hono,
  etag,
  RETAINED_304_HEADERS
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  createApp,
  Hono,
  etag,
  RETAINED_304_HEADERS
} = require('../src/index.js');

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

  // 1. Export verification
  assert.equal(typeof createApp, 'function', 'createApp must be a function');
  assert.equal(typeof Hono, 'function', 'Hono must be a function');
  assert.equal(typeof etag, 'function', 'etag must be a function');
  assert.ok(Array.isArray(RETAINED_304_HEADERS), 'RETAINED_304_HEADERS must be an array');
  assert.ok(RETAINED_304_HEADERS.includes('etag'), 'RETAINED_304_HEADERS must include etag');
  assert.ok(RETAINED_304_HEADERS.includes('cache-control'), 'RETAINED_304_HEADERS must include cache-control');

  // 2. Default ETag middleware generates strong ETag and handles 304 matching
  const defaultRes = await app.fetch(new Request('http://localhost/default/hello'));
  assert.equal(defaultRes.status, 200, 'initial GET should return 200');
  const strongEtag = defaultRes.headers.get('ETag');
  assert.ok(strongEtag, 'ETag header must be present');
  assert.ok(!strongEtag.startsWith('W/'), 'default ETag must be a strong validator (no W/ prefix)');
  assert.ok(strongEtag.startsWith('"') && strongEtag.endsWith('"'), 'ETag must be quoted');
  const bodyText = await defaultRes.text();
  assert.equal(bodyText, 'Hello Hono ETag');

  // Matching If-None-Match returns 304 Not Modified with empty body
  const cachedRes = await app.fetch(
    new Request('http://localhost/default/hello', {
      headers: { 'If-None-Match': strongEtag }
    })
  );
  assert.equal(cachedRes.status, 304, 'matching If-None-Match must return 304 Not Modified');
  assert.equal(cachedRes.headers.get('ETag'), strongEtag, '304 response must retain ETag header');
  const cachedBody = await cachedRes.text();
  assert.equal(cachedBody, '', '304 response body must be empty');

  // Wildcard If-None-Match returns 304 Not Modified
  const wildcardRes = await app.fetch(
    new Request('http://localhost/default/hello', {
      headers: { 'If-None-Match': '*' }
    })
  );
  assert.equal(wildcardRes.status, 304, 'wildcard If-None-Match must return 304');

  // Mismatched If-None-Match returns 200 with full body
  const mismatchedRes = await app.fetch(
    new Request('http://localhost/default/hello', {
      headers: { 'If-None-Match': '"different-etag"' }
    })
  );
  assert.equal(mismatchedRes.status, 200, 'mismatched If-None-Match must return 200');
  const mismatchedBody = await mismatchedRes.text();
  assert.equal(mismatchedBody, 'Hello Hono ETag');

  // 3. Weak ETag validation
  const weakRes = await app.fetch(new Request('http://localhost/weak/hello'));
  assert.equal(weakRes.status, 200, 'weak endpoint returns 200');
  const weakEtag = weakRes.headers.get('ETag');
  assert.ok(weakEtag, 'weak ETag header must be present');
  assert.ok(weakEtag.startsWith('W/'), 'weak ETag must start with W/');

  const weakCachedRes = await app.fetch(
    new Request('http://localhost/weak/hello', {
      headers: { 'If-None-Match': weakEtag }
    })
  );
  assert.equal(weakCachedRes.status, 304, 'matching weak If-None-Match must return 304');

  // 4. Custom digest generator (e.g. SHA-256 producing 64-char hex hash)
  const customDigestRes = await app.fetch(new Request('http://localhost/custom-digest/hello'));
  assert.equal(customDigestRes.status, 200, 'custom digest endpoint returns 200');
  const customEtag = customDigestRes.headers.get('ETag');
  assert.ok(customEtag, 'custom digest ETag header must be present');
  assert.equal(customEtag.length, 66, 'SHA-256 digest hex length should be 64 plus quotes');

  const customCachedRes = await app.fetch(
    new Request('http://localhost/custom-digest/hello', {
      headers: { 'If-None-Match': customEtag }
    })
  );
  assert.equal(customCachedRes.status, 304, 'matching custom digest If-None-Match must return 304');

  // 5. Custom retained headers filtering on 304 responses
  const retainedInitial = await app.fetch(new Request('http://localhost/retained/hello'));
  assert.equal(retainedInitial.status, 200);
  assert.equal(retainedInitial.headers.get('X-Custom-Cache'), 'custom-hit');
  assert.equal(retainedInitial.headers.get('X-Ignored-Header'), 'should-be-dropped');
  const retainedEtag = retainedInitial.headers.get('ETag');

  const retainedCached = await app.fetch(
    new Request('http://localhost/retained/hello', {
      headers: { 'If-None-Match': retainedEtag }
    })
  );
  assert.equal(retainedCached.status, 304);
  assert.equal(retainedCached.headers.get('ETag'), retainedEtag);
  assert.equal(retainedCached.headers.get('X-Custom-Cache'), 'custom-hit', 'retained header must be preserved');
  assert.equal(retainedCached.headers.get('X-Ignored-Header'), null, 'unretained header must be stripped on 304');

  // 6. Non-GET methods do not receive automatic ETag headers
  const postRes = await app.fetch(
    new Request('http://localhost/api/data', {
      method: 'POST'
    })
  );
  assert.equal(postRes.status, 201, 'POST request returns 201');
  assert.equal(postRes.headers.get('ETag'), null, 'POST request must not include ETag header');

  console.log('All hono/etag contract assertions passed successfully.');
}

testAll().catch((err) => {
  console.error('Contract test failure:', err);
  process.exit(1);
});

오리진 시더

익명