CodeSampleX

샘플

p-limit 3.1.0

검증된 샘플 — npm p-limit 3.1.0. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: pLimit validates that concurrency is an integer or Infinity greater…

sha256:fcc97873cf45b54230a77b23e3f8ff6dd54bb7e389f977758397dfe962e1f039

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
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@1
2026-08-21

케이스

HOW
목표
verify pkg:npm/p-limit@3.1.0
패키지
환경
node 22.23.2
생성일
2026-08-21T03:44:23Z

컨트랙트

  1. pLimit validates that concurrency is an integer or Infinity greater than or equal to 1
  2. limit passes through arguments and resolves with the return value or rejects with errors
  3. limit executes tasks concurrently up to the configured limit and queues subsequent tasks
  4. activeCount and pendingCount reflect currently executing and queued task counts
  5. clearQueue empties pending queued tasks while allowing active tasks to complete
  6. runWithConcurrency executes an array of async tasks with bounded concurrency

파일

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

Use EXACTLY these public packages and versions:
  - pkg:npm/p-limit@3.1.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:bf34efee7dfd85f5bd34609fbe385418cc20e9f8031d4818c476181da7885a6c","constraints":{"executionContext":"node"},"contract":["pLimit validates that concurrency is an integer or Infinity greater than or equal to 1","limit passes through arguments and resolves with the return value or rejects with errors","limit executes tasks concurrently up to the configured limit and queues subsequent tasks","activeCount and pendingCount reflect currently executing and queued task counts","clearQueue empties pending queued tasks while allowing active tasks to complete","runWithConcurrency executes an array of async tasks with bounded concurrency"],"goal":"verify pkg:npm/p-limit@3.1.0","kind":"HOW","packages":["pkg:npm/p-limit@3.1.0"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","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@3.1.0"],"schemaVersion":1,"subject":"pkg:npm/p-limit@3.1.0","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": "3.1.0"
      }
    },
    "node_modules/p-limit": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
      "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
      "license": "MIT",
      "dependencies": {
        "yocto-queue": "^0.1.0"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/yocto-queue": {
      "version": "0.1.0",
      "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
      "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
      "license": "MIT",
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    }
  }
}
package.json
{
  "name": "sample-p-limit",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for p-limit@3.1.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "p-limit": "3.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/p-limit@3.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/p-limit@3.1.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
'use strict';

const pLimit = require('p-limit');

/**
 * Creates a concurrency limiter with the specified concurrency limit.
 *
 * @param {number} concurrency - Maximum number of concurrent tasks (>= 1 or Infinity).
 * @returns {Function} Limiter function that wraps async tasks.
 */
function createLimiter(concurrency) {
  return pLimit(concurrency);
}

/**
 * Executes an array of async task functions with bounded concurrency.
 *
 * @param {Array<() => Promise<any>>} tasks - List of asynchronous task generator functions.
 * @param {number} concurrency - Maximum number of concurrent tasks.
 * @returns {Promise<Array<any>>} Array of resolved task results.
 */
async function runWithConcurrency(tasks, concurrency) {
  const limit = pLimit(concurrency);
  return Promise.all(tasks.map((task) => limit(task)));
}

module.exports = {
  pLimit,
  createLimiter,
  runWithConcurrency
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { pLimit, createLimiter, runWithConcurrency } = require('../src/index.js');

async function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function testAll() {
  // 1. Export verification
  assert.equal(typeof pLimit, 'function', 'pLimit export must be a function');
  assert.equal(typeof createLimiter, 'function', 'createLimiter helper must be a function');
  assert.equal(typeof runWithConcurrency, 'function', 'runWithConcurrency helper must be a function');

  // 2. Concurrency validation
  assert.throws(
    () => pLimit(0),
    {
      name: 'TypeError',
      message: 'Expected `concurrency` to be a number from 1 and up'
    },
    'pLimit should throw TypeError when concurrency is 0'
  );

  assert.throws(
    () => pLimit(-1),
    {
      name: 'TypeError',
      message: 'Expected `concurrency` to be a number from 1 and up'
    },
    'pLimit should throw TypeError when concurrency is negative'
  );

  assert.throws(
    () => pLimit(1.5),
    {
      name: 'TypeError',
      message: 'Expected `concurrency` to be a number from 1 and up'
    },
    'pLimit should throw TypeError when concurrency is a non-integer float'
  );

  assert.throws(
    () => pLimit('1'),
    {
      name: 'TypeError',
      message: 'Expected `concurrency` to be a number from 1 and up'
    },
    'pLimit should throw TypeError when concurrency is a string'
  );

  assert.doesNotThrow(() => pLimit(1), 'pLimit(1) should not throw');
  assert.doesNotThrow(() => pLimit(Infinity), 'pLimit(Infinity) should not throw');

  // 3. Argument passing and return value resolution
  const limit1 = pLimit(1);
  const sumResult = await limit1(async (a, b, c) => a + b + c, 10, 20, 30);
  assert.equal(sumResult, 60, 'limit should pass arguments and resolve with return value');

  // Rejection handling
  await assert.rejects(
    async () => {
      await limit1(async () => {
        throw new Error('task failure');
      });
    },
    {
      name: 'Error',
      message: 'task failure'
    },
    'limit should propagate rejections'
  );

  // 4. Concurrency bounding and task execution order
  const concurrency = 2;
  const limit2 = pLimit(concurrency);
  let activeRunning = 0;
  let maxActive = 0;
  const executionOrder = [];

  const taskList = [1, 2, 3, 4, 5].map((id) => async () => {
    activeRunning++;
    if (activeRunning > maxActive) {
      maxActive = activeRunning;
    }
    executionOrder.push(`start-${id}`);
    await delay(30);
    executionOrder.push(`end-${id}`);
    activeRunning--;
    return id * 10;
  });

  const results = await Promise.all(taskList.map((task) => limit2(task)));
  assert.deepEqual(results, [10, 20, 30, 40, 50], 'all tasks should resolve with correct values');
  assert.ok(maxActive <= concurrency, `max concurrent tasks (${maxActive}) must not exceed limit (${concurrency})`);
  assert.equal(activeRunning, 0, 'active task count must return to 0');

  // 5. activeCount and pendingCount property tracking
  const limitSingle = pLimit(1);
  assert.equal(limitSingle.activeCount, 0, 'initial activeCount should be 0');
  assert.equal(limitSingle.pendingCount, 0, 'initial pendingCount should be 0');

  let resolveTask1;
  let resolveTask2;
  const task1Promise = new Promise((res) => { resolveTask1 = res; });
  const task2Promise = new Promise((res) => { resolveTask2 = res; });

  const p1 = limitSingle(async () => {
    await task1Promise;
    return 't1';
  });
  const p2 = limitSingle(async () => {
    await task2Promise;
    return 't2';
  });

  // Allow microtask to enqueue
  await delay(10);

  assert.equal(limitSingle.activeCount, 1, 'activeCount should reflect 1 running task');
  assert.equal(limitSingle.pendingCount, 1, 'pendingCount should reflect 1 queued task');

  resolveTask1();
  await p1;
  await delay(10);

  assert.equal(limitSingle.activeCount, 1, 'activeCount should reflect next running task');
  assert.equal(limitSingle.pendingCount, 0, 'pendingCount should now be 0');

  resolveTask2();
  await p2;
  await delay(10);

  assert.equal(limitSingle.activeCount, 0, 'activeCount should be 0 when all tasks complete');
  assert.equal(limitSingle.pendingCount, 0, 'pendingCount should be 0 when all tasks complete');

  // 6. clearQueue behavior
  const limitClear = pLimit(1);
  let resolveBlocking;
  const blockingPromise = new Promise((res) => { resolveBlocking = res; });
  let taskRan = false;

  const runningTask = limitClear(async () => {
    await blockingPromise;
    return 'unblocked';
  });

  const queuedTask = limitClear(async () => {
    taskRan = true;
    return 'never';
  });

  await delay(10);
  assert.equal(limitClear.pendingCount, 1, 'one task should be queued');

  limitClear.clearQueue();
  assert.equal(limitClear.pendingCount, 0, 'pendingCount should become 0 after clearQueue()');

  resolveBlocking();
  await runningTask;
  await delay(20);

  assert.equal(taskRan, false, 'cleared queue task should never execute');

  // 7. runWithConcurrency helper verification
  const helperTasks = [
    async () => { await delay(10); return 'a'; },
    async () => { await delay(10); return 'b'; },
    async () => { await delay(10); return 'c'; }
  ];
  const helperResults = await runWithConcurrency(helperTasks, 2);
  assert.deepEqual(helperResults, ['a', 'b', 'c'], 'runWithConcurrency helper should resolve all results');

  console.log('All p-limit contract tests passed successfully.');
}

testAll().catch((err) => {
  console.error('Contract test failure:', err);
  process.exit(1);
});

오리진 시더

익명