CodeSampleX

Ejemplo

lru-cache 10.4.3

Muestra verificada para npm lru-cache 10.4.3. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó: LRUCache get, set, and has operations…

sha256:c28dbf8264fe3e311e1cda8403c17d34b335eaf6e9ee159fc783b9cdaa4e0cd4

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-07

Caso

HOW
Objetivo
verify pkg:npm/lru-cache@10.4.3
Paquetes
Creado
2026-08-20T07:18:17Z

Contrato

  1. LRUCache get, set, and has operations store values, evict LRU entries upon reaching max capacity, and maintain recency order
  2. LRUCache sizeCalculation and maxSize track item weights, enforce size limits, and evict entries when total size exceeds maxSize
  3. LRUCache ttl configuration with updateAgeOnGet and purgeStale manages time-based entry expiration and stale item cleanup
  4. LRUCache dispose and disposeAfter callbacks execute with proper dispose reasons on eviction, deletion, and overwrites
  5. LRUCache fetchMethod and memoMethod resolve missing entries, support asynchronous fetching, and coalesce concurrent lookups
  6. LRUCache dump and load serialize and restore cache entries with metadata across instances

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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

Use EXACTLY these public packages and versions:
  - pkg:npm/lru-cache@10.4.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:a88d862928bd0af69b1a37b0552ecf66a83ae19c8b897b7065548eaeb9818ce3","contract":["LRUCache get, set, and has operations store values, evict LRU entries upon reaching max capacity, and maintain recency order","LRUCache sizeCalculation and maxSize track item weights, enforce size limits, and evict entries when total size exceeds maxSize","LRUCache ttl configuration with updateAgeOnGet and purgeStale manages time-based entry expiration and stale item cleanup","LRUCache dispose and disposeAfter callbacks execute with proper dispose reasons on eviction, deletion, and overwrites","LRUCache fetchMethod and memoMethod resolve missing entries, support asynchronous fetching, and coalesce concurrent lookups","LRUCache dump and load serialize and restore cache entries with metadata across instances"],"goal":"verify pkg:npm/lru-cache@10.4.3","kind":"HOW","packages":["pkg:npm/lru-cache@10.4.3"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"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@10.4.3"],"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": "10.4.3"
      }
    },
    "node_modules/lru-cache": {
      "version": "10.4.3",
      "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
      "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
      "license": "ISC"
    }
  }
}
package.json
{
  "name": "lru-cache-sample",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "lru-cache": "10.4.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/lru-cache@10.4.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/lru-cache@10.4.3"
  ]
}
src/index.mjs
import { LRUCache } from 'lru-cache';

/**
 * Creates a standard capacity-bounded LRUCache instance.
 *
 * @template {object} K
 * @template {object} V
 * @param {import('lru-cache').LRUCache.Options<K, V, unknown>} options
 * @returns {LRUCache<K, V>}
 */
export function createCache(options) {
  return new LRUCache(options);
}

/**
 * Creates a size-bounded LRUCache instance with custom size calculation.
 *
 * @template {object} K
 * @template {object} V
 * @param {number} maxSize
 * @param {(value: V, key: K) => number} sizeCalculation
 * @param {Omit<import('lru-cache').LRUCache.OptionsBase<K, V, unknown>, 'maxSize' | 'sizeCalculation'>} [options]
 * @returns {LRUCache<K, V>}
 */
export function createSizedCache(maxSize, sizeCalculation, options = {}) {
  return new LRUCache({
    ...options,
    maxSize,
    sizeCalculation,
  });
}

/**
 * Creates a time-expiring LRUCache instance.
 *
 * @template {object} K
 * @template {object} V
 * @param {number} ttl
 * @param {Omit<import('lru-cache').LRUCache.OptionsBase<K, V, unknown>, 'ttl'>} [options]
 * @returns {LRUCache<K, V>}
 */
export function createTTLCache(ttl, options = {}) {
  return new LRUCache({
    max: 100,
    ...options,
    ttl,
  });
}

/**
 * Creates an LRUCache with an asynchronous fetcher function.
 *
 * @template {object} K
 * @template {object} V
 * @template [FC=unknown]
 * @param {import('lru-cache').LRUCache.Fetcher<K, V, FC>} fetchMethod
 * @param {Omit<import('lru-cache').LRUCache.OptionsBase<K, V, FC>, 'fetchMethod'>} [options]
 * @returns {LRUCache<K, V, FC>}
 */
export function createFetchCache(fetchMethod, options = {}) {
  return new LRUCache({
    max: 100,
    ...options,
    fetchMethod,
  });
}

/**
 * Creates an LRUCache with a synchronous memoizer function.
 *
 * @template {object} K
 * @template {object} V
 * @template [FC=unknown]
 * @param {import('lru-cache').LRUCache.Memoizer<K, V, FC>} memoMethod
 * @param {Omit<import('lru-cache').LRUCache.OptionsBase<K, V, FC>, 'memoMethod'>} [options]
 * @returns {LRUCache<K, V, FC>}
 */
export function createMemoCache(memoMethod, options = {}) {
  return new LRUCache({
    max: 100,
    ...options,
    memoMethod,
  });
}

/**
 * Dumps entries from a cache into a serializable array of tuples.
 *
 * @template {object} K
 * @template {object} V
 * @param {LRUCache<K, V>} cache
 * @returns {Array<[K, import('lru-cache').LRUCache.Entry<V>]>}
 */
export function serializeCache(cache) {
  return cache.dump();
}

/**
 * Restores dumped entries into a newly created LRUCache instance.
 *
 * @template {object} K
 * @template {object} V
 * @param {import('lru-cache').LRUCache.Options<K, V, unknown>} options
 * @param {Array<[K, import('lru-cache').LRUCache.Entry<V>]>} entries
 * @returns {LRUCache<K, V>}
 */
