CodeSampleX

サンプル

bser 2.1.1: Accumulator, dumpToBuffer, loadFromBuffer

検証済みサンプル — npm bser 2.1.1: Accumulator, dumpToBuffer, loadFromBuffer. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました.

sha256:fbc965d355ce29b22e67d40315eb89066961008bd55f6633a87036f27c6bd6d9

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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/bser@2.1.1
パッケージ
シンボル
  • bser.Accumulator
  • bser.dumpToBuffer
  • bser.loadFromBuffer
環境
node 22.23.2
作成日
2026-08-27T15:48:00Z

コントラクト

  1. bser.dumpToBuffer serializes JavaScript primitive values, objects, and arrays into BSER binary encoded Buffers
  2. bser.dumpToBuffer omits undefined object properties and throws an Error when serializing unsupported types
  3. bser.loadFromBuffer deserializes BSER binary Buffers into equivalent JavaScript data structures
  4. bser.loadFromBuffer throws an Error when excess unparsed data follows the BSER payload
  5. bser.Accumulator manages an expandable buffer tracking read and write offsets with space reservation
  6. bser.Accumulator writes and reads byte, integer, double, and string values preserving binary fidelity

ファイル

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 pkg:npm/bser@2.1.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/bser@2.1.1
Demonstrate these symbols/APIs:
  - bser.Accumulator
  - bser.dumpToBuffer
  - bser.loadFromBuffer

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:79061292c944861dc37633faf89b29c6003f697aaf2380e1709c58cb0627d2b6","contract":["bser.dumpToBuffer serializes JavaScript primitive values, objects, and arrays into BSER binary encoded Buffers","bser.dumpToBuffer omits undefined object properties and throws an Error when serializing unsupported types","bser.loadFromBuffer deserializes BSER binary Buffers into equivalent JavaScript data structures","bser.loadFromBuffer throws an Error when excess unparsed data follows the BSER payload","bser.Accumulator manages an expandable buffer tracking read and write offsets with space reservation","bser.Accumulator writes and reads byte, integer, double, and string values preserving binary fidelity"],"goal":"verify pkg:npm/bser@2.1.1","kind":"HOW","packages":["pkg:npm/bser@2.1.1"],"schemaVersion":1,"symbols":["bser.Accumulator","bser.dumpToBuffer","bser.loadFromBuffer"]},"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/bser@2.1.1"],"schemaVersion":1,"subject":"pkg:npm/bser@2.1.1","symbols":["bser.Accumulator","bser.dumpToBuffer","bser.loadFromBuffer"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-bser",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-bser",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "bser": "2.1.1"
      }
    },
    "node_modules/bser": {
      "version": "2.1.1",
      "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz",
      "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==",
      "license": "Apache-2.0",
      "dependencies": {
        "node-int64": "^0.4.0"
      }
    },
    "node_modules/node-int64": {
      "version": "0.4.0",
      "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",
      "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-bser",
  "version": "1.0.0",
  "description": "Clean-room verification sample for bser",
  "main": "src/index.js",
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "bser": "2.1.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/bser@2.1.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bser@2.1.1"
  ],
  "symbols": [
    "bser.Accumulator",
    "bser.dumpToBuffer",
    "bser.loadFromBuffer"
  ]
}
src/index.js
import bser from 'bser';

/**
 * Serializes any supported JavaScript value into a BSER Buffer.
 *
 * @param {unknown} value - Value to serialize.
 * @returns {Buffer} BSER-encoded binary buffer.
 */
export function serialize(value) {
  return bser.dumpToBuffer(value);
}

/**
 * Deserializes a BSER binary buffer back into a JavaScript value.
 *
 * @param {Buffer} buffer - BSER-encoded buffer.
 * @returns {unknown} Deserialized JavaScript value.
 */
export function deserialize(buffer) {
  return bser.loadFromBuffer(buffer);
}

/**
 * Creates a new Accumulator with the given initial capacity.
 *
 * @param {number} [initialSize=8192] - Initial buffer size in bytes.
 * @returns {bser.Accumulator} An instance of Accumulator.
 */
export function createAccumulator(initialSize = 8192) {
  return new bser.Accumulator(initialSize);
}

/**
 * Encodes multiple values into an Accumulator sequentially.
 *
 * @param {bser.Accumulator} acc - Accumulator instance.
 * @param {Array<unknown>} values - Values to serialize and append.
 */
