CodeSampleX

Exemple

@cacheable/utils 2.5.0: Stats

Échantillon vérifié pour npm @cacheable/utils 2.5.0: Stats. Le contrat s'est exécuté sur node 22 · linux debian/x64 · docker et a réussi.

sha256:404bc0b33cb12b478aae297dbc80c2b29556bc278990aab92e726b29466c58c1

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-09-05

Cas

HOW
Objectif
verify pkg:npm/%40cacheable/utils@2.5.0
Paquets
Symboles
  • Stats
Environnement
node 22.23.2
Créé
2026-09-05T16:13:56Z

Contrat

  1. Stats initializes in a disabled state by default and ignores counter updates until enabled
  2. Stats enable and disable methods and property setter toggle tracking state
  3. Stats tracks hits, misses, gets, sets, deletes, clears, and item count with increment and decrement
  4. Stats computes hitRate and missRate from hits and misses or returns zero when no lookups occurred
  5. Stats reset and clear methods reset all counters to zero and update the lastReset timestamp
  6. Stats toJSON and snapshot return complete serializable metric representations including timestamps
  7. Stats per-key tracking records operations per key and returns sorted mostUsedKeys and leastUsedKeys
  8. Stats subscribe binds event emitter events to counter updates via event map and unsubscribe detaches them

Fichiers

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

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/%40cacheable/utils@2.5.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40cacheable/utils@2.5.0

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:e0451b95d2be7856ee21d11fd04f24601f280549cd14b873c95df0e182db552b","contract":["Stats initializes in a disabled state by default and ignores counter updates until enabled","Stats enable and disable methods and property setter toggle tracking state","Stats tracks hits, misses, gets, sets, deletes, clears, and item count with increment and decrement","Stats computes hitRate and missRate from hits and misses or returns zero when no lookups occurred","Stats reset and clear methods reset all counters to zero and update the lastReset timestamp","Stats toJSON and snapshot return complete serializable metric representations including timestamps","Stats per-key tracking records operations per key and returns sorted mostUsedKeys and leastUsedKeys","Stats subscribe binds event emitter events to counter updates via event map and unsubscribe detaches them"],"goal":"verify pkg:npm/%40cacheable/utils@2.5.0","kind":"HOW","packages":["pkg:npm/%40cacheable/utils@2.5.0"],"schemaVersion":1,"symbols":["Stats"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40cacheable/utils@2.5.0"],"schemaVersion":1,"subject":"pkg:npm/%40cacheable/utils@2.5.0","symbols":["Stats"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-cacheable-utils",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-cacheable-utils",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@cacheable/utils": "2.5.0"
      }
    },
    "node_modules/@cacheable/utils": {
      "version": "2.5.0",
      "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz",
      "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==",
      "license": "MIT",
      "dependencies": {
        "hashery": "^1.5.1",
        "keyv": "^5.6.0"
      }
    },
    "node_modules/@keyv/serialize": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz",
      "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==",
      "license": "MIT"
    },
    "node_modules/hashery": {
      "version": "1.5.1",
      "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz",
      "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==",
      "license": "MIT",
      "dependencies": {
        "hookified": "^1.15.0"
      },
      "engines": {
        "node": ">=20"
      }
    },
    "node_modules/hookified": {
      "version": "1.15.1",
      "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz",
      "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==",
      "license": "MIT"
    },
    "node_modules/keyv": {
      "version": "5.6.0",
      "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz",
      "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==",
      "license": "MIT",
      "dependencies": {
        "@keyv/serialize": "^1.1.1"
      }
    }
  }
}
package.json
{
  "name": "sample-cacheable-utils",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@cacheable/utils": "2.5.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40cacheable/utils@2.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40cacheable/utils@2.5.0"
  ]
}
src/index.mjs
import { Stats } from '@cacheable/utils';

/**
 * Creates and initializes a new Stats instance.
 * @param {import('@cacheable/utils').StatsOptions} [options]
 * @returns {Stats}
 */
export function createStats(options) {
  return new Stats(options);
}

export { Stats };
export default Stats;
test/contract.mjs
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import { Stats } from '@cacheable/utils';
import { createStats } from '../src/index.mjs';

// 1. Stats initializes in a disabled state by default and ignores counter updates until enabled
{
  const stats = new Stats();
  assert.equal(stats.enabled, false);
  assert.equal(stats.hits, 0);
  assert.equal(stats.misses, 0);
  assert.equal(stats.gets, 0);
  assert.equal(stats.sets, 0);
  assert.equal(stats.lastUpdated, undefined);

  // Updates are ignored when disabled
  stats.incrementHits();
  stats.incrementMisses();
  stats.increment('gets', 5);
  stats.recordKey('user:1', 'hits');

  assert.equal(stats.hits, 0);
  assert.equal(stats.misses, 0);
  assert.equal(stats.gets, 0);
  assert.equal(stats.trackedKeys.size, 0);
  assert.equal(stats.lastUpdated, undefined);
}

// 2. Stats enable and disable methods and property setter toggle tracking state
{
  const stats = createStats();
  assert.equal(stats.enabled, false);

  stats.enable();
  assert.equal(stats.enabled, true);

  stats.disable();
  assert.equal(stats.enabled, false);

  stats.enabled = true;
  assert.equal(stats.enabled, true);

  stats.enabled = false;
  assert.equal(stats.enabled, false);
}

