CodeSampleX

Пример

lru-cache 6.0.0

Проверенный пример — npm lru-cache 6.0.0. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: LRUCache forEach and rforEach iterate entries…

sha256:995d32a9e702d870e256643bd88645702233bc06ceec3b83ce6799810bb95b6c

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

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

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

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

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

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

Кейс

HOW
Цель
verify pkg:npm/lru-cache@6.0.0
Пакеты
Окружение
node 22.23.2
Создан
2026-08-20T07:29:58Z

Контракт

  1. LRUCache forEach and rforEach iterate entries in most-recently-used and least-recently-used order without updating item recency
  2. LRUCache keys and values return arrays of keys and values in order from newest to oldest without mutating cache state
  3. LRUCache peek retrieves cached values and inspects items without updating use recency or triggering updateAgeOnGet
  4. LRUCache pop removes and returns the least recently used entry from the cache
  5. LRUCache noDisposeOnSet suppresses disposal callback during key overwrites while preserving disposal on eviction and deletion
  6. LRUCache stale and allowStale options return expired entries on get instead of returning undefined

Файлы

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

Скачать артефакт с исходным кодом (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/lru-cache@6.0.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/lru-cache@6.0.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:1ffd117f6273bc3e6d69e6920a835d78d5cf0bb9c40a123f11458853a850c969","constraints":{"executionContext":"node"},"contract":["LRUCache forEach and rforEach iterate entries in most-recently-used and least-recently-used order without updating item recency","LRUCache keys and values return arrays of keys and values in order from newest to oldest without mutating cache state","LRUCache peek retrieves cached values and inspects items without updating use recency or triggering updateAgeOnGet","LRUCache pop removes and returns the least recently used entry from the cache","LRUCache noDisposeOnSet suppresses disposal callback during key overwrites while preserving disposal on eviction and deletion","LRUCache stale and allowStale options return expired entries on get instead of returning undefined"],"goal":"verify pkg:npm/lru-cache@6.0.0","kind":"HOW","packages":["pkg:npm/lru-cache@6.0.0"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"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/lru-cache@6.0.0"],"schemaVersion":1,"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "lru-cache-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "lru-cache-sample",
      "version": "1.0.0",
      "dependencies": {
        "lru-cache": "6.0.0"
      }
    },
    "node_modules/lru-cache": {
      "version": "6.0.0",
      "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
      "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
      "license": "ISC",
      "dependencies": {
        "yallist": "^4.0.0"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/yallist": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
      "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
      "license": "ISC"
    }
  }
}
package.json
{
  "name": "lru-cache-sample",
  "version": "1.0.0",
  "dependencies": {
    "lru-cache": "6.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/lru-cache@6.0.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/lru-cache@6.0.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const LRUCache = require('lru-cache');

/**
 * Creates an LRU cache with iteration and non-mutating inspection utilities.
 *
 * @param {import('lru-cache').Options<any, any> | number} [options]
 * @returns {LRUCache}
 */
function createCache(options) {
  return new LRUCache(options);
}

/**
 * Collects entries in forward (MRU to LRU) order using forEach.
 *
 * @param {LRUCache} cache
 * @returns {Array<{ key: any, value: any }>}
 */
function collectForward(cache) {
  const entries = [];
  cache.forEach((value, key) => {
    entries.push({ key, value });
  });
  return entries;
}

/**
 * Collects entries in reverse (LRU to MRU) order using rforEach.
 *
 * @param {LRUCache} cache
 * @returns {Array<{ key: any, value: any }>}
 */
function collectReverse(cache) {
  const entries = [];
  cache.rforEach((value, key) => {
    entries.push({ key, value });
  });
  return entries;
}

/**
 * Creates an LRU cache with noDisposeOnSet enabled.
 *
 * @param {number} max
 * @param {(key: any, value: any) => void} dispose
 * @returns {LRUCache}
 */
function createNoDisposeOnSetCache(max, dispose) {
  return new LRUCache({
    max,
    dispose,
    noDisposeOnSet: true,
  });
}

/**
 * Creates an LRU cache that allows reading stale values.
 *
 * @param {number} max
 * @param {number} maxAge
 * @returns {LRUCache}
 */
function createStaleCache(max, maxAge) {
  return new LRUCache({
    max,
    maxAge,
    stale: true,
  });
}

module.exports = {
  LRUCache,
  createCache,
  collectForward,
  collectReverse,
  createNoDisposeOnSetCache,
  createStaleCache,
};
test/contract.js
const assert = require('node:assert/strict');
const {
  LRUCache,
  createCache,
  collectForward,
  collectReverse,
  createNoDisposeOnSetCache,
  createStaleCache,
} = require('../src/index.js');

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

async function main() {
  // Contract 1: LRUCache forEach and rforEach iterate entries in most-recently-used and least-recently-used order without updating item recency
  {
    const cache = createCache({ max: 5 });
    cache.set('first', 1);
    cache.set('second', 2);
    cache.set('third', 3);

    // forEach iterates from newest (MRU) to oldest (LRU)
    const forward = collectForward(cache);
    assert.deepStrictEqual(forward, [
      { key: 'third', value: 3 },
      { key: 'second', value: 2 },
      { key: 'first', value: 1 },
    ]);

    // rforEach iterates from oldest (LRU) to newest (MRU)
    const reverse = collectReverse(cache);
    assert.deepStrictEqual(reverse, [
      { key: 'first', value: 1 },
      { key: 'second', value: 2 },
      { key: 'third', value: 3 },
    ]);

    // Ensure iteration did not alter recency order
    // If recency was altered, the next insertion would evict a different element
    cache.set('fourth', 4);
    cache.set('fifth', 5);
    cache.set('sixth', 6); // Evicts oldest ('first')

    assert.strictEqual(cache.has('first'), false, 'Oldest entry first should be evicted');
    assert.strictEqual(cache.has('second'), true);
    assert.strictEqual(cache.has('third'), true);
    assert.strictEqual(cache.has('fourth'), true);
    assert.strictEqual(cache.has('fifth'), true);
    assert.strictEqual(cache.has('sixth'), true);
  }

  // Contract 2: LRUCache keys and values return arrays of keys and values in order from newest to oldest without mutating cache state
  {
    const cache = createCache({ max: 4 });
    cache.set('k1', 'v1');
    cache.set('k2', 'v2');
    cache.set('k3', 'v3');

    assert.deepStrictEqual(cache.keys(), ['k3', 'k2', 'k1']);
    assert.deepStrictEqual(cache.values(), ['v3', 'v2', 'v1']);
    assert.strictEqual(cache.itemCount, 3);

    // Reading keys and values does not mutate recency
    cache.set('k4', 'v4');
    cache.set('k5', 'v5'); // Capacity 4 reached; k1 was oldest and should be evicted
    assert.strictEqual(cache.has('k1'), false);
    assert.deepStrictEqual(cache.keys(), ['k5', 'k4', 'k3', 'k2']);
    assert.deepStrictEqual(cache.values(), ['v5', 'v4', 'v3', 'v2']);
  }

  // Contract 3: LRUCache peek retrieves cached values and inspects items without updating use recency or triggering updateAgeOnGet
  {
    const cache = createCache({ max: 2 });
    cache.set('a', 100);
    cache.set('b', 200);

    // Peek on 'a' returns value 100
    assert.strictEqual(cache.peek('a'), 100);

    // Since peek does not update recency, 'a' remains the least recently used
    // Adding 'c' must evict 'a', not 'b'
    cache.set('c', 300);
    assert.strictEqual(cache.has('a'), false, 'Key a should be evicted because peek does not update recency');
    assert.strictEqual(cache.has('b'), true);
    assert.strictEqual(cache.has('c'), true);

    // Peek on non-existent key returns undefined
    assert.strictEqual(cache.peek('nonexistent'), undefined);
  }

  // Contract 4: LRUCache pop removes and returns the least recently used entry from the cache
  {
    const cache = createCache({ max: 3 });
    cache.set('alpha', 10);
    cache.set('beta', 20);
    cache.set('gamma', 30);

    // Oldest item is 'alpha'
    const popped = cache.pop();
    assert.strictEqual(popped.key, 'alpha');
    assert.strictEqual(popped.value, 10);
    assert.strictEqual(cache.has('alpha'), false);
    assert.strictEqual(cache.itemCount, 2);

    // Next oldest item is 'beta'
    const poppedNext = cache.pop();
    assert.strictEqual(poppedNext.key, 'beta');
    assert.strictEqual(poppedNext.value, 20);
    assert.strictEqual(cache.itemCount, 1);

    // Empty cache pop returns null
    cache.pop();
    assert.strictEqual(cache.itemCount, 0);
    assert.strictEqual(cache.pop(), null);
  }

  // Contract 5: LRUCache noDisposeOnSet suppresses disposal callback during key overwrites while preserving disposal on eviction and deletion
  {
    const disposed = [];
    const cache = createNoDisposeOnSetCache(2, (key, value) => {
      disposed.push({ key, value });
    });

    cache.set('x', 1);
    cache.set('y', 2);

    // Overwriting 'x' should NOT trigger dispose because noDisposeOnSet is true
    cache.set('x', 10);
    assert.deepStrictEqual(disposed, [], 'Dispose should not be called when overwriting an existing key with noDisposeOnSet');

    // Eviction of 'y' when capacity exceeded DOES trigger dispose
    cache.set('z', 3);
    assert.deepStrictEqual(disposed, [{ key: 'y', value: 2 }], 'Eviction should trigger dispose');

    // Explicit del DOES trigger dispose
    cache.del('x');
    assert.deepStrictEqual(disposed, [
      { key: 'y', value: 2 },
      { key: 'x', value: 10 },
    ]);
  }

  // Contract 6: LRUCache stale and allowStale options return expired entries on get instead of returning undefined
  {
    const cache = createStaleCache(5, 100);
    cache.set('temp', 'preserved-stale');

    // Wait until maxAge has passed
    await delay(150);

    // has() returns false because item is stale
    assert.strictEqual(cache.has('temp'), false);

    // get() returns the stale value because stale: true is enabled
    assert.strictEqual(cache.get('temp'), 'preserved-stale');

    // Once retrieved as stale, it is evicted from cache
    assert.strictEqual(cache.get('temp'), undefined);
  }

  console.log('All pkg:npm/lru-cache@6.0.0 contracts passed successfully.');
}

main().catch(err => {
  console.error(err);
  process.exit(1);
});

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

аноним