CodeSampleX

Пример

@xmldom/xmldom 0.9.10

Проверенный пример — npm @xmldom/xmldom 0.9.10. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: DOMParser parses XML string and builds…

sha256:718f19f5b2c5cef87ff69e23e4423daf794661fd8863f3783119c4a2443bdbff

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

Кейс

HOW
Цель
verify pkg:npm/%40xmldom/xmldom@0.9.10
Пакеты
Создан
2026-08-27T17:21:16Z

Контракт

  1. DOMParser parses XML string and builds DOM Document with element nodes, attributes, and text content
  2. DOMParser correctly parses XML namespaces and retrieves namespaced elements via getElementsByTagNameNS
  3. DOM Document supports creating Element, Text, CDATASection, and Comment nodes and appending them to the DOM tree
  4. XMLSerializer serializes DOM Document and nodes into well-formed XML strings with escaped characters and self-closing tags
  5. DOMParser onError callback captures parser warnings and errors, and onErrorStopParsing / onWarningStopParsing halt parsing on errors
  6. DOMImplementation creates XML documents with DocumentType declarations programmatically

Файлы

  • 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 pkg:npm/%40xmldom/xmldom@0.9.10
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40xmldom/xmldom@0.9.10

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:a18ce366e854291bd78faa19f3fd3b6d46607dc2b13421a869a3dfc1b65931d1","contract":["DOMParser parses XML string and builds DOM Document with element nodes, attributes, and text content","DOMParser correctly parses XML namespaces and retrieves namespaced elements via getElementsByTagNameNS","DOM Document supports creating Element, Text, CDATASection, and Comment nodes and appending them to the DOM tree","XMLSerializer serializes DOM Document and nodes into well-formed XML strings with escaped characters and self-closing tags","DOMParser onError callback captures parser warnings and errors, and onErrorStopParsing / onWarningStopParsing halt parsing on errors","DOMImplementation creates XML documents with DocumentType declarations programmatically"],"goal":"verify pkg:npm/%40xmldom/xmldom@0.9.10","kind":"HOW","packages":["pkg:npm/%40xmldom/xmldom@0.9.10"],"schemaVersion":1},"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/%40xmldom/xmldom@0.9.10"],"schemaVersion":1,"subject":"pkg:npm/%40xmldom/xmldom@0.9.10","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-xmldom",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-xmldom",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@xmldom/xmldom": "0.9.10"
      }
    },
    "node_modules/@xmldom/xmldom": {
      "version": "0.9.10",
      "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.10.tgz",
      "integrity": "sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==",
      "license": "MIT",
      "engines": {
        "node": ">=14.6"
      }
    }
  }
}
package.json
{
  "name": "sample-xmldom",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "@xmldom/xmldom": "0.9.10"
  },
  "scripts": {
    "test": "node test/contract.mjs"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40xmldom/xmldom@0.9.10",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40xmldom/xmldom@0.9.10"
  ]
}
src/index.mjs
import {
  DOMParser,
  XMLSerializer,
  DOMImplementation,
  MIME_TYPE,
  ParseError,
  onErrorStopParsing,
  onWarningStopParsing
} from '@xmldom/xmldom';

/**
 * Parses an XML string into a DOM Document.
 * @param {string} xml
 * @param {string} [mimeType=MIME_TYPE.XML_TEXT]
 * @param {object} [options]
 * @returns {Document}
 */
export function parseXml(xml, mimeType = MIME_TYPE.XML_TEXT, options = {}) {
  const parser = new DOMParser(options);
  return parser.parseFromString(xml, mimeType);
}

/**
 * Serializes a DOM Document or Node to an XML string.
 * @param {Node} node
 * @returns {string}
 */
export function serializeXml(node) {
  const serializer = new XMLSerializer();
  return serializer.serializeToString(node);
}

/**
 * Creates a new XML document programmatically with DOMImplementation.
 * @param {string} namespaceURI
 * @param {string} qualifiedName
 * @returns {Document}
 */
export function createXmlDocument(namespaceURI = null, qualifiedName = 'root') {
  const impl = new DOMImplementation();
  return impl.createDocument(namespaceURI, qualifiedName, null);
}

export {
  DOMParser,
  XMLSerializer,
  DOMImplementation,
  MIME_TYPE,
  ParseError,
  onErrorStopParsing,
  onWarningStopParsing
};
test/contract.mjs
import assert from 'node:assert/strict';
import {
  DOMParser,
  XMLSerializer,
  DOMImplementation,
  MIME_TYPE,
  ParseError,
  onErrorStopParsing,
  onWarningStopParsing
} from '@xmldom/xmldom';
import { parseXml, serializeXml, createXmlDocument } from '../src/index.mjs';

