CodeSampleX

示例

lru-cache 6.0.0: LRU.set

已验证示例 — npm lru-cache 6.0.0: LRU.set. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: LRUCache get, set, and has operations store values, evict least…

sha256:8ad93c52e727ab02715ee91a3b0d5f9c6ba383fd9c065b186ab66e453d324066

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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
包
符号
  • LRU.set
环境
node 22.23.2
创建时间
2026-08-20T07:22:25Z

契约

  1. LRUCache get, set, and has operations store values, evict least recently used entries upon reaching max capacity, and update recency order
  2. LRUCache custom length calculation tracks total items weight, enforces max capacity limit, and evicts entries when limit is exceeded
  3. LRUCache maxAge configuration with updateAgeOnGet and prune manages time-based entry expiration and stale entry cleanup
  4. LRUCache dispose callback executes on item eviction, deletion, and overwrites with key and value arguments
  5. LRUCache dump and load serialize and restore cache entries across instances while preserving entry expiration

文件

  • 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
Demonstrate these symbols/APIs:
  - LRU.set
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:5b48ab8a1c369b49aecdb412bd88384d1e3cd88497d86c20a02ef4180e02ce9c","constraints":{"executionContext":"node"},"contract":["LRUCache get, set, and has operations store values, evict least recently used entries upon reaching max capacity, and update recency order","LRUCache custom length calculation tracks total items weight, enforces max capacity limit, and evicts entries when limit is exceeded","LRUCache maxAge configuration with updateAgeOnGet and prune manages time-based entry expiration and stale entry cleanup","LRUCache dispose callback executes on item eviction, deletion, and overwrites with key and value arguments","LRUCache dump and load serialize and restore cache entries across instances while preserving entry expiration"],"goal":"verify pkg:npm/lru-cache@6.0.0","kind":"HOW","packages":["pkg:npm/lru-cache@6.0.0"],"schemaVersion":1,"symbols":["LRU.set"]},"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,"symbols":["LRU.set"],"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"
  ],
  "symbols": [
    "LRU.set"
  ],
  "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 instance with the specified options.
 *
 * @param {import('lru-cache').Options<any, any> | number} options
 * @returns {LRUCache}
 */
function createCache(options) {
  return new LRUCache(options);
}

/**
 * Creates an LRU cache with custom length/weight calculator.
 *
 * @param {number} max
 * @param {(value: any, key: any) => number} lengthCalculator
 * @returns {LRUCache}
 */
function createWeightedCache(max, lengthCalculator) {
  return new LRUCache({
    max,
    length: lengthCalculator,
  });
}

/**
 * Creates an LRU cache with time-to-live expiration.
 *
 * @param {number} max
 * @param {number} maxAge
 * @param {boolean} [updateAgeOnGet=false]
 * @returns {LRUCache}
 */
function createTimedCache(max, maxAge, updateAgeOnGet = false) {
  return new LRUCache({
    max,
    maxAge,
    updateAgeOnGet,
  });
}

/**
 * Serializes entries from an LRU cache.
 *
 * @param {LRUCache} cache
 * @returns {Array<{ k: any, v: any, e: number }>}
 */
function serializeCache(cache) {
  return cache.dump();
}

/**
 * Restores dumped entries into a new LRU cache instance.
 *
 * @param {import('lru-cache').Options<any, any> | number} options
 * @param {Array<{ k: any, v: any, e: number }>} entries
 * @returns {LRUCache}
 */
function restoreCache(options, entries) {
  const cache = new LRUCache(options);
  cache.load(entries);
  return cache;
}

module.exports = {
  LRUCache,
  createCache,
  createWeightedCache,
  createTimedCache,
  serializeCache,
  restoreCache,
};
test/contract.js
const assert = require('node:assert/strict');
const {
  LRUCache,
  createCache,
  createWeightedCache,
  createTimedCache,
  serializeCache,
  restoreCache,
} = require('../src/index.js');

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

