CodeSampleX

サンプル

@cacheable/utils 2.5.0: getOrSet

検証済みサンプル — npm @cacheable/utils 2.5.0: getOrSet. node 22 · linux debian/x64 · docker で contract を実行し、成功しました: getOrSet returns cached value without executing…

sha256:9119b876f46e9ca9ac730eb0122a943fad9291a7535d51652b13e4382c5f6f47

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 npm

検証実行環境

環境 コントラクト ステージ 実行日
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

ケース

HOW
ゴール
verify getOrSet in pkg:npm/%40cacheable/utils@2.5.0
パッケージ
シンボル
  • getOrSet
作成日
2026-09-05T17:10:13Z

コントラクト

  1. getOrSet returns cached value without executing setter on cache hit
  2. getOrSet executes setter, stores result in cache with ttl, and returns computed value on cache miss
  3. getOrSet supports deriving cache key dynamically using a key generator function
  4. getOrSet coalesces concurrent calls for the same key into a single setter invocation
  5. getOrSet emits errors on cache instance and rethrows them when throwErrors is configured
  6. getOrSet stores caught errors in cache when cacheErrors is enabled

ファイル

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

ソースアーティファクトをダウンロード (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 getOrSet in pkg:npm/%40cacheable/utils@2.5.0
Kind: HOW

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

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:202cc5e7eb510b88f324751917c6262e53cb135c3952c7855b4e77545e37165e","contract":["getOrSet returns cached value without executing setter on cache hit","getOrSet executes setter, stores result in cache with ttl, and returns computed value on cache miss","getOrSet supports deriving cache key dynamically using a key generator function","getOrSet coalesces concurrent calls for the same key into a single setter invocation","getOrSet emits errors on cache instance and rethrows them when throwErrors is configured","getOrSet stores caught errors in cache when cacheErrors is enabled"],"goal":"verify getOrSet in pkg:npm/%40cacheable/utils@2.5.0","kind":"HOW","packages":["pkg:npm/%40cacheable/utils@2.5.0"],"schemaVersion":1,"symbols":["getOrSet"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40cacheable/utils@2.5.0"],"schemaVersion":1,"subject":"pkg:npm/%40cacheable/utils@2.5.0","symbols":["getOrSet"],"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",
  "private": true,
  "description": "Clean-room verification of @cacheable/utils getOrSet",
  "type": "module",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "@cacheable/utils": "2.5.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify getOrSet in pkg:npm/%40cacheable/utils@2.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40cacheable/utils@2.5.0"
  ],
  "symbols": [
    "getOrSet"
  ]
}
src/index.js
import { getOrSet } from '@cacheable/utils';

/**
 * Retrieve a value from cache or compute and store it using getOrSet.
 * @param {string | Function} key - Cache key or function returning cache key.
 * @param {() => Promise<any>} fn - Async setter function invoked on cache miss.
 * @param {object} options - Options including cache instance, ttl, etc.
 * @returns {Promise<any>} The cached or newly computed value.
 */
export async function fetchOrCompute(key, fn, options) {
  return getOrSet(key, fn, options);
}

export { getOrSet };
test/contract.mjs
import assert from 'node:assert';
import EventEmitter from 'node:events';
import { getOrSet, fetchOrCompute } from '../src/index.js';

class MockCache extends EventEmitter {
  constructor() {
    super();
    this.map = new Map();
    this.sets = [];
  }
  async get(key) {
    return this.map.get(key);
  }
  async set(key, value, ttl) {
    this.map.set(key, value);
    this.sets.push({ key, value, ttl });
  }
  async has(key) {
    return this.map.has(key);
  }
}

// 1. getOrSet returns cached value without executing setter on cache hit
{
  const cache = new MockCache();
  cache.map.set('k1', 'existing-value');
  let setterCalled = false;
  const result = await getOrSet('k1', async () => {
    setterCalled = true;
    return 'new-value';
  }, { cache });
  assert.strictEqual(result, 'existing-value');
  assert.strictEqual(setterCalled, false);

  const helperResult = await fetchOrCompute('k1', async () => {
    setterCalled = true;
    return 'helper-new';
  }, { cache });
  assert.strictEqual(helperResult, 'existing-value');
  assert.strictEqual(setterCalled, false);
}

// 2. getOrSet executes setter, stores result in cache with ttl, and returns computed value on cache miss
{
  const cache = new MockCache();
  let callCount = 0;
  const result = await getOrSet('k2', async () => {
    callCount++;
    return 'computed-value';
  }, { cache, ttl: 3000 });

  assert.strictEqual(result, 'computed-value');
  assert.strictEqual(callCount, 1);
  assert.strictEqual(await cache.get('k2'), 'computed-value');
  assert.strictEqual(cache.sets[0].ttl, 3000);
}

// 3. getOrSet supports deriving cache key dynamically using a key generator function
{
  const cache = new MockCache();
  const keyFn = (opts) => `prefix:${opts.cacheId}`;
  const result = await getOrSet(keyFn, async () => 'dynamic-result', { cache, cacheId: 'session-123' });
  assert.strictEqual(result, 'dynamic-result');
  assert.strictEqual(await cache.get('prefix:session-123'), 'dynamic-result');
}

// 4. getOrSet coalesces concurrent calls for the same key into a single setter invocation
{
  const cache = new MockCache();
  let callCount = 0;
  const slowTask = async () => {
    callCount++;
    await new Promise((resolve) => setTimeout(resolve, 30));
    return `coalesced-${callCount}`;
  };

  const [res1, res2, res3] = await Promise.all([
    getOrSet('k-shared', slowTask, { cache }),
    getOrSet('k-shared', slowTask, { cache }),
    getOrSet('k-shared', slowTask, { cache }),
  ]);

  assert.strictEqual(callCount, 1);
  assert.strictEqual(res1, 'coalesced-1');
  assert.strictEqual(res2, 'coalesced-1');
  assert.strictEqual(res3, 'coalesced-1');
}

// 5. getOrSet emits errors on cache instance and rethrows them when throwErrors is configured
{
  const cache = new MockCache();
  let emittedError = null;
  cache.on('error', (err) => {
    emittedError = err;
  });

  let thrown = false;
  try {
    await getOrSet('k-fail', async () => {
      throw new Error('computation failure');
    }, { cache, throwErrors: true });
  } catch (err) {
    thrown = true;
    assert.strictEqual(err.message, 'computation failure');
  }

  assert.strictEqual(thrown, true);
  assert.strictEqual(emittedError?.message, 'computation failure');
}

// 6. getOrSet stores caught errors in cache when cacheErrors is enabled
{
  const cache = new MockCache();
  cache.on('error', () => {});
  const sampleError = new Error('persisted failure');

  await getOrSet('k-cache-err', async () => {
    throw sampleError;
  }, { cache, cacheErrors: true, throwErrors: false });

  assert.strictEqual(await cache.get('k-cache-err'), sampleError);
}

console.log('All getOrSet contract tests passed.');

オリジンシーダー

匿名