// Assertion 1: DOMParser parses XML string and builds DOM Document with element nodes, attributes, and text content
{
  const xml = '<bookstore><book id="1"><title lang="en">JavaScript Guide</title><price>29.99</price></book></bookstore>';
  const doc = parseXml(xml);

  assert.ok(doc, 'Parsed document should exist');
  assert.equal(doc.documentElement.nodeName, 'bookstore');

  const books = doc.getElementsByTagName('book');
  assert.equal(books.length, 1);
  assert.equal(books[0].getAttribute('id'), '1');

  const title = doc.getElementsByTagName('title')[0];
  assert.equal(title.textContent, 'JavaScript Guide');
  assert.equal(title.getAttribute('lang'), 'en');
}

// Assertion 2: DOMParser correctly parses XML namespaces and retrieves namespaced elements via getElementsByTagNameNS
{
  const xml = '<root xmlns:ns="https://example.com/schema"><ns:item id="i1">Content</ns:item></root>';
  const doc = parseXml(xml);

  const items = doc.getElementsByTagNameNS('https://example.com/schema', 'item');
  assert.equal(items.length, 1);
  assert.equal(items[0].getAttribute('id'), 'i1');
  assert.equal(items[0].textContent, 'Content');
}

// Assertion 3: DOM Document supports creating Element, Text, CDATASection, and Comment nodes and appending them to the DOM tree
{
  const parser = new DOMParser();
  const doc = parser.parseFromString('<root/>', MIME_TYPE.XML_TEXT);

  const element = doc.createElement('child');
  element.setAttribute('status', 'active');

  const textNode = doc.createTextNode('Hello World');
  element.appendChild(textNode);

  const cdata = doc.createCDATASection('<raw>&data</raw>');
  element.appendChild(cdata);

  const comment = doc.createComment('test comment');
  element.appendChild(comment);

  doc.documentElement.appendChild(element);

  const output = serializeXml(doc);

  assert.ok(output.includes('<child status="active">'));
  assert.ok(output.includes('Hello World'));
  assert.ok(output.includes('<![CDATA[<raw>&data</raw>]]>'));
  assert.ok(output.includes('<!--test comment-->'));
}

// Assertion 4: XMLSerializer serializes DOM Document and nodes into well-formed XML strings with escaped characters and self-closing tags
{
  const xml = '<data attr="val &amp; &quot;quote&quot;"><empty/><text>&lt;special&gt;</text></data>';
  const doc = parseXml(xml);
  const serialized = serializeXml(doc);

  assert.equal(serialized, xml);
}

// Assertion 5: DOMParser onError callback captures parser warnings and errors, and onErrorStopParsing / onWarningStopParsing halt parsing on errors
{
  const reported = [];
  const parser = new DOMParser({
    onError: (level, message) => {
      reported.push({ level, message });
    }
  });

  assert.throws(
    () => {
      parser.parseFromString('<invalid><unclosed></invalid>', MIME_TYPE.XML_TEXT);
    },
    (err) => err instanceof ParseError
  );
  assert.ok(reported.length > 0, 'onError callback should receive parse errors');
  assert.equal(reported[0].level, 'fatalError');

  // Test onErrorStopParsing helper
  const strictParser = new DOMParser({
    onError: onErrorStopParsing
  });

  assert.throws(() => {
    strictParser.parseFromString('<unclosed><tag>', MIME_TYPE.XML_TEXT);
  });

  // Test onWarningStopParsing helper
  const warningStrictParser = new DOMParser({
    onError: onWarningStopParsing
  });

  assert.throws(() => {
    warningStrictParser.parseFromString('<unclosed><tag>', MIME_TYPE.XML_TEXT);
  });
}

// Assertion 6: DOMImplementation creates XML documents with DocumentType declarations programmatically
{
  const doc = createXmlDocument('http://www.w3.org/1999/xhtml', 'html');

  assert.ok(doc);
  assert.equal(doc.documentElement.nodeName, 'html');

  const impl = new DOMImplementation();
  const docType = impl.createDocumentType('html', '', '');
  const docWithType = impl.createDocument('http://www.w3.org/1999/xhtml', 'html', docType);

  assert.ok(docWithType);
  assert.equal(docWithType.doctype.name, 'html');
}

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

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

аноним