Exemple
w3c-xmlserializer 5.0.0: Serialize DOM node to XML string using w3c-xmlserializer
Échantillon vérifié pour npm w3c-xmlserializer 5.0.0: Serialize DOM node to XML string using w3c-xmlserializer. Le contrat s'est exécuté sur node 22 · linux…
sha256:ebeb0cf5b951948a8894fa3edea78b8f0a8e6e76f08a160b53f174ea252a7e55
Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré.
Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes.
MIT-0
Preuves d'exécution
L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.
- Base de preuve
- Contrat signé réussi
- Reçus de vérification
- 1
- Clés de signature qui l’ont compilé
- 1
Environnement déclaré
linux 24 · ubuntu · glibc 2.39 x64 npm
Environnements des exécutions de vérification
| Environnement | Contrat | Étapes | Exécution |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-20 |
Cas
HOW- Objectif
- Serialize DOM node to XML string using w3c-xmlserializer
- Paquets
- Créé
- 2026-08-20T22:44:53Z
Contrat
- serialize(root) converts DOM Element nodes with attributes, text, comments, processing instructions, and CDATA sections into well-formed XML strings
- serialize(root) handles XML namespaces and namespace prefixes on elements and attributes according to W3C specification
- serialize(root) serializes Document, DocumentType, and DocumentFragment nodes
- serialize(root, { requireWellFormed: true }) throws error when encountering non-well-formed XML constructs such as illegal hyphens in comments or invalid node types
Fichiers
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.js
- test/contract.mjs
Code source
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: Serialize DOM node to XML string using w3c-xmlserializer
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/w3c-xmlserializer@5.0.0
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.
{"case":{"caseId":"case:sha256:97576d15c724b60c947addf65b67c58a24ad7eaebcb3bbee683642685002af6a","contract":["serialize(root) converts DOM Element nodes with attributes, text, comments, processing instructions, and CDATA sections into well-formed XML strings","serialize(root) handles XML namespaces and namespace prefixes on elements and attributes according to W3C specification","serialize(root) serializes Document, DocumentType, and DocumentFragment nodes","serialize(root, { requireWellFormed: true }) throws error when encountering non-well-formed XML constructs such as illegal hyphens in comments or invalid node types"],"goal":"Serialize DOM node to XML string using w3c-xmlserializer","kind":"HOW","packages":["pkg:npm/w3c-xmlserializer@5.0.0"],"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/w3c-xmlserializer@5.0.0"],"schemaVersion":1,"subject":"pkg:npm/w3c-xmlserializer@5.0.0","verifierAdapter":"node-typescript@1"}
{
"name": "w3c-xmlserializer-sample",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "w3c-xmlserializer-sample",
"version": "1.0.0",
"dependencies": {
"w3c-xmlserializer": "5.0.0"
}
},
"node_modules/w3c-xmlserializer": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
"integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
"license": "MIT",
"dependencies": {
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
"integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
}
}
}
}
{
"name": "w3c-xmlserializer-sample",
"version": "1.0.0",
"type": "module",
"dependencies": {
"w3c-xmlserializer": "5.0.0"
}
}
{
"schemaVersion": 1,
"goal": "Serialize DOM node to XML string using w3c-xmlserializer",
"kind": "HOW",
"packages": [
"pkg:npm/w3c-xmlserializer@5.0.0"
]
}
import serialize from 'w3c-xmlserializer';
/**
* Serializes a DOM node tree to an XML string according to the W3C XMLSerializer specification.
*
* @param {object} root - The root DOM node to serialize (Element, Document, DocumentFragment, etc.).
* @param {object} [options] - Serialization options.
* @param {boolean} [options.requireWellFormed=false] - Whether to enforce well-formedness constraints.
* @returns {string} The serialized XML string.
*/
export function serializeToXml(root, options = {}) {
return serialize(root, options);
}
/**
* Creates a minimal DOM Element node representation compatible with W3C XMLSerializer.
*
* @param {string} localName - Element local name.
* @param {object} [options]
* @param {string|null} [options.prefix=null] - Namespace prefix.
* @param {string|null} [options.namespaceURI=null] - Namespace URI.
* @param {Array<{prefix?: string|null, localName: string, value: string, namespaceURI?: string|null}>} [options.attributes=[]] - Element attributes.
* @param {Array<object>} [options.childNodes=[]] - Child nodes.
* @returns {object} Mock DOM Element node.
*/
export function createElementNode(localName, { prefix = null, namespaceURI = null, attributes = [], childNodes = [] } = {}) {
return {
nodeType: 1,
prefix,
localName,
namespaceURI,
attributes: attributes.map(attr => ({
prefix: attr.prefix ?? null,
localName: attr.localName,
value: attr.value,
namespaceURI: attr.namespaceURI ?? null
})),
childNodes
};
}
/**
* Creates a minimal DOM Text node representation.
*
* @param {string} data - Text node character data.
* @returns {object} Mock DOM Text node.
*/
export function createTextNode(data) {
return {
nodeType: 3,
data
};
}
/**
* Creates a minimal DOM Comment node representation.
*
* @param {string} data - Comment node text.
* @returns {object} Mock DOM Comment node.
*/
export function createCommentNode(data) {
return {
nodeType: 8,
data
};
}
/**
* Creates a minimal DOM ProcessingInstruction node representation.
*
* @param {string} target - Processing instruction target name.
* @param {string} data - Processing instruction content.
* @returns {object} Mock DOM ProcessingInstruction node.
*/
export function createProcessingInstructionNode(target, data) {
return {
nodeType: 7,
target,
data
};
}
/**
* Creates a minimal DOM CDATASection node representation.
*
* @param {string} data - CDATA section data.
* @returns {object} Mock DOM CDATASection node.
*/
export function createCDataSectionNode(data) {
return {
nodeType: 4,
data
};
}
/**
* Creates a minimal DOM DocumentType node representation.
*
* @param {string} name - Document type name.
* @param {string} [publicId=''] - Public identifier.
* @param {string} [systemId=''] - System identifier.
* @returns {object} Mock DOM DocumentType node.
*/
export function createDocumentTypeNode(name, publicId = '', systemId = '') {
return {
nodeType: 10,
name,
publicId,
systemId
};
}
/**
* Creates a minimal DOM Document node representation.
*
* @param {Array<object>} childNodes - Document child nodes (e.g. DocumentType, root Element).
* @returns {object} Mock DOM Document node.
*/
export function createDocumentNode(childNodes = []) {
return {
nodeType: 9,
childNodes
};
}
/**
* Creates a minimal DOM DocumentFragment node representation.
*
* @param {Array<object>} childNodes - Fragment child nodes.
* @returns {object} Mock DOM DocumentFragment node.
*/
export function createDocumentFragmentNode(childNodes = []) {
return {
nodeType: 11,
childNodes
};
}
export default serializeToXml;
import assert from 'node:assert/strict';
import serialize, {
serializeToXml,
createElementNode,
createTextNode,
createCommentNode,
createProcessingInstructionNode,
createCDataSectionNode,
createDocumentTypeNode,
createDocumentNode,
createDocumentFragmentNode
} from '../src/index.js';
function testElementWithChildrenSerialization() {
// Test Element nodes with attributes, text, comment, PI, and CDATA
const root = createElementNode('catalog', {
attributes: [
{ localName: 'name', value: 'main' },
{ localName: 'escaped', value: 'a & b < c > "d"' }
],
childNodes: [
createCommentNode(' catalog entries '),
createProcessingInstructionNode('xml-stylesheet', 'type="text/xsl" href="style.xsl"'),
createElementNode('book', {
attributes: [{ localName: 'id', value: 'bk101' }],
childNodes: [
createElementNode('title', {
childNodes: [createTextNode('XML & DOM Essentials <v1>')]
}),
createCDataSectionNode('Code snippet: <tag attr="val"> & 100% valid')
]
})
]
});
const xml = serializeToXml(root);
assert.strictEqual(
xml,
'<catalog name="main" escaped="a & b < c > "d""><!-- catalog entries --><?xml-stylesheet type="text/xsl" href="style.xsl"?><book id="bk101"><title>XML & DOM Essentials <v1></title><![CDATA[Code snippet: <tag attr="val"> & 100% valid]]></book></catalog>'
);
}
function testNamespaceHandling() {
// Test XML namespace prefixes, default namespaces, and prefixed attributes
const svg = createElementNode('svg', {
prefix: 'svg',
namespaceURI: 'http://www.w3.org/2000/svg',
attributes: [
{ prefix: 'xmlns', localName: 'svg', value: 'http://www.w3.org/2000/svg', namespaceURI: 'http://www.w3.org/2000/xmlns/' },
{ prefix: null, localName: 'viewBox', value: '0 0 100 100', namespaceURI: null }
],
childNodes: [
createElementNode('circle', {
prefix: 'svg',
namespaceURI: 'http://www.w3.org/2000/svg',
attributes: [
{ prefix: null, localName: 'cx', value: '50', namespaceURI: null },
{ prefix: null, localName: 'cy', value: '50', namespaceURI: null },
{ prefix: null, localName: 'r', value: '40', namespaceURI: null }
]
})
]
});
const xml = serializeToXml(svg);
assert.strictEqual(
xml,
'<svg:svg xmlns:svg="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><svg:circle cx="50" cy="50" r="40"/></svg:svg>'
);
}
function testDocumentAndFragmentSerialization() {
// Test Document node with DocumentType and HTML root
const doc = createDocumentNode([
createDocumentTypeNode('html'),
createElementNode('html', {
namespaceURI: 'http://www.w3.org/1999/xhtml',
attributes: [
{ prefix: null, localName: 'xmlns', value: 'http://www.w3.org/1999/xhtml', namespaceURI: 'http://www.w3.org/2000/xmlns/' }
],
childNodes: [
createElementNode('body', {
namespaceURI: 'http://www.w3.org/1999/xhtml',
childNodes: [createTextNode('Clean-Room Verification')]
})
]
})
]);
const docXml = serializeToXml(doc);
assert.strictEqual(
docXml,
'<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><body>Clean-Room Verification</body></html>'
);
// Test DocumentFragment node
const fragment = createDocumentFragmentNode([
createElementNode('item', { attributes: [{ localName: 'n', value: '1' }] }),
createElementNode('item', { attributes: [{ localName: 'n', value: '2' }] })
]);
const fragmentXml = serializeToXml(fragment);
assert.strictEqual(fragmentXml, '<item n="1"/><item n="2"/>');
}
function testRequireWellFormedValidation() {
// Test requireWellFormed throwing error on invalid comment content (double hyphen)
const invalidComment = createCommentNode('invalid -- comment');
assert.throws(
() => serializeToXml(invalidComment, { requireWellFormed: true }),
{
name: 'Error',
message: /Failed to serialize XML: found hyphens in illegal places in comment node data\./
}
);
// Test invalid node type throws TypeError
assert.throws(
() => serializeToXml({ nodeType: 99 }),
{
name: 'TypeError',
message: /Failed to serialize XML: only Nodes can be serialized\./
}
);
}
function main() {
testElementWithChildrenSerialization();
testNamespaceHandling();
testDocumentAndFragmentSerialization();
testRequireWellFormedValidation();
console.log('All pkg:npm/w3c-xmlserializer@5.0.0 contracts passed successfully.');
}
main();
Seeder d'origine
anonyme