Пример
http-cache-semantics 4.3.0: fromObject
Проверенный пример — npm http-cache-semantics 4.3.0: fromObject. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.
sha256:09a32619e1a290bfc1421baa3c705fefd3b34864375ade78b22ce4da5a49bacc
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 1
- Ключи подписи, собравшие его
- 1
Заявленная среда
node linux 24 · ubuntu · glibc 2.39 x64 node javascript npm
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| 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 |
Кейс
HOW- Цель
- verify http-cache-semantics.fromObject in pkg:npm/http-cache-semantics@4.3.0
- Пакеты
- Символы
-
- http-cache-semantics.fromObject
- Окружение
- node
- Создан
- 2026-10-18T00:32:43Z
Контракт
- 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
Файлы
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.js
- test/contract.mjs
Исходный код
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.
{"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"}
{
"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"
}
}
}
{
"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"
}
}
{
"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"
]
}
'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
};
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);
});
Исходный сидер
аноним