CodeSampleX

Пример

iconv-lite 0.6.3: iconv.decode

Проверенный пример — npm iconv-lite 0.6.3: iconv.decode. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: iconv.decode(buf, 'utf-8')…

sha256:84a72c1c4a44e54d43d634d67b8b64e2143ada95137498eecf32b37ee63bc375

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-26

Кейс

HOW
Цель
verify iconv.decode in pkg:npm/iconv-lite@0.6.3
Пакеты
Символы
  • iconv.decode
Окружение
node 22.23.2
Создан
2026-08-26T06:14:39Z

Контракт

  1. iconv.decode(buf, 'utf-8') decodes UTF-8 Buffer to string
  2. iconv.decode(buf, encoding) decodes single-byte encodings including windows-1251 and iso-8859-1
  3. iconv.decode(buf, encoding) decodes multi-byte encodings including utf-16le and gbk
  4. iconv.decode canonicalizes encoding names (case-insensitive and punctuation-insensitive aliases like 'UTF-8', 'utf8', 'WINDOWS-1251', 'cp1251')
  5. iconv.decode strips leading byte order mark (BOM) by default for BOM-aware encodings like UTF-8
  6. iconv.decode(buf, encoding, { stripBOM: false }) preserves leading BOM '\uFEFF'
  7. iconv.decode returns empty string for empty Buffer input
  8. iconv.decode replaces invalid byte sequences with unicode replacement character '\uFFFD'
  9. iconv.decode throws Error for unrecognized encoding names
  10. iconv.decode accepts string input by coercing binary string to Buffer

Файлы

  • NOTES.md
  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.cjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# iconv-lite Public API Behavior: iconv.decode

## Overview
`iconv-lite` provides pure JavaScript character encoding conversion for Node.js. This sample verifies the decoding behavior, encoding normalization rules, BOM handling, invalid byte sequence substitution, and error handling of `iconv.decode`.

## Pinned Release
- `iconv-lite`: `0.6.3`
- Runtime: Node.js (tested on Node 22 CommonJS)

## Observed Behavior & Traps

### 1. Multi-Byte and Single-Byte Decoding
- `iconv.decode(buf, encoding, options)` decodes binary Buffer or Uint8Array instances into JavaScript UTF-16 strings.
- Supported encodings include standard Unicode encodings (`utf-8`, `utf-16le`, `utf-16be`), single-byte encodings (e.g. `windows-1251`, `iso-8859-1`, `cp437`), and East Asian multi-byte encodings (e.g. `gbk`, `shift_jis`, `euc-kr`, `big5`).

### 2. Encoding Name Canonicalization
- Encoding strings are normalized by `iconv._canonicalizeEncoding(encoding)`: all non-alphanumeric characters are stripped and characters are converted to lowercase.
- Consequently, `'UTF-8'`, `'utf-8'`, `'utf8'`, `'UTF_8'` all resolve to the same UTF-8 codec.
- Code page aliases like `'windows-1251'`, `'WINDOWS-1251'`, `'win1251'`, and `'cp1251'` resolve identically.

### 3. Byte Order Mark (BOM) Stripping
- For BOM-aware codecs (`utf-8`, `utf-16le`, `utf-16be`), `iconv.decode` automatically strips leading BOM by default (`stripBOM: true`).
- Passing options `{ stripBOM: false }` preserves the leading `\uFEFF` character in the decoded string output.

### 4. Invalid Byte Handling
- When encountering malformed or invalid byte sequences in a valid encoding, `iconv.decode` does not throw; instead it emits the replacement character `\uFFFD` (for Unicode output) or `?` (for single-byte output).

### 5. Empty Buffer and String Inputs
- Decoding an empty buffer (`Buffer.alloc(0)`) returns an empty string `""`.
- If a string is passed as the `buf` argument instead of a Buffer, `iconv.decode` coerces it to a binary buffer and returns the decoded string.

