CodeSampleX

Пример

@webassemblyjs/wasm-gen 1.14.1

Проверенный пример — npm @webassemblyjs/wasm-gen 1.14.1. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: encodeU32 encodes unsigned…

sha256:6b81e0152e0e70affa465dfad479a5149c95aaa57ed639994a955fd28a4b9a7a

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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/@webassemblyjs/wasm-gen@1.14.1
Пакеты
Окружение
node 22.23.2
Создан
2026-08-27T23:30:34Z

Контракт

  1. encodeU32 encodes unsigned 32-bit integers into LEB128 byte arrays
  2. encodeNode encodes StringLiteral AST nodes into length-prefixed UTF-8 vectors
  3. encodeNode encodes Instr AST nodes for WebAssembly instructions and constants
  4. encodeNode encodes TypeInstruction AST nodes into binary function signatures
  5. encodeNode encodes ModuleExport and ModuleImport AST nodes for WebAssembly modules
  6. encodeNode encodes Func and Global AST definitions
  7. buildSimpleWasmBinary assembles executable WebAssembly binary modules verified via WebAssembly.Instance
  8. encodeNode throws an error when given unsupported AST node types

Файлы

  • 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/@webassemblyjs/wasm-gen@1.14.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40webassemblyjs/wasm-gen@1.14.1

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:3b4805605be97a4050e0447582b458adc1f6afd7cb687880a51ecf08cf38f71b","contract":["encodeU32 encodes unsigned 32-bit integers into LEB128 byte arrays","encodeNode encodes StringLiteral AST nodes into length-prefixed UTF-8 vectors","encodeNode encodes Instr AST nodes for WebAssembly instructions and constants","encodeNode encodes TypeInstruction AST nodes into binary function signatures","encodeNode encodes ModuleExport and ModuleImport AST nodes for WebAssembly modules","encodeNode encodes Func and Global AST definitions","buildSimpleWasmBinary assembles executable WebAssembly binary modules verified via WebAssembly.Instance","encodeNode throws an error when given unsupported AST node types"],"goal":"verify pkg:npm/@webassemblyjs/wasm-gen@1.14.1","kind":"HOW","packages":["pkg:npm/%40webassemblyjs/wasm-gen@1.14.1"],"schemaVersion":1},"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/%40webassemblyjs/wasm-gen@1.14.1"],"schemaVersion":1,"subject":"pkg:npm/%40webassemblyjs/wasm-gen@1.14.1","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-wasm-gen",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-wasm-gen",
      "version": "1.0.0",
      "dependencies": {
        "@webassemblyjs/wasm-gen": "1.14.1"
      }
    },
    "node_modules/@webassemblyjs/ast": {
      "version": "1.14.1",
      "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz",
      "integrity": "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==",
      "license": "MIT",
      "dependencies": {
        "@webassemblyjs/helper-numbers": "1.13.2",
        "@webassemblyjs/helper-wasm-bytecode": "1.13.2"
      }
    },
    "node_modules/@webassemblyjs/floating-point-hex-parser": {
      "version": "1.13.2",
      "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz",
      "integrity": "sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==",
      "license": "MIT"
    },
    "node_modules/@webassemblyjs/helper-api-error": {
      "version": "1.13.2",
      "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz",
      "integrity": "sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==",
      "license": "MIT"
    },
    "node_modules/@webassemblyjs/helper-numbers": {
      "version": "1.13.2",
      "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz",
      "integrity": "sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==",
      "license": "MIT",
      "dependencies": {
        "@webassemblyjs/floating-point-hex-parser": "1.13.2",
        "@webassemblyjs/helper-api-error": "1.13.2",
        "@xtuc/long": "4.2.2"
      }
    },
    "node_modules/@webassemblyjs/helper-wasm-bytecode": {
      "version": "1.13.2",
      "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz",
      "integrity": "sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==",
      "license": "MIT"
    },
    "node_modules/@webassemblyjs/ieee754": {
      "version": "1.13.2",
      "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz",
      "integrity": "sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==",
      "license": "MIT",
      "dependencies": {
        "@xtuc/ieee754": "^1.2.0"
      }
    },
    "node_modules/@webassemblyjs/leb128": {
      "version": "1.13.2",
      "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.13.2.tgz",
      "integrity": "sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==",
      "license": "Apache-2.0",
      "dependencies": {
        "@xtuc/long": "4.2.2"
      }
    },
    "node_modules/@webassemblyjs/utf8": {
      "version": "1.13.2",
      "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.13.2.tgz",
      "integrity": "sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==",
      "license": "MIT"
    },
    "node_modules/@webassemblyjs/wasm-gen": {
      "version": "1.14.1",
      "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz",
      "integrity": "sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==",
      "license": "MIT",
      "dependencies": {
        "@webassemblyjs/ast": "1.14.1",
        "@webassemblyjs/helper-wasm-bytecode": "1.13.2",
        "@webassemblyjs/ieee754": "1.13.2",
        "@webassemblyjs/leb128": "1.13.2",
        "@webassemblyjs/utf8": "1.13.2"
      }
    },
    "node_modules/@xtuc/ieee754": {
      "version": "1.2.0",
      "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz",
      "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==",
      "license": "BSD-3-Clause"
    },
    "node_modules/@xtuc/long": {
      "version": "4.2.2",
      "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz",
      "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==",
      "license": "Apache-2.0"
    }
  }
}
package.json
{
  "name": "sample-wasm-gen",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of @webassemblyjs/wasm-gen",
  "main": "src/index.js",
  "dependencies": {
    "@webassemblyjs/wasm-gen": "1.14.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/@webassemblyjs/wasm-gen@1.14.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40webassemblyjs/wasm-gen@1.14.1"
  ]
}
src/index.js
const wasmGen = require('@webassemblyjs/wasm-gen');

