CodeSampleX

샘플

lru-cache 11.5.3

검증된 샘플 — npm lru-cache 11.5.3. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: require('lru-cache') exports LRUCache in CommonJS and constructor…

sha256:25e97073113eab4e6fcdae27d3e83be61cf0edeb6c4f0ba04e2e9c7ca80e0fb2

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
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-11-21

케이스

HOW
목표
verify pkg:npm/lru-cache@11.5.3
패키지
환경
node 22.23.2
생성일
2026-11-21T17:30:11Z

컨트랙트

  1. require('lru-cache') exports LRUCache in CommonJS and constructor throws TypeError when no capacity limit is provided
  2. LRU eviction removes the least recently used entry, get() promotes recency while peek() preserves order, and dispose receives evict, set, and delete reasons
  3. maxSize and maxEntrySize enforce sizeCalculation bounds, rejecting oversized items with status.maxEntrySizeExceeded and maintaining calculatedSize
  4. deterministic TTL tracking via custom perf clock with ttlResolution: 0 reports getRemainingTTL, preserves expired entries under allowStale with noDeleteOnStaleGet, and clears them via purgeStale()
  5. memo() caches memoMethod results with status.memo miss/hit reporting and dump()/load() round-trips entries in MRU order
  6. fetch() coalesces concurrent requests per key, allowStaleOnFetchRejection returns stale values on rejection, and forceFetch() rejects when fetchMethod returns undefined

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/cache.cjs
  • test/contract.cjs

