CodeSampleX

Пример

resedit 1.7.2: Resource

Проверенный пример — npm resedit 1.7.2: Resource. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: Resource.VersionInfo.createEmpty…

sha256:39ae36ab7df0fea9087801d30bf91cd0b3f3ca562a2216e10903da1e6ae5497b

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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 resedit.Resource in pkg:npm/resedit@1.7.2
Пакеты
Символы
  • resedit.Resource
Окружение
node 22.23.2
Создан
2026-09-06T11:04:47Z

Контракт

  1. Resource.VersionInfo.createEmpty creates empty version resource and sets file version, product version, and fixed info flags
  2. Resource.VersionInfo sets and retrieves localized string values in executable resource entries
  3. Resource.StringTable adds and retrieves localized string entries by integer ID and replaces string entries for executable resources
  4. Resource.IconGroupEntry.replaceIconsForResource populates icon group and icon resource entries queryable via fromEntries

Файлы

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.js

Скачать артефакт с исходным кодом (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 resedit.Resource in pkg:npm/resedit@1.7.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/resedit@1.7.2
Demonstrate these symbols/APIs:
  - resedit.Resource

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:4d3d4b40510d461335e150d34a8b50087f9fa62b83d20a6a31cada88d4f464f1","contract":["Resource.VersionInfo.createEmpty creates empty version resource and sets file version, product version, and fixed info flags","Resource.VersionInfo sets and retrieves localized string values in executable resource entries","Resource.StringTable adds and retrieves localized string entries by integer ID and replaces string entries for executable resources","Resource.IconGroupEntry.replaceIconsForResource populates icon group and icon resource entries queryable via fromEntries"],"goal":"verify resedit.Resource in pkg:npm/resedit@1.7.2","kind":"HOW","packages":["pkg:npm/resedit@1.7.2"],"schemaVersion":1,"symbols":["resedit.Resource"]},"contractCommand":["node","test/contract.js"],"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/resedit@1.7.2"],"schemaVersion":1,"subject":"pkg:npm/resedit@1.7.2","symbols":["resedit.Resource"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const ResEdit = require('resedit');

/**
 * Creates and populates Resource structures for a PE executable.
 *
 * @param {Object} [options]
 * @param {Object} [options.version]
 * @param {Object} [options.strings]
 * @param {Array<Object>} [options.icons]
 * @returns {{ exe: ResEdit.NtExecutable, res: ResEdit.NtExecutableResource, binary: ArrayBuffer }}
 */
function buildExecutableWithResources(options = {}) {
  const exe = ResEdit.NtExecutable.createEmpty(false, false);
  const res = ResEdit.NtExecutableResource.from(exe);

  if (options.version) {
    const vi = ResEdit.Resource.VersionInfo.createEmpty();
    const lang = options.version.lang || 1033;
    const codepage = options.version.codepage || 1200;
    vi.lang = lang;

    if (options.version.fileVersion) {
      const fv = options.version.fileVersion;
      vi.setFileVersion(fv.major || 0, fv.minor || 0, fv.patch || 0, fv.build || 0, lang);
    }
    if (options.version.productVersion) {
      const pv = options.version.productVersion;
      vi.setProductVersion(pv.major || 0, pv.minor || 0, pv.patch || 0, pv.build || 0, lang);
    }

    if (options.version.flags !== undefined) {
      vi.fixedInfo.fileFlags = options.version.flags;
      vi.fixedInfo.fileFlagsMask = options.version.flagsMask !== undefined ? options.version.flagsMask : options.version.flags;
    }
    if (options.version.fileOS !== undefined) {
      vi.fixedInfo.fileOS = options.version.fileOS;
    }
    if (options.version.fileType !== undefined) {
      vi.fixedInfo.fileType = options.version.fileType;
    }

    if (options.version.stringValues) {
      vi.setStringValues({ lang, codepage }, options.version.stringValues);
    }

    vi.outputToResourceEntries(res.entries);
  }

  if (options.strings) {
    const st = new ResEdit.Resource.StringTable();
    st.lang = options.strings.lang || 1033;
    for (const [idStr, text] of Object.entries(options.strings.items || {})) {
      st.setById(Number(idStr), text);
    }
    st.replaceStringEntriesForExecutable(res);
  }

  if (options.icons && options.icons.length > 0) {
    for (const iconGroup of options.icons) {
      const groupID = iconGroup.id || 1;
      const lang = iconGroup.lang || 1033;
      ResEdit.Resource.IconGroupEntry.replaceIconsForResource(res.entries, groupID, lang, iconGroup.items);
    }
  }

  res.outputResource(exe);
  const binary = exe.generate();

  return { exe, res, binary };
}

/**
 * Extracts and inspects Resource entries from executable binary data.
 *
 * @param {ArrayBuffer|Buffer} binary
 * @param {number} [lang=1033]
 * @param {number} [codepage=1200]
 * @returns {{ versionInfo: ResEdit.Resource.VersionInfo|null, stringTable: ResEdit.Resource.StringTable|null, iconGroups: Array<ResEdit.Resource.IconGroupEntry> }}
 */
function inspectExecutableResources(binary, lang = 1033, codepage = 1200) {
  const exe = ResEdit.NtExecutable.from(binary);
  const res = ResEdit.NtExecutableResource.from(exe);

  const viList = ResEdit.Resource.VersionInfo.fromEntries(res.entries);
  const versionInfo = viList.length > 0 ? viList[0] : null;

  let stringTable = null;
  try {
    stringTable = ResEdit.Resource.StringTable.fromEntries(lang, res.entries);
  } catch (_err) {
    stringTable = null;
  }

  const iconGroups = ResEdit.Resource.IconGroupEntry.fromEntries(res.entries);

  return {
    versionInfo,
    stringTable,
    iconGroups
  };
}

/**
 * Creates a minimal 1x1 32bpp IconItem for testing icon resource entries.
 *
 * @returns {ResEdit.Data.IconItem}
 */
function createMinimalIconItem() {
  const header = Buffer.alloc(40 + 4);
  header.writeUInt32LE(40, 0);
  header.writeInt32LE(1, 4);
  header.writeInt32LE(2, 8);
  header.writeUInt16LE(1, 12);
  header.writeUInt16LE(32, 14);
  return ResEdit.Data.IconItem.from(header.buffer);
}

module.exports = {
  buildExecutableWithResources,
  inspectExecutableResources,
  createMinimalIconItem,
  Resource: ResEdit.Resource
};
package-lock.json
{
  "name": "sample-resedit-resource",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-resedit-resource",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "resedit": "1.7.2"
      }
    },
    "node_modules/pe-library": {
      "version": "0.4.1",
      "resolved": "https://registry.npmjs.org/pe-library/-/pe-library-0.4.1.tgz",
      "integrity": "sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==",
      "license": "MIT",
      "engines": {
        "node": ">=12",
        "npm": ">=6"
      },
      "funding": {
        "type": "github",
        "url": "https://github.com/sponsors/jet2jet"
      }
    },
    "node_modules/resedit": {
      "version": "1.7.2",
      "resolved": "https://registry.npmjs.org/resedit/-/resedit-1.7.2.tgz",
      "integrity": "sha512-vHjcY2MlAITJhC0eRD/Vv8Vlgmu9Sd3LX9zZvtGzU5ZImdTN3+d6e/4mnTyV8vEbyf1sgNIrWxhWlrys52OkEA==",
      "license": "MIT",
      "dependencies": {
        "pe-library": "^0.4.1"
      },
      "engines": {
        "node": ">=12",
        "npm": ">=6"
      },
      "funding": {
        "type": "github",
        "url": "https://github.com/sponsors/jet2jet"
      }
    }
  }
}
package.json
{
  "name": "sample-resedit-resource",
  "version": "1.0.0",
  "private": true,
  "description": "verify resedit.Resource in pkg:npm/resedit@1.7.2",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "resedit": "1.7.2"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify resedit.Resource in pkg:npm/resedit@1.7.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/resedit@1.7.2"
  ],
  "symbols": [
    "resedit.Resource"
  ]
}
test/contract.js
'use strict';

