CodeSampleX

Exemple

lru-cache 7.18.3

Échantillon vérifié pour npm lru-cache 7.18.3. Le contrat s'est exécuté sur node 22 · linux alpine/x64 · docker et a réussi : LRUCache get, set, has, delete…

sha256:62c55450abe4213233b1d90d8cd9af0663ef1c4ae1864cc7a5cbdcb838a3b7dd

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-21
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-09-07

Cas

HOW
Objectif
verify pkg:npm/lru-cache@7.18.3
Paquets
Créé
2026-08-21T13:53:13Z

Contrat

  1. LRUCache get, set, has, delete, and clear operations manage key-value pairs with max capacity eviction and track cache size
  2. LRUCache ttl and purgeStale manage time-to-live entry expiration with allowStale option
  3. LRUCache maxSize with custom sizeCalculation calculates total entry size and evicts items when size limit is exceeded
  4. LRUCache dispose callback is invoked on entry eviction, deletion, and overwrite with key, value, and eviction reason
  5. LRUCache fetch method asynchronously retrieves and caches values with concurrent request deduplication

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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@7.18.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/lru-cache@7.18.3

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:1cfa773d1b31497d9631659aec49dcd9642a0fdb41a7bec4db615c3f552c9772","contract":["LRUCache get, set, has, delete, and clear operations manage key-value pairs with max capacity eviction and track cache size","LRUCache ttl and purgeStale manage time-to-live entry expiration with allowStale option","LRUCache maxSize with custom sizeCalculation calculates total entry size and evicts items when size limit is exceeded","LRUCache dispose callback is invoked on entry eviction, deletion, and overwrite with key, value, and eviction reason","LRUCache fetch method asynchronously retrieves and caches values with concurrent request deduplication"],"goal":"verify pkg:npm/lru-cache@7.18.3","kind":"HOW","packages":["pkg:npm/lru-cache@7.18.3"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"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/lru-cache@7.18.3"],"schemaVersion":1,"subject":"pkg:npm/lru-cache@7.18.3","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-lru-cache",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-lru-cache",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "lru-cache": "7.18.3"
      }
    },
    "node_modules/lru-cache": {
      "version": "7.18.3",
      "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz",
      "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==",
      "license": "ISC",
      "engines": {
        "node": ">=12"
      }
    }
  }
}
package.json
{
  "name": "sample-lru-cache",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for lru-cache",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "lru-cache": "7.18.3"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/lru-cache@7.18.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/lru-cache@7.18.3"
  ]
}
src/index.js
const LRUCache = require('lru-cache');

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

module.exports = {
  LRUCache,
  createCache
};
test/contract.js
const assert = require('node:assert');
const LRUCache = require('lru-cache');
const { createCache } = require('../src/index.js');