export function appendSerializedValues(acc, values) {
  for (const val of values) {
    const dumped = bser.dumpToBuffer(val);
    acc.append(dumped);
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import bser from 'bser';
import {
  serialize,
  deserialize,
  createAccumulator,
  appendSerializedValues
} from '../src/index.js';

// 1. bser.dumpToBuffer serializes JavaScript primitive values, objects, and arrays into BSER binary encoded Buffers
{
  const primitives = [
    'hello bser',
    '',
    42,
    -100,
    3.14159,
    true,
    false,
    null,
    [1, 'two', true, null, [3, 4]],
    { name: 'watchman', version: 1, active: true, nested: { count: 10 } }
  ];

  for (const item of primitives) {
    const directBuf = bser.dumpToBuffer(item);
    const helperBuf = serialize(item);

    assert.ok(Buffer.isBuffer(directBuf), 'bser.dumpToBuffer must return a Buffer');
    assert.ok(Buffer.isBuffer(helperBuf), 'serialize helper must return a Buffer');
    assert.equal(directBuf.length > 0, true, 'Serialized buffer must not be empty');
    assert.deepEqual(directBuf, helperBuf, 'Direct and helper serialization must match');

    // Verify BSER magic header (0x00, 0x01)
    assert.equal(directBuf[0], 0x00, 'First header byte must be 0x00');
    assert.equal(directBuf[1], 0x01, 'Second header byte must be 0x01');
  }
}

// 2. bser.dumpToBuffer omits undefined object properties and throws an Error when serializing unsupported types
{
  const objWithUndefined = {
    keep: 'value',
    omitMe: undefined,
    count: 10
  };
  const buf = bser.dumpToBuffer(objWithUndefined);
  const loaded = bser.loadFromBuffer(buf);

  assert.deepEqual(loaded, { keep: 'value', count: 10 });
  assert.equal('omitMe' in loaded, false, 'Undefined property must be omitted from serialization');

  assert.throws(
    () => bser.dumpToBuffer(() => 'unsupported function'),
    /cannot serialize type function to BSER/,
    'dumpToBuffer must throw when serializing functions'
  );

  assert.throws(
    () => bser.dumpToBuffer(Symbol('unsupported')),
    /cannot serialize type symbol to BSER/,
    'dumpToBuffer must throw when serializing symbols'
  );
}

// 3. bser.loadFromBuffer deserializes BSER binary Buffers into equivalent JavaScript data structures
{
  const testPayload = {
    message: 'payload roundtrip',
    numericArray: [10, 20, 30, 40],
    nested: {
      enabled: true,
      score: 99.5,
      none: null
    }
  };

  const encoded = bser.dumpToBuffer(testPayload);
  const decodedDirect = bser.loadFromBuffer(encoded);
  const decodedHelper = deserialize(encoded);

  assert.deepEqual(decodedDirect, testPayload, 'loadFromBuffer must reconstruct original structure');
  assert.deepEqual(decodedHelper, testPayload, 'deserialize helper must reconstruct original structure');
}

// 4. bser.loadFromBuffer throws an Error when excess unparsed data follows the BSER payload
{
  const validBuffer = bser.dumpToBuffer({ valid: true });
  const excessBuffer = Buffer.concat([validBuffer, Buffer.from([0x99, 0x88, 0x77])]);

  assert.throws(
    () => bser.loadFromBuffer(excessBuffer),
    /excess data found after input buffer, use BunserBuf instead/,
    'loadFromBuffer must reject buffers with trailing unparsed data'
  );
}

// 5. bser.Accumulator manages an expandable buffer tracking read and write offsets with space reservation
{
  const acc = new bser.Accumulator(16);
  assert.ok(acc instanceof bser.Accumulator, 'acc must be an instance of bser.Accumulator');
  assert.equal(acc.readOffset, 0, 'Initial readOffset must be 0');
  assert.equal(acc.writeOffset, 0, 'Initial writeOffset must be 0');
  assert.equal(acc.readAvail(), 0, 'Initial readAvail must be 0');
  assert.ok(acc.writeAvail() >= 16, 'Initial writeAvail must accommodate initial size hint');

  const initialCapacity = acc.buf.length;
  // Reserve space larger than current capacity to trigger expansion
  acc.reserve(initialCapacity * 2);
  assert.ok(acc.buf.length >= initialCapacity * 2, 'reserve must expand buffer capacity');

  const helperAcc = createAccumulator(32);
  appendSerializedValues(helperAcc, [{ a: 1 }, { b: 2 }]);
  assert.ok(helperAcc.readAvail() > 0, 'Accumulator must contain readable bytes after append');
}

// 6. bser.Accumulator writes and reads byte, integer, double, and string values preserving binary fidelity
{
  const acc = new bser.Accumulator(256);

  acc.writeByte(120);
  acc.writeInt(30000, 2);
  acc.writeInt(2000000, 4);
  acc.writeDouble(12345.678);
  acc.append(Buffer.from('binary-string-segment', 'utf-8'));

  assert.equal(acc.readInt(1), 120, 'readInt(1) must return written byte');
  assert.equal(acc.readInt(2), 30000, 'readInt(2) must return written 16-bit int');
  assert.equal(acc.readInt(4), 2000000, 'readInt(4) must return written 32-bit int');
  assert.ok(Math.abs(acc.readDouble() - 12345.678) < 1e-6, 'readDouble must return written float');
  assert.equal(acc.readString(21), 'binary-string-segment', 'readString must return appended string');
  assert.equal(acc.readAvail(), 0, 'All written bytes must have been consumed');
}

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

オリジンシーダー

匿名