CodeSampleX

示例

@noble/hashes 2.3.0: utf8ToBytes

已验证示例 — npm @noble/hashes 2.3.0: utf8ToBytes. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: utf8ToBytes is exported as a function from submodule…

sha256:cd802344731cac4dc680b6039983380ef45ee054249be1a626a1ee8317ec1fd9

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-06

案例

HOW
目标
verify @noble/hashes.utf8ToBytes in pkg:npm/%40noble/hashes@2.3.0
包
符号
  • @noble/hashes.utf8ToBytes
环境
node 22.23.2
创建时间
2026-09-06T11:00:33Z

契约

  1. utf8ToBytes is exported as a function from submodule @noble/hashes/utils.js whereas root module import throws
  2. utf8ToBytes encodes ASCII and empty strings to expected Uint8Array representations
  3. utf8ToBytes encodes multi-byte Unicode strings and 4-byte surrogate emojis to valid UTF-8 byte sequences
  4. utf8ToBytes validates input types and strictly throws TypeError when non-string arguments are supplied
  5. utf8ToBytes output integrates seamlessly with hash functions like sha256 to produce standard cryptographic digests

文件

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

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Notes: @noble/hashes utf8ToBytes submodule export and input validation

## `search_known_solution` Result

An initial search of known solutions for `@noble/hashes@2.3.0` with symbol `@noble/hashes.utf8ToBytes` returned `NO_SAFE_MATCH`.

## Pinned Release

- `@noble/hashes`: `2.3.0`
- Runtime: Node.js (`>=20.19.0`, tested on Node 22.23.2)

## What a Naive Model Would Write

A naive model or developer migrating to or using `@noble/hashes` often assumes:
1. `utf8ToBytes` can be imported directly from the package root:
   ```javascript
   import { utf8ToBytes } from '@noble/hashes';
   ```
2. Or imported from the extensionless path:
   ```javascript
   import { utf8ToBytes } from '@noble/hashes/utils';
   ```
3. Or that `utf8ToBytes` will permissively accept an already-encoded `Uint8Array` or coerce non-string values like numbers or objects into strings before encoding.

## How the Wrong Version Fails

1. **Root Import Fails**: The root module entry `index.js` explicitly throws an exception:
   `Error: root module cannot be imported: import submodules instead. Check out README`
2. **Subpath Without Extension Fails**: Under Node.js ESM package resolution, omitting `.js` throws:
   `ERR_PACKAGE_PATH_NOT_EXPORTED`
   Importing `@noble/hashes/utils.js` with the explicit file extension is required.
3. **Strict Type Assertion**: `utf8ToBytes` performs a strict `typeof str !== 'string'` check, throwing `TypeError: string expected`. Passing `Uint8Array`, numbers, null, or undefined fails immediately instead of silently coercing.
4. **Correct Usage**:
   ```javascript
   import { utf8ToBytes } from '@noble/hashes/utils.js';
   const bytes = utf8ToBytes('my-utf8-string');
   ```
   The returned `Uint8Array` is directly accepted by hash, HMAC, and KDF functions in `@noble/hashes` (e.g. `sha256(bytes)`).
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 @noble/hashes.utf8ToBytes in pkg:npm/%40noble/hashes@2.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40noble/hashes@2.3.0
Demonstrate these symbols/APIs:
  - @noble/hashes.utf8ToBytes

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:62f25b3b9440d401fc78ff478677aa523c870812715edb8f964f65d3dd38efc1","contract":["utf8ToBytes is exported as a function from submodule @noble/hashes/utils.js whereas root module import throws","utf8ToBytes encodes ASCII and empty strings to expected Uint8Array representations","utf8ToBytes encodes multi-byte Unicode strings and 4-byte surrogate emojis to valid UTF-8 byte sequences","utf8ToBytes validates input types and strictly throws TypeError when non-string arguments are supplied","utf8ToBytes output integrates seamlessly with hash functions like sha256 to produce standard cryptographic digests"],"goal":"verify @noble/hashes.utf8ToBytes in pkg:npm/%40noble/hashes@2.3.0","kind":"HOW","packages":["pkg:npm/%40noble/hashes@2.3.0"],"schemaVersion":1,"symbols":["@noble/hashes.utf8ToBytes"]},"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/%40noble/hashes@2.3.0"],"schemaVersion":1,"subject":"pkg:npm/%40noble/hashes@2.3.0","symbols":["@noble/hashes.utf8ToBytes"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-noble-hashes-utf8tobytes",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-noble-hashes-utf8tobytes",
      "version": "1.0.0",
      "dependencies": {
        "@noble/hashes": "2.3.0"
      }
    },
    "node_modules/@noble/hashes": {
      "version": "2.3.0",
      "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.3.0.tgz",
      "integrity": "sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ==",
      "license": "MIT",
      "engines": {
        "node": ">= 20.19.0"
      },
      "funding": {
        "url": "https://paulmillr.com/funding/"
      }
    }
  }
}
package.json
{
  "name": "sample-noble-hashes-utf8tobytes",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "@noble/hashes": "2.3.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @noble/hashes.utf8ToBytes in pkg:npm/%40noble/hashes@2.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40noble/hashes@2.3.0"
  ],
  "symbols": [
    "@noble/hashes.utf8ToBytes"
  ]
}
src/index.mjs
import { utf8ToBytes } from '@noble/hashes/utils.js';
import { sha256 } from '@noble/hashes/sha2.js';

