サンプル
@cacheable/utils 2.5.0: wrap
検証済みサンプル — npm @cacheable/utils 2.5.0: wrap. node 22 · linux debian/x64 · docker で contract を実行し、成功しました: wrap memoizes the return value of an async function…
sha256:7df8c072e95fe6534231b2ff9a7ce797ee225dbf089ffcdab6c519b74504bbf0
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。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 wrap in pkg:npm/%40cacheable/utils@2.5.0
- パッケージ
- シンボル
-
- wrap
- 作成日
- 2026-09-05T17:12:07Z
コントラクト
- wrap memoizes the return value of an async function for identical arguments using the provided cache instance
- wrap re-executes the underlying function when invoked with different arguments
- wrap coalesces concurrent invocations with identical arguments to prevent cache stampedes
- wrap applies custom key prefixes when generating default cache keys
- wrap uses custom createKey functions to derive cache keys from function references and arguments
- wrap forwards configured ttl values to the underlying cache store during set operations
- wrap rethrows errors from the wrapped function when throwErrors is enabled
- wrap caches errors returned by the wrapped function when cacheErrors is enabled
ファイル
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
ソース
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 wrap 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:
- wrap
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.
{"case":{"caseId":"case:sha256:79b0abda6aba7a4875b0bf639330477832db54f91680efa1ff3565168155ef72","contract":["wrap memoizes the return value of an async function for identical arguments using the provided cache instance","wrap re-executes the underlying function when invoked with different arguments","wrap coalesces concurrent invocations with identical arguments to prevent cache stampedes","wrap applies custom key prefixes when generating default cache keys","wrap uses custom createKey functions to derive cache keys from function references and arguments","wrap forwards configured ttl values to the underlying cache store during set operations","wrap rethrows errors from the wrapped function when throwErrors is enabled","wrap caches errors returned by the wrapped function when cacheErrors is enabled"],"goal":"verify wrap in pkg:npm/%40cacheable/utils@2.5.0","kind":"HOW","packages":["pkg:npm/%40cacheable/utils@2.5.0"],"schemaVersion":1,"symbols":["wrap"]},"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":["wrap"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-cacheable-utils-wrap",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-cacheable-utils-wrap",
"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"
}
}
}
}
{
"name": "sample-cacheable-utils-wrap",
"version": "1.0.0",
"type": "module",
"private": true,
"license": "MIT-0",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"@cacheable/utils": "2.5.0"
}
}
{
"schemaVersion": 1,
"goal": "verify wrap in pkg:npm/%40cacheable/utils@2.5.0",
"kind": "HOW",
"packages": [
"pkg:npm/%40cacheable/utils@2.5.0"
],
"symbols": [
"wrap"
]
}
import { wrap } from '@cacheable/utils';
import { EventEmitter } from 'node:events';
/**
* In-memory cache implementation conforming to CacheInstance.
*/
export class MemoryCache extends EventEmitter {
constructor() {
super();
this.store = new Map();
this.ttls = new Map();
}
async get(key) {
return this.store.get(key);
}
async set(key, value, ttl) {
this.store.set(key, value);
if (ttl !== undefined) {
this.ttls.set(key, ttl);
}
}
async has(key) {
return this.store.has(key);
}
async delete(key) {
this.store.delete(key);
this.ttls.delete(key);
}
async clear() {
this.store.clear();
this.ttls.clear();
}
}
/**
* Creates a cached version of an async function with an optional cache instance.
* @param {Function} fn Function to wrap.
* @param {Object} [options={}] Options for wrap and cache.
* @returns {{ cache: MemoryCache, wrapped: Function }}
*/
export function createCachedFunction(fn, options = {}) {
const cache = options.cache ?? new MemoryCache();
const wrapped = wrap(fn, { cache, ...options });
return { cache, wrapped };
}
export { wrap };
export default wrap;
import assert from 'node:assert/strict';
import { wrap } from '@cacheable/utils';
import { MemoryCache, createCachedFunction } from '../src/index.mjs';
// 1. wrap memoizes the return value of an async function for identical arguments using the provided cache instance
{
const cache = new MemoryCache();
let calls = 0;
const fn = async (x) => {
calls++;
return x * 10;
};
const wrapped = wrap(fn, { cache });
const res1 = await wrapped(5);
const res2 = await wrapped(5);
assert.equal(res1, 50, 'First call returns computed value');
assert.equal(res2, 50, 'Second call returns cached value');
assert.equal(calls, 1, 'Underlying function called only once');
}
// 2. wrap re-executes the underlying function when invoked with different arguments
{
const { cache, wrapped } = createCachedFunction(async (name) => `hello ${name}`);
const r1 = await wrapped('alice');
const r2 = await wrapped('bob');
assert.equal(r1, 'hello alice');
assert.equal(r2, 'hello bob');
assert.equal(cache.store.size, 2, 'Cache contains entries for both distinct arguments');
}
// 3. wrap coalesces concurrent invocations with identical arguments to prevent cache stampedes
{
const cache = new MemoryCache();
let executions = 0;
const slowFn = wrap(async (id) => {
executions++;
await new Promise((resolve) => setTimeout(resolve, 30));
return `item-${id}`;
}, { cache });
const [resA, resB, resC] = await Promise.all([
slowFn(42),
slowFn(42),
slowFn(42)
]);
assert.equal(resA, 'item-42');
assert.equal(resB, 'item-42');
assert.equal(resC, 'item-42');
assert.equal(executions, 1, 'Underlying function executed once during concurrent requests');
}
// 4. wrap applies custom key prefixes when generating default cache keys
{
const cache = new MemoryCache();
const testFn = async (v) => v + 1;
const wrapped = wrap(testFn, { cache, keyPrefix: 'my-service' });
await wrapped(100);
const keys = [...cache.store.keys()];
assert.equal(keys.length, 1);
assert.ok(keys[0].startsWith('my-service::'), 'Cache key should start with configured keyPrefix');
}
// 5. wrap uses custom createKey functions to derive cache keys from function references and arguments
{
const cache = new MemoryCache();
const customKey = (fn, args) => `custom-key:${args[0]}:${args[1]}`;
const wrapped = wrap(async (a, b) => a + b, {
cache,
createKey: customKey
});
await wrapped('alpha', 'beta');
assert.ok(cache.store.has('custom-key:alpha:beta'), 'Cache should have custom formatted key');
}
// 6. wrap forwards configured ttl values to the underlying cache store during set operations
{
const cache = new MemoryCache();
const wrapped = wrap(async (x) => x * 2, {
cache,
ttl: 3600
});
await wrapped(7);
const key = [...cache.store.keys()][0];
assert.equal(cache.ttls.get(key), 3600, 'Configured ttl forwarded to cache store');
}
// 7. wrap rethrows errors from the wrapped function when throwErrors is enabled
{
const cache = new MemoryCache();
cache.on('error', () => {}); // Handle emitted error event
const wrapped = wrap(async () => {
throw new Error('computation failed');
}, { cache, throwErrors: true });
await assert.rejects(
async () => { await wrapped(); },
{ message: 'computation failed' },
'Wrapped function should reject with underlying error when throwErrors is true'
);
}
// 8. wrap caches errors returned by the wrapped function when cacheErrors is enabled
{
const cache = new MemoryCache();
cache.on('error', () => {});
let failures = 0;
const errorFn = wrap(async () => {
failures++;
throw new Error('fatal');
}, { cache, cacheErrors: true });
// First call captures error and caches it
const first = await errorFn();
// Second call retrieves cached error without invoking the function again
const second = await errorFn();
assert.ok(first === undefined || first instanceof Error, 'First execution completes error handling');
assert.ok(second instanceof Error, 'Second execution returns cached Error instance');
assert.equal(second.message, 'fatal');
assert.equal(failures, 1, 'Function executed only once despite error');
}
console.log('Contract tests passed successfully.');
オリジンシーダー
匿名