CodeSampleX

Exemplo

keyv 4.5.4

Amostra verificada para npm keyv 4.5.4. O contrato rodou em node 22 · linux alpine/x64 · docker e passou: Keyv initializes in-memory key-value store and…

sha256:70ace232043eb9d4d704fe191313515652f2fa57f97e3a5f572cf831485cb3fe

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 alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-28

Caso

HOW
Objetivo
verify pkg:npm/keyv@4.5.4
Pacotes
Ambiente
node 22.23.2
Criado
2026-08-28T03:22:08Z

Contrato

  1. Keyv initializes in-memory key-value store and supports set, get, has, delete, and clear methods
  2. Keyv handles structured data including JSON objects, nested arrays, booleans, and numbers
  3. Keyv expires keys accurately when time-to-live (TTL) in milliseconds is specified
  4. Keyv namespaces isolate key-value pairs across separate instances sharing the same store
  5. Keyv delete returns true for existing keys and false when deleting non-existent keys

Arquivos

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

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 pkg:npm/keyv@4.5.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/keyv@4.5.4
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:93d02c91edac97b54b2b193516eaf45df72bac0f720f1584f2234b217c5c28f7","constraints":{"executionContext":"node"},"contract":["Keyv initializes in-memory key-value store and supports set, get, has, delete, and clear methods","Keyv handles structured data including JSON objects, nested arrays, booleans, and numbers","Keyv expires keys accurately when time-to-live (TTL) in milliseconds is specified","Keyv namespaces isolate key-value pairs across separate instances sharing the same store","Keyv delete returns true for existing keys and false when deleting non-existent keys"],"goal":"verify pkg:npm/keyv@4.5.4","kind":"HOW","packages":["pkg:npm/keyv@4.5.4"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"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/keyv@4.5.4"],"schemaVersion":1,"subject":"pkg:npm/keyv@4.5.4","verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const Keyv = require('keyv');

/**
 * Creates a Keyv store instance with optional configuration.
 * @param {object} [options={}] - Keyv constructor options.
 * @returns {Keyv}
 */
function createStore(options = {}) {
  return new Keyv(options);
}

/**
 * Sets a key-value pair in the store with an optional TTL in milliseconds.
 * @param {Keyv} store - The Keyv instance.
 * @param {string} key - The key name.
 * @param {*} value - The value to store.
 * @param {number} [ttl] - Time-to-live in milliseconds.
 * @returns {Promise<boolean>}
 */
async function setKey(store, key, value, ttl) {
  return store.set(key, value, ttl);
}

/**
 * Retrieves the value associated with a key from the store.
 * @param {Keyv} store - The Keyv instance.
 * @param {string} key - The key name.
 * @returns {Promise<*>}
 */
async function getKey(store, key) {
  return store.get(key);
}

/**
 * Checks whether a key exists in the store.
 * @param {Keyv} store - The Keyv instance.
 * @param {string} key - The key name.
 * @returns {Promise<boolean>}
 */
async function hasKey(store, key) {
  return store.has(key);
}

/**
 * Deletes a key from the store.
 * @param {Keyv} store - The Keyv instance.
 * @param {string} key - The key name.
 * @returns {Promise<boolean>}
 */
async function deleteKey(store, key) {
  return store.delete(key);
}

/**
 * Clears all keys in the store.
 * @param {Keyv} store - The Keyv instance.
 * @returns {Promise<void>}
 */
async function clearStore(store) {
  return store.clear();
}

module.exports = {
  createStore,
  setKey,
  getKey,
  hasKey,
  deleteKey,
  clearStore
};
package-lock.json
{
  "name": "sample-keyv",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-keyv",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "keyv": "4.5.4"
      }
    },
    "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-keyv",
  "version": "1.0.0",
  "private": true,
  "description": "verify pkg:npm/keyv@4.5.4",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "keyv": "4.5.4"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/keyv@4.5.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/keyv@4.5.4"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.js
