CodeSampleX

Пример

cacheable-request 7.0.4

Проверенный пример — npm cacheable-request 7.0.4. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: CacheableRequest constructor requires a…

sha256:e25aac6f00e34175a95fe9f0dcb4bfe2b8b790dd2f13f496a5d60c9cd3253f4d

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-26

Кейс

HOW
Цель
verify pkg:npm/cacheable-request@7.0.4
Пакеты
Создан
2026-08-26T09:17:48Z

Контракт

  1. CacheableRequest constructor requires a function for request parameter
  2. CacheableRequest exposes RequestError and CacheError error classes
  3. First request fetches from origin server and caches response
  4. Second identical request returns response from cache without origin server request
  5. forceRefresh option bypasses cache and fetches fresh response from origin
  6. Responses with no-store cache control header are not stored in cache
  7. Custom cache storage store can be provided to CacheableRequest constructor
  8. CacheableRequest emits error event with RequestError on connection failures

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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 pkg:npm/cacheable-request@7.0.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/cacheable-request@7.0.4

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:3da2714796dee7b81c73f302d0f852cb9eb12f28b74f03f2fc1f03d42499c33d","contract":["CacheableRequest constructor requires a function for request parameter","CacheableRequest exposes RequestError and CacheError error classes","First request fetches from origin server and caches response","Second identical request returns response from cache without origin server request","forceRefresh option bypasses cache and fetches fresh response from origin","Responses with no-store cache control header are not stored in cache","Custom cache storage store can be provided to CacheableRequest constructor","CacheableRequest emits error event with RequestError on connection failures"],"goal":"verify pkg:npm/cacheable-request@7.0.4","kind":"HOW","packages":["pkg:npm/cacheable-request@7.0.4"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"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/cacheable-request@7.0.4"],"schemaVersion":1,"subject":"pkg:npm/cacheable-request@7.0.4","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-cacheable-request",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-cacheable-request",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "cacheable-request": "7.0.4"
      }
    },
    "node_modules/cacheable-request": {
      "version": "7.0.4",
      "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz",
      "integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==",
      "license": "MIT",
      "dependencies": {
        "clone-response": "^1.0.2",
        "get-stream": "^5.1.0",
        "http-cache-semantics": "^4.0.0",
        "keyv": "^4.0.0",
        "lowercase-keys": "^2.0.0",
        "normalize-url": "^6.0.1",
        "responselike": "^2.0.0"
      },
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/clone-response": {
      "version": "1.0.3",
      "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz",
      "integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==",
      "license": "MIT",
      "dependencies": {
        "mimic-response": "^1.0.0"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/end-of-stream": {
      "version": "1.4.5",
      "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
      "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
      "license": "MIT",
      "dependencies": {
        "once": "^1.4.0"
      }
    },
    "node_modules/get-stream": {
      "version": "5.2.0",
      "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
      "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",
      "license": "MIT",
      "dependencies": {
        "pump": "^3.0.0"
      },
      "engines": {
        "node": ">=8"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "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"
    },
    "node_modules/json-buffer": {
      "version": "3.0.1",
      "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
      "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",
      "license": "MIT"
    },
    "node_modules/keyv": {
      "version": "4.5.4",
      "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
      "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",
      "license": "MIT",
      "dependencies": {
        "json-buffer": "3.0.1"
      }
    },
    "node_modules/lowercase-keys": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",
      "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/mimic-response": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz",
      "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==",
      "license": "MIT",
      "engines": {
        "node": ">=4"
      }
    },
    "node_modules/normalize-url": {
      "version": "6.1.0",
      "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",
      "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==",
      "license": "MIT",
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/once": {
      "version": "1.4.0",
      "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
      "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
      "license": "ISC",
      "dependencies": {
        "wrappy": "1"
      }
    },
    "node_modules/pump": {
      "version": "3.0.4",
      "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
      "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
      "license": "MIT",
      "dependencies": {
        "end-of-stream": "^1.1.0",
        "once": "^1.3.1"
      }
    },
    "node_modules/responselike": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz",
      "integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==",
      "license": "MIT",
      "dependencies": {
        "lowercase-keys": "^2.0.0"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/wrappy": {
      "version": "1.0.2",
      "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
      "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
      "license": "ISC"
    }
  }
}
package.json
{
  "name": "sample-cacheable-request",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for cacheable-request@7.0.4",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "cacheable-request": "7.0.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/cacheable-request@7.0.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/cacheable-request@7.0.4"
  ]
}
src/index.js
const CacheableRequest = require('cacheable-request');

