CodeSampleX

Ejemplo

p-locate 5.0.0: pLocate

Muestra verificada para npm p-locate 5.0.0: pLocate. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó: pLocate resolves with the first…

sha256:32943f55f4980b0857355c33635c069265b7eeeb42d6d4748b96aceec2d69e96

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:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

Caso

HOW
Objetivo
verify pLocate in pkg:npm/p-locate@5.0.0
Paquetes
Símbolos
  • pLocate
Entorno
node 22.23.2
Creado
2026-08-27T10:04:11Z

Contrato

  1. pLocate resolves with the first element in iterable that satisfies an async or sync tester function
  2. pLocate resolves to undefined when no element in iterable satisfies tester
  3. pLocate supports iterables containing promises that resolve to elements
  4. pLocate preserves input order by default when async testers resolve out of order
  5. pLocate with preserveOrder false returns the fastest resolving match
  6. pLocate respects concurrency option to limit parallel tester executions
  7. pLocate works with non-array iterables such as Set and generator functions
  8. pLocate propagates errors when a tester throws or an input promise rejects

Archivos

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

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 pLocate in pkg:npm/p-locate@5.0.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/p-locate@5.0.0
Demonstrate these symbols/APIs:
  - pLocate

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:1105c50067421428e93227c4971784aebbcced3dc0094d848933868f8ec5564a","contract":["pLocate resolves with the first element in iterable that satisfies an async or sync tester function","pLocate resolves to undefined when no element in iterable satisfies tester","pLocate supports iterables containing promises that resolve to elements","pLocate preserves input order by default when async testers resolve out of order","pLocate with preserveOrder false returns the fastest resolving match","pLocate respects concurrency option to limit parallel tester executions","pLocate works with non-array iterables such as Set and generator functions","pLocate propagates errors when a tester throws or an input promise rejects"],"goal":"verify pLocate in pkg:npm/p-locate@5.0.0","kind":"HOW","packages":["pkg:npm/p-locate@5.0.0"],"schemaVersion":1,"symbols":["pLocate"]},"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-locate@5.0.0"],"schemaVersion":1,"subject":"pkg:npm/p-locate@5.0.0","symbols":["pLocate"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-p-locate",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-p-locate",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "p-locate": "5.0.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/p-locate": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",
      "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",
      "license": "MIT",
      "dependencies": {
        "p-limit": "^3.0.2"
      },
      "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-locate",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "p-locate": "5.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pLocate in pkg:npm/p-locate@5.0.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/p-locate@5.0.0"
  ],
  "symbols": [
    "pLocate"
  ]
}
src/index.mjs
import pLocate from 'p-locate';

/**
 * Finds the first element in an iterable that satisfies the tester function.
 * @param {Iterable} iterable Input iterable of values or promises.
 * @param {Function} tester Predicate function returning boolean or Promise<boolean>.
 * @param {object} [options] Optional settings (concurrency, preserveOrder).
 * @returns {Promise<*|undefined>} The first matching element, or undefined.
 */
export async function findFirstMatch(iterable, tester, options) {
  return pLocate(iterable, tester, options);
}

/**
 * Finds the first matching element without preserving input order (fastest resolving match).
 * @param {Iterable} iterable Input iterable of values or promises.
 * @param {Function} tester Predicate function returning boolean or Promise<boolean>.
 * @param {number} [concurrency=Infinity] Concurrency limit.
 * @returns {Promise<*|undefined>} The first resolved matching element, or undefined.
 */
export async function findFirstResolvedMatch(iterable, tester, concurrency = Infinity) {
  return pLocate(iterable, tester, { preserveOrder: false, concurrency });
}

/**
 * Finds the first matching element with limited concurrency.
 * @param {Iterable} iterable Input iterable of values or promises.
 * @param {Function} tester Predicate function returning boolean or Promise<boolean>.
 * @param {number} concurrency Concurrency limit.
 * @returns {Promise<*|undefined>} The first matching element, or undefined.
 */
export async function findWithConcurrency(iterable, tester, concurrency) {
  return pLocate(iterable, tester, { concurrency });
}

export { pLocate };
export default pLocate;
test/contract.mjs
import assert from 'node:assert/strict';
import pLocate from 'p-locate';
import { findFirstMatch, findFirstResolvedMatch, findWithConcurrency } from '../src/index.mjs';

