CodeSampleX

Exemplo

@sinonjs/fake-timers 15.4.0: install, withGlobal

Amostra verificada para npm @sinonjs/fake-timers 15.4.0: install, withGlobal. O contrato rodou em node 22 · linux alpine/x64 · docker e passou.

sha256:96447dcd5d5b19e99cb5ab2aeb60c9b28d54a22b7c47d623ac6a563b9abab4dd

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-26

Caso

HOW
Objetivo
verify pkg:npm/%40sinonjs/fake-timers@15.4.0
Pacotes
Símbolos
  • @sinonjs/fake-timers.install
  • @sinonjs/fake-timers.withGlobal
Ambiente
node 22.23.2
Criado
2026-08-26T07:44:57Z

Contrato

  1. install replaces global timer functions and initializes now to configured timestamp
  2. global setTimeout and clearTimeout are controlled by fake clock tick
  3. global setInterval and clearInterval repeat and stop as time advances
  4. clock.tickAsync advances time and awaits asynchronous timer callbacks
  5. clock.setSystemTime updates Date.now without triggering scheduled timer callbacks
  6. clock.runAll executes all scheduled timers across global queue
  7. clock.next advances time to the timestamp of the next scheduled timer and executes it
  8. clock.countTimers reports the current count of pending scheduled timers
  9. clock.jump advances time by specified milliseconds and fires scheduled callbacks
  10. withGlobal provides fake timer functions bound to a custom context object
  11. clock.uninstall restores native global timer functions and Date

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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/%40sinonjs/fake-timers@15.4.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40sinonjs/fake-timers@15.4.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:9b0e6dd223b0d60646a5a738dcc7430dbbeb72328e624c7235ad624d9a7eaee8","constraints":{"executionContext":"node"},"contract":["install replaces global timer functions and initializes now to configured timestamp","global setTimeout and clearTimeout are controlled by fake clock tick","global setInterval and clearInterval repeat and stop as time advances","clock.tickAsync advances time and awaits asynchronous timer callbacks","clock.setSystemTime updates Date.now without triggering scheduled timer callbacks","clock.runAll executes all scheduled timers across global queue","clock.next advances time to the timestamp of the next scheduled timer and executes it","clock.countTimers reports the current count of pending scheduled timers","clock.jump advances time by specified milliseconds and fires scheduled callbacks","withGlobal provides fake timer functions bound to a custom context object","clock.uninstall restores native global timer functions and Date"],"goal":"verify pkg:npm/%40sinonjs/fake-timers@15.4.0","kind":"HOW","packages":["pkg:npm/%40sinonjs/fake-timers@15.4.0"],"schemaVersion":1,"symbols":["@sinonjs/fake-timers.install","@sinonjs/fake-timers.withGlobal"]},"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/%40sinonjs/fake-timers@15.4.0"],"schemaVersion":1,"subject":"pkg:npm/%40sinonjs/fake-timers@15.4.0","symbols":["@sinonjs/fake-timers.install","@sinonjs/fake-timers.withGlobal"],"verifierAdapter":"node-typescript@1"}
index.mjs
import FakeTimers from '@sinonjs/fake-timers';

export const { install, withGlobal, createClock } = FakeTimers;

/**
 * Installs fake timers globally with the given configuration options.
 *
 * @param {import('@sinonjs/fake-timers').FakeTimerInstallOpts} [config={}] - Installation options
 * @returns {import('@sinonjs/fake-timers').InstalledClock} Clock instance controlling global timers
 */
export function setupFakeTimers(config = {}) {
  return install(config);
}

/**
 * Creates fake timer methods bound to a specific global context object.
 *
 * @param {object} globalObject - The global context object to bind
 * @returns {typeof FakeTimers} FakeTimers module bound to the context
 */
export function createWithGlobal(globalObject) {
  return withGlobal(globalObject);
}