async function main() {
  // Contract 1: LRUCache get, set, and has operations store values, evict least recently used entries upon reaching max capacity, and update recency order
  {
    const cache = createCache({ max: 3 });
    assert.strictEqual(cache.set('a', 1), true);
    assert.strictEqual(cache.set('b', 2), true);
    assert.strictEqual(cache.set('c', 3), true);

    assert.strictEqual(cache.itemCount, 3);
    assert.strictEqual(cache.has('a'), true);
    assert.strictEqual(cache.get('a'), 1);

    // Accessing 'a' makes 'b' the oldest (least recently used) entry
    cache.set('d', 4);
    assert.strictEqual(cache.has('b'), false, 'Key b should be evicted as least recently used');
    assert.strictEqual(cache.get('a'), 1);
    assert.strictEqual(cache.get('c'), 3);
    assert.strictEqual(cache.get('d'), 4);

    // peek reads without updating recency order
    assert.strictEqual(cache.peek('c'), 3);
    cache.set('e', 5);
    assert.strictEqual(cache.has('a'), false, 'Key a should be evicted next because peek on c did not touch recency');

    // del removes a key
    cache.del('d');
    assert.strictEqual(cache.has('d'), false);
    assert.strictEqual(cache.itemCount, 2);

    // reset clears all entries
    cache.reset();
    assert.strictEqual(cache.itemCount, 0);
  }

  // Contract 2: LRUCache custom length calculation tracks total items weight, enforces max capacity limit, and evicts entries when limit is exceeded
  {
    const cache = createWeightedCache(100, (value) => value.length);

    cache.set('item1', 'short'); // length 5
    cache.set('item2', 'x'.repeat(40)); // length 40
    cache.set('item3', 'y'.repeat(50)); // length 50

    assert.strictEqual(cache.length, 95);
    assert.strictEqual(cache.itemCount, 3);

    // Adding item4 (length 15) brings total length to 110 (> 100), triggering eviction of item1 and item2
    cache.set('item4', 'z'.repeat(15));
    assert.strictEqual(cache.has('item1'), false);
    assert.strictEqual(cache.has('item2'), false);
    assert.strictEqual(cache.has('item3'), true);
    assert.strictEqual(cache.has('item4'), true);
    assert.strictEqual(cache.length, 65);

    // Entry exceeding max capacity is rejected
    const oversized = 'w'.repeat(150);
    const added = cache.set('tooLarge', oversized);
    assert.strictEqual(added, false);
    assert.strictEqual(cache.has('tooLarge'), false);
    assert.strictEqual(cache.length, 65);
  }

  // Contract 3: LRUCache maxAge configuration with updateAgeOnGet and prune manages time-based entry expiration and stale entry cleanup
  {
    const cache = createTimedCache(10, 200, true);

    cache.set('temp1', 'val1');
    cache.set('temp2', 'val2');

    await delay(120);
    // Accessing temp1 resets its age
    assert.strictEqual(cache.get('temp1'), 'val1');

    await delay(120);
    // temp2 has exceeded 200ms TTL (240ms total), temp1 was refreshed at 120ms (now 120ms old < 200ms)
    assert.strictEqual(cache.has('temp2'), false, 'temp2 should expire after 240ms');
    assert.strictEqual(cache.get('temp2'), undefined);
    assert.strictEqual(cache.get('temp1'), 'val1', 'temp1 remains accessible due to updateAgeOnGet');

    // Setting entry with custom maxAge and testing prune
    cache.set('temp3', 'val3', 50);
    await delay(70);
    assert.strictEqual(cache.has('temp3'), false);
    assert.strictEqual(cache.itemCount, 2); // temp3 is still in Map before prune

    cache.prune();
    assert.strictEqual(cache.itemCount, 1); // prune sweeps expired items
  }

  // Contract 4: LRUCache dispose callback executes on item eviction, deletion, and overwrites with key and value arguments
  {
    const events = [];
    const cache = new LRUCache({
      max: 2,
      dispose: (key, value) => {
        events.push({ key, value });
      },
    });

    cache.set('k1', 'v1');
    cache.set('k2', 'v2');

    // Eviction on reaching capacity
    cache.set('k3', 'v3');
    assert.deepStrictEqual(events, [
      { key: 'k1', value: 'v1' },
    ]);

    // Overwriting existing key
    cache.set('k3', 'v3-updated');
    assert.deepStrictEqual(events, [
      { key: 'k1', value: 'v1' },
      { key: 'k3', value: 'v3' },
    ]);

    // Explicit deletion
    cache.del('k2');
    assert.deepStrictEqual(events, [
      { key: 'k1', value: 'v1' },
      { key: 'k3', value: 'v3' },
      { key: 'k2', value: 'v2' },
    ]);
  }

  // Contract 5: LRUCache dump and load serialize and restore cache entries across instances while preserving entry expiration
  {
    const sourceCache = createCache({ max: 5 });
    sourceCache.set('x', 10);
    sourceCache.set('y', 20);
    sourceCache.set('z', 30);

    const serialized = serializeCache(sourceCache);
    assert.ok(Array.isArray(serialized));
    assert.strictEqual(serialized.length, 3);

    const targetCache = restoreCache({ max: 5 }, serialized);
    assert.strictEqual(targetCache.get('x'), 10);
    assert.strictEqual(targetCache.get('y'), 20);
    assert.strictEqual(targetCache.get('z'), 30);
    assert.strictEqual(targetCache.itemCount, 3);
  }

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

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

原始种子者

匿名