CodeSampleX

Ejemplo

toad-cache 3.7.4: LruObjectHitStatistics

Muestra verificada para npm toad-cache 3.7.4: LruObjectHitStatistics. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó.

sha256:905d1c4c3b93ff7acff564d36f7d4c06245e186872c351d799d559f74163cde5

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
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-27

Caso

HOW
Objetivo
verify toad-cache.LruObjectHitStatistics in pkg:npm/toad-cache@3.7.4
Paquetes
Símbolos
  • toad-cache.LruObjectHitStatistics
Entorno
node 22.23.2
Creado
2026-11-27T00:04:50Z

Contrato

  1. new LruObjectHitStatistics(max, ttl, cacheId) throws when cacheId is missing or empty, and rejects negative max or ttl values
  2. omitting max and ttl defaults to max=1000 and ttl=0, while explicit max=0 disables eviction
  3. LruHitStatistics is exported as an alias of LruObjectHitStatistics
  4. get() tracks hits, falsyHits (including 0, '', null), emptyHits (subset of falsyHits for '', null, undefined), and misses while updating LRU recency
  5. exceeding max on set() evicts the least recently used entry and increments evictions while keeping cacheSize updated; updating an existing key increments sets without evicting
  6. delete() increments invalidateOne only for existing keys, clear() increments invalidateAll and zeroes cacheSize, and evict() on an empty cache does not increment evictions
  7. expired entries removed during get() increment expirations without incrementing misses or invalidateOne
  8. passing a shared HitStatisticsRecord aggregates multiple LruObjectHitStatistics instances and resetForCache() resets only the target cacheId

