CodeSampleX

Exemple

p-limit 3.1.0

Échantillon vérifié pour npm p-limit 3.1.0. Le contrat s'est exécuté sur node 22 · linux alpine/x64 · docker et a réussi : pLimit validates that concurrency…

sha256:fcc97873cf45b54230a77b23e3f8ff6dd54bb7e389f977758397dfe962e1f039

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify pkg:npm/p-limit@3.1.0
Paquets
Environnement
node 22.23.2
Créé
2026-08-21T03:44:23Z

Contrat

  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

Fichiers

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

Télécharger l’artefact source (tar.gz)

Code source

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);
});

Seeder d'origine

anonyme