CodeSampleX

Ejemplo

nanoid 3.3.17: custom-random

Muestra verificada para npm nanoid 3.3.17: custom-random. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó.

sha256:74a557ba2336d0303a00904a83f1a51d39f6542aae71f3242d903b39c39bb0f7

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-26

Caso

HOW
Objetivo
verify nanoid/custom-random in pkg:npm/nanoid@3.3.17
Paquetes
Símbolos
  • nanoid/custom-random
Entorno
node 22.23.2
Creado
2026-08-26T04:46:47Z

Contrato

  1. assert customRandom returns a generator function configured with alphabet and default size
  2. assert customRandom generator produces identifiers of specified default length containing only valid alphabet characters
  3. assert customRandom generator supports dynamic size override at invocation time
  4. assert customRandom generator returns an empty string when requested size is zero or negative
  5. assert customRandom produces repeatable deterministic identifiers when supplied with a seeded pseudo-random generator
  6. assert customRandom operates correctly with nanoid default hardware random generator and custom hex alphabet
  7. assert customRandom handles non-power-of-two alphabets without modulo bias

Archivos

  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • 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 nanoid/custom-random in pkg:npm/nanoid@3.3.17
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/nanoid@3.3.17
Demonstrate these symbols/APIs:
  - nanoid/custom-random
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:22c5e2ac16caf7f4679546216859621b2718361b5dcba89060d9dfd60dd38a1a","constraints":{"executionContext":"node"},"contract":["assert customRandom returns a generator function configured with alphabet and default size","assert customRandom generator produces identifiers of specified default length containing only valid alphabet characters","assert customRandom generator supports dynamic size override at invocation time","assert customRandom generator returns an empty string when requested size is zero or negative","assert customRandom produces repeatable deterministic identifiers when supplied with a seeded pseudo-random generator","assert customRandom operates correctly with nanoid default hardware random generator and custom hex alphabet","assert customRandom handles non-power-of-two alphabets without modulo bias"],"goal":"verify nanoid/custom-random in pkg:npm/nanoid@3.3.17","kind":"HOW","packages":["pkg:npm/nanoid@3.3.17"],"schemaVersion":1,"symbols":["nanoid/custom-random"]},"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/nanoid@3.3.17"],"schemaVersion":1,"subject":"pkg:npm/nanoid@3.3.17","symbols":["nanoid/custom-random"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { customRandom, random, urlAlphabet } from 'nanoid';

/**
 * Creates a custom random identifier generator with specified alphabet, size, and random function.
 * @param {string} alphabet
 * @param {number} defaultSize
 * @param {(bytes: number) => Uint8Array} [getRandom=random]
 * @returns {(size?: number) => string}
 */
export function createCustomGenerator(alphabet, defaultSize, getRandom = random) {
  return customRandom(alphabet, defaultSize, getRandom);
}

