CodeSampleX

샘플

@cacheable/utils 2.5.0: coalesceAsync

검증된 샘플 — npm @cacheable/utils 2.5.0: coalesceAsync. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: coalesceAsync deduplicates concurrent…

sha256:bd0c1aca6fadd296bbaa7fbe1f1caf7f4a7fdc3bab0aee82fb6f6ffeb6798d7d

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
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
환경
node 22.23.2
생성일
2026-09-05T16:18:33Z

컨트랙트

  1. coalesceAsync deduplicates concurrent executions with the same key to run the function only once
  2. coalesceAsync resolves all concurrent callers with the identical returned value
  3. coalesceAsync propagates an error to all concurrent callers when the worker function rejects
  4. coalesceAsync executes the worker function again for subsequent calls after the initial promise settles
  5. coalesceAsync executes calls with distinct keys concurrently and independently without grouping them
  6. coalesceAsync handles worker functions that return immediate synchronous values as well as promises

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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:8fb696408dfc3309bba478eda2e95902c03a9f340e7b186dd3db970f26fd8c1e","contract":["coalesceAsync deduplicates concurrent executions with the same key to run the function only once","coalesceAsync resolves all concurrent callers with the identical returned value","coalesceAsync propagates an error to all concurrent callers when the worker function rejects","coalesceAsync executes the worker function again for subsequent calls after the initial promise settles","coalesceAsync executes calls with distinct keys concurrently and independently without grouping them","coalesceAsync handles worker functions that return immediate synchronous values as well as promises"],"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","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","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-coalesce",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-cacheable-utils-coalesce",
      "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-coalesce",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "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.mjs
import { coalesceAsync } from '@cacheable/utils';

/**
 * Executes an async function, coalescing concurrent calls sharing the same key.
 * @template T
 * @param {string} key - Grouping key
 * @param {() => T | PromiseLike<T>} fn - Function to coalesce
 * @returns {Promise<T>}
 */
export async function runCoalesced(key, fn) {
  return coalesceAsync(key, fn);
}

export { coalesceAsync };
export default coalesceAsync;
test/contract.mjs
import assert from 'node:assert/strict';
import { coalesceAsync } from '@cacheable/utils';
import { runCoalesced } from '../src/index.mjs';

// 1. coalesceAsync deduplicates concurrent executions with the same key to run the function only once
{
  let executions = 0;
  const worker = async () => {
    executions++;
    await new Promise((resolve) => setTimeout(resolve, 30));
    return 'computed-value';
  };

  const [a, b, c] = await Promise.all([
    coalesceAsync('concurrent-run', worker),
    coalesceAsync('concurrent-run', worker),
    runCoalesced('concurrent-run', worker),
  ]);

  assert.equal(executions, 1);
  assert.equal(a, 'computed-value');
  assert.equal(b, 'computed-value');
  assert.equal(c, 'computed-value');
}

// 2. coalesceAsync resolves all concurrent callers with the identical returned value
{
  const sharedObj = { id: 101, timestamp: Date.now() };
  const worker = async () => {
    await new Promise((resolve) => setTimeout(resolve, 20));
    return sharedObj;
  };

  const [first, second] = await Promise.all([
    coalesceAsync('shared-obj-key', worker),
    coalesceAsync('shared-obj-key', worker),
  ]);

  assert.equal(first, second);
  assert.deepEqual(first, sharedObj);
}

// 3. coalesceAsync propagates an error to all concurrent callers when the worker function rejects
{
  let attempts = 0;
  const failingWorker = async () => {
    attempts++;
    await new Promise((resolve) => setTimeout(resolve, 20));
    throw new Error('database connection timeout');
  };

  const outcomes = await Promise.allSettled([
    coalesceAsync('error-key', failingWorker),
    coalesceAsync('error-key', failingWorker),
  ]);

  assert.equal(attempts, 1);
  assert.equal(outcomes.length, 2);
  assert.equal(outcomes[0].status, 'rejected');
  assert.equal(outcomes[1].status, 'rejected');
  assert.equal(outcomes[0].reason.message, 'database connection timeout');
  assert.equal(outcomes[1].reason.message, 'database connection timeout');
}

// 4. coalesceAsync executes the worker function again for subsequent calls after the initial promise settles
{
  let invocationCount = 0;
  const sequentialWorker = async () => {
    invocationCount++;
    return `seq-${invocationCount}`;
  };

  const result1 = await coalesceAsync('seq-key', sequentialWorker);
  assert.equal(result1, 'seq-1');
  assert.equal(invocationCount, 1);

  const result2 = await coalesceAsync('seq-key', sequentialWorker);
  assert.equal(result2, 'seq-2');
  assert.equal(invocationCount, 2);
}

// 5. coalesceAsync executes calls with distinct keys concurrently and independently without grouping them
{
  let runA = 0;
  let runB = 0;

  const fnA = async () => {
    runA++;
    await new Promise((resolve) => setTimeout(resolve, 25));
    return 'group-A';
  };

  const fnB = async () => {
    runB++;
    await new Promise((resolve) => setTimeout(resolve, 25));
    return 'group-B';
  };

  const [resA, resB] = await Promise.all([
    coalesceAsync('key-distinct-1', fnA),
    coalesceAsync('key-distinct-2', fnB),
  ]);

  assert.equal(runA, 1);
  assert.equal(runB, 1);
  assert.equal(resA, 'group-A');
  assert.equal(resB, 'group-B');
}

// 6. coalesceAsync handles worker functions that return immediate synchronous values as well as promises
{
  let syncRuns = 0;
  const syncFn = () => {
    syncRuns++;
    return 9999;
  };

  const res = await coalesceAsync('sync-key', syncFn);
  assert.equal(res, 9999);
  assert.equal(syncRuns, 1);
}

console.log('Contract tests passed successfully.');

오리진 시더

익명