CodeSampleX

Пример

toad-cache 3.7.4: FifoMap

Проверенный пример — npm toad-cache 3.7.4: FifoMap. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: new FifoMap() defaults to max=1000…

sha256:2a53853e690466960793e631adb94a54b244c61ca5d6da31488ba8e279c7663b

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-22

Кейс

HOW
Цель
verify toad-cache.FifoMap in pkg:npm/toad-cache@3.7.4
Пакеты
Символы
  • toad-cache.FifoMap
Окружение
node 22.23.2
Создан
2026-11-22T17:51:48Z

Контракт

  1. new FifoMap() defaults to max=1000, ttl=0, size=0 and accepts non-string Map keys such as objects and numbers
  2. new FifoMap(max, ttlInMsecs) throws 'Invalid max value' or 'Invalid ttl value' for negative, non-integer, or non-numeric arguments, while max=0 disables capacity eviction
  3. set() evicts the oldest inserted entry when size reaches max, and neither get() nor overwriting an existing key via set() moves that key out of its FIFO position
  4. getMany(), delete(), deleteMany(), evict(), keys(), and clear() maintain accurate entries, Map key iteration order, and size
  5. When ttlInMsecs > 0, expiresAt(key) reports the expiration timestamp, get(key) deletes and returns undefined once Date.now() >= expiry, and overwriting a key refreshes its expiry without changing FIFO order

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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.FifoMap 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.FifoMap
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:6c6f01e1ba13f850bd04b7e7a029d33cbb25577f27213e70c3dbc03d6fc6aa7f","constraints":{"executionContext":"node"},"contract":["new FifoMap() defaults to max=1000, ttl=0, size=0 and accepts non-string Map keys such as objects and numbers","new FifoMap(max, ttlInMsecs) throws 'Invalid max value' or 'Invalid ttl value' for negative, non-integer, or non-numeric arguments, while max=0 disables capacity eviction","set() evicts the oldest inserted entry when size reaches max, and neither get() nor overwriting an existing key via set() moves that key out of its FIFO position","getMany(), delete(), deleteMany(), evict(), keys(), and clear() maintain accurate entries, Map key iteration order, and size","When ttlInMsecs \u003e 0, expiresAt(key) reports the expiration timestamp, get(key) deletes and returns undefined once Date.now() \u003e= expiry, and overwriting a key refreshes its expiry without changing FIFO order"],"goal":"verify toad-cache.FifoMap in pkg:npm/toad-cache@3.7.4","kind":"HOW","packages":["pkg:npm/toad-cache@3.7.4"],"schemaVersion":1,"symbols":["toad-cache.FifoMap"]},"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.FifoMap"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "toad-cache-fifomap-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "toad-cache-fifomap-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-fifomap-sample",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "toad-cache": "3.7.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify toad-cache.FifoMap in pkg:npm/toad-cache@3.7.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/toad-cache@3.7.4"
  ],
  "symbols": [
    "toad-cache.FifoMap"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.cjs
'use strict';

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

function createFifoCache(max, ttlInMsecs) {
  return new FifoMap(max, ttlInMsecs);
}

module.exports = {
  createFifoCache,
};
test/contract.cjs
'use strict';

const assert = require('node:assert/strict');
const { FifoMap } = require('toad-cache');
const { createFifoCache } = require('../src/index.cjs');

// 1. Defaults and Map key identity semantics
{
  const cache = createFifoCache();
  assert.equal(cache instanceof FifoMap, true);
  assert.equal(cache.max, 1000);
  assert.equal(cache.ttl, 0);
  assert.equal(cache.size, 0);

  const objKeyA = { id: 1 };
  const objKeyB = { id: 1 };
  cache.set(objKeyA, 'alpha');
  cache.set(1, 'num-one');
  cache.set('1', 'str-one');

  assert.equal(cache.size, 3);
  assert.equal(cache.get(objKeyA), 'alpha');
  assert.equal(cache.get(objKeyB), undefined);
  assert.equal(cache.get(1), 'num-one');
  assert.equal(cache.get('1'), 'str-one');
  assert.equal(cache.expiresAt(objKeyA), 0);
  assert.equal(cache.expiresAt('missing'), undefined);
}

// 2. Constructor validation and unlimited capacity (max = 0)
{
  assert.throws(() => new FifoMap(-1), /Invalid max value/);
  assert.throws(() => new FifoMap(1.5), /Invalid max value/);
  assert.throws(() => new FifoMap('10'), /Invalid max value/);
  assert.throws(() => new FifoMap(NaN), /Invalid max value/);
  assert.throws(() => new FifoMap(null), /Invalid max value/);

  assert.throws(() => new FifoMap(10, -1), /Invalid ttl value/);
  assert.throws(() => new FifoMap(10, 0.5), /Invalid ttl value/);
  assert.throws(() => new FifoMap(10, '50'), /Invalid ttl value/);
  assert.throws(() => new FifoMap(10, NaN), /Invalid ttl value/);

  const unlimited = new FifoMap(0, 0);
  unlimited.set('a', 1);
  unlimited.set('b', 2);
  unlimited.set('c', 3);
  assert.equal(unlimited.size, 3);
  assert.deepEqual(unlimited.getMany(['a', 'b', 'c']), [1, 2, 3]);
}

// 3. Strict FIFO eviction: get() and overwrite set() do not change eviction order
{
  const cache = new FifoMap(2);
  cache.set('first', 'v1');
  cache.set('second', 'v2');

  // Reading or updating 'first' must NOT move it ahead of 'second'
  assert.equal(cache.get('first'), 'v1');
  cache.set('first', 'v1-updated');
  assert.equal(cache.get('first'), 'v1-updated');
  assert.equal(cache.size, 2);

  // Inserting 'third' evicts 'first' (oldest inserted), keeping 'second' and 'third'
  cache.set('third', 'v3');
  assert.equal(cache.size, 2);
  assert.equal(cache.get('first'), undefined);
  assert.equal(cache.get('second'), 'v2');
  assert.equal(cache.get('third'), 'v3');
  assert.deepEqual(Array.from(cache.keys()), ['second', 'third']);
}

// 4. getMany(), delete(), deleteMany(), evict(), keys(), and clear()
{
  const cache = new FifoMap(5);
  cache.set('k1', 10);
  cache.set('k2', 20);
  cache.set('k3', 30);
  cache.set('k4', 40);

  assert.deepEqual(cache.getMany(['k1', 'missing', 'k3']), [10, undefined, 30]);
  assert.deepEqual(Array.from(cache.keys()), ['k1', 'k2', 'k3', 'k4']);

  // Manual evict removes oldest ('k1')
  cache.evict();
  assert.equal(cache.size, 3);
  assert.equal(cache.get('k1'), undefined);
  assert.deepEqual(Array.from(cache.keys()), ['k2', 'k3', 'k4']);

  // delete middle entry and non-existent entry
  cache.delete('k3');
  cache.delete('non-existent');
  assert.equal(cache.size, 2);
  assert.deepEqual(Array.from(cache.keys()), ['k2', 'k4']);

  // deleteMany
  cache.deleteMany(['k2', 'missing']);
  assert.equal(cache.size, 1);
  assert.deepEqual(Array.from(cache.keys()), ['k4']);

  // clear resets size and pointers; evict on empty cache is safe no-op
  cache.clear();
  assert.equal(cache.size, 0);
  assert.equal(cache.first, null);
  assert.equal(cache.last, null);
  cache.evict();
  assert.equal(cache.size, 0);
}

// 5. TTL expiration and expiry refresh on overwrite without reordering FIFO
{
  const realDateNow = Date.now;
  let now = 1_700_000_000_000;
  Date.now = () => now;

  try {
    const cache = new FifoMap(2, 100);
    cache.set('a', 'va');
    assert.equal(cache.expiresAt('a'), now + 100);

    now += 40;
    cache.set('b', 'vb');
    assert.equal(cache.expiresAt('b'), now + 100);

    // Overwrite 'a' refreshes its expiry to now + 100 but keeps 'a' as oldest in FIFO order
    now += 20;
    cache.set('a', 'va2');
    assert.equal(cache.expiresAt('a'), now + 100);
    assert.equal(cache.get('a'), 'va2');

    // Inserting 'c' evicts 'a' (still oldest) even though 'a' has a later expiry than 'b'
    cache.set('c', 'vc');
    assert.equal(cache.get('a'), undefined);
    assert.equal(cache.get('b'), 'vb');
    assert.equal(cache.get('c'), 'vc');

    // Advance past 'b' expiry (set at t+40, expires at t+140; currently t+60)
    now += 80; // t+140 => b.expiry <= now, c.expiry is t+160
    assert.equal(cache.get('b'), undefined);
    assert.equal(cache.size, 1);
    assert.equal(cache.get('c'), 'vc');

    // Advance past 'c' expiry
    now += 20; // t+160 => c.expiry <= now
    assert.deepEqual(cache.getMany(['b', 'c']), [undefined, undefined]);
    assert.equal(cache.size, 0);
  } finally {
    Date.now = realDateNow;
  }
}

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

Исходный сидер

аноним