const assert = require('assert');
const ResEdit = require('resedit');
const {
  buildExecutableWithResources,
  inspectExecutableResources,
  createMinimalIconItem,
  Resource
} = require('../index.js');

async function testContract() {
  // 1. Contract: Resource.VersionInfo.createEmpty creates empty version resource and sets file version, product version, and fixed info flags
  const vi = Resource.VersionInfo.createEmpty();
  assert.ok(vi, 'Resource.VersionInfo.createEmpty must return a VersionInfo instance');
  vi.lang = 1033;
  vi.setFileVersion(1, 2, 3, 4, 1033);
  vi.setProductVersion(2, 0, 0, 1, 1033);

  vi.fixedInfo.fileFlags = Resource.VersionFileFlags.Debug | Resource.VersionFileFlags.Patched;
  vi.fixedInfo.fileFlagsMask = Resource.VersionFileFlags.Debug | Resource.VersionFileFlags.Patched;
  vi.fixedInfo.fileOS = Resource.VersionFileOS.NT_Windows32;
  vi.fixedInfo.fileType = Resource.VersionFileType.App;

  assert.strictEqual(vi.fixedInfo.fileFlags, Resource.VersionFileFlags.Debug | Resource.VersionFileFlags.Patched);
  assert.strictEqual(vi.fixedInfo.fileOS, Resource.VersionFileOS.NT_Windows32);
  assert.strictEqual(vi.fixedInfo.fileType, Resource.VersionFileType.App);

  // 2. Contract: Resource.VersionInfo sets and retrieves localized string values in executable resource entries
  vi.setStringValues(
    { lang: 1033, codepage: 1200 },
    {
      FileDescription: 'Sample Resource Executable',
      ProductName: 'CodeSampleX Resource Demo',
      FileVersion: '1.2.3.4',
      ProductVersion: '2.0.0.1',
      LegalCopyright: 'MIT-0'
    }
  );

  const initialEntries = [];
  vi.outputToResourceEntries(initialEntries);
  assert.ok(initialEntries.length > 0, 'outputToResourceEntries must generate resource entries');

  const parsedViList = Resource.VersionInfo.fromEntries(initialEntries);
  assert.strictEqual(parsedViList.length, 1, 'fromEntries must parse VersionInfo from entries');
  const parsedStrings = parsedViList[0].getStringValues({ lang: 1033, codepage: 1200 });
  assert.strictEqual(parsedStrings.FileDescription, 'Sample Resource Executable');
  assert.strictEqual(parsedStrings.ProductName, 'CodeSampleX Resource Demo');
  assert.strictEqual(parsedStrings.FileVersion, '1.2.3.4');
  assert.strictEqual(parsedStrings.ProductVersion, '2.0.0.1');

  // 3. Contract: Resource.StringTable adds and retrieves localized string entries by integer ID and replaces string entries for executable resources
  const st = new Resource.StringTable();
  st.lang = 1033;
  st.setById(101, 'Status OK');
  st.setById(102, 'Operation Complete');
  assert.strictEqual(st.getById(101), 'Status OK');
  assert.strictEqual(st.getById(102), 'Operation Complete');
  assert.strictEqual(st.getById(999), null, 'unassigned ID must return null');

  const allStrings = st.getAllStrings();
  assert.strictEqual(allStrings.length, 2);
  assert.deepStrictEqual(allStrings, [
    { id: 101, text: 'Status OK' },
    { id: 102, text: 'Operation Complete' }
  ]);

  // 4. Contract: Resource.IconGroupEntry.replaceIconsForResource populates icon group and icon resource entries queryable via fromEntries
  const iconItem = createMinimalIconItem();
  assert.ok(iconItem, 'createMinimalIconItem must return an IconItem');
  Resource.IconGroupEntry.replaceIconsForResource(initialEntries, 1, 1033, [iconItem]);

  const parsedIconGroups = Resource.IconGroupEntry.fromEntries(initialEntries);
  assert.strictEqual(parsedIconGroups.length, 1, 'Resource entries must contain one IconGroupEntry');
  assert.strictEqual(parsedIconGroups[0].id, 1);
  const extractedIcons = parsedIconGroups[0].getIconItemsFromEntries(initialEntries);
  assert.strictEqual(extractedIcons.length, 1, 'IconGroupEntry must extract associated icon items');

  // 5. Full round-trip integration test via buildExecutableWithResources & inspectExecutableResources
  const buildResult = buildExecutableWithResources({
    version: {
      lang: 1033,
      codepage: 1200,
      fileVersion: { major: 2, minor: 1, patch: 0, build: 0 },
      productVersion: { major: 2, minor: 0, patch: 0, build: 0 },
      flags: Resource.VersionFileFlags.Debug,
      fileOS: Resource.VersionFileOS.NT_Windows32,
      fileType: Resource.VersionFileType.App,
      stringValues: {
        FileDescription: 'Roundtrip Executable',
        ProductName: 'ResEdit Demo'
      }
    },
    strings: {
      lang: 1033,
      items: {
        201: 'Roundtrip String 201',
        202: 'Roundtrip String 202'
      }
    },
    icons: [
      {
        id: 10,
        lang: 1033,
        items: [iconItem]
      }
    ]
  });

  assert.ok(buildResult.binary instanceof ArrayBuffer, 'generate must produce an ArrayBuffer');
  assert.ok(buildResult.binary.byteLength > 0, 'generated binary must not be empty');

  const inspected = inspectExecutableResources(buildResult.binary, 1033, 1200);
  assert.ok(inspected.versionInfo, 'inspected binary must have VersionInfo');
  assert.strictEqual(inspected.versionInfo.fixedInfo.fileFlags, Resource.VersionFileFlags.Debug);
  assert.strictEqual(inspected.versionInfo.fixedInfo.fileOS, Resource.VersionFileOS.NT_Windows32);
  assert.strictEqual(inspected.versionInfo.fixedInfo.fileType, Resource.VersionFileType.App);

  const inspectedStrings = inspected.versionInfo.getStringValues({ lang: 1033, codepage: 1200 });
  assert.strictEqual(inspectedStrings.FileDescription, 'Roundtrip Executable');
  assert.strictEqual(inspectedStrings.ProductName, 'ResEdit Demo');

  assert.ok(inspected.stringTable, 'inspected binary must have StringTable');
  assert.strictEqual(inspected.stringTable.getById(201), 'Roundtrip String 201');
  assert.strictEqual(inspected.stringTable.getById(202), 'Roundtrip String 202');

  assert.strictEqual(inspected.iconGroups.length, 1, 'inspected binary must have one IconGroupEntry');
  assert.strictEqual(inspected.iconGroups[0].id, 10);

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

testContract().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

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

аноним