CodeSampleX

Exemplo

toad-cache 3.7.4: LruMap

Amostra verificada para npm toad-cache 3.7.4: LruMap. O contrato rodou em node 22 · linux debian/x64 · docker e passou: require('toad-cache').LruMap…

sha256:cf5860194342423f86d44adb38671e0b2d88992b879fdc672c08b93820f60b54

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-29

Caso

HOW
Objetivo
verify toad-cache.LruMap in pkg:npm/toad-cache@3.7.4
Pacotes
Símbolos
  • toad-cache.LruMap
Ambiente
node 22.23.2
Criado
2026-11-29T02:30:34Z

Contrato

  1. require('toad-cache').LruMap constructs with default max=1000 and ttl=0, treats max=0 as unlimited capacity, and throws Error('Invalid max value') or Error('Invalid ttl value') for negative or non-integer parameters
  2. LruMap stores distinct object, number, string, and symbol keys without string coercion
  3. When size reaches max (> 0), set() evicts the least-recently-used entry, while get() and set() updates bump accessed entries to most-recently-used
  4. getMany() returns values aligned to input keys with undefined for misses, keys() returns an IterableIterator, evict() removes the least-recently-used entry, and delete(), deleteMany(), and clear() remove entries and update size
  5. With ttlInMsecs > 0, expiresAt() returns the numeric expiry timestamp (0 when ttl=0, undefined when absent) and get() lazily deletes expired entries and returns undefined

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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.LruMap 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.LruMap
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:eb4f6b751bbf9310c026a6a9e3e536b9d6dba43ffcf48f6ffa4a11110d0ffc58","constraints":{"executionContext":"node"},"contract":["require('toad-cache').LruMap constructs with default max=1000 and ttl=0, treats max=0 as unlimited capacity, and throws Error('Invalid max value') or Error('Invalid ttl value') for negative or non-integer parameters","LruMap stores distinct object, number, string, and symbol keys without string coercion","When size reaches max (\u003e 0), set() evicts the least-recently-used entry, while get() and set() updates bump accessed entries to most-recently-used","getMany() returns values aligned to input keys with undefined for misses, keys() returns an IterableIterator, evict() removes the least-recently-used entry, and delete(), deleteMany(), and clear() remove entries and update size","With ttlInMsecs \u003e 0, expiresAt() returns the numeric expiry timestamp (0 when ttl=0, undefined when absent) and get() lazily deletes expired entries and returns undefined"],"goal":"verify toad-cache.LruMap in pkg:npm/toad-cache@3.7.4","kind":"HOW","packages":["pkg:npm/toad-cache@3.7.4"],"schemaVersion":1,"symbols":["toad-cache.LruMap"]},"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.LruMap"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const { LruMap } = require('toad-cache');

function createLruMap(max, ttlInMsecs) {
  return new LruMap(max, ttlInMsecs);
}

module.exports = {
  LruMap,
  createLruMap,
};
package-lock.json
{
  "name": "toad-cache-lrumap-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "toad-cache-lrumap-sample",
      "version": "1.0.0",
      "license": "MIT-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-lrumap-sample",
  "version": "1.0.0",
  "private": true,
  "description": "Minimal CJS sample verifying toad-cache.LruMap in toad-cache@3.7.4",
  "main": "index.js",
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "toad-cache": "3.7.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify toad-cache.LruMap in pkg:npm/toad-cache@3.7.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/toad-cache@3.7.4"
  ],
  "symbols": [
    "toad-cache.LruMap"
  ],
  "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 { setTimeout: delay } = require('node:timers/promises');
const { LruMap } = require('toad-cache');
const { createLruMap } = require('../index.js');

