CodeSampleX

샘플

base64-js 1.5.1: byteLength

검증된 샘플 — npm base64-js 1.5.1: byteLength. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: byteLength calculates correct decoded byte size for…

sha256:48dc3ef5ac007eb7cbe7fe38b20b5391bdada2e6816cbdbadf836b568cd800bd

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
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 byteLength in pkg:npm/base64-js@1.5.1
패키지
심벌
  • byteLength
생성일
2026-08-26T11:22:39Z

컨트랙트

  1. byteLength calculates correct decoded byte size for unpadded and padded base64 strings
  2. byteLength matches the exact length of toByteArray decoded Uint8Array
  3. byteLength handles empty base64 string returning zero length
  4. byteLength throws Error when base64 string length is not a multiple of 4
  5. byteLength accurately computes byte lengths for multi-chunk base64 payloads

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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 byteLength in pkg:npm/base64-js@1.5.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/base64-js@1.5.1
Demonstrate these symbols/APIs:
  - byteLength

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:82a99b36f08b791e868c44c741013385b498e5e95ff13dda11b7a18f2a496871","contract":["byteLength calculates correct decoded byte size for unpadded and padded base64 strings","byteLength matches the exact length of toByteArray decoded Uint8Array","byteLength handles empty base64 string returning zero length","byteLength throws Error when base64 string length is not a multiple of 4","byteLength accurately computes byte lengths for multi-chunk base64 payloads"],"goal":"verify byteLength in pkg:npm/base64-js@1.5.1","kind":"HOW","packages":["pkg:npm/base64-js@1.5.1"],"schemaVersion":1,"symbols":["byteLength"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/base64-js@1.5.1"],"schemaVersion":1,"subject":"pkg:npm/base64-js@1.5.1","symbols":["byteLength"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "base64-js-byte-length-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "base64-js-byte-length-sample",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "base64-js": "1.5.1"
      }
    },
    "node_modules/base64-js": {
      "version": "1.5.1",
      "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
      "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/feross"
        },
        {
          "type": "patreon",
          "url": "https://www.patreon.com/feross"
        },
        {
          "type": "consulting",
          "url": "https://feross.org/support"
        }
      ],
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "base64-js-byte-length-sample",
  "version": "1.0.0",
  "description": "verify byteLength in pkg:npm/base64-js@1.5.1",
  "type": "module",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "base64-js": "1.5.1"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify byteLength in pkg:npm/base64-js@1.5.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/base64-js@1.5.1"
  ],
  "symbols": [
    "byteLength"
  ]
}
src/index.mjs
import base64 from 'base64-js';

const { byteLength, toByteArray, fromByteArray } = base64;

/**
 * Calculates the byte length of a base64 encoded string without decoding.
 *
 * @param {string} b64 - Base64 encoded string.
 * @returns {number} Decoded length in bytes.
 */
export function getDecodedByteLength(b64) {
  return byteLength(b64);
}

/**
 * Validates if the base64 string length is valid (multiple of 4) and returns its decoded length.
 *
 * @param {string} b64 - Base64 encoded string.
 * @returns {{ valid: boolean, length?: number, error?: string }}
 */
export function validateAndCalculateLength(b64) {
  try {
    const length = byteLength(b64);
    return { valid: true, length };
  } catch (err) {
    return { valid: false, error: err.message };
  }
}

/**
 * Verifies that byteLength matches the actual length of decoded Uint8Array from toByteArray.
 *
 * @param {string} b64 - Base64 encoded string.
 * @returns {boolean} True if byteLength equals toByteArray(b64).length.
 */
export function matchesDecodedBufferLength(b64) {
  const calculatedLen = byteLength(b64);
  const decoded = toByteArray(b64);
  return calculatedLen === decoded.length;
}

/**
 * Allocates a Uint8Array with the exact byte size determined by byteLength and decodes into it.
 *
 * @param {string} b64 - Base64 encoded string.
 * @returns {Uint8Array} Decoded byte array.
 */
