Exemplo
http-cache-semantics 4.2.0: evaluate HTTP request and response cache freshness and revalidation headers
Amostra verificada para npm http-cache-semantics 4.2.0: evaluate HTTP request and response cache freshness and revalidation headers. O contrato rodou em node…
sha256:982f82c954cea8abe34c7c02dbedcedc053b3f0d96ed43c84af05213311331c1
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 npm 10
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-08-28 |
Caso
HOW- Objetivo
- evaluate HTTP request and response cache freshness and revalidation headers
- Pacotes
- Símbolos
-
- CachePolicy
- Ambiente
- node 22.23.2
- Criado
- 2026-08-28T05:53:19Z
Contrato
- CachePolicy.storable evaluates whether an HTTP response can be stored in cache according to Cache-Control headers
- CachePolicy.stale evaluates whether a cached HTTP response has expired based on max-age
- CachePolicy.satisfiesWithoutRevalidation determines if a cached response can satisfy a new incoming HTTP request
- CachePolicy.revalidationHeaders generates conditional request headers including if-none-match for 304 revalidation
- CachePolicy.revalidatedPolicy returns updated policy instance merging cached headers with 304 revalidation response headers
Arquivos
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
Código-fonte
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: evaluate HTTP request and response cache freshness and revalidation headers
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/http-cache-semantics@4.2.0
Demonstrate these symbols/APIs:
- CachePolicy
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:8501183094d71489e86ef91f0e6500534a9579ee4b4e486a3f97d9d9a7c7fbaa","contract":["CachePolicy.storable evaluates whether an HTTP response can be stored in cache according to Cache-Control headers","CachePolicy.stale evaluates whether a cached HTTP response has expired based on max-age","CachePolicy.satisfiesWithoutRevalidation determines if a cached response can satisfy a new incoming HTTP request","CachePolicy.revalidationHeaders generates conditional request headers including if-none-match for 304 revalidation","CachePolicy.revalidatedPolicy returns updated policy instance merging cached headers with 304 revalidation response headers"],"goal":"evaluate HTTP request and response cache freshness and revalidation headers","kind":"HOW","packages":["pkg:npm/http-cache-semantics@4.2.0"],"schemaVersion":1,"symbols":["CachePolicy"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/http-cache-semantics@4.2.0"],"schemaVersion":1,"subject":"pkg:npm/http-cache-semantics@4.2.0","symbols":["CachePolicy"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-http-cache-semantics",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-http-cache-semantics",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"http-cache-semantics": "4.2.0"
}
},
"node_modules/http-cache-semantics": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",
"integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==",
"license": "BSD-2-Clause"
}
}
}
{
"name": "sample-http-cache-semantics",
"version": "1.0.0",
"private": true,
"description": "evaluate HTTP request and response cache freshness and revalidation headers",
"type": "module",
"main": "index.mjs",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"http-cache-semantics": "4.2.0"
},
"license": "MIT-0"
}
{
"schemaVersion": 1,
"goal": "evaluate HTTP request and response cache freshness and revalidation headers",
"kind": "HOW",
"packages": [
"pkg:npm/http-cache-semantics@4.2.0"
],
"symbols": [
"CachePolicy"
]
}
import CachePolicy from 'http-cache-semantics';
export { CachePolicy };
/**
* Creates a new CachePolicy instance.
* @param {object} request - Request representation { url, method, headers }
* @param {object} response - Response representation { status, headers }
* @param {object} [options] - CachePolicy options
* @returns {CachePolicy}
*/
export function createCachePolicy(request, response, options) {
return new CachePolicy(request, response, options);
}
/**
* Evaluates whether an HTTP request/response pair is storable in cache.
* @param {object} request - Request representation
* @param {object} response - Response representation
* @param {object} [options] - CachePolicy options
* @returns {boolean}
*/
export function isResponseStorable(request, response, options) {
const policy = new CachePolicy(request, response, options);
return policy.storable();
}
/**
* Checks if a cached policy is still fresh (not stale).
* @param {CachePolicy} policy
* @returns {boolean}
*/
export function isCacheFresh(policy) {
return !policy.stale();
}
/**
* Checks if a cached response satisfies a new incoming request without contacting origin.
* @param {CachePolicy} policy
* @param {object} request
* @returns {boolean}
*/
export function canSatisfyRequest(policy, request) {
return policy.satisfiesWithoutRevalidation(request);
}
/**
* Generates conditional request headers for cache revalidation.
* @param {CachePolicy} policy
* @param {object} request
* @returns {Record<string, string>}
*/
export function getRevalidationHeaders(policy, request) {
return policy.revalidationHeaders(request);
}
/**
* Revalidates a cached policy with a 304 or new response.
* @param {CachePolicy} policy
* @param {object} revalidationRequest
* @param {object} revalidationResponse
* @returns {{ policy: CachePolicy, modified: boolean, matches: boolean }}
*/
export function applyRevalidation(policy, revalidationRequest, revalidationResponse) {
return policy.revalidatedPolicy(revalidationRequest, revalidationResponse);
}
import assert from 'node:assert';
import CachePolicy from 'http-cache-semantics';
import {
createCachePolicy,
isResponseStorable,
isCacheFresh,
canSatisfyRequest,
getRevalidationHeaders,
applyRevalidation,
} from '../src/index.mjs';
function runContractTests() {
const req = {
url: 'https://example.com/api/items',
method: 'GET',
headers: {
accept: 'application/json',
},
};
const resFresh = {
status: 200,
headers: {
'cache-control': 'public, max-age=3600',
etag: '"v1-etag"',
'last-modified': 'Wed, 21 Oct 2025 07:28:00 GMT',
'content-type': 'application/json',
},
};
// 1. Contract: CachePolicy.storable evaluates whether an HTTP response can be stored in cache
const policyFresh = createCachePolicy(req, resFresh);
assert.strictEqual(policyFresh.storable(), true, 'Cacheable response must be storable');
assert.strictEqual(isResponseStorable(req, resFresh), true, 'Helper isResponseStorable must return true');
const resUnstorable = {
status: 200,
headers: {
'cache-control': 'no-store',
},
};
const policyUnstorable = createCachePolicy(req, resUnstorable);
assert.strictEqual(policyUnstorable.storable(), false, 'no-store response must not be storable');
assert.strictEqual(isResponseStorable(req, resUnstorable), false, 'Helper isResponseStorable must return false for no-store');
// 2. Contract: CachePolicy.stale evaluates whether a cached HTTP response has expired
assert.strictEqual(policyFresh.stale(), false, 'Fresh response must not be stale');
assert.strictEqual(isCacheFresh(policyFresh), true, 'Helper isCacheFresh must return true');
assert.strictEqual(policyFresh.timeToLive() > 0, true, 'timeToLive must be positive for fresh cache');
const resStale = {
status: 200,
headers: {
'cache-control': 'public, max-age=0',
etag: '"v1-etag"',
},
};
const policyStale = createCachePolicy(req, resStale);
assert.strictEqual(policyStale.stale(), true, 'max-age=0 response must be stale immediately');
assert.strictEqual(isCacheFresh(policyStale), false, 'Helper isCacheFresh must return false for stale response');
// 3. Contract: CachePolicy.satisfiesWithoutRevalidation determines if cached response satisfies a new request
assert.strictEqual(policyFresh.satisfiesWithoutRevalidation(req), true, 'Fresh cached response must satisfy matching GET request');
assert.strictEqual(canSatisfyRequest(policyFresh, req), true, 'Helper canSatisfyRequest must return true');
const reqDifferentMethod = {
url: 'https://example.com/api/items',
method: 'POST',
headers: {
accept: 'application/json',
},
};
assert.strictEqual(policyFresh.satisfiesWithoutRevalidation(reqDifferentMethod), false, 'Cached GET response must not satisfy POST request');
assert.strictEqual(policyStale.satisfiesWithoutRevalidation(req), false, 'Stale cached response must not satisfy request without revalidation');
// 4. Contract: CachePolicy.revalidationHeaders generates conditional request headers for 304 revalidation
const revalHeaders = policyStale.revalidationHeaders(req);
assert.strictEqual(revalHeaders['if-none-match'], '"v1-etag"', 'revalidationHeaders must include if-none-match matching etag');
const helperRevalHeaders = getRevalidationHeaders(policyStale, req);
assert.strictEqual(helperRevalHeaders['if-none-match'], '"v1-etag"', 'Helper getRevalidationHeaders must include etag');
// 5. Contract: CachePolicy.revalidatedPolicy returns updated policy merging cached headers with 304 response headers
const revalReq = {
url: 'https://example.com/api/items',
method: 'GET',
headers: revalHeaders,
};
const reval304Res = {
status: 304,
headers: {
'cache-control': 'public, max-age=7200',
etag: '"v1-etag"',
},
};
const revalidationResult = applyRevalidation(policyStale, revalReq, reval304Res);
assert.strictEqual(revalidationResult.matches, true, 'Revalidated 304 response must match policy');
assert.strictEqual(revalidationResult.modified, false, '304 Not Modified must indicate unmodified content');
assert.strictEqual(revalidationResult.policy.storable(), true, 'Revalidated policy must be storable');
assert.strictEqual(revalidationResult.policy.stale(), false, 'Revalidated policy with fresh max-age must not be stale');
// 6. Contract: Serialization and deserialization via toObject and fromObject
const serialized = policyFresh.toObject();
assert.strictEqual(typeof serialized, 'object', 'toObject must return an object');
const restoredPolicy = CachePolicy.fromObject(serialized);
assert.strictEqual(restoredPolicy.storable(), true, 'Restored policy must maintain storable state');
assert.strictEqual(restoredPolicy.stale(), false, 'Restored policy must maintain freshness state');
console.log('Contract tests passed successfully.');
}
runContractTests();
Seeder de origem
anônimo