CodeSampleX

Пример

nanoid 3.3.17: customAlphabet, customRandom, urlAlphabet

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

sha256:6f00427d823d3dd2c8c24373f8488be1eefc09c06c016c3c4f06987434610e9b

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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 pkg:npm/nanoid@3.3.17
Пакеты
Символы
  • nanoid
  • customAlphabet
  • customRandom
  • urlAlphabet
  • random
Окружение
node 22.23.2
Создан
2026-08-27T16:16:49Z

Контракт

  1. require nanoid, customAlphabet, customRandom, urlAlphabet, and random in CommonJS
  2. assert default nanoid produces 21 URL-safe characters
  3. assert nanoid with custom length produces specified character count
  4. assert customAlphabet produces IDs using only the custom character set and supports size override
  5. assert customRandom with explicit crypto random bytes produces matching ID
  6. assert random returns Uint8Array buffer of requested byte length
  7. assert 1000 consecutively generated nanoid IDs are unique

Файлы

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

Скачать артефакт с исходным кодом (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 pkg:npm/nanoid@3.3.17
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/nanoid@3.3.17
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:58bb48200304906b09902799ea57c3b7b3eaa45af2121c58ceb8d867e28e8f13","constraints":{"executionContext":"node"},"contract":["require nanoid, customAlphabet, customRandom, urlAlphabet, and random in CommonJS","assert default nanoid produces 21 URL-safe characters","assert nanoid with custom length produces specified character count","assert customAlphabet produces IDs using only the custom character set and supports size override","assert customRandom with explicit crypto random bytes produces matching ID","assert random returns Uint8Array buffer of requested byte length","assert 1000 consecutively generated nanoid IDs are unique"],"goal":"verify pkg:npm/nanoid@3.3.17","kind":"HOW","packages":["pkg:npm/nanoid@3.3.17"],"schemaVersion":1,"symbols":["nanoid","customAlphabet","customRandom","urlAlphabet","random"]},"contractCommand":["node","test/contract.js"],"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","customAlphabet","customRandom","urlAlphabet","random"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-sample-nanoid",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-sample-nanoid",
      "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": "csx-sample-nanoid",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "dependencies": {
    "nanoid": "3.3.17"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/nanoid@3.3.17",
  "kind": "HOW",
  "packages": [
    "pkg:npm/nanoid@3.3.17"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const { nanoid, customAlphabet, customRandom, urlAlphabet, random } = require('nanoid');

function generateId(size) {
  return size !== undefined ? nanoid(size) : nanoid();
}

function createCustomGenerator(alphabet, size) {
  return customAlphabet(alphabet, size);
}

function createCustomRandomGenerator(alphabet, size, randomFn) {
  return customRandom(alphabet, size, randomFn || random);
}

module.exports = {
  generateId,
  createCustomGenerator,
  createCustomRandomGenerator,
  urlAlphabet,
  nanoid,
  customAlphabet,
  customRandom,
  random
};
test/contract.js
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const {
  generateId,
  createCustomGenerator,
  createCustomRandomGenerator,
  urlAlphabet,
  nanoid,
  customAlphabet,
  customRandom,
  random
} = require('../src/index.js');

// 1. Verify module exports and types
assert.equal(typeof nanoid, 'function', 'nanoid should be a function');
assert.equal(typeof customAlphabet, 'function', 'customAlphabet should be a function');
assert.equal(typeof customRandom, 'function', 'customRandom should be a function');
assert.equal(typeof random, 'function', 'random should be a function');
assert.equal(typeof urlAlphabet, 'string', 'urlAlphabet should be a string');
assert.equal(urlAlphabet.length, 64, 'urlAlphabet should contain exactly 64 characters');

// 2. Default ID generation (21 url-safe characters)
const id1 = generateId();
assert.equal(typeof id1, 'string', 'generateId should return a string');
assert.equal(id1.length, 21, 'default nanoid should produce a 21-character string');
assert.match(id1, /^[A-Za-z0-9_-]{21}$/, 'default nanoid should only contain URL-safe characters');

// 3. Custom length ID generation
const idCustomLength = generateId(32);
assert.equal(idCustomLength.length, 32, 'nanoid(32) should produce a 32-character string');
assert.match(idCustomLength, /^[A-Za-z0-9_-]{32}$/, 'custom length nanoid should contain URL-safe characters');

// 4. Custom alphabet ID generation
const alphabet = '0123456789abcdef';
const hexGen = createCustomGenerator(alphabet, 16);
const hexId = hexGen();
assert.equal(hexId.length, 16, 'customAlphabet generator should produce expected length');
assert.match(hexId, /^[0-9a-f]{16}$/, 'customAlphabet generator should only produce chars from specified alphabet');

// Custom alphabet with runtime length override
const hexIdOverride = hexGen(8);
assert.equal(hexIdOverride.length, 8, 'customAlphabet generator with size override should produce 8 characters');
assert.match(hexIdOverride, /^[0-9a-f]{8}$/, 'customAlphabet generator with size override should only contain hex chars');

// 5. Custom random generator with explicit crypto random bytes
const customRng = (bytes) => crypto.randomBytes(bytes);
const customRngGen = createCustomRandomGenerator('ABCDEF123456', 10, customRng);
const rngId = customRngGen();
assert.equal(rngId.length, 10, 'customRandom generator should produce expected length');
assert.match(rngId, /^[A-F1-6]{10}$/, 'customRandom generator should only produce chars from specified alphabet');

// 6. random() function test
const randomBytes = random(16);
assert.equal(randomBytes instanceof Uint8Array, true, 'random() should return a Uint8Array');
assert.equal(randomBytes.length, 16, 'random(16) should return a 16-byte array');

// 7. Uniqueness test across 1000 generated IDs
const seen = new Set();
for (let i = 0; i < 1000; i++) {
  seen.add(generateId());
}
assert.equal(seen.size, 1000, '1000 consecutively generated nanoid IDs should all be unique');

console.log('CONTRACT PASS: nanoid 3.3.17 contract assertions verified successfully.');

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

аноним