CodeSampleX

Пример

nanoid 3.3.17: customRandom

Проверенный пример — npm nanoid 3.3.17: customRandom. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: customRandom creates an ID…

sha256:7f2d69b35402b412a43f4eec31ea86259362644853db804d2c70b36929bcb145

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
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

Кейс

HOW
Цель
verify nanoid.customRandom in pkg:npm/nanoid@3.3.17
Пакеты
Символы
  • nanoid.customRandom
Окружение
node 22.23.2
Создан
2026-08-27T16:21:56Z

Контракт

  1. customRandom creates an ID generator using a specified alphabet, default size, and random byte generator
  2. generated IDs only contain characters from the provided alphabet
  3. the generator produces strings of the default size when invoked without arguments
  4. the generator produces strings of the requested size when passed an explicit size argument
  5. the generator returns an empty string when size is zero or negative
  6. the generator produces deterministic output given a deterministic random byte provider
  7. customRandom integrates seamlessly with nanoid built-in random byte generator
  8. customRandom works correctly across alphabets of varying lengths

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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.customRandom 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.customRandom

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:2174f38901b9b6059dfef0701c0953ac77dc6d9d7234210beeb312815d98e500","contract":["customRandom creates an ID generator using a specified alphabet, default size, and random byte generator","generated IDs only contain characters from the provided alphabet","the generator produces strings of the default size when invoked without arguments","the generator produces strings of the requested size when passed an explicit size argument","the generator returns an empty string when size is zero or negative","the generator produces deterministic output given a deterministic random byte provider","customRandom integrates seamlessly with nanoid built-in random byte generator","customRandom works correctly across alphabets of varying lengths"],"goal":"verify nanoid.customRandom in pkg:npm/nanoid@3.3.17","kind":"HOW","packages":["pkg:npm/nanoid@3.3.17"],"schemaVersion":1,"symbols":["nanoid.customRandom"]},"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/nanoid@3.3.17"],"schemaVersion":1,"subject":"pkg:npm/nanoid@3.3.17","symbols":["nanoid.customRandom"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-nanoid-customrandom",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-nanoid-customrandom",
      "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==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/ai"
        }
      ],
      "license": "MIT",
      "bin": {
        "nanoid": "bin/nanoid.cjs"
      },
      "engines": {
        "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
      }
    }
  }
}
package.json
{
  "name": "sample-nanoid-customrandom",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "nanoid": "3.3.17"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify nanoid.customRandom in pkg:npm/nanoid@3.3.17",
  "kind": "HOW",
  "packages": [
    "pkg:npm/nanoid@3.3.17"
  ],
  "symbols": [
    "nanoid.customRandom"
  ]
}
src/index.mjs
import { customRandom, random, urlAlphabet } from 'nanoid';

/**
 * Creates a custom nanoid generator with the specified alphabet, size, and random byte provider.
 * @param {string} alphabet Characters to use in generated IDs.
 * @param {number} size Default length of generated IDs.
 * @param {function(number): Uint8Array} getRandom Byte generator function.
 * @returns {function(number=): string} ID generator function.
 */
export function createCustomGenerator(alphabet, size, getRandom) {
  return customRandom(alphabet, size, getRandom);
}

/**
 * Creates a deterministic nanoid generator using a custom PRNG / byte source.
 * @param {string} alphabet Characters to use in generated IDs.
 * @param {number} size Default length of generated IDs.
 * @param {function(number): Uint8Array} customByteSource Byte provider function.
 * @returns {function(number=): string} ID generator function.
 */
export function createDeterministicGenerator(alphabet, size, customByteSource) {
  return customRandom(alphabet, size, customByteSource);
}

export { customRandom, random, urlAlphabet };
export default customRandom;
test/contract.mjs
import assert from 'node:assert/strict';
import { customRandom, random, urlAlphabet } from 'nanoid';
import { createCustomGenerator, createDeterministicGenerator } from '../src/index.mjs';

