CodeSampleX

샘플

p-limit 7.3.1

검증된 샘플 — npm p-limit 7.3.1. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: pLimit restricts concurrent execution of async tasks to the specified…

sha256:f5d58d0179ad13ebaa65cfa72909dc74718dd536be55c5cda2c19a7e3c770f6a

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
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-23
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-08

케이스

HOW
목표
verify pkg:npm/p-limit@7.3.1
패키지
환경
node 22.23.2
생성일
2026-08-23T05:57:47Z

컨트랙트

  1. pLimit restricts concurrent execution of async tasks to the specified concurrency limit
  2. limit tracks activeCount and pendingCount reflecting real-time queue state
  3. limit passes through arguments to the wrapped async function and resolves with return value
  4. limit.clearQueue discards pending tasks while allowing active tasks to complete
  5. limit.clearQueue with rejectOnClear rejects pending tasks with an AbortError
  6. limit.concurrency getter and setter dynamically adjust active task capacity
  7. limit.map concurrently maps iterable items with the concurrency limit
  8. limitFunction wraps a function with a shared concurrency limiter
  9. pLimit throws a TypeError when given invalid concurrency or rejectOnClear options

파일

  • 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/p-limit@7.3.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/p-limit@7.3.1

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:92ed1fbdb58ffd134e19c64339c663a3eba6d41a95abeb92493e6d3ca098eca8","contract":["pLimit restricts concurrent execution of async tasks to the specified concurrency limit","limit tracks activeCount and pendingCount reflecting real-time queue state","limit passes through arguments to the wrapped async function and resolves with return value","limit.clearQueue discards pending tasks while allowing active tasks to complete","limit.clearQueue with rejectOnClear rejects pending tasks with an AbortError","limit.concurrency getter and setter dynamically adjust active task capacity","limit.map concurrently maps iterable items with the concurrency limit","limitFunction wraps a function with a shared concurrency limiter","pLimit throws a TypeError when given invalid concurrency or rejectOnClear options"],"goal":"verify pkg:npm/p-limit@7.3.1","kind":"HOW","packages":["pkg:npm/p-limit@7.3.1"],"schemaVersion":1},"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/p-limit@7.3.1"],"schemaVersion":1,"subject":"pkg:npm/p-limit@7.3.1","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-p-limit",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-p-limit",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "p-limit": "7.3.1"
      }
    },
    "node_modules/p-limit": {
      "version": "7.3.1",
      "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-7.3.1.tgz",
      "integrity": "sha512-0trZaiG7Y7kN/Egy9a8j47t9osC0Tch4PaIWd9yGF6bvmlk7muExRvGNYb8sXBwEKMoNKsbNN9P8EefuQekE4Q==",
      "license": "MIT",
      "dependencies": {
        "yocto-queue": "^1.2.1"
      },
      "engines": {
        "node": ">=20"
      }
    },
    "node_modules/yocto-queue": {
      "version": "1.2.2",
      "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.2.tgz",
      "integrity": "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==",
      "license": "MIT",
      "engines": {
        "node": ">=12.20"
      }
    }
  }
}
package.json
{
  "name": "sample-p-limit",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "p-limit": "7.3.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/p-limit@7.3.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/p-limit@7.3.1"
  ]
}
src/index.mjs
import pLimit, { limitFunction } from 'p-limit';

/**
 * Creates a concurrency limiter function.
 * @param {number|object} options Concurrency count or options object.
 * @returns {Function} Limiter function.
 */
export function createLimiter(options) {
  return pLimit(options);
}

/**
 * Concurrently maps an iterable through an async mapper with a specified concurrency limit.
 * @param {Iterable} iterable Input items.
 * @param {Function} mapper Async mapper function (item, index).
 * @param {number|object} [options=2] Concurrency or options.
 * @returns {Promise<Array>} Resolved array of results.
 */
export async function mapWithLimit(iterable, mapper, options = 2) {
  const limit = pLimit(options);
  return limit.map(iterable, mapper);
}

/**
 * Wraps a function with limited concurrency across all calls.
 * @param {Function} fn Async function to wrap.
 * @param {number|object} options Concurrency or options.
 * @returns {Function} Wrapped rate-limited function.
 */
export function wrapLimitedFunction(fn, options) {
  return limitFunction(fn, options);
}

export { pLimit, limitFunction };
export default pLimit;
test/contract.mjs
import assert from 'node:assert/strict';
import pLimit, { limitFunction } from 'p-limit';
import { createLimiter, mapWithLimit, wrapLimitedFunction } from '../src/index.mjs';

// 1. pLimit restricts concurrent execution of async tasks to the specified concurrency limit
{
  const limit = pLimit(2);
  let active = 0;
  let maxActive = 0;

  const runTask = (val) => limit(async () => {
    active++;
    maxActive = Math.max(maxActive, active);
    await new Promise(resolve => setTimeout(resolve, 25));
    active--;
    return val * 2;
  });

  const results = await Promise.all([runTask(1), runTask(2), runTask(3), runTask(4)]);
  assert.deepEqual(results, [2, 4, 6, 8]);
  assert.equal(maxActive, 2);
}

