CodeSampleX

Ejemplo

uuid 14.0.1: Supply a 16-byte Uint8Array generator to v4 options.rng for deterministic entropy and decode buffer outputs with stringify

Muestra verificada para npm uuid 14.0.1: Supply a 16-byte Uint8Array generator to v4 options.rng for deterministic entropy and decode buffer outputs with…

sha256:3dad9d47b302dcfbbddb1d03c9bb8e3c19e51dba749ec10e59342ea124bb1952

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
3
Claves de firma que lo compilaron
3
Entorno declarado node linux x64 node node npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
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-09-07

Caso

HOW
Objetivo
Supply a 16-byte Uint8Array generator to v4 options.rng for deterministic entropy and decode buffer outputs with stringify
Paquetes
Símbolos
  • v4
  • stringify
  • validate
  • version
Entorno
node
Creado
2026-08-16T07:08:04Z

Contrato

  1. assert v4({ rng: () => Math.random() }) throws TypeError when given a scalar random float callback
  2. assert v4({ rng: byteSupplier }) returns a valid v4 UUID string with RFC4122 version and variant bits applied
  3. assert v4(options, buf, offset) writes raw bytes directly into buf and returns the buffer reference instead of a string
  4. assert stringify(buf, offset) decodes the canonical UUID string from the binary buffer
  5. assert v4(options, buf, offset) throws RangeError when target buffer is smaller than 16 bytes

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# Notes

- **search_known_solution result**: Found existing sample `sha256:480c1cd73d2b874c0975ff73c562ac5427aa029495a4c7609b4d9d87ab41fd00` ("Import uuid v9+ without the removed default export breaking the build").
- **What a model would write instead**: `v4({ rng: () => Math.random() })` expecting a standard `0..1` random float generator, and `const str = v4(options, buf, offset)` expecting `str` to be a formatted UUID string.
- **How the wrong version fails**: Fails loudly at runtime with `TypeError: Cannot create property '6' on number` when indexing the returned scalar, and passing `buf` mutates and returns the `Uint8Array` instance (`=== buf`) rather than returning a string.
csx.json
{"case":{"caseId":"case:sha256:bf949bd6dc608b3ea1146b3acf361e045ace5a11cb488a7b09b786a542345ab2","contract":["assert v4({ rng: () =\u003e Math.random() }) throws TypeError when given a scalar random float callback","assert v4({ rng: byteSupplier }) returns a valid v4 UUID string with RFC4122 version and variant bits applied","assert v4(options, buf, offset) writes raw bytes directly into buf and returns the buffer reference instead of a string","assert stringify(buf, offset) decodes the canonical UUID string from the binary buffer","assert v4(options, buf, offset) throws RangeError when target buffer is smaller than 16 bytes"],"goal":"Supply a 16-byte Uint8Array generator to v4 options.rng for deterministic entropy and decode buffer outputs with stringify","kind":"HOW","packages":["pkg:npm/uuid@14.0.1"],"schemaVersion":1,"symbols":["v4","stringify","validate","version"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/uuid@14.0.1"],"schemaVersion":1,"symbols":["v4","stringify","validate","version"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-sample-uuid-config",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-sample-uuid-config",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "uuid": "14.0.1"
      }
    },
    "node_modules/uuid": {
      "version": "14.0.1",
      "resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.1.tgz",
      "integrity": "sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew==",
      "funding": [
        "https://github.com/sponsors/broofa",
        "https://github.com/sponsors/ctavan"
      ],
      "license": "MIT",
      "bin": {
        "uuid": "dist-node/bin/uuid"
      }
    }
  }
}
package.json
{
  "name": "csx-sample-uuid-config",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "uuid": "14.0.1"
  }
}
src/index.mjs
import { v4, stringify, validate, version } from 'uuid';

/**
 * Generates a v4 UUID using a custom RNG entropy source.
 * In uuid v9+, `options.rng` must be a generator returning a 16-byte Uint8Array/Array.
 * Passing a standard float-returning callback like `() => Math.random()` throws TypeError.
 */
export function generateDeterministicUuid(byteSupplier) {
  return v4({ rng: byteSupplier });
}

/**
 * Writes raw UUID bytes directly into an existing buffer at the specified offset.
 * `v4(options, buf, offset)` returns `buf` itself (a Uint8Array), NOT a string.
 */
export function writeUuidToBuffer(byteSupplier, buffer, offset = 0) {
  return v4({ rng: byteSupplier }, buffer, offset);
}

/**
 * Decodes a canonical UUID string from a binary buffer at the specified offset.
 */
export function readUuidFromBuffer(buffer, offset = 0) {
  return stringify(buffer, offset);
}

/**
 * Attempts to call v4 with an invalid scalar-returning RNG function.
 */
export function tryInvalidRng(scalarRng) {
  return v4({ rng: scalarRng });
}

export { validate, version };
test/contract.mjs
import { strict as assert } from 'node:assert';
import {
  generateDeterministicUuid,
  writeUuidToBuffer,
  readUuidFromBuffer,
  tryInvalidRng,
  validate,
  version
} from '../src/index.mjs';

// 1. Naive assumption: options.rng accepts a standard JS random number callback () => Math.random()
// Reality: v4 throws TypeError because it expects rng() to return a 16-byte buffer/array
assert.throws(
  () => tryInvalidRng(() => Math.random()),
  { name: 'TypeError' }
);

// 2. Correct configuration: options.rng must return an ArrayLike of >= 16 bytes
const fixedEntropy = new Uint8Array([
  0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
  0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10
]);

let calls = 0;
const rngSupplier = () => {
  calls++;
  return new Uint8Array(fixedEntropy);
};

const id = generateDeterministicUuid(rngSupplier);
assert.equal(calls, 1);
assert.equal(typeof id, 'string');
assert.equal(validate(id), true);
assert.equal(version(id), 4);
// RFC4122 transforms byte 6 (0x07 -> 0x47) and byte 8 (0x09 -> 0x89)
assert.equal(id, '01020304-0506-4708-890a-0b0c0d0e0f10');

// 3. Binary buffer writing: v4(options, buf, offset) returns buf itself (NOT a string)
const targetBuffer = new Uint8Array(32);
const offset = 8;
const returnedBuffer = writeUuidToBuffer(rngSupplier, targetBuffer, offset);

assert.equal(returnedBuffer, targetBuffer);
assert.equal(typeof returnedBuffer, 'object');
assert.equal(returnedBuffer instanceof Uint8Array, true);
assert.equal(returnedBuffer[offset + 6], 0x47);
assert.equal(returnedBuffer[offset + 8], 0x89);

// 4. Binary decoding: stringify(buf, offset) recovers the canonical UUID string
const decodedId = readUuidFromBuffer(targetBuffer, offset);
assert.equal(decodedId, '01020304-0506-4708-890a-0b0c0d0e0f10');

// 5. Buffer bounds safety: writes exceeding buffer length throw RangeError
assert.throws(
  () => writeUuidToBuffer(rngSupplier, new Uint8Array(10), 0),
  { name: 'RangeError' }
);

console.log('CONTRACT PASS: uuid v4 options.rng accepts 16-byte supplier and handles buffer offset serialization');

Seeder de origen

csx-seed