CodeSampleX

Exemplo

bare-buffer 3.7.0: Buffer

Amostra verificada para npm bare-buffer 3.7.0: Buffer. O contrato rodou em node 22 · linux alpine/x64 · docker e passou: Buffer.alloc creates…

sha256:e589288e1fcc6e2c6f85e8bb939d25794c7b2f3e5c960d894386055d124ebf6c

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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 in pkg:npm/bare-buffer@3.7.0
Pacotes
Símbolos
  • Buffer
Ambiente
node 22.23.2
Criado
2026-08-27T05:15:56Z

Contrato

  1. Buffer.alloc creates zero-initialized buffers of specified length and supports custom fill values
  2. Buffer.from creates buffers from byte arrays, existing buffers, and encoded strings
  3. Buffer.concat combines multiple buffers into a contiguous single buffer with optional totalLength
  4. Buffer.isBuffer identifies bare-buffer instances and rejects non-buffer values
  5. Buffer compare and equals evaluate buffer content ordering and strict byte equality
  6. Buffer copy and slice transfer and view slices of binary data between buffers
  7. Buffer read and write methods serialize and deserialize multi-byte integers in BE and LE byte orders
  8. Buffer write and toString encode and decode text using utf8, hex, and base64 codecs

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 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
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: esm
  - 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:87548b3e81caf00d9ee1dac0a3c9a6b3074a1c7d292d65b41613de13d3b02b6f","constraints":{"executionContext":"node"},"contract":["Buffer.alloc creates zero-initialized buffers of specified length and supports custom fill values","Buffer.from creates buffers from byte arrays, existing buffers, and encoded strings","Buffer.concat combines multiple buffers into a contiguous single buffer with optional totalLength","Buffer.isBuffer identifies bare-buffer instances and rejects non-buffer values","Buffer compare and equals evaluate buffer content ordering and strict byte equality","Buffer copy and slice transfer and view slices of binary data between buffers","Buffer read and write methods serialize and deserialize multi-byte integers in BE and LE byte orders","Buffer write and toString encode and decode text using utf8, hex, and base64 codecs"],"goal":"verify Buffer in pkg:npm/bare-buffer@3.7.0","kind":"HOW","packages":["pkg:npm/bare-buffer@3.7.0"],"schemaVersion":1,"symbols":["Buffer"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","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/bare-buffer@3.7.0"],"schemaVersion":1,"subject":"pkg:npm/bare-buffer@3.7.0","symbols":["Buffer"],"verifierAdapter":"node-typescript@1"}
index.js
import { createRequire } from 'node:module';
import path from 'node:path';

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

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;
    },
    validateAscii(buf, offset, len) {
      return nodeBuffer.isAscii ? nodeBuffer.isAscii(nodeBuffer.from(buf, offset, len)) : nodeBuffer.from(buf, offset, len).every(b => b <= 0x7f);
    },
    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 allocateBuffer(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding);
}

export function createBufferFrom(source, encoding) {
  return Buffer.from(source, encoding);
}

export function concatBuffers(list, totalLength) {
  return Buffer.concat(list, totalLength);
}

export function compareBuffers(a, b) {
  return Buffer.compare(a, b);
}

export function areBuffersEqual(a, b) {
  return a.equals(b);
}

export function copyBuffer(src, target, targetStart = 0, sourceStart = 0, sourceEnd = src.byteLength) {
  return src.copy(target, targetStart, sourceStart, sourceEnd);
}