const encodeNode = wasmGen.encodeNode;
const encodeU32 = wasmGen.encodeU32;

/**
 * Creates a standard WebAssembly binary header.
 * @returns {number[]} 8-byte WebAssembly magic header and version
 */
function createWasmHeader() {
  return [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
}

/**
 * Encodes a section payload with section ID and LEB128 length prefix.
 * @param {number} sectionId - WebAssembly binary section ID
 * @param {number[]} payload - Vector of section payload bytes
 * @returns {number[]} Encoded section bytes
 */
function encodeSection(sectionId, payload) {
  const sizeBytes = encodeU32(payload.length);
  return [sectionId, ...sizeBytes, ...payload];
}

/**
 * Encodes a single WebAssembly instruction node.
 * @param {string} id - Instruction name (e.g. 'const', 'add', 'end')
 * @param {string} [object] - Type prefix (e.g. 'i32', 'i64')
 * @param {Array<{type: string, value: number}>} [args] - Instruction arguments
 * @returns {number[]} Bytecode array
 */
function encodeInstruction(id, object, args) {
  const node = { type: 'Instr', id };
  if (object) {
    node.object = object;
  }
  if (args && args.length > 0) {
    node.args = args;
  }
  return encodeNode(node);
}

/**
 * Assembles a complete WebAssembly module binary from sections.
 * @param {object} options
 * @param {Array<{params: string[], results: string[]}>} options.types - Function type definitions
 * @param {number[]} options.funcTypes - Function type index mappings
 * @param {Array<{name: string, funcIndex: number}>} options.exports - Export definitions
 * @param {Array<Array<object>>} options.codeBodies - Function body instruction arrays
 * @returns {Uint8Array} Assembled WebAssembly binary buffer
 */
function buildSimpleWasmBinary(options = {}) {
  const bytes = [...createWasmHeader()];

  if (options.types && options.types.length > 0) {
    const typeNodes = options.types.flatMap((t) =>
      encodeNode({
        type: 'TypeInstruction',
        functype: {
          params: t.params.map((valtype) => ({ valtype })),
          results: t.results
        }
      })
    );
    const typePayload = [...encodeU32(options.types.length), ...typeNodes];
    bytes.push(...encodeSection(1, typePayload));
  }

  if (options.funcTypes && options.funcTypes.length > 0) {
    const funcNodes = options.funcTypes.flatMap((typeIdx) =>
      encodeNode({
        type: 'IndexInFuncSection',
        index: { type: 'NumberLiteral', value: typeIdx }
      })
    );
    const funcPayload = [...encodeU32(options.funcTypes.length), ...funcNodes];
    bytes.push(...encodeSection(3, funcPayload));
  }

  if (options.exports && options.exports.length > 0) {
    const exportNodes = options.exports.flatMap((exp) =>
      encodeNode({
        type: 'ModuleExport',
        name: exp.name,
        descr: { exportType: 'Func', id: { type: 'NumberLiteral', value: exp.funcIndex } }
      })
    );
    const exportPayload = [...encodeU32(options.exports.length), ...exportNodes];
    bytes.push(...encodeSection(7, exportPayload));
  }

  if (options.codeBodies && options.codeBodies.length > 0) {
    const bodyNodes = options.codeBodies.flatMap((bodyInstrs) =>
      encodeNode({
        type: 'Func',
        body: bodyInstrs
      })
    );
    const codePayload = [...encodeU32(options.codeBodies.length), ...bodyNodes];
    bytes.push(...encodeSection(10, codePayload));
  }

  return new Uint8Array(bytes);
}

module.exports = {
  encodeNode,
  encodeU32,
  createWasmHeader,
  encodeSection,
  encodeInstruction,
  buildSimpleWasmBinary
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  encodeNode,
  encodeU32,
  createWasmHeader,
  encodeSection,
  encodeInstruction,
  buildSimpleWasmBinary
} = require('../src/index.js');

// 1. Export verification
assert.strictEqual(typeof encodeNode, 'function', 'encodeNode should be a function');
assert.strictEqual(typeof encodeU32, 'function', 'encodeU32 should be a function');
assert.strictEqual(typeof createWasmHeader, 'function', 'createWasmHeader should be a function');
assert.strictEqual(typeof encodeSection, 'function', 'encodeSection should be a function');
assert.strictEqual(typeof encodeInstruction, 'function', 'encodeInstruction should be a function');
assert.strictEqual(typeof buildSimpleWasmBinary, 'function', 'buildSimpleWasmBinary should be a function');

// 2. encodeU32 LEB128 unsigned 32-bit integer encoding
assert.deepStrictEqual(encodeU32(0), [0], 'encodeU32(0) should be [0]');
assert.deepStrictEqual(encodeU32(1), [1], 'encodeU32(1) should be [1]');
assert.deepStrictEqual(encodeU32(42), [42], 'encodeU32(42) should be [42]');
assert.deepStrictEqual(encodeU32(127), [127], 'encodeU32(127) should be [127]');
assert.deepStrictEqual(encodeU32(128), [128, 1], 'encodeU32(128) should be [128, 1]');
assert.deepStrictEqual(encodeU32(16384), [128, 128, 1], 'encodeU32(16384) should be [128, 128, 1]');

// 3. encodeNode for StringLiteral AST nodes (length-prefixed UTF-8)
const stringBytes = encodeNode({
  type: 'StringLiteral',
  value: 'wasm'
});
assert.deepStrictEqual(stringBytes, [4, 119, 97, 115, 109], 'StringLiteral encodes length + UTF-8 bytes');

// 4. encodeNode for Instr AST nodes
const constInstr = encodeNode({
  type: 'Instr',
  id: 'const',
  object: 'i32',
  args: [{ type: 'NumberLiteral', value: 10 }]
});
assert.deepStrictEqual(constInstr, [0x41, 10], 'i32.const 10 encodes to [0x41, 10]');

const addInstr = encodeNode({
  type: 'Instr',
  id: 'add',
  object: 'i32'
});
assert.deepStrictEqual(addInstr, [0x6a], 'i32.add encodes to [0x6a]');

const subInstr = encodeInstruction('sub', 'i32');
assert.deepStrictEqual(subInstr, [0x6b], 'i32.sub encodes to [0x6b]');

const mulInstr = encodeInstruction('mul', 'i32');
assert.deepStrictEqual(mulInstr, [0x6c], 'i32.mul encodes to [0x6c]');

const nopInstr = encodeInstruction('nop');
assert.deepStrictEqual(nopInstr, [0x01], 'nop encodes to [0x01]');

// 5. encodeNode for TypeInstruction AST nodes
const typeSig = encodeNode({
  type: 'TypeInstruction',
  functype: {
    params: [{ valtype: 'i32' }, { valtype: 'i32' }],
    results: ['i32']
  }
});
// 0x60 (func), vector of 2 params [i32 (0x7f), i32 (0x7f)], vector of 1 result [i32 (0x7f)]
assert.deepStrictEqual(typeSig, [0x60, 2, 0x7f, 0x7f, 1, 0x7f], 'TypeInstruction encodes function signature');

// 6. encodeNode for ModuleExport and ModuleImport AST nodes
const exportBytes = encodeNode({
  type: 'ModuleExport',
  name: 'add',
  descr: {
    exportType: 'Func',
    id: { type: 'NumberLiteral', value: 0 }
  }
});
assert.deepStrictEqual(
  exportBytes,
  [3, 97, 100, 100, 0, 0],
  'ModuleExport encodes name, export kind (0=Func), and func index'
);

const importBytes = encodeNode({
  type: 'ModuleImport',
  module: 'env',
  name: 'log',
  descr: {
    type: 'FuncImportDescr',
    id: { type: 'NumberLiteral', value: 0 }
  }
});
assert.deepStrictEqual(
  importBytes,
  [3, 101, 110, 118, 3, 108, 111, 103, 0, 0],
  'ModuleImport encodes module name, import name, import kind, and type index'
);

// 7. encodeNode for Global and Func AST nodes
const globalNode = encodeNode({
  type: 'Global',
  globalType: {
    valtype: 'i32',
    mutability: 'var'
  },
  init: [
    { type: 'Instr', id: 'const', object: 'i32', args: [{ type: 'NumberLiteral', value: 10 }] },
    { type: 'Instr', id: 'end' }
  ]
});
assert.deepStrictEqual(
  globalNode,
  [0x7f, 1, 0x41, 10, 0x0b],
  'Global node encodes valtype, mutability flag, and init expression'
);

const funcBody = encodeNode({
  type: 'Func',
  body: [
    { type: 'Instr', id: 'get_local', args: [{ type: 'NumberLiteral', value: 0 }] },
    { type: 'Instr', id: 'get_local', args: [{ type: 'NumberLiteral', value: 1 }] },
    { type: 'Instr', id: 'add', object: 'i32' },
    { type: 'Instr', id: 'end' }
  ]
});
// func body size: 7 bytes (1 byte local count + 6 instruction bytes)
assert.deepStrictEqual(
  funcBody,
  [7, 0, 0x20, 0, 0x20, 1, 0x6a, 0x0b],
  'Func body encodes size, locals vector, and instructions'
);

// 8. Error handling for unsupported AST node types
assert.throws(
  () => {
    encodeNode({ type: 'UnsupportedNodeType' });
  },
  /Unsupported encoding for node of type/,
  'encodeNode throws descriptive error for unsupported AST node types'
);

// 9. Full WebAssembly binary construction, compilation, and execution
const wasmBinary = buildSimpleWasmBinary({
  types: [
    { params: ['i32', 'i32'], results: ['i32'] }
  ],
  funcTypes: [0, 0],
  exports: [
    { name: 'add', funcIndex: 0 },
    { name: 'multiply', funcIndex: 1 }
  ],
  codeBodies: [
    // add(a, b) = a + b
    [
      { type: 'Instr', id: 'get_local', args: [{ type: 'NumberLiteral', value: 0 }] },
      { type: 'Instr', id: 'get_local', args: [{ type: 'NumberLiteral', value: 1 }] },
      { type: 'Instr', id: 'add', object: 'i32' },
      { type: 'Instr', id: 'end' }
    ],
    // multiply(a, b) = a * b
    [
      { type: 'Instr', id: 'get_local', args: [{ type: 'NumberLiteral', value: 0 }] },
      { type: 'Instr', id: 'get_local', args: [{ type: 'NumberLiteral', value: 1 }] },
      { type: 'Instr', id: 'mul', object: 'i32' },
      { type: 'Instr', id: 'end' }
    ]
  ]
});

assert.ok(wasmBinary instanceof Uint8Array, 'Binary is Uint8Array');
assert.ok(WebAssembly.validate(wasmBinary), 'WebAssembly binary is structurally valid');

const wasmModule = new WebAssembly.Module(wasmBinary);
const wasmInstance = new WebAssembly.Instance(wasmModule);

assert.strictEqual(typeof wasmInstance.exports.add, 'function', 'Exported add function is callable');
assert.strictEqual(typeof wasmInstance.exports.multiply, 'function', 'Exported multiply function is callable');

assert.strictEqual(wasmInstance.exports.add(20, 22), 42, 'add(20, 22) should equal 42');
assert.strictEqual(wasmInstance.exports.add(-5, 10), 5, 'add(-5, 10) should equal 5');
assert.strictEqual(wasmInstance.exports.multiply(6, 7), 42, 'multiply(6, 7) should equal 42');
assert.strictEqual(wasmInstance.exports.multiply(9, 9), 81, 'multiply(9, 9) should equal 81');

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

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

аноним