CodeSampleX

Ejemplo

fresh 0.5.2: check HTTP response freshness with request and response headers using fresh

Muestra verificada para npm fresh 0.5.2: check HTTP response freshness with request and response headers using fresh. El contrato se ejecutó en node 22 …

sha256:612a4011131cfe30b4d974b6b2757da90660d06a9dd6facd643b7a59cd47204f

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-27

Caso

HOW
Objetivo
check HTTP response freshness with request and response headers using fresh
Paquetes
Símbolos
  • fresh
Creado
2026-08-27T14:06:47Z

Contrato

  1. fresh returns true when if-none-match request header matches response etag header
  2. fresh returns true when if-none-match matches response weak etag header (W/ prefix)
  3. fresh returns false when if-none-match does not match response etag header
  4. fresh returns true when if-modified-since request header is equal to or after response last-modified header
  5. fresh returns false when if-modified-since request header is before response last-modified header
  6. fresh returns false when cache-control request header contains no-cache
  7. fresh returns false for unconditional requests without if-none-match or if-modified-since headers

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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: check HTTP response freshness with request and response headers using fresh
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/fresh@0.5.2
Demonstrate these symbols/APIs:
  - fresh

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:9f6f02e2b4aef6c226c0505179a279937bfd386ffaaf247acc3fc6b9f93849c4","contract":["fresh returns true when if-none-match request header matches response etag header","fresh returns true when if-none-match matches response weak etag header (W/ prefix)","fresh returns false when if-none-match does not match response etag header","fresh returns true when if-modified-since request header is equal to or after response last-modified header","fresh returns false when if-modified-since request header is before response last-modified header","fresh returns false when cache-control request header contains no-cache","fresh returns false for unconditional requests without if-none-match or if-modified-since headers"],"goal":"check HTTP response freshness with request and response headers using fresh","kind":"HOW","packages":["pkg:npm/fresh@0.5.2"],"schemaVersion":1,"symbols":["fresh"]},"contractCommand":["node","test/contract.cjs"],"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/fresh@0.5.2"],"schemaVersion":1,"subject":"pkg:npm/fresh@0.5.2","symbols":["fresh"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const fresh = require('fresh');

/**
 * Checks whether a cached response is still fresh given request and response headers.
 *
 * @param {Record<string, string | undefined>} reqHeaders HTTP request headers
 * @param {Record<string, string | undefined>} resHeaders HTTP response headers
 * @returns {boolean} True if the client cache is fresh (304 Not Modified), false otherwise (200 OK)
 */
function isFresh(reqHeaders, resHeaders) {
  return fresh(reqHeaders, resHeaders);
}

module.exports = {
  isFresh,
  fresh
};
package-lock.json
{
  "name": "sample-fresh",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-fresh",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "fresh": "0.5.2"
      }
    },
    "node_modules/fresh": {
      "version": "0.5.2",
      "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
      "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.6"
      }
    }
  }
}
package.json
{
  "name": "sample-fresh",
  "version": "1.0.0",
  "private": true,
  "description": "check HTTP response freshness with request and response headers using fresh",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "fresh": "0.5.2"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "check HTTP response freshness with request and response headers using fresh",
  "kind": "HOW",
  "packages": [
    "pkg:npm/fresh@0.5.2"
  ],
  "symbols": [
    "fresh"
  ]
}
test/contract.cjs
'use strict';

const assert = require('assert');
const fresh = require('fresh');
const { isFresh } = require('../index.js');

function testFresh() {
  // 1. Matching strong ETag -> fresh (true)
  assert.strictEqual(
    fresh({ 'if-none-match': '"xyz123"' }, { 'etag': '"xyz123"' }),
    true,
    'matching etag should return true'
  );
  assert.strictEqual(
    isFresh({ 'if-none-match': '"xyz123"' }, { 'etag': '"xyz123"' }),
    true,
    'isFresh helper with matching etag should return true'
  );

  // 2. Matching weak ETag -> fresh (true)
  assert.strictEqual(
    fresh({ 'if-none-match': 'W/"xyz123"' }, { 'etag': '"xyz123"' }),
    true,
    'weak etag in request should match strong etag in response'
  );
  assert.strictEqual(
    fresh({ 'if-none-match': '"xyz123"' }, { 'etag': 'W/"xyz123"' }),
    true,
    'strong etag in request should match weak etag in response'
  );

  // 3. Mismatched ETag -> stale (false)
  assert.strictEqual(
    fresh({ 'if-none-match': '"abc999"' }, { 'etag': '"xyz123"' }),
    false,
    'mismatched etag should return false'
  );

  // 4. If-Modified-Since is equal to or newer than Last-Modified -> fresh (true)
  assert.strictEqual(
    fresh(
      { 'if-modified-since': 'Tue, 18 Aug 2026 12:00:00 GMT' },
      { 'last-modified': 'Tue, 18 Aug 2026 12:00:00 GMT' }
    ),
    true,
    'equal modified date should return true'
  );
  assert.strictEqual(
    fresh(
      { 'if-modified-since': 'Tue, 18 Aug 2026 13:00:00 GMT' },
      { 'last-modified': 'Tue, 18 Aug 2026 12:00:00 GMT' }
    ),
    true,
    'newer if-modified-since date should return true'
  );

  // 5. If-Modified-Since is older than Last-Modified -> stale (false)
  assert.strictEqual(
    fresh(
      { 'if-modified-since': 'Tue, 18 Aug 2026 11:00:00 GMT' },
      { 'last-modified': 'Tue, 18 Aug 2026 12:00:00 GMT' }
    ),
    false,
    'older if-modified-since date should return false'
  );

  // 6. Cache-Control: no-cache -> always stale (false)
  assert.strictEqual(
    fresh(
      { 'cache-control': 'no-cache', 'if-none-match': '"xyz123"' },
      { 'etag': '"xyz123"' }
    ),
    false,
    'cache-control no-cache should force return false'
  );

  // 7. Unconditional request -> stale (false)
  assert.strictEqual(
    fresh({}, { 'etag': '"xyz123"' }),
    false,
    'unconditional request should return false'
  );

  console.log('Contract tests passed successfully.');
}

try {
  testFresh();
  process.exit(0);
} catch (err) {
  console.error('Contract test failed:', err);
  process.exit(1);
}

Seeder de origen

anónimo