async function main() {
  // 1. Constructor defaults, unlimited max=0, and parameter validation
  assert.equal(typeof LruMap, 'function');

  const defaultCache = new LruMap();
  assert.equal(defaultCache.max, 1000);
  assert.equal(defaultCache.ttl, 0);
  assert.equal(defaultCache.size, 0);
  assert.equal(defaultCache.first, null);
  assert.equal(defaultCache.last, null);

  assert.throws(() => new LruMap(-1), { message: 'Invalid max value' });
  assert.throws(() => new LruMap(1.5), { message: 'Invalid max value' });
  assert.throws(() => new LruMap('2'), { message: 'Invalid max value' });
  assert.throws(() => new LruMap(10, -1), { message: 'Invalid ttl value' });
  assert.throws(() => new LruMap(10, 0.5), { message: 'Invalid ttl value' });

  const unlimited = createLruMap(0, 0);
  unlimited.set('k1', 1);
  unlimited.set('k2', 2);
  unlimited.set('k3', 3);
  assert.equal(unlimited.size, 3);
  assert.equal(unlimited.expiresAt('k1'), 0);
  assert.equal(unlimited.expiresAt('missing'), undefined);

  // 2. Non-string key identity (Map-backed storage without key stringification)
  const typedKeys = new LruMap(10);
  const objA = { id: 1 };
  const objB = { id: 1 };
  const sym = Symbol('entry');
  typedKeys.set(objA, 'first-obj');
  typedKeys.set(objB, 'second-obj');
  typedKeys.set(1, 'num-one');
  typedKeys.set('1', 'str-one');
  typedKeys.set(sym, 'sym-val');
  assert.equal(typedKeys.size, 5);
  assert.equal(typedKeys.get(objA), 'first-obj');
  assert.equal(typedKeys.get(objB), 'second-obj');
  assert.equal(typedKeys.get(1), 'num-one');
  assert.equal(typedKeys.get('1'), 'str-one');
  assert.equal(typedKeys.get(sym), 'sym-val');

  // 3. LRU eviction order and recency bumping on get() and set() updates
  const lru = new LruMap(2);
  lru.set('a', 1);
  lru.set('b', 2);
  assert.equal(lru.get('a'), 1); // bumps 'a' ahead of 'b'
  lru.set('c', 3); // evicts least-recently-used 'b'
  assert.equal(lru.size, 2);
  assert.equal(lru.get('b'), undefined);
  assert.equal(lru.get('a'), 1);
  assert.equal(lru.get('c'), 3);

  // Updating an existing key refreshes its value and bumps recency without evicting
  lru.set('a', 10); // 'a' becomes MRU; 'c' is now LRU
  assert.equal(lru.size, 2);
  lru.set('d', 4); // evicts 'c'
  assert.equal(lru.get('c'), undefined);
  assert.equal(lru.get('a'), 10);
  assert.equal(lru.get('d'), 4);

  // 4. getMany(), keys() iterator, evict(), delete(), deleteMany(), clear()
  const managed = new LruMap(5);
  managed.set('x', 'val-x');
  managed.set('y', 'val-y');
  managed.set('z', 'val-z');
  managed.set('w', 'val-w');

  assert.deepEqual(managed.getMany(['x', 'absent', 'z']), ['val-x', undefined, 'val-z']);

  const keyIter = managed.keys();
  assert.equal(typeof keyIter.next, 'function');
  assert.deepEqual(Array.from(keyIter), ['x', 'y', 'z', 'w']);

  // After getMany(['x', 'absent', 'z']), LRU order is y -> w -> x -> z
  managed.evict(); // evicts 'y'
  assert.equal(managed.get('y'), undefined);
  assert.equal(managed.size, 3);

  managed.delete('w');
  assert.equal(managed.get('w'), undefined);
  assert.equal(managed.size, 2);

  managed.deleteMany(['x', 'absent']);
  assert.equal(managed.get('x'), undefined);
  assert.equal(managed.size, 1);
  assert.equal(managed.get('z'), 'val-z');

  managed.clear();
  assert.equal(managed.size, 0);
  assert.equal(managed.first, null);
  assert.equal(managed.last, null);
  assert.equal(managed.get('z'), undefined);

  // 5. TTL expiration and expiresAt()
  const ttlMs = 30;
  const before = Date.now();
  const expiring = new LruMap(5, ttlMs);
  expiring.set('temp', 'alive');
  const expiry = expiring.expiresAt('temp');
  assert.equal(typeof expiry, 'number');
  assert.ok(expiry >= before + ttlMs);
  assert.equal(expiring.get('temp'), 'alive');

  await delay(ttlMs + 40);
  assert.equal(expiring.get('temp'), undefined);
  assert.equal(expiring.size, 0);
  assert.equal(expiring.expiresAt('temp'), undefined);
}

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

Seeder de origem

anônimo