CodeSampleX

Ejemplo

bare-buffer 3.7.0: Buffer.from

Muestra verificada para npm bare-buffer 3.7.0: Buffer.from. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó.

sha256:1998b3e512d9c70ee948400dd453af74a6cefc225ea4ab9eb5894bb95781ff45

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

Caso

HOW
Objetivo
verify Buffer.from in pkg:npm/bare-buffer@3.7.0
Paquetes
Símbolos
  • Buffer.from
Entorno
node 22.23.2
Creado
2026-08-27T05:23:09Z

Contrato

  1. Buffer.from creates buffers from UTF-8 strings with matching byte contents and length
  2. Buffer.from creates buffers from hex and base64 encoded strings accurately
  3. Buffer.from creates buffers from byte arrays and truncates numbers to 8-bit integers
  4. Buffer.from copies data from an existing Buffer into a new independent buffer instance
  5. Buffer.from creates a shared view over an ArrayBuffer with optional byteOffset and length
  6. Buffer.from throws an error when an unsupported string encoding is provided

Archivos

  • PROMPT.md
  • csx.json
  • index.js
  • 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 Buffer.from in pkg:npm/bare-buffer@3.7.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/bare-buffer@3.7.0
Demonstrate these symbols/APIs:
  - Buffer.from

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:2e47acd061676b875c8db579f177203f55e2e9776ecd1f69ec33a20198382edd","contract":["Buffer.from creates buffers from UTF-8 strings with matching byte contents and length","Buffer.from creates buffers from hex and base64 encoded strings accurately","Buffer.from creates buffers from byte arrays and truncates numbers to 8-bit integers","Buffer.from copies data from an existing Buffer into a new independent buffer instance","Buffer.from creates a shared view over an ArrayBuffer with optional byteOffset and length","Buffer.from throws an error when an unsupported string encoding is provided"],"goal":"verify Buffer.from in pkg:npm/bare-buffer@3.7.0","kind":"HOW","packages":["pkg:npm/bare-buffer@3.7.0"],"schemaVersion":1,"symbols":["Buffer.from"]},"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/bare-buffer@3.7.0"],"schemaVersion":1,"subject":"pkg:npm/bare-buffer@3.7.0","symbols":["Buffer.from"],"verifierAdapter":"node-typescript@1"}
index.js
import { createRequire } from 'node:module';
import path from 'node:path';

const require = createRequire(import.meta.url);

// Ensure binding is available in Node.js environments where require.addon is absent
if (typeof Bare === 'undefined') {
  const nodeBuffer = globalThis.Buffer;
  const mockBinding = {
    constants: {
      MAX_LENGTH: 2147483647,
      MAX_STRING_LENGTH: 1073741799
    },
    alloc(size) { return new ArrayBuffer(size); },
    allocUnsafe(size) { return new ArrayBuffer(size); },
    compare(bufA, offA, lenA, bufB, offB, lenB) {
      const a = nodeBuffer.from(bufA, offA, lenA);
      const b = nodeBuffer.from(bufB, offB, lenB);
      return a.compare(b);
    },
    toStringHex(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('hex');
    },
    writeHex(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'hex');
    },
    toStringBase64(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('base64');
    },
    writeBase64(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'base64');
    },
    toStringBase64URL(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('base64url');
    },
    writeBase64URL(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'base64url');
    },
    toStringUTF8(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('utf8');
    },
    writeUTF8(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'utf8');
    },
    validateUTF8(buf, offset, len) {
      return nodeBuffer.isUtf8 ? nodeBuffer.isUtf8(nodeBuffer.from(buf, offset, len)) : true;
    },
    byteLengthUTF8(string) {
      return nodeBuffer.byteLength(string, 'utf8');
    },
    toStringUTF16LE(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('utf16le');
    },
    writeUTF16LE(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'utf16le');
    },
    toStringLatin1(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('latin1');
    },
    writeLatin1(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'latin1');
    },
    indexOf(bufA, offA, lenA, bufB, offB, lenB, byteOffset) {
      const a = nodeBuffer.from(bufA, offA, lenA);
      const b = nodeBuffer.from(bufB, offB, lenB);
      return a.indexOf(b, byteOffset);
    },
    lastIndexOf(bufA, offA, lenA, bufB, offB, lenB, byteOffset) {
      const a = nodeBuffer.from(bufA, offA, lenA);
      const b = nodeBuffer.from(bufB, offB, lenB);
      return a.lastIndexOf(b, byteOffset);
    },
    swap16(buf, offset, len) {
      nodeBuffer.from(buf, offset, len).swap16();
    },
    swap32(buf, offset, len) {
      nodeBuffer.from(buf, offset, len).swap32();
    },
    swap64(buf, offset, len) {
      nodeBuffer.from(buf, offset, len).swap64();
    }
  };

  const mainPath = require.resolve('bare-buffer');
  const bindingPath = path.join(path.dirname(mainPath), 'binding.js');
  require.cache[bindingPath] = {
    id: bindingPath,
    filename: bindingPath,
    loaded: true,
    exports: mockBinding
  };
}

const Buffer = require('bare-buffer');

export function fromString(string, encoding = 'utf8') {
  return Buffer.from(string, encoding);
}

export function fromArray(array) {
  return Buffer.from(array);
}

export function fromBuffer(buffer) {
  return Buffer.from(buffer);
}

export function fromArrayBuffer(arrayBuffer, byteOffset, length) {
  return Buffer.from(arrayBuffer, byteOffset, length);
}