// 1. pLocate resolves with the first element in iterable that satisfies an async or sync tester function
{
  const items = ['apple', 'banana', 'cherry'];
  const syncResult = await pLocate(items, (item) => item.startsWith('b'));
  assert.equal(syncResult, 'banana');

  const asyncResult = await pLocate(items, async (item) => {
    await new Promise((resolve) => setTimeout(resolve, 10));
    return item.length > 5;
  });
  assert.equal(asyncResult, 'banana');

  const helperResult = await findFirstMatch(items, (item) => item === 'cherry');
  assert.equal(helperResult, 'cherry');
}

// 2. pLocate resolves to undefined when no element in iterable satisfies tester
{
  const numbers = [1, 2, 3, 4, 5];
  const result = await pLocate(numbers, (num) => num > 100);
  assert.equal(result, undefined);

  const emptyResult = await pLocate([], () => true);
  assert.equal(emptyResult, undefined);
}

// 3. pLocate supports iterables containing promises that resolve to elements
{
  const promiseItems = [
    Promise.resolve('alpha'),
    new Promise((resolve) => setTimeout(() => resolve('beta'), 15)),
    Promise.resolve('gamma'),
  ];
  const result = await pLocate(promiseItems, async (item) => item.startsWith('b'));
  assert.equal(result, 'beta');
}

// 4. pLocate preserves input order by default when async testers resolve out of order
{
  const items = ['first', 'second', 'third'];
  const delayMap = {
    first: 40,
    second: 20,
    third: 5,
  };

  const result = await pLocate(items, async (item) => {
    await new Promise((resolve) => setTimeout(resolve, delayMap[item]));
    return true; // all match, but 'first' should win due to order preservation
  });

  assert.equal(result, 'first');
}

// 5. pLocate with preserveOrder false returns the fastest resolving match
{
  const items = ['slow-match', 'fast-match', 'medium-match'];
  const delayMap = {
    'slow-match': 50,
    'fast-match': 10,
    'medium-match': 30,
  };

  const result = await pLocate(
    items,
    async (item) => {
      await new Promise((resolve) => setTimeout(resolve, delayMap[item]));
      return true;
    },
    { preserveOrder: false }
  );

  assert.equal(result, 'fast-match');

  const helperResult = await findFirstResolvedMatch(
    items,
    async (item) => {
      await new Promise((resolve) => setTimeout(resolve, delayMap[item]));
      return true;
    }
  );
  assert.equal(helperResult, 'fast-match');
}

// 6. pLocate respects concurrency option to limit parallel tester executions
{
  const items = [1, 2, 3, 4, 5, 6];
  let active = 0;
  let maxActive = 0;

  const result = await pLocate(
    items,
    async (item) => {
      active++;
      maxActive = Math.max(maxActive, active);
      await new Promise((resolve) => setTimeout(resolve, 20));
      active--;
      return item === 4;
    },
    { concurrency: 2 }
  );

  assert.equal(result, 4);
  assert.equal(maxActive, 2);

  let helperMaxActive = 0;
  let helperActive = 0;
  const helperRes = await findWithConcurrency(
    items,
    async (item) => {
      helperActive++;
      helperMaxActive = Math.max(helperMaxActive, helperActive);
      await new Promise((resolve) => setTimeout(resolve, 15));
      helperActive--;
      return item === 3;
    },
    1
  );
  assert.equal(helperRes, 3);
  assert.equal(helperMaxActive, 1);
}

// 7. pLocate works with non-array iterables such as Set and generator functions
{
  const set = new Set(['cat', 'dog', 'elephant']);
  const setResult = await pLocate(set, (animal) => animal.length > 5);
  assert.equal(setResult, 'elephant');

  function* generateValues() {
    yield 10;
    yield 20;
    yield 30;
  }
  const genResult = await pLocate(generateValues(), (val) => val >= 20);
  assert.equal(genResult, 20);
}

// 8. pLocate propagates errors when a tester throws or an input promise rejects
{
  const errorTester = pLocate([1, 2, 3], () => {
    throw new Error('tester failed');
  });
  await assert.rejects(errorTester, {
    name: 'Error',
    message: 'tester failed',
  });

  const rejectedInput = pLocate(
    [Promise.reject(new Error('input rejected'))],
    () => true
  );
  await assert.rejects(rejectedInput, {
    name: 'Error',
    message: 'input rejected',
  });
}

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

Seeder de origen

anónimo