// 1. customRandom creates an ID generator using a specified alphabet, default size, and random byte generator
{
  const nanoid = customRandom('abcdef123456', 10, random);
  assert.equal(typeof nanoid, 'function', 'customRandom must return a generator function');

  const id = nanoid();
  assert.equal(typeof id, 'string', 'generator must return a string');
  assert.equal(id.length, 10, 'generator must return ID of default size 10');
}

// 2. generated IDs only contain characters from the provided alphabet
{
  const alphabet = 'abcABC123!_';
  const nanoid = customRandom(alphabet, 20, random);

  for (let i = 0; i < 50; i++) {
    const id = nanoid();
    for (const char of id) {
      assert.ok(alphabet.includes(char), `Character "${char}" must belong to alphabet`);
    }
  }
}

// 3. the generator produces strings of the default size when invoked without arguments
{
  const sizes = [1, 5, 16, 21, 64];
  for (const size of sizes) {
    const nanoid = customRandom('0123456789', size, random);
    assert.equal(nanoid().length, size, `ID length must match configured default size ${size}`);
  }
}

// 4. the generator produces strings of the requested size when passed an explicit size argument
{
  const nanoid = customRandom('abcdef012345', 12, random);
  assert.equal(nanoid().length, 12, 'default size must be 12');
  assert.equal(nanoid(5).length, 5, 'custom size override must be 5');
  assert.equal(nanoid(30).length, 30, 'custom size override must be 30');
  assert.equal(nanoid(1).length, 1, 'custom size override must be 1');
}

// 5. the generator returns an empty string when size is zero or negative
{
  const nanoid = customRandom('abcdef', 10, random);
  assert.equal(nanoid(0), '', 'size 0 must yield empty string');
  assert.equal(nanoid(-1), '', 'negative size must yield empty string');
  assert.equal(nanoid(-100), '', 'negative size must yield empty string');

  const zeroDefault = customRandom('abcdef', 0, random);
  assert.equal(zeroDefault(), '', 'default size 0 must yield empty string');
}

// 6. the generator produces deterministic output given a deterministic random byte provider
{
  // A deterministic byte source returning fixed sequence [0, 1, 2, 3, 4, 5, ...]
  let sequenceIndex = 0;
  const deterministicBytes = (step) => {
    const buffer = new Uint8Array(step);
    for (let i = 0; i < step; i++) {
      buffer[i] = sequenceIndex++;
    }
    return buffer;
  };

  const alphabet = 'abcdefghij';
  const nanoidDeterministic1 = customRandom(alphabet, 5, deterministicBytes);
  const output1 = nanoidDeterministic1();

  sequenceIndex = 0;
  const nanoidDeterministic2 = customRandom(alphabet, 5, deterministicBytes);
  const output2 = nanoidDeterministic2();

  assert.equal(output1, output2, 'deterministic byte source must produce identical outputs');
  assert.equal(output1.length, 5);
}

// 7. customRandom integrates seamlessly with nanoid built-in random byte generator
{
  const nanoid = customRandom(urlAlphabet, 21, random);
  const id1 = nanoid();
  const id2 = nanoid();
  assert.equal(id1.length, 21);
  assert.equal(id2.length, 21);
  assert.notEqual(id1, id2, 'sequential random IDs must differ');
}

// 8. customRandom works correctly across alphabets of varying lengths
{
  // Binary alphabet (length 2)
  const binaryGen = customRandom('01', 8, random);
  const binId = binaryGen();
  assert.match(binId, /^[01]{8}$/);

  // Hex alphabet (length 16)
  const hexGen = customRandom('0123456789abcdef', 16, random);
  const hexId = hexGen();
  assert.match(hexId, /^[0-9a-f]{16}$/);

  // Single character alphabet (length 1)
  const singleGen = customRandom('a', 5, random);
  assert.equal(singleGen(), 'aaaaa');

  // Helpers from index.mjs
  const helperCustom = createCustomGenerator('xyz', 6, random);
  assert.match(helperCustom(), /^[xyz]{6}$/);

  let counter = 0;
  const helperDeterministic = createDeterministicGenerator('0123456789', 4, (bytes) => {
    const b = new Uint8Array(bytes);
    b.fill(counter++);
    return b;
  });
  assert.equal(helperDeterministic().length, 4);
}

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

Исходный сидер

аноним