async function runContractTests() {
  // 1. LRUCache get, set, has, delete, and clear operations manage key-value pairs with max capacity eviction and track cache size
  const cache = createCache({ max: 3 });
  assert.strictEqual(cache.size, 0, 'initial size should be 0');

  cache.set('a', 100);
  cache.set('b', 200);
  cache.set('c', 300);
  assert.strictEqual(cache.size, 3, 'size should be 3 after 3 additions');
  assert.strictEqual(cache.get('a'), 100, 'get(a) should return 100');
  assert.strictEqual(cache.has('b'), true, 'has(b) should be true');

  // Accessing 'a' makes 'b' the least recently used entry
  cache.set('d', 400); // Exceeds max 3, 'b' must be evicted
  assert.strictEqual(cache.has('b'), false, 'least recently used key b should be evicted');
  assert.strictEqual(cache.has('a'), true, 'key a should still exist');
  assert.strictEqual(cache.has('c'), true, 'key c should still exist');
  assert.strictEqual(cache.has('d'), true, 'key d should still exist');
  assert.strictEqual(cache.size, 3, 'size should remain at max capacity 3');

  // delete and clear operations
  assert.strictEqual(cache.delete('c'), true, 'delete(c) should return true');
  assert.strictEqual(cache.has('c'), false, 'key c should no longer exist after delete');
  assert.strictEqual(cache.size, 2, 'size should be 2 after deleting one key');

  cache.clear();
  assert.strictEqual(cache.size, 0, 'size should be 0 after clear');
  assert.strictEqual(cache.has('a'), false, 'cache should be empty after clear');

  // 2. LRUCache ttl and purgeStale manage time-to-live entry expiration with allowStale option
  const ttlCache = createCache({ max: 10, ttl: 50, allowStale: true });
  ttlCache.set('tempKey', 'tempVal');
  assert.strictEqual(ttlCache.get('tempKey'), 'tempVal', 'get should return value before ttl expiration');

  await new Promise((resolve) => setTimeout(resolve, 60));
  // allowStale is true on cache, so get returns stale value unless disallowed
  assert.strictEqual(ttlCache.get('tempKey'), 'tempVal', 'get should return stale value when allowStale is true');
  assert.strictEqual(ttlCache.get('tempKey', { allowStale: false }), undefined, 'get with allowStale:false should return undefined for expired key');

  ttlCache.purgeStale();
  assert.strictEqual(ttlCache.get('tempKey'), undefined, 'purgeStale should remove expired entry completely');

  // 3. LRUCache maxSize with custom sizeCalculation calculates total entry size and evicts items when size limit is exceeded
  const sizeCache = createCache({
    maxSize: 100,
    sizeCalculation: (value) => value.length
  });

  sizeCache.set('item1', 'A'.repeat(40));
  sizeCache.set('item2', 'B'.repeat(40));
  assert.strictEqual(sizeCache.calculatedSize, 80, 'calculatedSize should equal sum of entry lengths');

  // Adding item3 (length 40) makes total 120 > maxSize 100, item1 must be evicted
  sizeCache.set('item3', 'C'.repeat(40));
  assert.strictEqual(sizeCache.has('item1'), false, 'item1 should be evicted due to maxSize overflow');
  assert.strictEqual(sizeCache.has('item2'), true, 'item2 should remain');
  assert.strictEqual(sizeCache.has('item3'), true, 'item3 should remain');
  assert.strictEqual(sizeCache.calculatedSize, 80, 'calculatedSize should adjust after eviction');

  // 4. LRUCache dispose callback is invoked on entry eviction, deletion, and overwrite with key, value, and eviction reason
  const disposalEvents = [];
  const dispCache = createCache({
    max: 2,
    dispose: (value, key, reason) => {
      disposalEvents.push({ key, value, reason });
    }
  });

  dispCache.set('k1', 'v1');
  dispCache.set('k2', 'v2');
  dispCache.set('k1', 'v1_updated'); // Overwrite -> reason: 'set'
  dispCache.set('k3', 'v3'); // Evicts k2 -> reason: 'evict'
  dispCache.delete('k3'); // Delete -> reason: 'delete'

  assert.deepStrictEqual(disposalEvents, [
    { key: 'k1', value: 'v1', reason: 'set' },
    { key: 'k2', value: 'v2', reason: 'evict' },
    { key: 'k3', value: 'v3', reason: 'delete' }
  ], 'dispose callback should record correct key, value, and reason for set, evict, and delete');

  // 5. LRUCache fetch method asynchronously retrieves and caches values with concurrent request deduplication
  let fetchCallCount = 0;
  const asyncCache = createCache({
    max: 10,
    fetchMethod: async (key) => {
      fetchCallCount++;
      return `fetched:${key}`;
    }
  });

  // Concurrent fetch calls for the same key should deduplicate to a single fetchMethod invocation
  const [resA, resB] = await Promise.all([
    asyncCache.fetch('sharedKey'),
    asyncCache.fetch('sharedKey')
  ]);

  assert.strictEqual(resA, 'fetched:sharedKey', 'first fetch result should match');
  assert.strictEqual(resB, 'fetched:sharedKey', 'concurrent fetch result should match');
  assert.strictEqual(fetchCallCount, 1, 'concurrent fetch calls should be deduplicated into 1 call');

  // Subsequent fetch for cached key should return cached value without calling fetchMethod
  const resC = await asyncCache.fetch('sharedKey');
  assert.strictEqual(resC, 'fetched:sharedKey', 'cached fetch result should match');
  assert.strictEqual(fetchCallCount, 1, 'subsequent fetch should use cache without invoking fetchMethod');

  console.log('Contract tests passed successfully.');
}

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

Seeder d'origine

anonyme