// 3. Stats tracks hits, misses, gets, sets, deletes, clears, and item count with increment and decrement
{
  const stats = new Stats({ enabled: true });

  stats.incrementHits(2);
  stats.incrementMisses(3);
  stats.incrementGets();
  stats.incrementSets(4);
  stats.incrementDeletes();
  stats.incrementClears(2);

  assert.equal(stats.hits, 2);
  assert.equal(stats.misses, 3);
  assert.equal(stats.gets, 1);
  assert.equal(stats.sets, 4);
  assert.equal(stats.deletes, 1);
  assert.equal(stats.clears, 2);

  // Item count tracking
  stats.incrementCount(10);
  assert.equal(stats.count, 10);
  stats.decreaseCount(3);
  assert.equal(stats.count, 7);
  stats.setCount(15);
  assert.equal(stats.count, 15);

  // Unified increment / decrement
  stats.increment('hits', 3);
  assert.equal(stats.hits, 5);
  stats.decrement('hits', 1);
  assert.equal(stats.hits, 4);
}

// 4. Stats computes hitRate and missRate from hits and misses or returns zero when no lookups occurred
{
  const stats = new Stats({ enabled: true });
  assert.equal(stats.hitRate, 0);
  assert.equal(stats.missRate, 0);

  stats.incrementHits(3);
  stats.incrementMisses(1);
  assert.equal(stats.hitRate, 0.75);
  assert.equal(stats.missRate, 0.25);

  stats.incrementMisses(2); // 3 hits, 3 misses
  assert.equal(stats.hitRate, 0.5);
  assert.equal(stats.missRate, 0.5);
}

// 5. Stats reset and clear methods reset all counters to zero and update the lastReset timestamp
{
  const stats = new Stats({ enabled: true });
  stats.incrementHits(5);
  stats.incrementSets(3);
  stats.setCount(8);
  assert.equal(stats.hits, 5);
  assert.equal(stats.lastReset, undefined);

  stats.reset();
  assert.equal(stats.hits, 0);
  assert.equal(stats.sets, 0);
  assert.equal(stats.count, 0);
  assert.equal(stats.hitRate, 0);
  assert.equal(typeof stats.lastReset, 'number');

  // clear is an alias of reset
  stats.incrementMisses(4);
  assert.equal(stats.misses, 4);
  stats.clear();
  assert.equal(stats.misses, 0);
}

// 6. Stats toJSON and snapshot return complete serializable metric representations including timestamps
{
  const stats = new Stats({ enabled: true });
  stats.incrementHits(6);
  stats.incrementMisses(2);
  stats.incrementSets(1);
  stats.setCount(10);

  const snapshot = stats.toJSON();
  assert.equal(snapshot.enabled, true);
  assert.equal(snapshot.hits, 6);
  assert.equal(snapshot.misses, 2);
  assert.equal(snapshot.hitRate, 0.75);
  assert.equal(snapshot.missRate, 0.25);
  assert.equal(snapshot.sets, 1);
  assert.equal(snapshot.count, 10);
  assert.equal(typeof snapshot.lastUpdated, 'number');

  const snapshotAlias = stats.snapshot();
  assert.deepEqual(snapshot, snapshotAlias);
}

// 7. Stats per-key tracking records operations per key and returns sorted mostUsedKeys and leastUsedKeys
{
  const stats = new Stats({ enabled: true, trackKeys: true });

  stats.recordKey('user:alpha', 'hits', 10);
  stats.recordKey('user:beta', 'hits', 5);
  stats.recordKey('user:gamma', 'misses', 1);

  assert.equal(stats.trackedKeys.size, 3);

  const alphaStats = stats.keyStats('user:alpha');
  assert.equal(alphaStats?.hits, 10);
  assert.equal(alphaStats?.count, 10);
  assert.equal(alphaStats?.hitRate, 1);

  const mostUsed = stats.mostUsedKeys(2);
  assert.equal(mostUsed.length, 2);
  assert.equal(mostUsed[0].key, 'user:alpha');
  assert.equal(mostUsed[1].key, 'user:beta');

  const leastUsed = stats.leastUsedKeys(1);
  assert.equal(leastUsed.length, 1);
  assert.equal(leastUsed[0].key, 'user:gamma');

  stats.clearKeys();
  assert.equal(stats.trackedKeys.size, 0);
  assert.equal(stats.keyStats('user:alpha'), undefined);
}

// 8. Stats subscribe binds event emitter events to counter updates via event map and unsubscribe detaches them
{
  const emitter = new EventEmitter();
  const stats = new Stats({ enabled: true });

  stats.subscribe(emitter, {
    'cache:hit': ['hits', 'gets'],
    'cache:miss': ['misses', 'gets'],
    'cache:evict': (s) => s.incrementDeletes(),
  });

  emitter.emit('cache:hit');
  emitter.emit('cache:hit');
  emitter.emit('cache:miss');
  emitter.emit('cache:evict');

  assert.equal(stats.hits, 2);
  assert.equal(stats.misses, 1);
  assert.equal(stats.gets, 3);
  assert.equal(stats.deletes, 1);

  stats.unsubscribe(emitter);

  emitter.emit('cache:hit');
  assert.equal(stats.hits, 2);
  assert.equal(stats.gets, 3);
}

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

Seeder d'origine

anonyme