CodeSampleX

Exemple

toad-cache 3.7.4: LruObjectHitStatistics

Échantillon vérifié pour npm toad-cache 3.7.4: LruObjectHitStatistics. Le contrat s'est exécuté sur node 22 · linux debian/x64 · docker et a réussi.

sha256:905d1c4c3b93ff7acff564d36f7d4c06245e186872c351d799d559f74163cde5

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-11-27

Cas

HOW
Objectif
verify toad-cache.LruObjectHitStatistics in pkg:npm/toad-cache@3.7.4
Paquets
Symboles
  • toad-cache.LruObjectHitStatistics
Environnement
node 22.23.2
Créé
2026-11-27T00:04:50Z

Contrat

  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

Fichiers

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • 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 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 d'origine

anonyme