export { Buffer };
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",
      "license": "MIT-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,
  "description": "Clean-room verification of Buffer in bare-buffer",
  "license": "MIT-0",
  "dependencies": {
    "bare-buffer": "3.7.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Buffer in pkg:npm/bare-buffer@3.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bare-buffer@3.7.0"
  ],
  "symbols": [
    "Buffer"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "esm",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import Buffer, {
  allocateBuffer,
  createBufferFrom,
  concatBuffers,
  compareBuffers,
  areBuffersEqual,
  copyBuffer
} from '../index.js';

// 1. Buffer.alloc creates zero-initialized buffers of specified length and supports custom fill values
const zeroBuf = allocateBuffer(8);
assert.strictEqual(zeroBuf.length, 8, 'alloc should allocate specified byte length');
assert.deepStrictEqual(Array.from(zeroBuf), [0, 0, 0, 0, 0, 0, 0, 0], 'alloc should be zero-filled by default');

const filledBuf = allocateBuffer(4, 0x5a);
assert.strictEqual(filledBuf.length, 4, 'alloc with fill should match length');
assert.deepStrictEqual(Array.from(filledBuf), [0x5a, 0x5a, 0x5a, 0x5a], 'alloc should fill with specified byte');

// 2. Buffer.from creates buffers from byte arrays, existing buffers, and encoded strings
const fromArray = createBufferFrom([10, 20, 30, 40]);
assert.strictEqual(fromArray.length, 4, 'from array length should match source array');
assert.strictEqual(fromArray[0], 10);
assert.strictEqual(fromArray[3], 40);

const fromString = createBufferFrom('hello world', 'utf8');
assert.strictEqual(fromString.length, 11, 'from string length should match utf8 byte count');
assert.strictEqual(fromString.toString('utf8'), 'hello world', 'decoded string should match source');

const fromExisting = createBufferFrom(fromArray);
assert.deepStrictEqual(Array.from(fromExisting), [10, 20, 30, 40], 'from Buffer should copy contents');

// 3. Buffer.concat combines multiple buffers into a contiguous single buffer with optional totalLength
const chunk1 = createBufferFrom([1, 2]);
const chunk2 = createBufferFrom([3, 4, 5]);
const chunk3 = createBufferFrom([6]);

const joined = concatBuffers([chunk1, chunk2, chunk3]);
assert.strictEqual(joined.length, 6, 'concat should combine lengths of all chunks');
assert.deepStrictEqual(Array.from(joined), [1, 2, 3, 4, 5, 6], 'concat should maintain chunk byte order');

const joinedBounded = concatBuffers([chunk1, chunk2, chunk3], 4);
assert.strictEqual(joinedBounded.length, 4, 'concat with totalLength should truncate if shorter');
assert.deepStrictEqual(Array.from(joinedBounded), [1, 2, 3, 4], 'concat truncated contents should match');

// 4. Buffer.isBuffer identifies bare-buffer instances and rejects non-buffer values
assert.strictEqual(Buffer.isBuffer(zeroBuf), true, 'Buffer instance must be recognized by isBuffer');
assert.strictEqual(Buffer.isBuffer(fromString), true, 'from instance must be recognized by isBuffer');
assert.strictEqual(Buffer.isBuffer(new Uint8Array(4)), false, 'standard Uint8Array without bare kind must not be bare Buffer');
assert.strictEqual(Buffer.isBuffer('not-a-buffer'), false, 'string must not be a buffer');
assert.strictEqual(Buffer.isBuffer({}), false, 'plain object must not be a buffer');
assert.strictEqual(Buffer.isBuffer(null), false, 'null must not be a buffer');

// 5. Buffer compare and equals evaluate buffer content ordering and strict byte equality
const bufA = createBufferFrom([1, 2, 3]);
const bufB = createBufferFrom([1, 2, 3]);
const bufC = createBufferFrom([1, 2, 4]);

assert.strictEqual(areBuffersEqual(bufA, bufB), true, 'equal buffers should return true for equals');
assert.strictEqual(areBuffersEqual(bufA, bufC), false, 'different buffers should return false for equals');
assert.strictEqual(compareBuffers(bufA, bufB), 0, 'identical buffers should compare to 0');
assert.strictEqual(compareBuffers(bufA, bufC), -1, 'lesser buffer should compare to negative');
assert.strictEqual(compareBuffers(bufC, bufA), 1, 'greater buffer should compare to positive');

// 6. Buffer copy and slice transfer and view slices of binary data between buffers
const srcBuf = createBufferFrom([100, 101, 102, 103, 104]);
const dstBuf = allocateBuffer(5, 0);
const copiedBytes = copyBuffer(srcBuf, dstBuf, 1, 1, 4);
assert.strictEqual(copiedBytes, 3, 'copy should return number of bytes transferred');
assert.deepStrictEqual(Array.from(dstBuf), [0, 101, 102, 103, 0], 'dstBuf should reflect copied slice at target offset');

const sliceBuf = srcBuf.subarray(1, 4);
assert.strictEqual(sliceBuf.length, 3, 'subarray length should match slice range');
assert.deepStrictEqual(Array.from(sliceBuf), [101, 102, 103], 'subarray values should match source slice');

// 7. Buffer read and write methods serialize and deserialize multi-byte integers in BE and LE byte orders
const numBuf = allocateBuffer(8);
numBuf.writeUInt8(0xfe, 0);
assert.strictEqual(numBuf.readUInt8(0), 0xfe, 'readUInt8 should match written byte');

numBuf.writeUInt16BE(0x1234, 1);
assert.strictEqual(numBuf.readUInt16BE(1), 0x1234, 'readUInt16BE should match written uint16');
assert.strictEqual(numBuf[1], 0x12, 'BE high byte at offset 1');
assert.strictEqual(numBuf[2], 0x34, 'BE low byte at offset 2');

numBuf.writeUInt16LE(0x1234, 3);
assert.strictEqual(numBuf.readUInt16LE(3), 0x1234, 'readUInt16LE should match written uint16');
assert.strictEqual(numBuf[3], 0x34, 'LE low byte at offset 3');
assert.strictEqual(numBuf[4], 0x12, 'LE high byte at offset 4');

numBuf.writeInt32BE(-123456, 4);
assert.strictEqual(numBuf.readInt32BE(4), -123456, 'readInt32BE should match negative 32-bit int');

// 8. Buffer write and toString encode and decode text using utf8, hex, and base64 codecs
const textBuf = allocateBuffer(16, 0);
const writtenUtf8 = textBuf.write('ABC', 0, 3, 'utf8');
assert.strictEqual(writtenUtf8, 3, 'utf8 write byte count should match string length');
assert.strictEqual(textBuf.toString('utf8', 0, 3), 'ABC', 'utf8 toString should decode written string');

const hexBuf = createBufferFrom('48656c6c6f', 'hex');
assert.strictEqual(hexBuf.toString('utf8'), 'Hello', 'hex decoded buffer should equal UTF-8 Hello');
assert.strictEqual(hexBuf.toString('hex'), '48656c6c6f', 'toString hex should match input hex');

const b64Buf = createBufferFrom('V29ybGQ=', 'base64');
assert.strictEqual(b64Buf.toString('utf8'), 'World', 'base64 decoded buffer should equal World');
assert.strictEqual(b64Buf.toString('base64'), 'V29ybGQ=', 'toString base64 should match input base64');

console.log('All contract assertions passed successfully.');

Seeder de origem

anônimo