CodeSampleX

Exemple

lru-cache 11.2.4

Échantillon vérifié pour npm lru-cache 11.2.4. Le contrat s'est exécuté sur node 22 · linux debian/x64 · docker et a réussi : assert CJS require('lru-cache')…

sha256:b47cf41aab4f6af36179644c8f609b335057c9e3c05c2b437ba65f31cd207f93

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
1
Clés de signature qui l’ont compilé
1
Environnement déclaré node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-12-01

Cas

HOW
Objectif
verify pkg:npm/lru-cache@11.2.4
Paquets
Environnement
node 22.23.2
Créé
2026-12-01T02:32:29Z

Contrat

  1. assert CJS require('lru-cache') exports LRUCache and evicts least-recently-used entries with dispose reason 'evict' and explicit delete reason 'delete'
  2. assert maxSize with sizeCalculation enforces total size budget and ignores single items exceeding maxSize
  3. assert ttl expiration with ttlResolution: 0 and perf.now() returns undefined from get() and false from has() while allowStale with noDeleteOnStaleGet returns stale values repeatedly
  4. assert fetchMethod coalesces concurrent fetch() calls for the same key and does not cache rejected promises

Fichiers

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

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

Use EXACTLY these public packages and versions:
  - pkg:npm/lru-cache@11.2.4
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:35726331fa1d45edd615c3aa66e3f7eb961d75bb86da0c8384739da22914e52e","constraints":{"executionContext":"node"},"contract":["assert CJS require('lru-cache') exports LRUCache and evicts least-recently-used entries with dispose reason 'evict' and explicit delete reason 'delete'","assert maxSize with sizeCalculation enforces total size budget and ignores single items exceeding maxSize","assert ttl expiration with ttlResolution: 0 and perf.now() returns undefined from get() and false from has() while allowStale with noDeleteOnStaleGet returns stale values repeatedly","assert fetchMethod coalesces concurrent fetch() calls for the same key and does not cache rejected promises"],"goal":"verify pkg:npm/lru-cache@11.2.4","kind":"HOW","packages":["pkg:npm/lru-cache@11.2.4"],"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.2.4"],"schemaVersion":1,"subject":"pkg:npm/lru-cache@11.2.4","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "lru-cache-verify-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "lru-cache-verify-sample",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "lru-cache": "11.2.4"
      }
    },
    "node_modules/lru-cache": {
      "version": "11.2.4",
      "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.4.tgz",
      "integrity": "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg==",
      "license": "BlueOak-1.0.0",
      "engines": {
        "node": "20 || >=22"
      }
    }
  }
}
package.json
{
  "name": "lru-cache-verify-sample",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "main": "src/index.cjs",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "lru-cache": "11.2.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/lru-cache@11.2.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/lru-cache@11.2.4"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.cjs
'use strict';

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

/**
 * Create a bounded LRUCache instance with optional TTL, size limits,
 * disposal tracking, and async fetch support.
 *
 * @param {import('lru-cache').LRUCache.Options<string, unknown, unknown>} options
 * @returns {LRUCache<string, unknown, unknown>}
 */
function createCache(options) {
  return new LRUCache(options);
}

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

const assert = require('node:assert/strict');
const { LRUCache, createCache } = require('../src/index.cjs');

async function main() {
  // 1. Verify CJS named export and LRU eviction order with dispose reasons
  assert.equal(typeof LRUCache, 'function');
  const disposed = [];
  const lru = createCache({
    max: 2,
    dispose(value, key, reason) {
      disposed.push({ key, value, reason });
    },
  });

  lru.set('a', 1);
  lru.set('b', 2);
  // Touch 'a' so 'b' becomes least-recently-used
  assert.equal(lru.get('a'), 1);
  lru.set('c', 3);

  assert.equal(lru.has('b'), false);
  assert.equal(lru.get('a'), 1);
  assert.equal(lru.get('c'), 3);
  assert.deepEqual(disposed, [{ key: 'b', value: 2, reason: 'evict' }]);

  assert.equal(lru.delete('a'), true);
  assert.deepEqual(disposed[1], { key: 'a', value: 1, reason: 'delete' });

  // 2. Verify maxSize + sizeCalculation enforces byte budget and skips oversized items
  const sized = createCache({
    maxSize: 10,
    sizeCalculation(value) {
      return Buffer.byteLength(value, 'utf8');
    },
  });
  sized.set('k1', '123456'); // size 6
  sized.set('k2', '123456'); // size 6 -> evicts k1
  assert.equal(sized.has('k1'), false);
  assert.equal(sized.get('k2'), '123456');
  assert.equal(sized.calculatedSize, 6);

  sized.set('too-big', '12345678901'); // size 11 > maxSize 10
  assert.equal(sized.has('too-big'), false);
  assert.equal(sized.get('k2'), '123456');

  // 3. Verify TTL expiration and allowStale + noDeleteOnStaleGet with deterministic perf clock
  // ttlResolution: 0 disables the 1ms cached timestamp so perf.now() advances immediately.
  let nowMs = 1000;
  const ttlCache = createCache({
    max: 4,
    ttl: 500,
    ttlResolution: 0,
    perf: { now: () => nowMs },
  });
  ttlCache.set('session', 'active');
  assert.equal(ttlCache.get('session'), 'active');

  nowMs = 1600; // 600ms elapsed > 500ms ttl
  assert.equal(ttlCache.has('session'), false);
  assert.equal(ttlCache.get('session'), undefined);

  const staleCache = createCache({
    max: 4,
    ttl: 500,
    ttlResolution: 0,
    allowStale: true,
    noDeleteOnStaleGet: true,
    perf: { now: () => nowMs },
  });
  nowMs = 2000;
  staleCache.set('token', 'stale-ok');
  nowMs = 2600;
  assert.equal(staleCache.has('token'), false);
  assert.equal(staleCache.get('token'), 'stale-ok');
  assert.equal(staleCache.get('token'), 'stale-ok');

  // 4. Verify async fetchMethod coalesces concurrent calls and does not cache rejections
  let fetchCalls = 0;
  const asyncCache = createCache({
    max: 4,
    async fetchMethod(key) {
      fetchCalls += 1;
      if (key === 'fail') {
        throw new Error('upstream failure');
      }
      await Promise.resolve();
      return `value:${key}`;
    },
  });

  const [v1, v2] = await Promise.all([
    asyncCache.fetch('item'),
    asyncCache.fetch('item'),
  ]);
  assert.equal(v1, 'value:item');
  assert.equal(v2, 'value:item');
  assert.equal(fetchCalls, 1);

  await assert.rejects(() => asyncCache.fetch('fail'), {
    message: 'upstream failure',
  });
  assert.equal(asyncCache.has('fail'), false);
}

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

Seeder d'origine

anonyme