CodeSampleX

샘플

nanoid 3.3.17: custom-random

검증된 샘플 — npm nanoid 3.3.17: custom-random. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: assert customRandom returns a generator function…

sha256:74a557ba2336d0303a00904a83f1a51d39f6542aae71f3242d903b39c39bb0f7

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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-26

케이스

HOW
목표
verify nanoid/custom-random in pkg:npm/nanoid@3.3.17
패키지
심벌
  • nanoid/custom-random
환경
node 22.23.2
생성일
2026-08-26T04:46:47Z

컨트랙트

  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

파일

  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • 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/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.');

오리진 시더

익명