CodeSampleX

Ejemplo

http-cache-semantics 4.3.0: fromObject

Muestra verificada para npm http-cache-semantics 4.3.0: fromObject. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó.

sha256:09a32619e1a290bfc1421baa3c705fefd3b34864375ade78b22ce4da5a49bacc

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

Entornos de las ejecuciones de verificación

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

Caso

HOW
Objetivo
verify http-cache-semantics.fromObject in pkg:npm/http-cache-semantics@4.3.0
Paquetes
Símbolos
  • http-cache-semantics.fromObject
Entorno
node
Creado
2026-10-18T00:32:43Z

Contrato

  1. CachePolicy.fromObject reconstructs a functional CachePolicy instance from a serialized state object
  2. Deserialized policy preserves caching decisions including storable and satisfiesWithoutRevalidation
  3. CachePolicy.fromObject correctly parses JSON-roundtripped serialization produced by toObject
  4. CachePolicy.fromObject rejects invalid serialization states with an Error matching Invalid serialization

Archivos

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

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: verify http-cache-semantics.fromObject in pkg:npm/http-cache-semantics@4.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/http-cache-semantics@4.3.0
Demonstrate these symbols/APIs:
  - http-cache-semantics.fromObject

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:4c64df226258ec3b93d6c3ac8839448cb435cd9661cef35ed5b0e74c09c5aa3b","contract":["CachePolicy.fromObject reconstructs a functional CachePolicy instance from a serialized state object","Deserialized policy preserves caching decisions including storable and satisfiesWithoutRevalidation","CachePolicy.fromObject correctly parses JSON-roundtripped serialization produced by toObject","CachePolicy.fromObject rejects invalid serialization states with an Error matching Invalid serialization"],"goal":"verify http-cache-semantics.fromObject in pkg:npm/http-cache-semantics@4.3.0","kind":"HOW","packages":["pkg:npm/http-cache-semantics@4.3.0"],"schemaVersion":1,"symbols":["http-cache-semantics.fromObject"]},"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","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/http-cache-semantics@4.3.0"],"schemaVersion":1,"subject":"pkg:npm/http-cache-semantics@4.3.0","symbols":["http-cache-semantics.fromObject"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "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.3.0"
      }
    },
    "node_modules/http-cache-semantics": {
      "version": "4.3.0",
      "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz",
      "integrity": "sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA==",
      "license": "BSD-2-Clause"
    }
  }
}
package.json
{
  "name": "sample-http-cache-semantics",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for http-cache-semantics@4.3.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "http-cache-semantics": "4.3.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify http-cache-semantics.fromObject in pkg:npm/http-cache-semantics@4.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/http-cache-semantics@4.3.0"
  ],
  "symbols": [
    "http-cache-semantics.fromObject"
  ]
}
src/index.js
'use strict';

const CachePolicy = require('http-cache-semantics');

function createPolicy(req, res, options) {
  return new CachePolicy(req, res, options);
}

function serializePolicy(policy) {
  return policy.toObject();
}

function deserializePolicy(obj) {
  return CachePolicy.fromObject(obj);
}

function isSatisfiedDirectly(policy, req) {
  return policy.satisfiesWithoutRevalidation(req);
}

module.exports = {
  CachePolicy,
  createPolicy,
  serializePolicy,
  deserializePolicy,
  isSatisfiedDirectly
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  CachePolicy,
  createPolicy,
  serializePolicy,
  deserializePolicy,
  isSatisfiedDirectly
} = require('../src/index.js');

async function testAll() {
  assert.equal(typeof CachePolicy, 'function', 'CachePolicy must be a constructor function');
  assert.equal(typeof CachePolicy.fromObject, 'function', 'CachePolicy.fromObject must be a static function');
  assert.equal(typeof createPolicy, 'function', 'createPolicy must be a function');
  assert.equal(typeof serializePolicy, 'function', 'serializePolicy must be a function');
  assert.equal(typeof deserializePolicy, 'function', 'deserializePolicy must be a function');
  assert.equal(typeof isSatisfiedDirectly, 'function', 'isSatisfiedDirectly must be a function');

  const req = {
    url: '/api/resource',
    method: 'GET',
    headers: {
      host: 'example.com',
      accept: 'application/json'
    }
  };

  const res = {
    status: 200,
    headers: {
      'cache-control': 'public, max-age=3600',
      'content-type': 'application/json',
      date: new Date().toUTCString(),
      etag: '"v1"'
    }
  };

  const policy = createPolicy(req, res, { shared: true });
  assert.equal(policy.storable(), true, 'policy should be storable');
  assert.equal(isSatisfiedDirectly(policy, req), true, 'policy should satisfy initial request directly');

  const serialized = serializePolicy(policy);
  assert.equal(typeof serialized, 'object', 'serialized policy must be an object');
  assert.equal(serialized.v, 1, 'serialization format version must be 1');
  assert.equal(serialized.m, 'GET', 'serialized method must match');
  assert.equal(serialized.u, '/api/resource', 'serialized url must match');

  const restoredPolicy = deserializePolicy(serialized);
  assert.ok(restoredPolicy instanceof CachePolicy, 'deserialized object must be an instance of CachePolicy');
  assert.equal(restoredPolicy.storable(), true, 'restored policy should be storable');
  assert.equal(restoredPolicy.satisfiesWithoutRevalidation(req), true, 'restored policy should satisfy original request');

  const nonMatchingReq = {
    url: '/api/other',
    method: 'GET',
    headers: { host: 'example.com' }
  };
  assert.equal(
    restoredPolicy.satisfiesWithoutRevalidation(nonMatchingReq),
    false,
    'restored policy must not satisfy a different URL'
  );

  const postReq = {
    url: '/api/resource',
    method: 'POST',
    headers: { host: 'example.com' }
  };
  assert.equal(
    restoredPolicy.satisfiesWithoutRevalidation(postReq),
    false,
    'restored policy must not satisfy a POST request'
  );

  const jsonString = JSON.stringify(serialized);
  const parsedObj = JSON.parse(jsonString);
  const jsonRestored = CachePolicy.fromObject(parsedObj);

  assert.ok(jsonRestored instanceof CachePolicy, 'json-restored instance must be CachePolicy');
  assert.equal(jsonRestored.storable(), true, 'json-restored policy must be storable');
  assert.equal(jsonRestored.satisfiesWithoutRevalidation(req), true, 'json-restored policy must satisfy request');
  assert.deepEqual(
    jsonRestored.toObject(),
    serialized,
    'round-tripped policy toObject() must deep-equal original serialization'
  );

  assert.throws(
    () => CachePolicy.fromObject({}),
    { message: /Invalid serialization/ },
    'fromObject({}) without version must throw Invalid serialization'
  );

  assert.throws(
    () => CachePolicy.fromObject({ v: 2 }),
    { message: /Invalid serialization/ },
    'fromObject with wrong version must throw Invalid serialization'
  );

  assert.throws(
    () => CachePolicy.fromObject(null),
    { message: /Response headers missing/ },
    'fromObject(null) falls through to constructor check and throws Response headers missing'
  );

  assert.throws(
    () => CachePolicy.fromObject(undefined),
    { message: /Response headers missing/ },
    'fromObject(undefined) falls through to constructor check and throws Response headers missing'
  );

  console.log('All http-cache-semantics.fromObject contract tests passed successfully.');
}

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

Seeder de origen

anónimo