export { customRandom, random, urlAlphabet };
package-lock.json
{
  "name": "sample-nanoid-custom-random",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-nanoid-custom-random",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "nanoid": "3.3.17"
      }
    },
    "node_modules/nanoid": {
      "version": "3.3.17",
      "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.17.tgz",
      "integrity": "sha512-xQLf0A3HOMlgHq0n247/LRuAOYmB7dXJ/DvAxGvsSBij45XtBSmQycu+F8ODbHwns/XyFZagyL1+J0Offw1E0g==",
      "license": "MIT",
      "bin": {
        "nanoid": "bin/nanoid.cjs"
      },
      "engines": {
        "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
      }
    }
  }
}
package.json
{
  "name": "sample-nanoid-custom-random",
  "version": "1.0.0",
  "description": "Demonstrate customRandom generator with custom alphabets and PRNGs in nanoid",
  "main": "index.mjs",
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "nanoid": "3.3.17"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify nanoid/custom-random in pkg:npm/nanoid@3.3.17",
  "kind": "HOW",
  "packages": [
    "pkg:npm/nanoid@3.3.17"
  ],
  "symbols": [
    "nanoid/custom-random"
  ],
  "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 { customRandom, random, urlAlphabet } from 'nanoid';

// 1. assert customRandom returns a generator function configured with alphabet and default size
{
  const generator = customRandom('abcdef', 10, (size) => new Uint8Array(size));
  assert.equal(typeof generator, 'function', 'customRandom must return a function');
}

// 2. assert customRandom generator produces identifiers of specified default length containing only valid alphabet characters
{
  const alphabet = '0123456789abcdef';
  const generator = customRandom(alphabet, 16, (size) => {
    const bytes = new Uint8Array(size);
    for (let i = 0; i < size; i++) {
      bytes[i] = (i * 37 + 11) & 0xff;
    }
    return bytes;
  });
  const id = generator();
  assert.equal(typeof id, 'string', 'Generated ID must be a string');
  assert.equal(id.length, 16, 'Generated ID must match default size of 16');
  for (const ch of id) {
    assert.ok(alphabet.includes(ch), `Character "${ch}" must belong to the custom alphabet`);
  }
}

// 3. assert customRandom generator supports dynamic size override at invocation time
{
  const alphabet = 'abcdefghijklmnopqrstuvwxyz';
  let counter = 0;
  const generator = customRandom(alphabet, 12, (size) => {
    const bytes = new Uint8Array(size);
    for (let i = 0; i < size; i++) {
      bytes[i] = (counter++) & 0xff;
    }
    return bytes;
  });

  const defaultId = generator();
  const overriddenId = generator(24);
  const shortId = generator(4);

  assert.equal(defaultId.length, 12, 'Default call must produce length 12');
  assert.equal(overriddenId.length, 24, 'Overridden call must produce length 24');
  assert.equal(shortId.length, 4, 'Short override call must produce length 4');
}

// 4. assert customRandom generator returns an empty string when requested size is zero or negative
{
  const generator = customRandom('abcdef', 8, (size) => new Uint8Array(size));
  assert.equal(generator(0), '', 'Size 0 must return empty string');
  assert.equal(generator(-1), '', 'Negative size -1 must return empty string');
  assert.equal(generator(-100), '', 'Negative size -100 must return empty string');
}

// 5. assert customRandom produces repeatable deterministic identifiers when supplied with a seeded pseudo-random generator
{
  const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const createSeededPRNG = (seed) => {
    let state = seed;
    return (size) => {
      const bytes = new Uint8Array(size);
      for (let i = 0; i < size; i++) {
        state = (state * 1664525 + 1013904223) >>> 0;
        bytes[i] = (state >>> 24) & 0xff;
      }
      return bytes;
    };
  };

  const gen1 = customRandom(alphabet, 16, createSeededPRNG(42));
  const gen2 = customRandom(alphabet, 16, createSeededPRNG(42));

  const sequence1 = [gen1(), gen1(), gen1()];
  const sequence2 = [gen2(), gen2(), gen2()];

  assert.deepEqual(sequence1, sequence2, 'Identical seeds must produce identical ID sequences');
  assert.equal(sequence1[0].length, 16);
}

// 6. assert customRandom operates correctly with nanoid default hardware random generator and custom hex alphabet
{
  const hexAlphabet = '0123456789ABCDEF';
  const hexIdGenerator = customRandom(hexAlphabet, 32, random);
  const id = hexIdGenerator();

  assert.equal(id.length, 32, 'Generated hex ID must have length 32');
  assert.match(id, /^[0-9A-F]{32}$/, 'Generated ID must strictly contain uppercase hex characters');
}

// 7. assert customRandom handles non-power-of-two alphabets without modulo bias
{
  const decimalAlphabet = '0123456789';
  const genDecimal = customRandom(decimalAlphabet, 20, random);
  const decimalId = genDecimal();
  assert.equal(decimalId.length, 20);
  assert.match(decimalId, /^[0-9]{20}$/);

  const alphanumericAlphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const genAlphanumeric = customRandom(alphanumericAlphabet, 25, random);
  const alphaId = genAlphanumeric();
  assert.equal(alphaId.length, 25);
  for (const ch of alphaId) {
    assert.ok(alphanumericAlphabet.includes(ch));
  }

  const urlAlphabetGen = customRandom(urlAlphabet, 21, random);
  const urlId = urlAlphabetGen();
  assert.equal(urlId.length, 21);
  for (const ch of urlId) {
    assert.ok(urlAlphabet.includes(ch));
  }
}

console.log('All contract tests passed successfully.');

Seeder de origen

anónimo