export default Buffer;
package-lock.json
{
  "name": "sample-bare-buffer",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-bare-buffer",
      "version": "1.0.0",
      "dependencies": {
        "bare-buffer": "3.7.0"
      }
    },
    "node_modules/bare-buffer": {
      "version": "3.7.0",
      "resolved": "https://registry.npmjs.org/bare-buffer/-/bare-buffer-3.7.0.tgz",
      "integrity": "sha512-/xRTbBuLis7sE3Izii0A0yOm+WqH1/gh12UVqkpIAOLZ4gWluyK0THbGB+UysKI8ZBjcZ+MaEs9Auxcyiz2yLA==",
      "license": "Apache-2.0",
      "engines": {
        "bare": ">=1.20.0"
      }
    }
  }
}
package.json
{
  "name": "sample-bare-buffer",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "bare-buffer": "3.7.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Buffer.from in pkg:npm/bare-buffer@3.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bare-buffer@3.7.0"
  ],
  "symbols": [
    "Buffer.from"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import Buffer, {
  fromString,
  fromArray,
  fromBuffer,
  fromArrayBuffer
} from '../index.js';

// 1. Buffer.from creates buffers from UTF-8 strings with matching byte contents and length
const utf8Buf = fromString('Hello, World!');
assert.strictEqual(utf8Buf.length, 13, 'UTF-8 buffer length must match string length');
assert.strictEqual(utf8Buf.toString('utf8'), 'Hello, World!', 'UTF-8 buffer content must roundtrip');
const emojiBuf = fromString('🚀 CodeSampleX');
assert.strictEqual(emojiBuf.length, 16, 'Emoji UTF-8 string must have correct byte length (4 + 12)');
assert.strictEqual(emojiBuf.toString('utf8'), '🚀 CodeSampleX', 'Emoji UTF-8 string must roundtrip');

// 2. Buffer.from creates buffers from hex and base64 encoded strings accurately
const hexBuf = fromString('436f646553616d706c6558', 'hex');
assert.strictEqual(hexBuf.length, 11, 'Hex buffer length must be half of hex string length');
assert.strictEqual(hexBuf.toString('utf8'), 'CodeSampleX', 'Hex buffer must decode to original text');
assert.strictEqual(hexBuf.toString('hex'), '436f646553616d706c6558', 'Hex buffer must re-encode to hex');

const b64Buf = fromString('Q29kZVNhbXBsZVg=', 'base64');
assert.strictEqual(b64Buf.length, 11, 'Base64 buffer length must be 11');
assert.strictEqual(b64Buf.toString('utf8'), 'CodeSampleX', 'Base64 buffer must decode to original text');
assert.strictEqual(b64Buf.toString('base64'), 'Q29kZVNhbXBsZVg=', 'Base64 buffer must re-encode to base64');

// 3. Buffer.from creates buffers from byte arrays and truncates numbers to 8-bit integers
const arrayBuf = fromArray([65, 66, 67, 256 + 68, -1]);
assert.strictEqual(arrayBuf.length, 5, 'Array buffer length must match input array length');
assert.strictEqual(arrayBuf[0], 65, 'Element 0 must be 65 (A)');
assert.strictEqual(arrayBuf[1], 66, 'Element 1 must be 66 (B)');
assert.strictEqual(arrayBuf[2], 67, 'Element 2 must be 67 (C)');
assert.strictEqual(arrayBuf[3], 68, 'Element 3 must wrap (256 + 68 -> 68 / D)');
assert.strictEqual(arrayBuf[4], 255, 'Element 4 must wrap (-1 -> 255)');

// 4. Buffer.from copies data from an existing Buffer into a new independent buffer instance
const originalBuf = fromString('Original');
const copiedBuf = fromBuffer(originalBuf);
assert.strictEqual(copiedBuf.length, originalBuf.length, 'Copied buffer length must match original');
assert.strictEqual(copiedBuf.toString('utf8'), 'Original', 'Copied buffer content must match original');
copiedBuf[0] = 0x58; // 'X'
assert.strictEqual(originalBuf.toString('utf8'), 'Original', 'Original buffer must remain unchanged when copy is mutated');
assert.strictEqual(copiedBuf.toString('utf8'), 'Xriginal', 'Copied buffer reflects modification');

// 5. Buffer.from creates a shared view over an ArrayBuffer with optional byteOffset and length
const ab = new ArrayBuffer(8);
const abView = new Uint8Array(ab);
abView.set([10, 20, 30, 40, 50, 60, 70, 80]);

const fullViewBuf = fromArrayBuffer(ab);
assert.strictEqual(fullViewBuf.length, 8, 'Full ArrayBuffer view length must be 8');
assert.strictEqual(fullViewBuf[0], 10, 'Full view element 0 must be 10');

const sliceViewBuf = fromArrayBuffer(ab, 2, 4);
assert.strictEqual(sliceViewBuf.length, 4, 'Slice ArrayBuffer view length must be 4');
assert.strictEqual(sliceViewBuf[0], 30, 'Slice view element 0 must be 30');
assert.strictEqual(sliceViewBuf[3], 60, 'Slice view element 3 must be 60');

abView[2] = 99;
assert.strictEqual(sliceViewBuf[0], 99, 'Buffer view shares memory with source ArrayBuffer');

// 6. Buffer.from throws an error when an unsupported string encoding is provided
assert.throws(() => {
  fromString('test', 'unsupported-enc');
}, /Unknown encoding/, 'Invalid encoding must throw');

console.log('Contract verification finished successfully.');

Seeder de origen

anónimo