CodeSampleX

샘플

sax 1.6.1: parser, createStream

검증된 샘플 — npm sax 1.6.1: parser, createStream. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: sax.parser in strict mode parses elements…

sha256:21e47602ad26d958b1b2951ccc46d8466b71bed3f44e5ef485d49fdf6b3c9244

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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-28

케이스

HOW
목표
verify pkg:npm/sax@1.6.1
패키지
심벌
  • sax.parser
  • sax.createStream
환경
node 22.23.2
생성일
2026-08-28T05:22:28Z

컨트랙트

  1. sax.parser in strict mode parses elements, attributes, text, and self-closing tags
  2. sax.parser parses CDATA sections and comments
  3. sax.parser handles processing instructions and doctype declarations
  4. sax.parser in non-strict mode with lowercase and trim options normalizes tag names and whitespace
  5. sax.parser decodes standard XML and numeric character entity references
  6. sax.createStream provides a writable stream interface for evented XML parsing
  7. sax.parser reports error events on malformed XML and supports parser resume

파일

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • 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/sax@1.6.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/sax@1.6.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:dd9cc5862df083ee6467e2d99985e6ba95d25c63ea3dbd975e4ef7a3807cb4ec","contract":["sax.parser in strict mode parses elements, attributes, text, and self-closing tags","sax.parser parses CDATA sections and comments","sax.parser handles processing instructions and doctype declarations","sax.parser in non-strict mode with lowercase and trim options normalizes tag names and whitespace","sax.parser decodes standard XML and numeric character entity references","sax.createStream provides a writable stream interface for evented XML parsing","sax.parser reports error events on malformed XML and supports parser resume"],"goal":"verify pkg:npm/sax@1.6.1","kind":"HOW","packages":["pkg:npm/sax@1.6.1"],"schemaVersion":1,"symbols":["sax.parser","sax.createStream"]},"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/sax@1.6.1"],"schemaVersion":1,"subject":"pkg:npm/sax@1.6.1","symbols":["sax.parser","sax.createStream"],"verifierAdapter":"node-typescript@1"}
index.js
const sax = require('sax');

/**
 * Creates a SAX parser instance.
 *
 * @param {boolean} strict - Whether to run parser in strict XML mode.
 * @param {object} [options] - Parser configuration options (e.g. { lowercase: true, trim: true }).
 * @returns {sax.SAXParser} SAX parser instance.
 */
function createParser(strict, options) {
  return sax.parser(strict, options);
}

/**
 * Creates a SAX stream for streaming XML parsing.
 *
 * @param {boolean} strict - Whether to run parser in strict XML mode.
 * @param {object} [options] - Stream parser options.
 * @returns {sax.SAXStream} SAX stream instance.
 */
function createStream(strict, options) {
  return sax.createStream(strict, options);
}

/**
 * Parses an XML string synchronously into an array of collected events.
 *
 * @param {string} xml - XML string to parse.
 * @param {boolean} [strict=true] - Strict mode flag.
 * @param {object} [options={}] - Parser options.
 * @returns {{ events: Array<object>, errors: Array<string> }} Collected parse events and error messages.
 */
function parseXml(xml, strict = true, options = {}) {
  const parser = sax.parser(strict, options);
  const events = [];
  const errors = [];

  parser.onopentag = (node) => {
    events.push({
      type: 'opentag',
      name: node.name,
      attributes: node.attributes,
      isSelfClosing: Boolean(node.isSelfClosing)
    });
  };

  parser.onclosetag = (tagName) => {
    events.push({
      type: 'closetag',
      name: tagName
    });
  };

  parser.ontext = (text) => {
    events.push({
      type: 'text',
      text
    });
  };

  parser.oncdata = (cdata) => {
    events.push({
      type: 'cdata',
      text: cdata
    });
  };

  parser.oncomment = (comment) => {
    events.push({
      type: 'comment',
      text: comment
    });
  };

  parser.ondoctype = (doctype) => {
    events.push({
      type: 'doctype',
      text: doctype
    });
  };

  parser.onprocessinginstruction = (pi) => {
    events.push({
      type: 'processinginstruction',
      name: pi.name,
      body: pi.body
    });
  };

  parser.onerror = (err) => {
    errors.push(err.message);
    parser.resume();
  };

  parser.write(xml).close();

  return { events, errors };
}