소스 아티팩트 내려받기 (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@11.5.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/lru-cache@11.5.3
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:c4137cd6746911b4edf66561ef552cf8bb5f1bd2530f2cf145c119384535b71f","constraints":{"executionContext":"node"},"contract":["require('lru-cache') exports LRUCache in CommonJS and constructor throws TypeError when no capacity limit is provided","LRU eviction removes the least recently used entry, get() promotes recency while peek() preserves order, and dispose receives evict, set, and delete reasons","maxSize and maxEntrySize enforce sizeCalculation bounds, rejecting oversized items with status.maxEntrySizeExceeded and maintaining calculatedSize","deterministic TTL tracking via custom perf clock with ttlResolution: 0 reports getRemainingTTL, preserves expired entries under allowStale with noDeleteOnStaleGet, and clears them via purgeStale()","memo() caches memoMethod results with status.memo miss/hit reporting and dump()/load() round-trips entries in MRU order","fetch() coalesces concurrent requests per key, allowStaleOnFetchRejection returns stale values on rejection, and forceFetch() rejects when fetchMethod returns undefined"],"goal":"verify pkg:npm/lru-cache@11.5.3","kind":"HOW","packages":["pkg:npm/lru-cache@11.5.3"],"schemaVersion":1},"contractCommand":["node","test/contract.cjs"],"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@11.5.3"],"schemaVersion":1,"subject":"pkg:npm/lru-cache@11.5.3","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "lru-cache-verify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "lru-cache-verify",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "lru-cache": "11.5.3"
      }
    },
    "node_modules/lru-cache": {
      "version": "11.5.3",
      "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
      "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
      "license": "BlueOak-1.0.0",
      "engines": {
        "node": "20 || >=22"
      }
    }
  }
}
package.json
{
  "name": "lru-cache-verify",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "lru-cache": "11.5.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/lru-cache@11.5.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/lru-cache@11.5.3"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/cache.cjs
'use strict';

const { LRUCache } = require('lru-cache');

function createBoundedCache(options) {
  return new LRUCache(options);
}

function createClock(initialMs = 1000) {
  let current = initialMs;
  return {
    perf: {
      now() {
        return current;
      },
    },
    advance(ms) {
      current += ms;
    },
  };
}

module.exports = {
  LRUCache,
  createBoundedCache,
  createClock,
};
test/contract.cjs
'use strict';

const assert = require('node:assert/strict');
const { LRUCache, createBoundedCache, createClock } = require('../src/cache.cjs');

async function main() {
  // 1. Named CommonJS export and constructor capacity validation
  assert.equal(typeof LRUCache, 'function');
  assert.throws(() => new LRUCache({}), TypeError);

  // 2. LRU eviction order, get() vs peek(), and dispose reasons
  const disposed = [];
  const lru = createBoundedCache({
    max: 2,
    dispose(value, key, reason) {
      disposed.push({ key, value, reason });
    },
  });

  lru.set('a', 1);
  lru.set('b', 2);
  assert.equal(lru.peek('a'), 1);
  assert.deepEqual([...lru.keys()], ['b', 'a']);

  assert.equal(lru.get('a'), 1);
  assert.deepEqual([...lru.keys()], ['a', 'b']);

  lru.set('c', 3);
  assert.equal(lru.has('b'), false);
  assert.deepEqual([...lru.keys()], ['c', 'a']);

  lru.set('a', 10);
  lru.delete('c');
  assert.deepEqual(disposed, [
    { key: 'b', value: 2, reason: 'evict' },
    { key: 'a', value: 1, reason: 'set' },
    { key: 'c', value: 3, reason: 'delete' },
  ]);

  // 3. Size-bounded cache with maxSize, maxEntrySize, and status tracking
  const sized = createBoundedCache({
    maxSize: 10,
    maxEntrySize: 6,
    sizeCalculation(value) {
      return value.length;
    },
  });

  const oversizedStatus = {};
  sized.set('too-big', '1234567', { status: oversizedStatus });
  assert.equal(sized.has('too-big'), false);
  assert.equal(oversizedStatus.maxEntrySizeExceeded, true);
  assert.equal(oversizedStatus.set, 'miss');

  sized.set('k1', '12345');
  sized.set('k2', '12345');
  assert.equal(sized.calculatedSize, 10);
  sized.set('k3', '12');
  assert.equal(sized.has('k1'), false);
  assert.equal(sized.has('k2'), true);
  assert.equal(sized.has('k3'), true);
  assert.equal(sized.calculatedSize, 7);

  // 4. Deterministic TTL expiration, stale reads, and purgeStale()
  const clock = createClock(1000);
  const ttlCache = createBoundedCache({
    max: 5,
    ttl: 100,
    ttlResolution: 0,
    perf: clock.perf,
  });

  ttlCache.set('token', 'fresh');
  assert.equal(ttlCache.getRemainingTTL('token'), 100);
  clock.advance(40);
  assert.equal(ttlCache.getRemainingTTL('token'), 60);

  clock.advance(70);
  assert.equal(ttlCache.has('token'), false);
  assert.equal(
    ttlCache.get('token', { allowStale: true, noDeleteOnStaleGet: true }),
    'fresh'
  );
  assert.equal(ttlCache.size, 1);
  assert.equal(ttlCache.purgeStale(), true);
  assert.equal(ttlCache.size, 0);
  assert.equal(ttlCache.purgeStale(), false);

  // 5. Synchronous memo() and dump()/load() serialization round-trip
  let memoCalls = 0;
  const memoCache = createBoundedCache({
    max: 5,
    memoMethod(key) {
      memoCalls += 1;
      return `computed:${key}`;
    },
  });

  const s1 = {};
  const s2 = {};
  assert.equal(memoCache.memo('x', { status: s1 }), 'computed:x');
  assert.equal(memoCache.memo('x', { status: s2 }), 'computed:x');
  assert.equal(memoCalls, 1);
  assert.equal(s1.memo, 'miss');
  assert.equal(s2.memo, 'hit');

  memoCache.set('y', 'manual:y');
  const snapshot = memoCache.dump();
  const restored = createBoundedCache({ max: 5 });
  restored.load(snapshot);
  assert.deepEqual([...restored.entries()], [
    ['y', 'manual:y'],
    ['x', 'computed:x'],
  ]);

  // 6. Async fetch() coalescing, forceFetch() rejection on undefined, stale fallback on rejection
  const fetchClock = createClock(5000);
  let fetchCount = 0;
  let mode = 'ok';
  const asyncCache = createBoundedCache({
    max: 5,
    ttl: 50,
    ttlResolution: 0,
    perf: fetchClock.perf,
    async fetchMethod(key) {
      fetchCount += 1;
      await Promise.resolve();
      if (mode === 'fail') {
        throw new Error('upstream failure');
      }
      if (mode === 'missing') {
        return undefined;
      }
      return `v${fetchCount}:${key}`;
    },
  });

  const [r1, r2] = await Promise.all([
    asyncCache.fetch('item'),
    asyncCache.fetch('item'),
  ]);
  assert.equal(r1, 'v1:item');
  assert.equal(r2, 'v1:item');
  assert.equal(fetchCount, 1);

  fetchClock.advance(60);
  mode = 'fail';
  const fallback = await asyncCache.fetch('item', {
    allowStaleOnFetchRejection: true,
  });
  assert.equal(fallback, 'v1:item');

  mode = 'missing';
  await assert.rejects(
    () => asyncCache.forceFetch('absent'),
    /fetch\(\) returned undefined/
  );
}

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

오리진 시더

익명