CodeSampleX

Ejemplo

use-debounce 10.1.0

Muestra verificada para npm use-debounce 10.1.0. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó: use-debounce package exports…

sha256:4e462771276e6a9a5bc027aba236955753a4286a64088e21a31a902150d9807e

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 debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-11

Caso

HOW
Objetivo
verify pkg:npm/use-debounce@10.1.0
Paquetes
Entorno
node 22.23.2
Creado
2026-09-11T08:32:22Z

Contrato

  1. use-debounce package exports useDebounce, useDebouncedCallback, and useThrottledCallback functions
  2. useDebouncedCallback delays invocation until the specified timeout elapses
  3. useDebouncedCallback cancel cancels pending invocation and resets pending state
  4. useDebouncedCallback flush immediately invokes pending invocation and returns result
  5. useDebouncedCallback supports leading edge execution
  6. useDebounce hook returns debounced value and control functions
  7. useThrottledCallback throttles calls with leading execution and trailing fallback

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 pkg:npm/use-debounce@10.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/use-debounce@10.1.0

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:5275cf58fb2f10688fd9222eec2bd19445cf47a6f63cf93b3cc7d5f0b994ba74","contract":["use-debounce package exports useDebounce, useDebouncedCallback, and useThrottledCallback functions","useDebouncedCallback delays invocation until the specified timeout elapses","useDebouncedCallback cancel cancels pending invocation and resets pending state","useDebouncedCallback flush immediately invokes pending invocation and returns result","useDebouncedCallback supports leading edge execution","useDebounce hook returns debounced value and control functions","useThrottledCallback throttles calls with leading execution and trailing fallback"],"goal":"verify pkg:npm/use-debounce@10.1.0","kind":"HOW","packages":["pkg:npm/use-debounce@10.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":"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/use-debounce@10.1.0"],"schemaVersion":1,"subject":"pkg:npm/use-debounce@10.1.0","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-use-debounce",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-use-debounce",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "react": "18.3.1",
        "use-debounce": "10.1.0"
      }
    },
    "node_modules/js-tokens": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
      "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
      "license": "MIT"
    },
    "node_modules/loose-envify": {
      "version": "1.4.0",
      "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
      "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
      "license": "MIT",
      "dependencies": {
        "js-tokens": "^3.0.0 || ^4.0.0"
      },
      "bin": {
        "loose-envify": "cli.js"
      }
    },
    "node_modules/react": {
      "version": "18.3.1",
      "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
      "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
      "license": "MIT",
      "dependencies": {
        "loose-envify": "^1.1.0"
      },
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/use-debounce": {
      "version": "10.1.0",
      "resolved": "https://registry.npmjs.org/use-debounce/-/use-debounce-10.1.0.tgz",
      "integrity": "sha512-lu87Za35V3n/MyMoEpD5zJv0k7hCn0p+V/fK2kWD+3k2u3kOCwO593UArbczg1fhfs2rqPEnHpULJ3KmGdDzvg==",
      "license": "MIT",
      "engines": {
        "node": ">= 16.0.0"
      },
      "peerDependencies": {
        "react": "*"
      }
    }
  }
}
package.json
{
  "name": "sample-use-debounce",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "description": "verify pkg:npm/use-debounce@10.1.0",
  "license": "MIT-0",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "react": "18.3.1",
    "use-debounce": "10.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/use-debounce@10.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/use-debounce@10.1.0"
  ]
}
src/index.mjs
import { useDebounce, useDebouncedCallback, useThrottledCallback } from 'use-debounce';

/**
 * Creates a debounced callback handler with configurable delay and options.
 *
 * @param {Function} callback - Function to debounce
 * @param {number} delayMs - Debounce delay in milliseconds
 * @param {object} [options] - Optional debounce configuration
 * @returns {Function} Debounced callback with cancel, flush, and isPending methods
 */
export function createDebouncedCallback(callback, delayMs, options) {
  return useDebouncedCallback(callback, delayMs, options);
}

/**
 * Creates a debounced value state with configurable delay and options.
 *
 * @param {*} value - Value to debounce
 * @param {number} delayMs - Debounce delay in milliseconds
 * @param {object} [options] - Optional debounce configuration
 * @returns {[*, object]} Array containing [debouncedValue, controlFunctions]
 */
export function createDebouncedValue(value, delayMs, options) {
  return useDebounce(value, delayMs, options);
}

/**
 * Creates a throttled callback handler with configurable interval and options.
 *
 * @param {Function} callback - Function to throttle
 * @param {number} intervalMs - Throttle interval in milliseconds
 * @param {object} [options] - Optional throttle configuration
 * @returns {Function} Throttled callback with cancel, flush, and isPending methods
 */