/**
 * Creates a cacheable request function wrapping a standard HTTP request function.
 *
 * @param {Function} request - The underlying request function (e.g., http.request).
 * @param {Object|string} [cacheAdapter] - Optional cache storage adapter or connection string for Keyv.
 * @returns {Function} Function to execute cacheable HTTP requests.
 */
function createCacheableRequest(request, cacheAdapter) {
  return new CacheableRequest(request, cacheAdapter);
}

module.exports = {
  CacheableRequest,
  createCacheableRequest,
  RequestError: CacheableRequest.RequestError,
  CacheError: CacheableRequest.CacheError
};
test/contract.mjs
import assert from 'node:assert/strict';
import http from 'node:http';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  CacheableRequest,
  createCacheableRequest,
  RequestError,
  CacheError
} = require('../src/index.js');

async function readStream(stream) {
  const chunks = [];
  for await (const chunk of stream) {
    chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
  }
  return Buffer.concat(chunks).toString('utf8');
}

async function testAll() {
  // 1. CacheableRequest constructor requires a function for request parameter
  assert.throws(
    () => new CacheableRequest('not-a-function'),
    {
      name: 'TypeError',
      message: 'Parameter `request` must be a function'
    },
    'Should throw TypeError when request parameter is not a function'
  );

  // 2. CacheableRequest exposes RequestError and CacheError error classes
  assert.equal(typeof RequestError, 'function', 'RequestError should be a constructor function');
  assert.equal(typeof CacheError, 'function', 'CacheError should be a constructor function');
  const reqErr = new RequestError(new Error('connection reset'));
  assert.equal(reqErr.name, 'RequestError');
  assert.equal(reqErr.message, 'connection reset');
  const cacheErr = new CacheError(new Error('store failure'));
  assert.equal(cacheErr.name, 'CacheError');
  assert.equal(cacheErr.message, 'store failure');

  // Start an offline local HTTP server for cache testing
  let hitCount = 0;
  const server = http.createServer((req, res) => {
    hitCount += 1;
    if (req.url === '/cacheable') {
      res.writeHead(200, {
        'Content-Type': 'application/json',
        'Cache-Control': 'public, max-age=3600',
        'ETag': '"sample-etag-v1"'
      });
      res.end(JSON.stringify({ hit: hitCount, payload: 'hello-cache' }));
    } else if (req.url === '/no-cache') {
      res.writeHead(200, {
        'Content-Type': 'text/plain',
        'Cache-Control': 'no-store'
      });
      res.end('no-store-body');
    } else {
      res.writeHead(404);
      res.end('not found');
    }
  });

  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  const port = server.address().port;
  const baseUrl = `http://127.0.0.1:${port}`;

  try {
    const cacheableRequest = createCacheableRequest(http.request);

    // 3. First request fetches from origin server and caches response
    const firstResponseData = await new Promise((resolve, reject) => {
      const cacheReq = cacheableRequest(`${baseUrl}/cacheable`, async (res) => {
        try {
          const body = await readStream(res);
          resolve({ res, body: JSON.parse(body) });
        } catch (err) {
          reject(err);
        }
      });
      cacheReq.on('error', reject);
      cacheReq.on('request', (req) => req.end());
    });

    assert.equal(firstResponseData.res.statusCode, 200);
    assert.equal(firstResponseData.res.fromCache, false, 'First response must not be from cache');
    assert.equal(firstResponseData.body.hit, 1);
    assert.equal(hitCount, 1, 'Server should have received 1 request');

    // 4. Second identical request returns response from cache without origin server request
    const secondResponseData = await new Promise((resolve, reject) => {
      const cacheReq = cacheableRequest(`${baseUrl}/cacheable`, async (res) => {
        try {
          const body = await readStream(res);
          resolve({ res, body: JSON.parse(body) });
        } catch (err) {
          reject(err);
        }
      });
      cacheReq.on('error', reject);
      cacheReq.on('request', (req) => req.end());
    });

    assert.equal(secondResponseData.res.statusCode, 200);
    assert.equal(secondResponseData.res.fromCache, true, 'Second response must be served from cache');
    assert.equal(secondResponseData.body.hit, 1, 'Body should contain original cached hit count');
    assert.equal(hitCount, 1, 'Server hit count should remain 1 because cache was used');

    // 5. forceRefresh option bypasses cache and fetches fresh response from origin
    const refreshResponseData = await new Promise((resolve, reject) => {
      const cacheReq = cacheableRequest({
        hostname: '127.0.0.1',
        port: port,
        path: '/cacheable',
        forceRefresh: true
      }, async (res) => {
        try {
          const body = await readStream(res);
          resolve({ res, body: JSON.parse(body) });
        } catch (err) {
          reject(err);
        }
      });
      cacheReq.on('error', reject);
      cacheReq.on('request', (req) => req.end());
    });

    assert.equal(refreshResponseData.res.statusCode, 200);
    assert.equal(refreshResponseData.res.fromCache, false, 'Refreshed response must not be from cache');
    assert.equal(refreshResponseData.body.hit, 2, 'Refreshed response body should show updated hit count');
    assert.equal(hitCount, 2, 'Server hit count should increment to 2');

    // 6. Responses with no-store cache control header are not stored in cache
    const noStoreFirst = await new Promise((resolve, reject) => {
      const cacheReq = cacheableRequest(`${baseUrl}/no-cache`, async (res) => {
        try {
          const body = await readStream(res);
          resolve({ res, body });
        } catch (err) {
          reject(err);
        }
      });
      cacheReq.on('error', reject);
      cacheReq.on('request', (req) => req.end());
    });
    assert.equal(noStoreFirst.res.fromCache, false);

    const noStoreSecond = await new Promise((resolve, reject) => {
      const cacheReq = cacheableRequest(`${baseUrl}/no-cache`, async (res) => {
        try {
          const body = await readStream(res);
          resolve({ res, body });
        } catch (err) {
          reject(err);
        }
      });
      cacheReq.on('error', reject);
      cacheReq.on('request', (req) => req.end());
    });
    assert.equal(noStoreSecond.res.fromCache, false, 'no-store response should not be served from cache');

    // 7. Custom cache storage store can be provided to CacheableRequest constructor
    const customStore = new Map();
    const customCacheableRequest = createCacheableRequest(http.request, customStore);
    const customResponseData = await new Promise((resolve, reject) => {
      const cacheReq = customCacheableRequest(`${baseUrl}/cacheable`, async (res) => {
        try {
          const body = await readStream(res);
          resolve({ res, body: JSON.parse(body) });
        } catch (err) {
          reject(err);
        }
      });
      cacheReq.on('error', reject);
      cacheReq.on('request', (req) => req.end());
    });
    assert.equal(customResponseData.res.statusCode, 200);
    assert.ok(customStore.size > 0, 'Custom cache store should contain cached entries');

  } finally {
    await new Promise((resolve) => server.close(resolve));
  }

  // 8. CacheableRequest emits error event with RequestError on connection failures
  const failingRequest = createCacheableRequest(http.request);
  const errorHandled = await new Promise((resolve) => {
    const cacheReq = failingRequest('http://127.0.0.1:1/unreachable', () => {});
    cacheReq.on('error', (err) => {
      resolve(err);
    });
    cacheReq.on('request', (req) => {
      req.on('error', () => {});
      req.end();
    });
  });
  assert.ok(errorHandled instanceof Error, 'Should emit an error on failed connection');
  assert.equal(errorHandled.name, 'RequestError', 'Error name should be RequestError');

  console.log('All cacheable-request contract tests passed successfully.');
}

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

Исходный сидер

аноним