export default {
  install,
  withGlobal,
  createClock,
  setupFakeTimers,
  createWithGlobal,
};
package-lock.json
{
  "name": "sample-fake-timers-install",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-fake-timers-install",
      "version": "1.0.0",
      "dependencies": {
        "@sinonjs/fake-timers": "15.4.0"
      }
    },
    "node_modules/@sinonjs/commons": {
      "version": "3.0.1",
      "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz",
      "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==",
      "license": "BSD-3-Clause",
      "dependencies": {
        "type-detect": "4.0.8"
      }
    },
    "node_modules/@sinonjs/fake-timers": {
      "version": "15.4.0",
      "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-15.4.0.tgz",
      "integrity": "sha512-DsG+8/LscQIQg68J6Ef3dv10u6nVyetYn923s3/sus5eaGfTo1of5WMZSLf0UJc9KDuKPilPH0UDJCjvNbDNCA==",
      "license": "BSD-3-Clause",
      "dependencies": {
        "@sinonjs/commons": "^3.0.1"
      }
    },
    "node_modules/type-detect": {
      "version": "4.0.8",
      "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",
      "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==",
      "license": "MIT",
      "engines": {
        "node": ">=4"
      }
    }
  }
}
package.json
{
  "name": "sample-fake-timers-install",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "@sinonjs/fake-timers": "15.4.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40sinonjs/fake-timers@15.4.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40sinonjs/fake-timers@15.4.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import FakeTimers, { install, setupFakeTimers, withGlobal, createWithGlobal } from '../index.mjs';

// Contract 1: install replaces global timer functions and initializes now to configured timestamp
{
  const initialTimestamp = 1700000000000;
  const originalSetTimeout = globalThis.setTimeout;
  const originalDateNow = Date.now;

  const clock = setupFakeTimers({ now: initialTimestamp });
  try {
    assert.strictEqual(typeof install, 'function');
    assert.strictEqual(typeof clock.tick, 'function');
    assert.strictEqual(typeof clock.tickAsync, 'function');
    assert.strictEqual(typeof clock.uninstall, 'function');
    assert.strictEqual(typeof clock.runAll, 'function');
    assert.strictEqual(typeof clock.setSystemTime, 'function');
    assert.strictEqual(typeof clock.countTimers, 'function');
    assert.strictEqual(typeof clock.next, 'function');
    assert.strictEqual(typeof clock.jump, 'function');
    assert.strictEqual(clock.now, initialTimestamp);
    assert.strictEqual(Date.now(), initialTimestamp);
    assert.notStrictEqual(globalThis.setTimeout, originalSetTimeout);
  } finally {
    clock.uninstall();
    assert.strictEqual(globalThis.setTimeout, originalSetTimeout);
    assert.strictEqual(Date.now, originalDateNow);
  }
}

// Contract 2: global setTimeout and clearTimeout are controlled by fake clock tick
{
  const clock = install({ now: 1000 });
  try {
    let executed = false;
    let receivedArg = null;
    const timerId = setTimeout((val) => {
      executed = true;
      receivedArg = val;
    }, 200, 'payload');

    assert.strictEqual(executed, false);
    clock.tick(199);
    assert.strictEqual(executed, false);
    assert.strictEqual(clock.now, 1199);

    clock.tick(1);
    assert.strictEqual(executed, true);
    assert.strictEqual(receivedArg, 'payload');
    assert.strictEqual(clock.now, 1200);

    let cancelledExecuted = false;
    const cancelId = setTimeout(() => {
      cancelledExecuted = true;
    }, 100);
    clearTimeout(cancelId);
    clock.tick(200);
    assert.strictEqual(cancelledExecuted, false);
  } finally {
    clock.uninstall();
  }
}

// Contract 3: global setInterval and clearInterval repeat and stop as time advances
{
  const clock = install({ now: 0 });
  try {
    let runs = 0;
    const intervalId = setInterval(() => {
      runs++;
    }, 50);

    clock.tick(125);
    assert.strictEqual(runs, 2);

    clock.tick(50);
    assert.strictEqual(runs, 3);

    clearInterval(intervalId);
    clock.tick(100);
    assert.strictEqual(runs, 3);
  } finally {
    clock.uninstall();
  }
}

// Contract 4: clock.tickAsync advances time and awaits asynchronous timer callbacks
{
  const clock = install({ now: 0 });
  try {
    let asyncCompleted = false;
    setTimeout(async () => {
      await Promise.resolve();
      asyncCompleted = true;
    }, 100);

    assert.strictEqual(asyncCompleted, false);
    await clock.tickAsync(100);
    assert.strictEqual(asyncCompleted, true);
  } finally {
    clock.uninstall();
  }
}

// Contract 5: clock.setSystemTime updates Date.now without triggering scheduled timer callbacks
{
  const clock = install({ now: 1000 });
  try {
    let fired = false;
    setTimeout(() => {
      fired = true;
    }, 500);

    clock.setSystemTime(5000);
    assert.strictEqual(clock.now, 5000);
    assert.strictEqual(Date.now(), 5000);
    assert.strictEqual(fired, false);
    assert.strictEqual(clock.countTimers(), 1);
  } finally {
    clock.uninstall();
  }
}

// Contract 6: clock.runAll executes all scheduled timers across global queue
{
  const clock = install({ now: 0 });
  try {
    const executed = [];
    setTimeout(() => executed.push('first'), 50);
    setTimeout(() => executed.push('third'), 150);
    setTimeout(() => executed.push('second'), 100);

    assert.strictEqual(clock.countTimers(), 3);
    clock.runAll();
    assert.deepEqual(executed, ['first', 'second', 'third']);
    assert.strictEqual(clock.countTimers(), 0);
    assert.strictEqual(clock.now, 150);
  } finally {
    clock.uninstall();
  }
}

// Contract 7: clock.next advances time to the timestamp of the next scheduled timer and executes it
{
  const clock = install({ now: 0 });
  try {
    const log = [];
    setTimeout(() => log.push('a'), 100);
    setTimeout(() => log.push('b'), 250);

    clock.next();
    assert.deepEqual(log, ['a']);
    assert.strictEqual(clock.now, 100);
    assert.strictEqual(clock.countTimers(), 1);

    clock.next();
    assert.deepEqual(log, ['a', 'b']);
    assert.strictEqual(clock.now, 250);
    assert.strictEqual(clock.countTimers(), 0);
  } finally {
    clock.uninstall();
  }
}

// Contract 8: clock.countTimers reports the current count of pending scheduled timers
{
  const clock = install({ now: 0 });
  try {
    assert.strictEqual(clock.countTimers(), 0);
    const t1 = setTimeout(() => {}, 100);
    const t2 = setTimeout(() => {}, 200);
    const t3 = setInterval(() => {}, 50);
    assert.strictEqual(clock.countTimers(), 3);

    clearTimeout(t1);
    assert.strictEqual(clock.countTimers(), 2);

    clearInterval(t3);
    assert.strictEqual(clock.countTimers(), 1);

    clearTimeout(t2);
    assert.strictEqual(clock.countTimers(), 0);
  } finally {
    clock.uninstall();
  }
}

// Contract 9: clock.jump advances time by specified milliseconds and fires scheduled callbacks
{
  const clock = install({ now: 0 });
  try {
    let called = false;
    setTimeout(() => {
      called = true;
    }, 500);

    clock.jump(600);
    assert.strictEqual(called, true);
    assert.strictEqual(clock.now, 600);
  } finally {
    clock.uninstall();
  }
}

// Contract 10: withGlobal provides fake timer functions bound to a custom context object
{
  const customContext = {
    Date: Date,
    setTimeout: globalThis.setTimeout,
    clearTimeout: globalThis.clearTimeout,
  };
  const scopedFakeTimers = createWithGlobal(customContext);
  assert.strictEqual(typeof scopedFakeTimers.createClock, 'function');
  assert.strictEqual(typeof scopedFakeTimers.install, 'function');

  const scopedClock = scopedFakeTimers.createClock(500);
  assert.strictEqual(scopedClock.now, 500);
}

// Contract 11: clock.uninstall restores native global timer functions and Date
{
  const nativeSetTimeout = globalThis.setTimeout;
  const nativeDate = globalThis.Date;

  const clock = install({ now: 12345 });
  assert.notStrictEqual(globalThis.setTimeout, nativeSetTimeout);

  clock.uninstall();
  assert.strictEqual(globalThis.setTimeout, nativeSetTimeout);
  assert.strictEqual(globalThis.Date, nativeDate);
}

console.log('All contracts passed.');

Seeder de origem

anônimo