export function createThrottledCallback(callback, intervalMs, options) {
  return useThrottledCallback(callback, intervalMs, options);
}

export { useDebounce, useDebouncedCallback, useThrottledCallback };
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import React from 'react';
import { useDebounce, useDebouncedCallback, useThrottledCallback } from 'use-debounce';
import {
  createDebouncedCallback,
  createDebouncedValue,
  createThrottledCallback
} from '../src/index.mjs';

const require = createRequire(import.meta.url);

// Ensure a safe browser-like environment on Node without external network calls
if (typeof globalThis.window === 'undefined') {
  globalThis.window = globalThis;
}
if (!globalThis.requestAnimationFrame) {
  globalThis.requestAnimationFrame = (cb) => setTimeout(cb, 16);
}
if (!globalThis.cancelAnimationFrame) {
  globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
}

// Minimal, reliable React Hook dispatcher for testing hooks offline in Node
function createHookContext() {
  const hooks = [];
  let index = 0;

  const dispatcher = {
    useRef(initial) {
      if (hooks[index] === undefined) {
        hooks[index] = { current: initial };
      }
      return hooks[index++];
    },
    useState(initial) {
      const stateIndex = index;
      if (hooks[stateIndex] === undefined) {
        hooks[stateIndex] = typeof initial === 'function' ? initial() : initial;
      }
      const setState = (action) => {
        hooks[stateIndex] = typeof action === 'function' ? action(hooks[stateIndex]) : action;
      };
      index++;
      return [hooks[stateIndex], setState];
    },
    useMemo(factory, deps) {
      const memoIndex = index;
      const prev = hooks[memoIndex];
      let hasChanged = true;
      if (prev && deps && prev.deps) {
        hasChanged = deps.some((dep, i) => !Object.is(dep, prev.deps[i]));
      }
      if (!prev || hasChanged) {
        hooks[memoIndex] = { value: factory(), deps };
      }
      index++;
      return hooks[memoIndex].value;
    },
    useCallback(fn, deps) {
      return dispatcher.useMemo(() => fn, deps);
    },
    useEffect(effect, deps) {
      const effectIndex = index;
      const prev = hooks[effectIndex];
      let hasChanged = true;
      if (prev && deps && prev.deps) {
        hasChanged = deps.some((dep, i) => !Object.is(dep, prev.deps[i]));
      }
      if (!prev || hasChanged) {
        if (prev && typeof prev.cleanup === 'function') {
          prev.cleanup();
        }
        const cleanup = effect();
        hooks[effectIndex] = { cleanup, deps };
      }
      index++;
    }
  };

  return {
    run(fn) {
      const prev = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher.current;
      React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher.current = dispatcher;
      index = 0;
      try {
        return fn();
      } finally {
        React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher.current = prev;
      }
    },
    cleanup() {
      for (const hook of hooks) {
        if (hook && typeof hook.cleanup === 'function') {
          hook.cleanup();
        }
      }
    }
  };
}

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