### 6. Unrecognized Encoding Error
- Passing an unrecognized encoding name throws `Error: Encoding not recognized: '<name>' (searched as: '...')`.

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 iconv.decode in pkg:npm/iconv-lite@0.6.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/iconv-lite@0.6.3
Demonstrate these symbols/APIs:
  - iconv.decode
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - 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:8cc497cae8a638de105edbe0b5ef3d4da1acb70f12b4e6310aa4fb182c9dce54","constraints":{"executionContext":"node"},"contract":["iconv.decode(buf, 'utf-8') decodes UTF-8 Buffer to string","iconv.decode(buf, encoding) decodes single-byte encodings including windows-1251 and iso-8859-1","iconv.decode(buf, encoding) decodes multi-byte encodings including utf-16le and gbk","iconv.decode canonicalizes encoding names (case-insensitive and punctuation-insensitive aliases like 'UTF-8', 'utf8', 'WINDOWS-1251', 'cp1251')","iconv.decode strips leading byte order mark (BOM) by default for BOM-aware encodings like UTF-8","iconv.decode(buf, encoding, { stripBOM: false }) preserves leading BOM '\\uFEFF'","iconv.decode returns empty string for empty Buffer input","iconv.decode replaces invalid byte sequences with unicode replacement character '\\uFFFD'","iconv.decode throws Error for unrecognized encoding names","iconv.decode accepts string input by coercing binary string to Buffer"],"goal":"verify iconv.decode in pkg:npm/iconv-lite@0.6.3","kind":"HOW","packages":["pkg:npm/iconv-lite@0.6.3"],"schemaVersion":1,"symbols":["iconv.decode"]},"contractCommand":["node","test/contract.cjs"],"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/iconv-lite@0.6.3"],"schemaVersion":1,"subject":"pkg:npm/iconv-lite@0.6.3","symbols":["iconv.decode"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "verify-iconv-decode",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "verify-iconv-decode",
      "version": "1.0.0",
      "dependencies": {
        "iconv-lite": "0.6.3"
      }
    },
    "node_modules/iconv-lite": {
      "version": "0.6.3",
      "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
      "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
      "license": "MIT",
      "dependencies": {
        "safer-buffer": ">= 2.1.2 < 3.0.0"
      },
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/safer-buffer": {
      "version": "2.1.2",
      "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
      "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "verify-iconv-decode",
  "version": "1.0.0",
  "private": true,
  "dependencies": {
    "iconv-lite": "0.6.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify iconv.decode in pkg:npm/iconv-lite@0.6.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/iconv-lite@0.6.3"
  ],
  "symbols": [
    "iconv.decode"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.cjs
const assert = require('node:assert/strict');
const iconv = require('iconv-lite');

// 1. iconv.decode decodes UTF-8 Buffer to string
const utf8Buf = Buffer.from('Hello, world!', 'utf8');
assert.strictEqual(iconv.decode(utf8Buf, 'utf-8'), 'Hello, world!');

// 2. iconv.decode decodes single-byte encodings (e.g. windows-1251, iso-8859-1)
const win1251Buf = Buffer.from([0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2]); // "Привет" in CP1251
assert.strictEqual(iconv.decode(win1251Buf, 'win1251'), 'Привет');

const iso88591Buf = Buffer.from([0xe9, 0xe0, 0xe7]); // "éàç" in ISO-8859-1
assert.strictEqual(iconv.decode(iso88591Buf, 'iso-8859-1'), 'éàç');

// 3. iconv.decode decodes multi-byte encodings (e.g. utf-16le, gbk)
const utf16leBuf = Buffer.from([0x48, 0x00, 0x69, 0x00]); // "Hi" in UTF-16LE
assert.strictEqual(iconv.decode(utf16leBuf, 'utf-16le'), 'Hi');

const gbkBuf = Buffer.from([0xc4, 0xe3, 0xba, 0xc3]); // "你好" in GBK
assert.strictEqual(iconv.decode(gbkBuf, 'gbk'), '你好');

// 4. iconv.decode canonicalizes encoding names (case-insensitive and punctuation-insensitive)
assert.strictEqual(iconv.decode(utf8Buf, 'UTF-8'), 'Hello, world!');
assert.strictEqual(iconv.decode(utf8Buf, 'utf8'), 'Hello, world!');
assert.strictEqual(iconv.decode(utf8Buf, 'UTF_8'), 'Hello, world!');
assert.strictEqual(iconv.decode(win1251Buf, 'WINDOWS-1251'), 'Привет');
assert.strictEqual(iconv.decode(win1251Buf, 'cp1251'), 'Привет');

// 5. iconv.decode strips leading BOM by default for BOM-aware codecs
const utf8BomBuf = Buffer.from([0xef, 0xbb, 0xbf, 0x61, 0x62, 0x63]);
assert.strictEqual(iconv.decode(utf8BomBuf, 'utf-8'), 'abc');
assert.strictEqual(iconv.decode(utf8BomBuf, 'utf-8').length, 3);

// 6. iconv.decode preserves BOM when stripBOM option is set to false
const withBom = iconv.decode(utf8BomBuf, 'utf-8', { stripBOM: false });
assert.strictEqual(withBom, '\ufeffabc');
assert.strictEqual(withBom.length, 4);

// 7. iconv.decode returns empty string for empty Buffer
assert.strictEqual(iconv.decode(Buffer.alloc(0), 'utf-8'), '');
assert.strictEqual(iconv.decode(Buffer.from([]), 'windows-1251'), '');

// 8. iconv.decode replaces invalid byte sequences with unicode replacement character (\uFFFD)
const invalidUtf8 = Buffer.from([0xff, 0xfe, 0x61]); // invalid UTF-8 start byte 0xff
const decodedInvalid = iconv.decode(invalidUtf8, 'utf-8');
assert.ok(decodedInvalid.includes('\ufffd'));

// 9. iconv.decode throws Error when encoding is unrecognized
assert.throws(
  () => iconv.decode(Buffer.from([0x61]), 'unknown-encoding-xyz'),
  (err) => err instanceof Error && /Encoding not recognized/.test(err.message)
);

// 10. iconv.decode handles string input by coercing binary string to buffer
assert.strictEqual(iconv.decode('Hello', 'utf-8'), 'Hello');

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

Исходный сидер

аноним