CodeSampleX

Пример

@cacheable/utils 2.5.0: coalesceAsync

Проверенный пример — npm @cacheable/utils 2.5.0: coalesceAsync. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:d7c126b496497fe24a203aca1832ea1e3cddb28d4958e8cb5fb50377e9d2166b

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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 pkg:npm/%40cacheable/utils@2.5.0
Пакеты
Символы
  • coalesceAsync
Создан
2026-09-05T16:31:33Z

Контракт

  1. coalesceAsync executes the async function and resolves with its return value
  2. coalesceAsync coalesces concurrent calls with the same key into a single invocation
  3. coalesceAsync executes independent calls concurrently for different keys
  4. coalesceAsync propagates thrown errors to all concurrent callers waiting on the same key
  5. coalesceAsync executes subsequent calls anew after prior invocation for the same key settles

Файлы

  • 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 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:
  - coalesceAsync

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:8e65053d52b6cba77a1f082d43f22881a45e7c7673ea6be2717d8a161cbeb4a7","contract":["coalesceAsync executes the async function and resolves with its return value","coalesceAsync coalesces concurrent calls with the same key into a single invocation","coalesceAsync executes independent calls concurrently for different keys","coalesceAsync propagates thrown errors to all concurrent callers waiting on the same key","coalesceAsync executes subsequent calls anew after prior invocation for the same key settles"],"goal":"verify pkg:npm/%40cacheable/utils@2.5.0","kind":"HOW","packages":["pkg:npm/%40cacheable/utils@2.5.0"],"schemaVersion":1,"symbols":["coalesceAsync"]},"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":["coalesceAsync"],"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 coalesceAsync",
  "type": "module",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "@cacheable/utils": "2.5.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40cacheable/utils@2.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40cacheable/utils@2.5.0"
  ],
  "symbols": [
    "coalesceAsync"
  ]
}
src/index.js
import { coalesceAsync } from '@cacheable/utils';

/**
 * Execute an async function coalescing concurrent calls with the same key.
 * @param {string} key - Cache or grouping key.
 * @param {() => Promise<any>} fnc - Async task function to execute.
 * @returns {Promise<any>}
 */
export async function executeCoalesced(key, fnc) {
  return coalesceAsync(key, fnc);
}

export { coalesceAsync };
test/contract.mjs
import assert from 'node:assert';
import { coalesceAsync, executeCoalesced } from '../src/index.js';

// 1. coalesceAsync executes the async function and resolves with its return value
const singleResult = await coalesceAsync('test-single', async () => 'resolved-value');
assert.strictEqual(singleResult, 'resolved-value');

const helperResult = await executeCoalesced('test-helper', async () => 'helper-value');
assert.strictEqual(helperResult, 'helper-value');

// 2. coalesceAsync coalesces concurrent calls with the same key into a single invocation
let callCount = 0;
const slowTask = async () => {
  callCount++;
  await new Promise((resolve) => setTimeout(resolve, 50));
  return `computed-${callCount}`;
};

const [c1, c2, c3] = await Promise.all([
  coalesceAsync('group-key', slowTask),
  coalesceAsync('group-key', slowTask),
  coalesceAsync('group-key', slowTask),
]);

assert.strictEqual(callCount, 1);
assert.strictEqual(c1, 'computed-1');
assert.strictEqual(c2, 'computed-1');
assert.strictEqual(c3, 'computed-1');

// 3. coalesceAsync executes independent calls concurrently for different keys
let distinctCallCount = 0;
const distinctTask = (name) => async () => {
  distinctCallCount++;
  await new Promise((resolve) => setTimeout(resolve, 20));
  return `result-${name}`;
};

const [resA, resB] = await Promise.all([
  coalesceAsync('key-alpha', distinctTask('alpha')),
  coalesceAsync('key-beta', distinctTask('beta')),
]);

assert.strictEqual(distinctCallCount, 2);
assert.strictEqual(resA, 'result-alpha');
assert.strictEqual(resB, 'result-beta');

// 4. coalesceAsync propagates thrown errors to all concurrent callers waiting on the same key
let failureCallCount = 0;
const failingTask = async () => {
  failureCallCount++;
  await new Promise((resolve) => setTimeout(resolve, 30));
  throw new Error('coalesced error failure');
};

const settledResults = await Promise.allSettled([
  coalesceAsync('err-group', failingTask),
  coalesceAsync('err-group', failingTask),
]);

assert.strictEqual(failureCallCount, 1);
assert.strictEqual(settledResults[0].status, 'rejected');
assert.strictEqual(settledResults[1].status, 'rejected');
assert.strictEqual(settledResults[0].reason.message, 'coalesced error failure');
assert.strictEqual(settledResults[1].reason.message, 'coalesced error failure');

// 5. coalesceAsync executes subsequent calls anew after prior invocation for the same key settles
let sequentialCount = 0;
const sequentialTask = async () => {
  sequentialCount++;
  return sequentialCount;
};

const seq1 = await coalesceAsync('settled-key', sequentialTask);
assert.strictEqual(seq1, 1);
assert.strictEqual(sequentialCount, 1);

const seq2 = await coalesceAsync('settled-key', sequentialTask);
assert.strictEqual(seq2, 2);
assert.strictEqual(sequentialCount, 2);

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

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

аноним