async function runContractTests() {
  // Contract 1: use-debounce package exports useDebounce, useDebouncedCallback, and useThrottledCallback functions
  {
    assert.strictEqual(typeof useDebounce, 'function', 'useDebounce must be a function');
    assert.strictEqual(typeof useDebouncedCallback, 'function', 'useDebouncedCallback must be a function');
    assert.strictEqual(typeof useThrottledCallback, 'function', 'useThrottledCallback must be a function');
    assert.strictEqual(typeof createDebouncedCallback, 'function', 'createDebouncedCallback must be a function');
    assert.strictEqual(typeof createDebouncedValue, 'function', 'createDebouncedValue must be a function');
    assert.strictEqual(typeof createThrottledCallback, 'function', 'createThrottledCallback must be a function');

    const pkgPath = require.resolve('use-debounce/package.json');
    assert.ok(fs.existsSync(pkgPath), 'package.json must exist');
    const pkgJson = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
    assert.strictEqual(pkgJson.name, 'use-debounce', 'package name must match');
    assert.strictEqual(pkgJson.version, '10.1.0', 'package version must be 10.1.0');
    assert.ok(pkgJson.exports, 'package must define exports mapping');
  }

  // Contract 2: useDebouncedCallback delays invocation until the specified timeout elapses
  {
    const ctx = createHookContext();
    let invocations = [];
    const debounced = ctx.run(() =>
      useDebouncedCallback((val) => {
        invocations.push(val);
        return val;
      }, 30)
    );

    assert.strictEqual(debounced.isPending(), false, 'initially not pending');
    debounced('first');
    debounced('second');

    assert.strictEqual(debounced.isPending(), true, 'pending after calls');
    assert.strictEqual(invocations.length, 0, 'callback not invoked synchronously');

    await sleep(50);

    assert.strictEqual(debounced.isPending(), false, 'no longer pending after timeout');
    assert.strictEqual(invocations.length, 1, 'callback invoked once on trailing edge');
    assert.strictEqual(invocations[0], 'second', 'callback received latest arguments');
    ctx.cleanup();
  }

  // Contract 3: useDebouncedCallback cancel cancels pending invocation and resets pending state
  {
    const ctx = createHookContext();
    let invocations = [];
    const debounced = ctx.run(() =>
      useDebouncedCallback((val) => {
        invocations.push(val);
      }, 40)
    );

    debounced('test-cancel');
    assert.strictEqual(debounced.isPending(), true, 'pending after call');

    debounced.cancel();
    assert.strictEqual(debounced.isPending(), false, 'pending cleared on cancel');

    await sleep(60);
    assert.strictEqual(invocations.length, 0, 'cancelled callback was never executed');
    ctx.cleanup();
  }

  // Contract 4: useDebouncedCallback flush immediately invokes pending invocation and returns result
  {
    const ctx = createHookContext();
    let callCount = 0;
    const debounced = ctx.run(() =>
      useDebouncedCallback((num) => {
        callCount++;
        return num * 10;
      }, 100)
    );

    debounced(7);
    assert.strictEqual(callCount, 0, 'not invoked immediately');
    assert.strictEqual(debounced.isPending(), true, 'pending');

    const result = debounced.flush();
    assert.strictEqual(result, 70, 'flush returns invocation result');
    assert.strictEqual(callCount, 1, 'invoked once during flush');
    assert.strictEqual(debounced.isPending(), false, 'pending cleared after flush');
    ctx.cleanup();
  }

  // Contract 5: useDebouncedCallback supports leading edge execution
  {
    const ctx = createHookContext();
    let calls = [];
    const debounced = ctx.run(() =>
      useDebouncedCallback(
        (val) => {
          calls.push(val);
        },
        40,
        { leading: true, trailing: false }
      )
    );

    debounced('lead-1');
    assert.strictEqual(calls.length, 1, 'leading call executed immediately');
    assert.strictEqual(calls[0], 'lead-1');

    debounced('lead-2');
    assert.strictEqual(calls.length, 1, 'subsequent call ignored while trailing is false');

    await sleep(60);
    assert.strictEqual(calls.length, 1, 'no extra calls after timeout');
    ctx.cleanup();
  }

  // Contract 6: useDebounce hook returns debounced value and control functions
  {
    const ctx = createHookContext();
    let [val1, ctrl1] = ctx.run(() => useDebounce('initial', 30));
    assert.strictEqual(val1, 'initial', 'initial value returned');
    assert.strictEqual(typeof ctrl1.flush, 'function', 'ctrl has flush');
    assert.strictEqual(typeof ctrl1.cancel, 'function', 'ctrl has cancel');
    assert.strictEqual(typeof ctrl1.isPending, 'function', 'ctrl has isPending');

    // Subsequent call with updated value
    let [val2, ctrl2] = ctx.run(() => useDebounce('updated', 30));
    assert.strictEqual(val2, 'initial', 'value remains initial before delay');
    assert.strictEqual(ctrl2.isPending(), true, 'pending update');

    ctrl2.flush();
    let [val3, ctrl3] = ctx.run(() => useDebounce('updated', 30));
    assert.strictEqual(val3, 'updated', 'value updated after flush');
    assert.strictEqual(ctrl3.isPending(), false, 'pending cleared after flush');
    ctx.cleanup();
  }

  // Contract 7: useThrottledCallback throttles calls with leading execution and trailing fallback
  {
    const ctx = createHookContext();
    let throttleValues = [];
    const throttled = ctx.run(() =>
      useThrottledCallback((v) => {
        throttleValues.push(v);
      }, 40)
    );

    throttled(1);
    assert.strictEqual(throttleValues.length, 1, 'leading execution runs immediately');
    assert.strictEqual(throttleValues[0], 1);

    throttled(2);
    throttled(3);
    assert.strictEqual(throttleValues.length, 1, 'intermediate calls throttled');
    assert.strictEqual(throttled.isPending(), true, 'trailing call is pending');

    await sleep(60);
    assert.strictEqual(throttleValues.length, 2, 'trailing execution runs after interval');
    assert.strictEqual(throttleValues[1], 3, 'trailing execution received latest value');
    assert.strictEqual(throttled.isPending(), false, 'not pending after completion');
    ctx.cleanup();
  }

  console.log('All contract assertions verified successfully.');
}

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

Seeder de origen

anónimo