CodeSampleX

Пример

flat-cache 4.0.1

Проверенный пример — npm flat-cache 4.0.1. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: create initializes a new cache instance and…

sha256:88ff90274b65a138a83726a14af69361160fcddaa8f38d85e3a88b5885075fcb

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

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

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

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

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

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

Кейс

HOW
Цель
verify pkg:npm/flat-cache@4.0.1
Пакеты
Окружение
node 22.23.2
Создан
2026-08-20T22:16:41Z

Контракт

  1. create initializes a new cache instance and setKey stores in-memory values
  2. getKey retrieves stored values and returns undefined for non-existent keys
  3. all returns all key-value pairs and keys returns all stored key names
  4. save persists the cache data to disk
  5. load recovers persisted key-value pairs from disk storage
  6. save with noPrune false removes keys that were not visited during the session
  7. removeKey deletes specific keys from the cache
  8. destroy clears in-memory state and removes the underlying cache file from disk
  9. clearCacheById deletes a cache file by identifier and directory

Файлы

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • 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 pkg:npm/flat-cache@4.0.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/flat-cache@4.0.1
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - 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:6dc59ae7e2b089185d1890526b3aa58e5703962a48a4f2d1374a1d1c34e1a283","constraints":{"executionContext":"node"},"contract":["create initializes a new cache instance and setKey stores in-memory values","getKey retrieves stored values and returns undefined for non-existent keys","all returns all key-value pairs and keys returns all stored key names","save persists the cache data to disk","load recovers persisted key-value pairs from disk storage","save with noPrune false removes keys that were not visited during the session","removeKey deletes specific keys from the cache","destroy clears in-memory state and removes the underlying cache file from disk","clearCacheById deletes a cache file by identifier and directory"],"goal":"verify pkg:npm/flat-cache@4.0.1","kind":"HOW","packages":["pkg:npm/flat-cache@4.0.1"],"schemaVersion":1},"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","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/flat-cache@4.0.1"],"schemaVersion":1,"subject":"pkg:npm/flat-cache@4.0.1","verifierAdapter":"node-typescript@1"}
index.js
const flatCache = require('flat-cache');

module.exports = {
  flatCache
};
package-lock.json
{
  "name": "sample-flat-cache",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-flat-cache",
      "version": "1.0.0",
      "dependencies": {
        "flat-cache": "4.0.1"
      }
    },
    "node_modules/flat-cache": {
      "version": "4.0.1",
      "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz",
      "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==",
      "license": "MIT",
      "dependencies": {
        "flatted": "^3.2.9",
        "keyv": "^4.5.4"
      },
      "engines": {
        "node": ">=16"
      }
    },
    "node_modules/flatted": {
      "version": "3.4.4",
      "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz",
      "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==",
      "license": "ISC"
    },
    "node_modules/json-buffer": {
      "version": "3.0.1",
      "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
      "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",
      "license": "MIT"
    },
    "node_modules/keyv": {
      "version": "4.5.4",
      "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
      "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",
      "license": "MIT",
      "dependencies": {
        "json-buffer": "3.0.1"
      }
    }
  }
}
package.json
{
  "name": "sample-flat-cache",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for flat-cache@4.0.1",
  "main": "index.js",
  "dependencies": {
    "flat-cache": "4.0.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/flat-cache@4.0.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/flat-cache@4.0.1"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "runtime": "node@22.23.2"
  }
}
test/contract.cjs
const assert = require('node:assert/strict');
const path = require('node:path');
const os = require('node:os');
const fs = require('node:fs');
const flatCache = require('flat-cache');

async function run() {
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'flat-cache-test-'));

  try {
    // 1. create initializes a new cache instance and setKey stores in-memory values
    const cache = flatCache.create('test-cache-1', tmpDir);
    assert.ok(cache, 'cache instance should be created');
    cache.setKey('sessionUser', 'alice');
    cache.setKey('sessionRole', 'admin');
    cache.setKey('loginCount', 5);

    // 2. getKey retrieves stored values and returns undefined for non-existent keys
    assert.equal(cache.getKey('sessionUser'), 'alice');
    assert.equal(cache.getKey('sessionRole'), 'admin');
    assert.equal(cache.getKey('loginCount'), 5);
    assert.equal(cache.getKey('nonExistentKey'), undefined);

    // 3. all returns all key-value pairs and keys returns all stored key names
    const allData = cache.all();
    assert.deepEqual(allData, {
      sessionUser: 'alice',
      sessionRole: 'admin',
      loginCount: 5
    });
    const keyList = cache.keys();
    assert.deepEqual(keyList.sort(), ['loginCount', 'sessionRole', 'sessionUser']);

    // 4. save persists the cache data to disk
    cache.save(true);
    const expectedFilePath = path.join(tmpDir, 'test-cache-1');
    assert.equal(fs.existsSync(expectedFilePath), true, 'cache file should exist after save');

    // 5. load recovers persisted key-value pairs from disk storage
    const loadedCache = flatCache.load('test-cache-1', tmpDir);
    assert.equal(loadedCache.getKey('sessionUser'), 'alice');
    assert.equal(loadedCache.getKey('sessionRole'), 'admin');
    assert.equal(loadedCache.getKey('loginCount'), 5);

    // 6. save with noPrune false removes keys that were not visited during the session
    const freshSession = flatCache.load('test-cache-1', tmpDir);
    assert.equal(freshSession.getKey('sessionUser'), 'alice');
    assert.equal(freshSession.getKey('loginCount'), 5);
    freshSession.save(false);

    const prunedCache = flatCache.load('test-cache-1', tmpDir);
    assert.equal(prunedCache.getKey('sessionUser'), 'alice');
    assert.equal(prunedCache.getKey('loginCount'), 5);
    assert.equal(prunedCache.getKey('sessionRole'), undefined);

    // 7. removeKey deletes specific keys from the cache
    prunedCache.removeKey('loginCount');
    assert.equal(prunedCache.getKey('loginCount'), undefined);
    assert.deepEqual(prunedCache.keys(), ['sessionUser']);

    // 8. destroy clears in-memory state and removes the underlying cache file from disk
    prunedCache.destroy();
    assert.equal(fs.existsSync(expectedFilePath), false, 'cache file should be deleted on destroy');
    assert.deepEqual(prunedCache.all(), {});
    assert.deepEqual(prunedCache.keys(), []);

    // 9. clearCacheById deletes a cache file by identifier and directory
    const tempCache = flatCache.create('temp-cache-file', tmpDir);
    tempCache.setKey('temp', 'data');
    tempCache.save(true);
    const tempFilePath = path.join(tmpDir, 'temp-cache-file');
    assert.equal(fs.existsSync(tempFilePath), true);
    const cleared = flatCache.clearCacheById('temp-cache-file', tmpDir);
    assert.equal(cleared, true);
    assert.equal(fs.existsSync(tempFilePath), false);

    console.log('All flat-cache contract assertions passed.');
  } finally {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  }
}

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

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

аноним