module.exports = {
  sax,
  createParser,
  createStream,
  parseXml
};
package-lock.json
{
  "name": "sample-sax",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-sax",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "sax": "1.6.1"
      }
    },
    "node_modules/sax": {
      "version": "1.6.1",
      "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
      "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
      "license": "BlueOak-1.0.0",
      "engines": {
        "node": ">=11.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-sax",
  "version": "1.0.0",
  "description": "Clean-room sample verifying sax functionality",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "sax": "1.6.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/sax@1.6.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/sax@1.6.1"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { Readable } from 'node:stream';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { sax, createParser, createStream, parseXml } = require('../index.js');

// 1. sax.parser in strict mode parses elements, attributes, text, and self-closing tags
{
  const parser = createParser(true);
  const events = [];

  parser.onopentag = (node) => {
    events.push({ type: 'open', name: node.name, attributes: node.attributes, isSelfClosing: node.isSelfClosing });
  };
  parser.ontext = (text) => {
    events.push({ type: 'text', text });
  };
  parser.onclosetag = (tagName) => {
    events.push({ type: 'close', name: tagName });
  };

  parser.write('<root id="1"><item name="alpha"/>Sample Text</root>');
  parser.close();

  assert.strictEqual(events.length, 5);
  assert.deepStrictEqual(events[0], { type: 'open', name: 'root', attributes: { id: '1' }, isSelfClosing: false });
  assert.deepStrictEqual(events[1], { type: 'open', name: 'item', attributes: { name: 'alpha' }, isSelfClosing: true });
  assert.deepStrictEqual(events[2], { type: 'close', name: 'item' });
  assert.deepStrictEqual(events[3], { type: 'text', text: 'Sample Text' });
  assert.deepStrictEqual(events[4], { type: 'close', name: 'root' });
}

// 2. sax.parser parses CDATA sections and comments
{
  const parser = createParser(true);
  const cdataList = [];
  const commentList = [];

  parser.oncdata = (cdata) => cdataList.push(cdata);
  parser.oncomment = (comment) => commentList.push(comment);

  parser.write('<root><!-- This is a comment --><![CDATA[raw & unescaped data <tag>]]></root>');
  parser.close();

  assert.deepStrictEqual(commentList, [' This is a comment ']);
  assert.deepStrictEqual(cdataList, ['raw & unescaped data <tag>']);
}

// 3. sax.parser handles processing instructions and doctype declarations
{
  const parser = createParser(true);
  const piList = [];
  let doctype = null;

  parser.onprocessinginstruction = (pi) => piList.push(pi);
  parser.ondoctype = (doc) => { doctype = doc; };

  parser.write('<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE root SYSTEM "root.dtd"><root/>');
  parser.close();

  assert.strictEqual(piList.length, 1);
  assert.strictEqual(piList[0].name, 'xml');
  assert.strictEqual(piList[0].body, 'version="1.0" encoding="UTF-8"');
  assert.strictEqual(doctype, ' root SYSTEM "root.dtd"');
}

// 4. sax.parser in non-strict mode with lowercase and trim options normalizes tag names and whitespace
{
  const parser = createParser(false, { lowercase: true, trim: true });
  const tags = [];
  const texts = [];

  parser.onopentag = (node) => tags.push(node.name);
  parser.ontext = (t) => texts.push(t);

  parser.write('<ROOT>   <CHILD ATTRIB="VAL">   text value   </CHILD> </ROOT>');
  parser.close();

  assert.deepStrictEqual(tags, ['root', 'child']);
  assert.deepStrictEqual(texts, ['text value']);
}

// 5. sax.parser decodes standard XML and numeric character entity references
{
  const parser = createParser(true);
  const texts = [];

  parser.ontext = (t) => texts.push(t);

  parser.write('<root>&amp; &lt; &gt; &quot; &apos; &#65; &#x42;</root>');
  parser.close();

  assert.strictEqual(texts.join(''), '& < > " \' A B');
}

// 6. sax.createStream provides a writable stream interface for evented XML parsing
{
  const stream = createStream(true);
  const tags = [];

  stream.on('opentag', (node) => tags.push(node.name));

  const readable = Readable.from(['<items><item id="1">', 'A</item><item id="2">B</item></items>']);
  await new Promise((resolve, reject) => {
    stream.on('end', resolve);
    stream.on('error', reject);
    readable.pipe(stream);
  });

  assert.deepStrictEqual(tags, ['items', 'item', 'item']);
}

// 7. sax.parser reports error events on malformed XML and supports parser resume
{
  const { events, errors } = parseXml('<root><unclosed></root>', true);

  assert.strictEqual(errors.length > 0, true);
  assert.strictEqual(errors[0].includes('Unexpected close tag'), true);
  assert.strictEqual(events.some((e) => e.type === 'opentag' && e.name === 'root'), true);
}

console.log('Contract assertions passed.');

오리진 시더

익명