'use strict';

const assert = require('node:assert');
const Keyv = require('keyv');
const {
  createStore,
  setKey,
  getKey,
  hasKey,
  deleteKey,
  clearStore
} = require('../index.js');

async function testBasicSetAndGet() {
  const store = createStore();
  const setSuccess = await setKey(store, 'hello', 'world');
  assert.strictEqual(setSuccess, true, 'set should return true on success');

  const value = await getKey(store, 'hello');
  assert.strictEqual(value, 'world', 'get should return the stored string');
}

async function testStructuredDataTypes() {
  const store = createStore();
  const payload = {
    id: 101,
    tags: ['database', 'cache'],
    active: true,
    nested: { count: 42 }
  };

  await setKey(store, 'payloadKey', payload);
  const result = await getKey(store, 'payloadKey');
  assert.deepStrictEqual(result, payload, 'get should retrieve deeply equal structured objects and arrays');
}

async function testHasAndDelete() {
  const store = createStore();
  await setKey(store, 'sessionToken', 'abc-123');

  const existsBefore = await hasKey(store, 'sessionToken');
  assert.strictEqual(existsBefore, true, 'has should return true for existing key');

  const deleteSuccess = await deleteKey(store, 'sessionToken');
  assert.strictEqual(deleteSuccess, true, 'delete should return true when key is successfully removed');

  const existsAfter = await hasKey(store, 'sessionToken');
  assert.strictEqual(existsAfter, false, 'has should return false after key is deleted');

  const valueAfter = await getKey(store, 'sessionToken');
  assert.strictEqual(valueAfter, undefined, 'get should return undefined for deleted key');

  const deleteMissing = await deleteKey(store, 'sessionToken');
  assert.strictEqual(deleteMissing, false, 'delete should return false when key does not exist');
}

async function testTtlExpiration() {
  const store = createStore();
  await setKey(store, 'temporaryKey', 'expiresSoon', 50);

  const valueImmediate = await getKey(store, 'temporaryKey');
  assert.strictEqual(valueImmediate, 'expiresSoon', 'get should return value before TTL expiration');

  await new Promise((resolve) => setTimeout(resolve, 60));

  const valueExpired = await getKey(store, 'temporaryKey');
  assert.strictEqual(valueExpired, undefined, 'get should return undefined after TTL expires');
}

async function testNamespaceIsolation() {
  const storeA = createStore({ namespace: 'nsA' });
  const storeB = createStore({ namespace: 'nsB' });

  await setKey(storeA, 'key1', 'valueA');
  await setKey(storeB, 'key1', 'valueB');

  assert.strictEqual(await getKey(storeA, 'key1'), 'valueA', 'storeA retrieves valueA');
  assert.strictEqual(await getKey(storeB, 'key1'), 'valueB', 'storeB retrieves valueB');

  await clearStore(storeA);
  assert.strictEqual(await getKey(storeA, 'key1'), undefined, 'clear on storeA removes storeA keys');
  assert.strictEqual(await getKey(storeB, 'key1'), 'valueB', 'clear on storeA does not affect storeB');
}

async function testDirectKeyvInstance() {
  const keyv = new Keyv();
  await keyv.set('directKey', 9999);
  const val = await keyv.get('directKey');
  assert.strictEqual(val, 9999, 'direct Keyv instance set/get works');
  assert.strictEqual(await keyv.has('directKey'), true, 'direct Keyv has works');
  assert.strictEqual(await keyv.delete('directKey'), true, 'direct Keyv delete works');
  assert.strictEqual(await keyv.has('directKey'), false, 'key no longer exists');
}

async function runAll() {
  await testBasicSetAndGet();
  await testStructuredDataTypes();
  await testHasAndDelete();
  await testTtlExpiration();
  await testNamespaceIsolation();
  await testDirectKeyvInstance();
  console.log('All contract tests passed successfully.');
}

runAll().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

Seeder de origem

anônimo