CodeSampleX

Exemplo

hono 4.13.7: etag

Amostra verificada para npm hono 4.13.7: etag. O contrato rodou em node 22 · linux debian/x64 · docker e passou: createApp configures Hono application with…

sha256:54fa0ff40c3407d88a6597e75db3e7910d76034de5b27d4f476ed9793e08d166

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

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-09-06

Caso

HOW
Objetivo
verify hono.etag in pkg:npm/hono@4.13.7
Pacotes
Símbolos
  • hono.etag
Ambiente
node 22.23.2
Criado
2026-09-06T04:05:45Z

Contrato

  1. createApp configures Hono application with etag middleware supporting strong and weak entity tags
  2. etag middleware generates strong ETag header and returns 200 for initial GET request
  3. etag middleware returns 304 Not Modified with empty body when If-None-Match matches response ETag
  4. etag middleware returns 200 with new payload when If-None-Match does not match response ETag
  5. etag middleware generates weak ETag formatted with W/ prefix when weak option is enabled
  6. etag middleware preserves specified retained headers and removes unlisted headers on 304 response
  7. etag middleware does not generate ETag headers for non-cacheable HTTP methods such as POST

Arquivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 hono.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:
  - hono.etag
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:2f5288a54519812b8e91b873c19f53a22b0dc119ebc0258a0bac643a72ee2ed2","constraints":{"executionContext":"node"},"contract":["createApp configures Hono application with etag middleware supporting strong and weak entity tags","etag middleware generates strong ETag header and returns 200 for initial GET request","etag middleware returns 304 Not Modified with empty body when If-None-Match matches response ETag","etag middleware returns 200 with new payload when If-None-Match does not match response ETag","etag middleware generates weak ETag formatted with W/ prefix when weak option is enabled","etag middleware preserves specified retained headers and removes unlisted headers on 304 response","etag middleware does not generate ETag headers for non-cacheable HTTP methods such as POST"],"goal":"verify hono.etag in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["hono.etag"]},"contractCommand":["node","test/contract.mjs"],"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.7"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.7","symbols":["hono.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 verification of hono.etag in pkg:npm/hono@4.13.7",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.13.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify hono.etag in pkg:npm/hono@4.13.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.7"
  ],
  "symbols": [
    "hono.etag"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
'use strict';

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

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

  // 1. Route with default strong ETag middleware
  app.use('/strong/*', etag());
  app.get('/strong/resource', (c) => {
    return c.text('Strong ETag content payload');
  });

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

  // 3. Route with custom retained headers on 304 response
  app.use(
    '/custom-retained/*',
    etag({
      retainedHeaders: [...RETAINED_304_HEADERS, 'x-custom-cache']
    })
  );
  app.get('/custom-retained/resource', (c) => {
    c.header('X-Custom-Cache', 'hit-candidate');
    c.header('X-Ignored-Header', 'should-be-removed');
    return c.text('Content with custom headers');
  });

  // 4. Route with non-GET method (POST) to verify ETag is not generated
  app.post('/strong/action', (c) => {
    return c.text('Action completed');
  });

  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 exported');
  assert.equal(typeof etag, 'function', 'etag middleware must be exported');
  assert.ok(Array.isArray(RETAINED_304_HEADERS), 'RETAINED_304_HEADERS must be an array');

  // 2. Strong ETag generation on initial GET request
  const res1 = await app.request('/strong/resource');
  assert.equal(res1.status, 200, 'Initial request should return status 200');
  const etag1 = res1.headers.get('ETag');
  assert.ok(etag1, 'Response must include ETag header');
  assert.ok(
    etag1.startsWith('"') && !etag1.startsWith('W/'),
    'Strong ETag must be enclosed in quotes without W/ prefix'
  );
  const body1 = await res1.text();
  assert.equal(body1, 'Strong ETag content payload');

  // 3. 304 Not Modified when If-None-Match matches ETag
  const res2 = await app.request('/strong/resource', {
    headers: { 'If-None-Match': etag1 }
  });
  assert.equal(res2.status, 304, 'Matching If-None-Match must return 304 Not Modified');
  assert.equal(res2.headers.get('ETag'), etag1, '304 response must retain ETag header');
  const body2 = await res2.text();
  assert.equal(body2, '', '304 response body must be empty');

  // 4. 200 OK when If-None-Match does not match ETag
  const res3 = await app.request('/strong/resource', {
    headers: { 'If-None-Match': '"mismatch-etag-value"' }
  });
  assert.equal(res3.status, 200, 'Mismatched If-None-Match must return 200');
  assert.equal(res3.headers.get('ETag'), etag1, 'Response must provide current ETag');
  const body3 = await res3.text();
  assert.equal(body3, 'Strong ETag content payload');

  // 5. Weak ETag generation with W/ prefix and matching
  const res4 = await app.request('/weak/resource');
  assert.equal(res4.status, 200, 'Initial weak request should return 200');
  const etagWeak = res4.headers.get('ETag');
  assert.ok(etagWeak, 'Weak response must include ETag header');
  assert.ok(etagWeak.startsWith('W/"'), 'Weak ETag must start with W/" prefix');

  const res5 = await app.request('/weak/resource', {
    headers: { 'If-None-Match': etagWeak }
  });
  assert.equal(res5.status, 304, 'Weak ETag match must return 304 Not Modified');
  assert.equal(res5.headers.get('ETag'), etagWeak);

  // 6. Custom retained headers on 304 response
  const resCustomInitial = await app.request('/custom-retained/resource');
  assert.equal(resCustomInitial.status, 200);
  const customEtag = resCustomInitial.headers.get('ETag');
  assert.ok(customEtag);

  const resCustom304 = await app.request('/custom-retained/resource', {
    headers: { 'If-None-Match': customEtag }
  });
  assert.equal(resCustom304.status, 304);
  assert.equal(
    resCustom304.headers.get('X-Custom-Cache'),
    'hit-candidate',
    'Custom retained header must be preserved in 304 response'
  );
  assert.equal(
    resCustom304.headers.get('X-Ignored-Header'),
    null,
    'Unretained header must be removed from 304 response'
  );

  // 7. Non-GET method (POST) must not receive ETag
  const resPost = await app.request('/strong/action', {
    method: 'POST'
  });
  assert.equal(resPost.status, 200);
  assert.equal(resPost.headers.get('ETag'), null, 'POST request must not have ETag header');

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

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

Seeder de origem

anônimo