// 2. limit tracks activeCount and pendingCount reflecting real-time queue state
{
  const limit = pLimit(1);
  let release;
  const p1 = limit(async () => {
    await new Promise(resolve => { release = resolve; });
    return 'first';
  });
  const p2 = limit(async () => 'second');

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(limit.activeCount, 1);
  assert.equal(limit.pendingCount, 1);

  release();
  const res = await Promise.all([p1, p2]);
  assert.deepEqual(res, ['first', 'second']);
  assert.equal(limit.activeCount, 0);
  assert.equal(limit.pendingCount, 0);
}

// 3. limit passes through arguments to the wrapped async function and resolves with return value
{
  const limit = pLimit(2);
  const result = await limit((a, b, c) => a + b + c, 'foo', '-', 'bar');
  assert.equal(result, 'foo-bar');
}

// 4. limit.clearQueue discards pending tasks while allowing active tasks to complete
{
  const limit = pLimit(1);
  let release;
  let secondRan = false;

  const activeTask = limit(async () => {
    await new Promise(resolve => { release = resolve; });
    return 'active-done';
  });
  const pendingTask = limit(async () => {
    secondRan = true;
    return 'pending-done';
  });

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(limit.pendingCount, 1);

  limit.clearQueue();
  assert.equal(limit.pendingCount, 0);

  release();
  const activeRes = await activeTask;
  assert.equal(activeRes, 'active-done');

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(secondRan, false);
}

// 5. limit.clearQueue with rejectOnClear rejects pending tasks with an AbortError
{
  const limit = pLimit({ concurrency: 1, rejectOnClear: true });
  let release;
  let rejectedError;

  const activeTask = limit(async () => {
    await new Promise(resolve => { release = resolve; });
    return 'done';
  });

  const pendingTask = limit(async () => 'never').catch(err => {
    rejectedError = err;
  });

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(limit.pendingCount, 1);

  limit.clearQueue();
  assert.equal(limit.pendingCount, 0);

  release();
  await activeTask;
  await pendingTask;

  assert.equal(rejectedError?.name, 'AbortError');
}

// 6. limit.concurrency getter and setter dynamically adjust active task capacity
{
  const limit = pLimit(1);
  assert.equal(limit.concurrency, 1);

  let release1;
  let release2;
  let startedCount = 0;

  const t1 = limit(async () => {
    startedCount++;
    await new Promise(resolve => { release1 = resolve; });
  });
  const t2 = limit(async () => {
    startedCount++;
    await new Promise(resolve => { release2 = resolve; });
  });

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(startedCount, 1);

  limit.concurrency = 2;
  assert.equal(limit.concurrency, 2);

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(startedCount, 2);

  release1();
  release2();
  await Promise.all([t1, t2]);
}

// 7. limit.map concurrently maps iterable items with the concurrency limit
{
  const limit = pLimit(2);
  const items = [10, 20, 30, 40];
  const mapped = await limit.map(items, async (item, index) => {
    await new Promise(resolve => setTimeout(resolve, 10));
    return item + index;
  });
  assert.deepEqual(mapped, [10, 21, 32, 43]);

  // Helper mapWithLimit
  const helperMapped = await mapWithLimit([1, 2, 3], async (x) => x * 10, 2);
  assert.deepEqual(helperMapped, [10, 20, 30]);
}

// 8. limitFunction wraps a function with a shared concurrency limiter
{
  let concurrentExecutions = 0;
  let peakExecutions = 0;

  const limitedFn = limitFunction(async (x) => {
    concurrentExecutions++;
    peakExecutions = Math.max(peakExecutions, concurrentExecutions);
    await new Promise(resolve => setTimeout(resolve, 20));
    concurrentExecutions--;
    return x * 10;
  }, 2);

  const results = await Promise.all([limitedFn(1), limitedFn(2), limitedFn(3), limitedFn(4)]);
  assert.deepEqual(results, [10, 20, 30, 40]);
  assert.equal(peakExecutions, 2);

  // Helper wrapLimitedFunction
  const wrapped = wrapLimitedFunction(async (x) => x + 5, 2);
  assert.equal(await wrapped(10), 15);
}

// 9. pLimit throws a TypeError when given invalid concurrency or rejectOnClear options
{
  assert.throws(() => pLimit(0), TypeError);
  assert.throws(() => pLimit(-1), TypeError);
  assert.throws(() => pLimit(1.5), TypeError);
  assert.throws(() => pLimit('invalid'), TypeError);
  assert.throws(() => pLimit({ concurrency: 1, rejectOnClear: 'not-a-bool' }), TypeError);
  assert.throws(() => createLimiter(0), TypeError);
}

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

오리진 시더

익명