CodeSampleX

Exemplo

exponential-backoff 3.1.3: backOff

Amostra verificada para npm exponential-backoff 3.1.3: backOff. O contrato rodou em node 22 · linux alpine/x64 · docker e passou.

sha256:5c54bec84008dd91d29a76ff3e26944d833a70bc3ac30ebfb200437c5bdadf65

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
2
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
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-07

Caso

HOW
Objetivo
verify pkg:npm/exponential-backoff@3.1.3
Pacotes
Símbolos
  • backOff
Ambiente
node 22.23.2
Criado
2026-08-26T07:35:16Z

Contrato

  1. backOff executes an async function and resolves with its return value on the first attempt without delay
  2. backOff retries a failing async function with exponential delay and resolves when a subsequent attempt succeeds
  3. backOff rejects with the last encountered error when numOfAttempts is exceeded
  4. backOff invokes the retry callback with the error and attempt index and stops retrying when retry returns false
  5. backOff supports asynchronous retry callbacks to determine whether to continue reattempts
  6. retryWithBackoff wraps backOff and passes custom options including startingDelay, numOfAttempts, and jitter

Arquivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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/exponential-backoff@3.1.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/exponential-backoff@3.1.3
Demonstrate these symbols/APIs:
  - backOff

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:ab9ad279ebfd7943324a14414bb38576327fdf583a5aa42ebf15440fc3416f1e","contract":["backOff executes an async function and resolves with its return value on the first attempt without delay","backOff retries a failing async function with exponential delay and resolves when a subsequent attempt succeeds","backOff rejects with the last encountered error when numOfAttempts is exceeded","backOff invokes the retry callback with the error and attempt index and stops retrying when retry returns false","backOff supports asynchronous retry callbacks to determine whether to continue reattempts","retryWithBackoff wraps backOff and passes custom options including startingDelay, numOfAttempts, and jitter"],"goal":"verify pkg:npm/exponential-backoff@3.1.3","kind":"HOW","packages":["pkg:npm/exponential-backoff@3.1.3"],"schemaVersion":1,"symbols":["backOff"]},"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/exponential-backoff@3.1.3"],"schemaVersion":1,"subject":"pkg:npm/exponential-backoff@3.1.3","symbols":["backOff"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-exponential-backoff",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-exponential-backoff",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "exponential-backoff": "3.1.3"
      }
    },
    "node_modules/exponential-backoff": {
      "version": "3.1.3",
      "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz",
      "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==",
      "license": "Apache-2.0"
    }
  }
}
package.json
{
  "name": "sample-exponential-backoff",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for exponential-backoff@3.1.3",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "exponential-backoff": "3.1.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/exponential-backoff@3.1.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/exponential-backoff@3.1.3"
  ],
  "symbols": [
    "backOff"
  ]
}
src/index.js
'use strict';

const { backOff } = require('exponential-backoff');

/**
 * Retries an asynchronous operation with exponential backoff.
 *
 * @template T
 * @param {() => Promise<T>} fn - The asynchronous operation to execute.
 * @param {import('exponential-backoff').BackoffOptions} [options] - Backoff configuration options.
 * @returns {Promise<T>} Result of the operation.
 */
async function retryWithBackoff(fn, options = {}) {
  return backOff(fn, options);
}

module.exports = {
  backOff,
  retryWithBackoff
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { backOff, retryWithBackoff } = require('../src/index.js');

async function testAll() {
  // 1. Export verification
  assert.equal(typeof backOff, 'function', 'backOff export must be a function');
  assert.equal(typeof retryWithBackoff, 'function', 'retryWithBackoff export must be a function');

  // 2. Immediate success without retry
  let callCount1 = 0;
  const result1 = await backOff(async () => {
    callCount1++;
    return 'immediate-success';
  });
  assert.equal(result1, 'immediate-success');
  assert.equal(callCount1, 1, 'should only be called once on immediate success');

  // 3. Retries on failure and succeeds
  let callCount2 = 0;
  const attemptsSeen = [];
  const result2 = await backOff(async () => {
    callCount2++;
    if (callCount2 < 3) {
      throw new Error(`fail ${callCount2}`);
    }
    return 'recovered';
  }, {
    numOfAttempts: 5,
    startingDelay: 5,
    timeMultiple: 1.5,
    retry: (err, attemptNumber) => {
      assert(err instanceof Error);
      attemptsSeen.push(attemptNumber);
      return true;
    }
  });
  assert.equal(result2, 'recovered');
  assert.equal(callCount2, 3);
  assert.deepEqual(attemptsSeen, [1, 2], 'retry callback receives the 1-based attempt number that failed');

  // 4. Max attempts exceeded throws last error
  let callCount3 = 0;
  await assert.rejects(
    async () => {
      await backOff(async () => {
        callCount3++;
        throw new Error(`persistent error ${callCount3}`);
      }, {
        numOfAttempts: 3,
        startingDelay: 5
      });
    },
    {
      name: 'Error',
      message: 'persistent error 3'
    },
    'should reject with the last error when numOfAttempts is exhausted'
  );
  assert.equal(callCount3, 3);

  // 5. Abort early when retry callback returns false
  let callCount4 = 0;
  await assert.rejects(
    async () => {
      await backOff(async () => {
        callCount4++;
        const error = new Error('non-retryable error');
        error.code = 'UNRECOVERABLE';
        throw error;
      }, {
        numOfAttempts: 5,
        startingDelay: 5,
        retry: (err) => {
          return err.code !== 'UNRECOVERABLE';
        }
      });
    },
    (err) => {
      return err.message === 'non-retryable error' && err.code === 'UNRECOVERABLE';
    },
    'should stop retrying immediately when retry returns false'
  );
  assert.equal(callCount4, 1, 'should not retry after retry returns false');

  // 6. Async retry callback support
  let callCount5 = 0;
  const asyncResult = await backOff(async () => {
    callCount5++;
    if (callCount5 === 1) {
      throw new Error('transient error');
    }
    return 'async-recovered';
  }, {
    numOfAttempts: 3,
    startingDelay: 5,
    retry: async (err, attemptNumber) => {
      await new Promise((resolve) => setTimeout(resolve, 5));
      return attemptNumber < 2;
    }
  });
  assert.equal(asyncResult, 'async-recovered');
  assert.equal(callCount5, 2);

  // 7. Custom options and retryWithBackoff wrapper
  let wrapperCount = 0;
  const wrapperResult = await retryWithBackoff(async () => {
    wrapperCount++;
    if (wrapperCount < 2) {
      throw new Error('first try fail');
    }
    return 42;
  }, {
    numOfAttempts: 4,
    startingDelay: 5,
    delayFirstAttempt: false,
    jitter: 'none',
    maxDelay: 50
  });
  assert.equal(wrapperResult, 42);
  assert.equal(wrapperCount, 2);

  console.log('All exponential-backoff contract tests passed successfully.');
}

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

Seeder de origem

anônimo