export function allocateAndDecode(b64) {
  const length = byteLength(b64);
  const buffer = new Uint8Array(length);
  const decoded = toByteArray(b64);
  buffer.set(decoded);
  return buffer;
}

/**
 * Calculates decoded byte lengths for a batch of base64 strings.
 *
 * @param {string[]} b64List - Array of base64 strings.
 * @returns {number[]} Array of calculated byte lengths.
 */
export function batchByteLengths(b64List) {
  return b64List.map((str) => byteLength(str));
}
test/contract.mjs
import assert from 'node:assert/strict';
import base64 from 'base64-js';
import {
  getDecodedByteLength,
  validateAndCalculateLength,
  matchesDecodedBufferLength,
  allocateAndDecode,
  batchByteLengths,
} from '../src/index.mjs';

const { byteLength, toByteArray, fromByteArray } = base64;

// Contract 1: byteLength calculates correct decoded byte size for unpadded and padded base64 strings
{
  // 'f' -> 'Zg==' (1 byte, 2 padding chars)
  assert.strictEqual(getDecodedByteLength('Zg=='), 1);
  assert.strictEqual(byteLength('Zg=='), 1);

  // 'fo' -> 'Zm8=' (2 bytes, 1 padding char)
  assert.strictEqual(getDecodedByteLength('Zm8='), 2);
  assert.strictEqual(byteLength('Zm8='), 2);

  // 'foo' -> 'Zm9v' (3 bytes, 0 padding chars)
  assert.strictEqual(getDecodedByteLength('Zm9v'), 3);
  assert.strictEqual(byteLength('Zm9v'), 3);

  // 'foobar' -> 'Zm9vYmFy' (6 bytes, 0 padding chars)
  assert.strictEqual(getDecodedByteLength('Zm9vYmFy'), 6);
  assert.strictEqual(byteLength('Zm9vYmFy'), 6);
}

// Contract 2: byteLength matches the exact length of toByteArray decoded Uint8Array
{
  const testStrings = [
    'Zg==',
    'Zm8=',
    'Zm9v',
    'Zm9vYmFy',
    'SGVsbG8gV29ybGQh', // "Hello World!" (12 bytes)
    'QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=', // A-Z (26 bytes)
  ];

  for (const str of testStrings) {
    assert.strictEqual(matchesDecodedBufferLength(str), true);
    const decoded = allocateAndDecode(str);
    assert.strictEqual(decoded.length, byteLength(str));
    assert.deepStrictEqual(decoded, toByteArray(str));
  }
}

// Contract 3: byteLength handles empty base64 string returning zero length
{
  assert.strictEqual(byteLength(''), 0);
  assert.strictEqual(getDecodedByteLength(''), 0);
  const result = validateAndCalculateLength('');
  assert.strictEqual(result.valid, true);
  assert.strictEqual(result.length, 0);
}

// Contract 4: byteLength throws Error when base64 string length is not a multiple of 4
{
  assert.throws(
    () => byteLength('abc'),
    {
      name: 'Error',
      message: 'Invalid string. Length must be a multiple of 4',
    }
  );

  const invalidResult = validateAndCalculateLength('abcde');
  assert.strictEqual(invalidResult.valid, false);
  assert.strictEqual(invalidResult.error, 'Invalid string. Length must be a multiple of 4');
}

// Contract 5: byteLength accurately computes byte lengths for multi-chunk base64 payloads
{
  const lengths = [10, 50, 100, 256, 1000, 5000];
  const b64List = [];

  for (const len of lengths) {
    const rawBytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      rawBytes[i] = (i * 31 + 7) % 256;
    }
    const b64 = fromByteArray(rawBytes);
    b64List.push(b64);
  }

  const calculated = batchByteLengths(b64List);
  assert.deepStrictEqual(calculated, lengths);
}

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

오리진 시더

익명