export { utf8ToBytes };

/**
 * Attempts to import the root module of @noble/hashes to verify submodule import restriction.
 * @returns {Promise<{ threw: boolean, errorMessage: string }>}
 */
export async function testRootImportRestriction() {
  try {
    await import('@noble/hashes');
    return { threw: false, errorMessage: '' };
  } catch (err) {
    return { threw: true, errorMessage: err.message };
  }
}

/**
 * Converts a UTF-8 string into bytes using @noble/hashes.utf8ToBytes.
 * @param {string} str - input string to convert
 * @returns {Uint8Array}
 */
export function encodeUtf8(str) {
  return utf8ToBytes(str);
}

/**
 * Encodes string to UTF-8 and computes SHA-256 hash digest.
 * Demonstrates interoperability with cryptographic functions in @noble/hashes.
 * @param {string} str - input string
 * @returns {Uint8Array} SHA-256 digest bytes
 */
export function hashUtf8String(str) {
  const bytes = utf8ToBytes(str);
  return sha256(bytes);
}

/**
 * Safely tests type enforcement of utf8ToBytes.
 * @param {*} value - non-string value to pass
 * @returns {{ threwTypeError: boolean, errorMessage: string }}
 */
export function testTypeValidation(value) {
  try {
    utf8ToBytes(value);
    return { threwTypeError: false, errorMessage: '' };
  } catch (err) {
    return {
      threwTypeError: err instanceof TypeError,
      errorMessage: err.message,
    };
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import { utf8ToBytes } from '@noble/hashes/utils.js';
import { bytesToHex } from '@noble/hashes/utils.js';
import { sha256 } from '@noble/hashes/sha2.js';
import {
  encodeUtf8,
  hashUtf8String,
  testRootImportRestriction,
  testTypeValidation,
} from '../src/index.mjs';

// 1. utf8ToBytes is exported as a function from submodule @noble/hashes/utils.js whereas root module import throws
assert.equal(typeof utf8ToBytes, 'function', 'utf8ToBytes must be exported as a function');
const rootCheck = await testRootImportRestriction();
assert.equal(rootCheck.threw, true, 'Importing @noble/hashes root module must throw');
assert.match(
  rootCheck.errorMessage,
  /root module cannot be imported: import submodules instead/,
  'Root import error must inform caller to import submodules'
);

// 2. utf8ToBytes encodes ASCII and empty strings to expected Uint8Array representations
const emptyBytes = encodeUtf8('');
assert.ok(emptyBytes instanceof Uint8Array, 'Empty result must be a Uint8Array');
assert.equal(emptyBytes.length, 0, 'Empty string must yield 0-length Uint8Array');

const asciiBytes = encodeUtf8('abc');
assert.deepEqual(
  asciiBytes,
  new Uint8Array([0x61, 0x62, 0x63]),
  'ASCII string abc must encode to [97, 98, 99]'
);

// 3. utf8ToBytes encodes multi-byte Unicode strings and 4-byte surrogate emojis to valid UTF-8 byte sequences
const koreanBytes = encodeUtf8('한글');
assert.deepEqual(
  koreanBytes,
  new Uint8Array([0xed, 0x95, 0x9c, 0xea, 0xb8, 0x80]),
  'Multi-byte Unicode characters must encode to valid UTF-8 bytes'
);

const emojiBytes = encodeUtf8('🔑');
assert.deepEqual(
  emojiBytes,
  new Uint8Array([0xf0, 0x9f, 0x94, 0x91]),
  '4-byte emoji must encode to standard 4-byte UTF-8 sequence'
);

// 4. utf8ToBytes validates input types and strictly throws TypeError when non-string arguments are supplied
const invalidInputs = [
  null,
  undefined,
  123,
  {},
  [1, 2, 3],
  new Uint8Array([1, 2, 3]),
  true,
];

for (const input of invalidInputs) {
  const check = testTypeValidation(input);
  assert.equal(
    check.threwTypeError,
    true,
    `utf8ToBytes must throw TypeError for input type ${typeof input}`
  );
  assert.equal(
    check.errorMessage,
    'string expected',
    'Error message must be "string expected"'
  );
}

// 5. utf8ToBytes output integrates seamlessly with hash functions like sha256 to produce standard cryptographic digests
const digest = hashUtf8String('hello world');
const hexDigest = bytesToHex(digest);
assert.equal(
  hexDigest,
  'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9',
  'SHA-256 of utf8ToBytes("hello world") must match canonical test vector'
);

console.log('Contract tests passed successfully.');

原始种子者

匿名