Archivos

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

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 toad-cache.LruObjectHitStatistics in pkg:npm/toad-cache@3.7.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/toad-cache@3.7.4
Demonstrate these symbols/APIs:
  - toad-cache.LruObjectHitStatistics
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:d3e21dc11cdd90ba7348fad1672a1014e5d150e67a7c89fd728211191b242d1b","constraints":{"executionContext":"node"},"contract":["new LruObjectHitStatistics(max, ttl, cacheId) throws when cacheId is missing or empty, and rejects negative max or ttl values","omitting max and ttl defaults to max=1000 and ttl=0, while explicit max=0 disables eviction","LruHitStatistics is exported as an alias of LruObjectHitStatistics","get() tracks hits, falsyHits (including 0, '', null), emptyHits (subset of falsyHits for '', null, undefined), and misses while updating LRU recency","exceeding max on set() evicts the least recently used entry and increments evictions while keeping cacheSize updated; updating an existing key increments sets without evicting","delete() increments invalidateOne only for existing keys, clear() increments invalidateAll and zeroes cacheSize, and evict() on an empty cache does not increment evictions","expired entries removed during get() increment expirations without incrementing misses or invalidateOne","passing a shared HitStatisticsRecord aggregates multiple LruObjectHitStatistics instances and resetForCache() resets only the target cacheId"],"goal":"verify toad-cache.LruObjectHitStatistics in pkg:npm/toad-cache@3.7.4","kind":"HOW","packages":["pkg:npm/toad-cache@3.7.4"],"schemaVersion":1,"symbols":["toad-cache.LruObjectHitStatistics"]},"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/toad-cache@3.7.4"],"schemaVersion":1,"subject":"pkg:npm/toad-cache@3.7.4","symbols":["toad-cache.LruObjectHitStatistics"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "toad-cache-lru-object-hit-statistics-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "toad-cache-lru-object-hit-statistics-sample",
      "version": "1.0.0",
      "dependencies": {
        "toad-cache": "3.7.4"
      }
    },
    "node_modules/toad-cache": {
      "version": "3.7.4",
      "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.4.tgz",
      "integrity": "sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg==",
      "license": "MIT",
      "engines": {
        "node": ">=20"
      }
    }
  }
}
package.json
{
  "name": "toad-cache-lru-object-hit-statistics-sample",
  "version": "1.0.0",
  "private": true,
  "description": "Minimal contract sample verifying LruObjectHitStatistics in toad-cache@3.7.4",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "toad-cache": "3.7.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify toad-cache.LruObjectHitStatistics in pkg:npm/toad-cache@3.7.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/toad-cache@3.7.4"
  ],
  "symbols": [
    "toad-cache.LruObjectHitStatistics"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.cjs
'use strict';

const assert = require('node:assert/strict');
const {
  LruObjectHitStatistics,
  LruHitStatistics,
  HitStatisticsRecord,
} = require('toad-cache');

function getBucket(cache, cacheId) {
  const all = cache.getStatistics();
  assert.ok(all[cacheId], `expected statistics bucket for ${cacheId}`);
  const dates = Object.keys(all[cacheId]);
  assert.equal(dates.length, 1);
  assert.match(dates[0], /^\d{4}-\d{2}-\d{2}$/);
  return all[cacheId][dates[0]];
}

// 1. Export identity and constructor validation
assert.equal(LruHitStatistics, LruObjectHitStatistics);

assert.throws(
  () => new LruObjectHitStatistics(10, 0),
  /Cache id is mandatory/,
);
assert.throws(
  () => new LruObjectHitStatistics(10, 0, ''),
  /Cache id is mandatory/,
);
assert.throws(
  () => new LruObjectHitStatistics(-1, 0, 'bad-max'),
  /Invalid max value/,
);
assert.throws(
  () => new LruObjectHitStatistics(10, -1, 'bad-ttl'),
  /Invalid ttl value/,
);

const defaultsCache = new LruObjectHitStatistics(undefined, undefined, 'defaults-cache');
assert.equal(defaultsCache.max, 1000);
assert.equal(defaultsCache.ttl, 0);
assert.deepEqual(getBucket(defaultsCache, 'defaults-cache'), {
  cacheSize: 0,
  hits: 0,
  falsyHits: 0,
  emptyHits: 0,
  misses: 0,
  expirations: 0,
  evictions: 0,
  invalidateOne: 0,
  invalidateAll: 0,
  sets: 0,
});

const unlimitedCache = new LruObjectHitStatistics(0, 0, 'unlimited-cache');
assert.equal(unlimitedCache.max, 0);
unlimitedCache.set('k1', 1);
unlimitedCache.set('k2', 2);
assert.equal(unlimitedCache.size, 2);
assert.equal(getBucket(unlimitedCache, 'unlimited-cache').evictions, 0);

// 2. Hits, falsyHits, emptyHits, misses, sets, and LRU eviction
const cache = new LruObjectHitStatistics(2, 0, 'lru-stats');

cache.set('a', 'alpha');
cache.set('b', 0);
assert.equal(cache.get('missing'), undefined);

// Truthy hit on 'a' bumps 'a' ahead of 'b'
assert.equal(cache.get('a'), 'alpha');
// Falsy (non-empty) hit on 'b' bumps 'b' ahead of 'a', making 'a' LRU
assert.equal(cache.get('b'), 0);

// Inserting 'c' at capacity 2 evicts least recently used key 'a'
cache.set('c', '');
assert.equal(cache.get('a'), undefined);
// Empty string counts as hit, falsyHit, and emptyHit
assert.equal(cache.get('c'), '');

// Updating existing key increments sets without evicting
cache.set('c', null);
assert.equal(cache.get('c'), null);

let stats = getBucket(cache, 'lru-stats');
assert.deepEqual(stats, {
  cacheSize: 2,
  hits: 4,
  falsyHits: 3,
  emptyHits: 2,
  misses: 2,
  expirations: 0,
  evictions: 1,
  invalidateOne: 0,
  invalidateAll: 0,
  sets: 4,
});

// 3. Invalidation (delete, clear) and empty evict()
cache.delete('does-not-exist');
assert.equal(getBucket(cache, 'lru-stats').invalidateOne, 0);

cache.delete('b');
stats = getBucket(cache, 'lru-stats');
assert.equal(stats.invalidateOne, 1);
assert.equal(stats.cacheSize, 1);

cache.clear();
stats = getBucket(cache, 'lru-stats');
assert.equal(stats.invalidateAll, 1);
assert.equal(stats.cacheSize, 0);

// Evicting an empty cache does not increment evictions
cache.evict();
assert.equal(getBucket(cache, 'lru-stats').evictions, 1);

// 4. TTL expiration increments expirations without incrementing misses or invalidateOne
const realDateNow = Date.now;
let fakeNow = realDateNow();
Date.now = () => fakeNow;
try {
  const ttlCache = new LruObjectHitStatistics(5, 100, 'ttl-cache');
  ttlCache.set('ephemeral', 'value');
  assert.equal(ttlCache.get('ephemeral'), 'value');

  fakeNow += 100;
  assert.equal(ttlCache.get('ephemeral'), undefined);

  const ttlStats = getBucket(ttlCache, 'ttl-cache');
  assert.equal(ttlStats.hits, 1);
  assert.equal(ttlStats.expirations, 1);
  assert.equal(ttlStats.misses, 0);
  assert.equal(ttlStats.invalidateOne, 0);
  assert.equal(ttlStats.cacheSize, 0);
} finally {
  Date.now = realDateNow;
}

// 5. Shared HitStatisticsRecord across multiple caches and selective reset
const sharedRecord = new HitStatisticsRecord();
const cacheOne = new LruObjectHitStatistics(10, 0, 'shared-one', sharedRecord, 24);
const cacheTwo = new LruObjectHitStatistics(10, 0, 'shared-two', sharedRecord, 24);

cacheOne.set('x', 'one');
assert.equal(cacheOne.get('x'), 'one');
cacheTwo.set('y', 'two');
assert.equal(cacheTwo.get('missing'), undefined);

const sharedAll = sharedRecord.getStatistics();
assert.strictEqual(cacheOne.getStatistics(), sharedAll);
assert.strictEqual(cacheTwo.getStatistics(), sharedAll);
assert.equal(getBucket(cacheOne, 'shared-one').hits, 1);
assert.equal(getBucket(cacheTwo, 'shared-two').misses, 1);

sharedRecord.resetForCache('shared-one');
assert.equal(getBucket(cacheOne, 'shared-one').hits, 0);
assert.equal(getBucket(cacheTwo, 'shared-two').misses, 1);

console.log('toad-cache.LruObjectHitStatistics contract passed');

Seeder de origen

anónimo