export function restoreCache(options, entries) {
  const cache = new LRUCache(options);
  cache.load(entries);
  return cache;
}

export { LRUCache };
test/contract.mjs
import assert from 'node:assert/strict';
import {
  createCache,
  createSizedCache,
  createTTLCache,
  createFetchCache,
  createMemoCache,
  serializeCache,
  restoreCache,
} from '../src/index.mjs';

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

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

    assert.strictEqual(cache.size, 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
    cache.peek('c');
    cache.set('e', 5);
    assert.strictEqual(cache.has('a'), false, 'Key a should be evicted next');

    // pop removes and returns the LRU item
    const popped = cache.pop();
    assert.strictEqual(popped, 3, 'Key c should be popped');
    assert.strictEqual(cache.has('c'), false);
  }

  // Contract 2: LRUCache sizeCalculation and maxSize track item weights, enforce size limits, and evict entries when total size exceeds maxSize
  {
    const cache = createSizedCache(100, (value) => value.length);

    cache.set('item1', 'short'); // size 5
    cache.set('item2', 'x'.repeat(40)); // size 40
    cache.set('item3', 'y'.repeat(50)); // size 50
    assert.strictEqual(cache.calculatedSize, 95);

    // Adding item4 (size 15) brings calculatedSize over 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.calculatedSize, 65);

    // Entry exceeding maxEntrySize (defaults to maxSize: 100) is ignored
    const oversized = 'w'.repeat(150);
    cache.set('tooLarge', oversized);
    assert.strictEqual(cache.has('tooLarge'), false);
    assert.strictEqual(cache.calculatedSize, 65);
  }

  // Contract 3: LRUCache ttl configuration with updateAgeOnGet and purgeStale manages time-based entry expiration and stale item cleanup
  {
    const cache = createTTLCache(50, {
      updateAgeOnGet: true,
      allowStale: false,
    });

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

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

    await delay(30);
    // temp2 has exceeded 50ms TTL, temp1 is refreshed
    assert.strictEqual(cache.has('temp2'), false, 'temp2 should expire after 60ms');
    assert.strictEqual(cache.get('temp2'), undefined);
    assert.strictEqual(cache.get('temp1'), 'val1', 'temp1 remains accessible due to updateAgeOnGet');

    // purgeStale explicitly removes all expired entries
    cache.set('temp3', 'val3', { ttl: 20 });
    await delay(30);
    assert.strictEqual(cache.size, 2);
    const purged = cache.purgeStale();
    assert.strictEqual(purged, true);
    assert.strictEqual(cache.size, 1);
    assert.strictEqual(cache.has('temp3'), false);
  }

  // Contract 4: LRUCache dispose and disposeAfter callbacks execute with proper dispose reasons on eviction, deletion, and overwrites
  {
    const events = [];
    const cache = createCache({
      max: 2,
      dispose: (value, key, reason) => {
        events.push({ phase: 'dispose', key, value, reason });
      },
      disposeAfter: (value, key, reason) => {
        events.push({ phase: 'disposeAfter', key, value, reason });
      },
    });

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

    // Eviction on reaching capacity
    cache.set('k3', 'v3');
    assert.deepStrictEqual(events.slice(0, 2), [
      { phase: 'dispose', key: 'k1', value: 'v1', reason: 'evict' },
      { phase: 'disposeAfter', key: 'k1', value: 'v1', reason: 'evict' },
    ]);

    // Overwriting existing key
    cache.set('k3', 'v3-updated');
    assert.deepStrictEqual(events.slice(2, 4), [
      { phase: 'dispose', key: 'k3', value: 'v3', reason: 'set' },
      { phase: 'disposeAfter', key: 'k3', value: 'v3', reason: 'set' },
    ]);

    // Explicit deletion
    cache.delete('k2');
    assert.deepStrictEqual(events.slice(4, 6), [
      { phase: 'dispose', key: 'k2', value: 'v2', reason: 'delete' },
      { phase: 'disposeAfter', key: 'k2', value: 'v2', reason: 'delete' },
    ]);
  }

  // Contract 5: LRUCache fetchMethod and memoMethod resolve missing entries, support asynchronous fetching, and coalesce concurrent lookups
  {
    let fetchCount = 0;
    const fetchCache = createFetchCache(async (key) => {
      fetchCount++;
      await delay(20);
      return `fetched_${key}`;
    });

    // Concurrent fetches for the same key are coalesced
    const [val1, val2] = await Promise.all([
      fetchCache.fetch('res1'),
      fetchCache.fetch('res1'),
    ]);
    assert.strictEqual(val1, 'fetched_res1');
    assert.strictEqual(val2, 'fetched_res1');
    assert.strictEqual(fetchCount, 1, 'In-flight fetches should coalesce to single fetch call');

    // Cached fetch returns immediately without re-invoking fetcher
    const cachedVal = await fetchCache.fetch('res1');
    assert.strictEqual(cachedVal, 'fetched_res1');
    assert.strictEqual(fetchCount, 1);

    // memoMethod computes and sets missing value synchronously
    const memoCache = createMemoCache((key) => `memo_${key}`);
    const m1 = memoCache.memo('itemA');
    const m2 = memoCache.memo('itemA');
    assert.strictEqual(m1, 'memo_itemA');
    assert.strictEqual(m2, 'memo_itemA');
    assert.strictEqual(memoCache.get('itemA'), 'memo_itemA');
  }

  // Contract 6: LRUCache dump and load serialize and restore cache entries with metadata across instances
  {
    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);

    const entryInfo = targetCache.info('x');
    assert.ok(entryInfo);
    assert.strictEqual(entryInfo.value, 10);
  }

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

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

Seeder de origen

anónimo