CodeSampleX

Ejemplo

p-limit 3.1.0

Muestra verificada para npm p-limit 3.1.0. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó: pLimit restricts concurrent execution of…

sha256:a81faa3901abd508cdbe0aef5e5b377ade2af965f7ae7aada76631446914ecf9

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-19

Caso

HOW
Objetivo
verify pkg:npm/p-limit@3.1.0
Paquetes
Entorno
node 22.23.2
Creado
2026-08-19T22:10:40Z

Contrato

  1. pLimit restricts concurrent execution of async tasks to the specified concurrency threshold
  2. limit exposes activeCount and pendingCount properties reflecting real-time queue state
  3. limit.clearQueue empties pending queued tasks while allowing active tasks to complete
  4. limit passes through arguments to the wrapped async function and resolves with the return value
  5. pLimit throws a TypeError when initialized with invalid concurrency values

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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:ce26529a57ef02aeb2cc7ac7c31df35cbc3679f23e2636cbc82878976bf70ac2","constraints":{"executionContext":"node"},"contract":["pLimit restricts concurrent execution of async tasks to the specified concurrency threshold","limit exposes activeCount and pendingCount properties reflecting real-time queue state","limit.clearQueue empties pending queued tasks while allowing active tasks to complete","limit passes through arguments to the wrapped async function and resolves with the return value","pLimit throws a TypeError when initialized with invalid concurrency values"],"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.js"],"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,"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "p-limit-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "p-limit-sample",
      "version": "1.0.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": "p-limit-sample",
  "version": "1.0.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
const pLimit = require('p-limit');

/**
 * Creates a concurrency limiter function.
 *
 * @param {number} concurrency - Maximum number of concurrent tasks.
 * @returns {import('p-limit').Limit}
 */
function createLimiter(concurrency) {
  return pLimit(concurrency);
}

/**
 * Executes an async task through a concurrency limiter.
 *
 * @param {import('p-limit').Limit} limiter
 * @param {(...args: any[]) => Promise<any>} fn
 * @param {...any} args
 * @returns {Promise<any>}
 */
function runWithLimit(limiter, fn, ...args) {
  return limiter(fn, ...args);
}

/**
 * Retrieves the current active and pending counts for a limiter.
 *
 * @param {import('p-limit').Limit} limiter
 * @returns {{ activeCount: number, pendingCount: number }}
 */
function getLimiterState(limiter) {
  return {
    activeCount: limiter.activeCount,
    pendingCount: limiter.pendingCount,
  };
}

/**
 * Clears any pending tasks waiting in the limiter queue.
 *
 * @param {import('p-limit').Limit} limiter
 */
function clearLimiterQueue(limiter) {
  limiter.clearQueue();
}

module.exports = {
  createLimiter,
  runWithLimit,
  getLimiterState,
  clearLimiterQueue,
  pLimit,
};
test/contract.js
const assert = require('node:assert/strict');
const {
  createLimiter,
  runWithLimit,
  getLimiterState,
  clearLimiterQueue,
} = require('../src/index.js');

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

async function main() {
  // Contract 1: pLimit restricts concurrent execution of async tasks to the specified concurrency threshold
  {
    const limit = createLimiter(2);
    let active = 0;
    let maxActive = 0;

    const task = async () => {
      active++;
      maxActive = Math.max(maxActive, active);
      await delay(20);
      active--;
      return 'done';
    };

    const results = await Promise.all([
      runWithLimit(limit, task),
      runWithLimit(limit, task),
      runWithLimit(limit, task),
      runWithLimit(limit, task),
      runWithLimit(limit, task),
    ]);

    assert.strictEqual(results.length, 5);
    assert.strictEqual(results.every(r => r === 'done'), true);
    assert.strictEqual(maxActive, 2, 'Max concurrent executions should not exceed concurrency limit');
  }

  // Contract 2: limit exposes activeCount and pendingCount properties reflecting real-time queue state
  {
    const limit = createLimiter(1);
    let release;
    const blocker = new Promise(resolve => {
      release = resolve;
    });

    const p1 = limit(() => blocker);
    const p2 = limit(() => delay(10));
    const p3 = limit(() => delay(10));

    await delay(5);

    const state = getLimiterState(limit);
    assert.strictEqual(state.activeCount, 1, 'activeCount should be 1');
    assert.strictEqual(state.pendingCount, 2, 'pendingCount should be 2');

    release();
    await Promise.all([p1, p2, p3]);

    const finalState = getLimiterState(limit);
    assert.strictEqual(finalState.activeCount, 0, 'activeCount should be 0 after completion');
    assert.strictEqual(finalState.pendingCount, 0, 'pendingCount should be 0 after completion');
  }

  // Contract 3: limit.clearQueue empties pending queued tasks while allowing active tasks to complete
  {
    const limit = createLimiter(1);
    let task1Started = false;
    let task1Finished = false;
    let task2Ran = false;
    let release1;
    const blocker = new Promise(resolve => {
      release1 = resolve;
    });

    const p1 = limit(async () => {
      task1Started = true;
      await blocker;
      task1Finished = true;
      return 'task1';
    });

    const p2 = limit(async () => {
      task2Ran = true;
      return 'task2';
    });

    await delay(5);
    assert.strictEqual(task1Started, true);
    assert.strictEqual(limit.pendingCount, 1);

    clearLimiterQueue(limit);
    assert.strictEqual(limit.pendingCount, 0, 'pendingCount should be 0 after clearQueue');

    release1();
    const res1 = await p1;
    assert.strictEqual(res1, 'task1');
    assert.strictEqual(task1Finished, true);
    assert.strictEqual(task2Ran, false, 'Cleared task should not run');
  }

  // Contract 4: limit passes through arguments to the wrapped async function and resolves with the return value
  {
    const limit = createLimiter(2);
    const multiply = async (a, b) => {
      await delay(5);
      return a * b;
    };

    const res = await runWithLimit(limit, multiply, 6, 7);
    assert.strictEqual(res, 42, 'Limiter should pass arguments and resolve with return value');
  }

  // Contract 5: pLimit throws a TypeError when initialized with invalid concurrency values
  {
    assert.throws(
      () => createLimiter(0),
      {
        name: 'TypeError',
        message: 'Expected `concurrency` to be a number from 1 and up',
      }
    );
    assert.throws(
      () => createLimiter(-1),
      {
        name: 'TypeError',
        message: 'Expected `concurrency` to be a number from 1 and up',
      }
    );
    assert.throws(
      () => createLimiter(1.5),
      {
        name: 'TypeError',
        message: 'Expected `concurrency` to be a number from 1 and up',
      }
    );
    assert.throws(
      () => createLimiter('invalid'),
      {
        name: 'TypeError',
        message: 'Expected `concurrency` to be a number from 1 and up',
      }
    );
  }

  console.log('All pkg:npm/p-limit@3.1.0 contracts passed successfully.');
}

main().catch(err => {
  console.error(err);
  process.exit(1);
});

Seeder de origen

anónimo