CodeSampleX

Exemplo

http-cache-semantics 4.2.0: fromObject

Amostra verificada para npm http-cache-semantics 4.2.0: fromObject. O contrato rodou em node 22 · linux debian/x64 · docker e passou.

sha256:e2b275172a6ccb79e16fce03e16e6c16d2dec713d639a63f4e1926847e3c481f

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-05

Caso

HOW
Objetivo
verify http-cache-semantics.fromObject in pkg:npm/http-cache-semantics@4.2.0
Pacotes
Símbolos
  • http-cache-semantics.fromObject
Ambiente
node 22.23.2
Criado
2026-09-05T22:46:12Z

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

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

Use EXACTLY these public packages and versions:
  - pkg:npm/http-cache-semantics@4.2.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:4ffa572e9ce06f41cc00ea80f24e64bfad15abfffb565e1b292564b95b8ee801","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.2.0","kind":"HOW","packages":["pkg:npm/http-cache-semantics@4.2.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","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":["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.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"
    }
  }
}
package.json
{
  "name": "sample-http-cache-semantics",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for http-cache-semantics@4.2.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "http-cache-semantics": "4.2.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify http-cache-semantics.fromObject in pkg:npm/http-cache-semantics@4.2.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/http-cache-semantics@4.2.0"
  ],
  "symbols": [
    "http-cache-semantics.fromObject"
  ]
}
src/index.js
'use strict';

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

/**
 * Creates a new CachePolicy from request and response objects.
 *
 * @param {Object} req - Request object with method, url, and headers.
 * @param {Object} res - Response object with status and headers.
 * @param {Object} [options] - Cache policy options.
 * @returns {CachePolicy} Created cache policy instance.
 */
function createPolicy(req, res, options) {
  return new CachePolicy(req, res, options);
}

/**
 * Serializes a CachePolicy instance into a plain JSON-serializable object.
 *
 * @param {CachePolicy} policy - CachePolicy instance to serialize.
 * @returns {Object} Serialized policy object.
 */
function serializePolicy(policy) {
  return policy.toObject();
}

/**
 * Reconstructs a CachePolicy instance from a serialized object.
 *
 * @param {Object} obj - Serialized policy object previously produced by toObject().
 * @returns {CachePolicy} Reconstructed CachePolicy instance.
 */
function deserializePolicy(obj) {
  return CachePolicy.fromObject(obj);
}

/**
 * Evaluates whether a cached policy satisfies a subsequent incoming request without revalidation.
 *
 * @param {CachePolicy} policy - CachePolicy instance to evaluate.
 * @param {Object} req - Incoming request object.
 * @returns {boolean} True if the cached response satisfies the request directly.
 */
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() {
  // 1. Export verification
  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');

  // Prepare standard sample request and response objects
  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"'
    }
  };

  // 2. Original policy creation and baseline verification
  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');

  // 3. Serialization and Deserialization via CachePolicy.fromObject
  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');

  // Verify non-matching requests are rejected by restored policy
  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'
  );

  // 4. JSON round-trip verification (stringifying and parsing serialized state)
  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'
  );

  // 5. Rejection of invalid serialized input
  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 origem

anônimo