Skip to content

fix: keep CDATA markers inside SVG in HTML mode - #113

Open
voischev wants to merge 1 commit into
masterfrom
fix/cdata
Open

voischev wants to merge 1 commit into
masterfrom
fix/cdata

Conversation

@voischev

Copy link
Copy Markdown
Member

Regression in 0.13.0 (htmlparser2 12): CDATA sections inside SVG lose their markers in HTML mode.

input:  <svg><style><![CDATA[a{color:red}]]></style></svg>
0.12:   <svg><style><![CDATA[a{color:red}]]></style></svg>
0.13.0: <svg><style>a{color:red}</style></svg>

input:  <svg><script>/*<![CDATA[*/x="<>"/*]]>*/</script></svg>
0.13.0: <svg><script>/**/x="<>"/**/</script></svg>

Cause. htmlparser2 12 tracks foreign content and, in HTML mode, reports a CDATA section inside SVG via ontext(value) only. oncdatastart/oncdataend fire only in xmlMode or with recognizeCDATA (see Parser.oncdata). The adapter therefore received just the inner text.

Fix. In ontext, when not in xmlMode/recognizeCDATA, the source at parser.startIndex starts with <![CDATA[ and the text itself does not (raw-text elements like HTML <script> already contain the markers), wrap the text back in <![CDATA[ … ]]>. Same source-slice approach as oncomment uses for declarations.

Behavior by context (0.11 / 0.12 → this PR):

  • SVG <style>/<script>: markers kept in 0.11/0.12, dropped in 0.13.0, kept again.
  • SVG <text>: 0.11/0.12 turned CDATA into a comment (<!--[CDATA[a<b]]-->, hiding the text), 0.13.0 dropped the markers; now kept as written.
  • Outside foreign content and MathML text integration points (<mi>): comment, unchanged (spec behavior).
  • xmlMode / recognizeCDATA: plain text without markers, unchanged (existing test).

Tests: SVG style/script, SVG text with surrounding text, no duplicated markers in raw-text <script>, comment outside foreign content and in <mi>, recognizeCDATA. The three new SVG tests fail without the fix. npm run check passes, coverage of src/index.ts 100%.

Downstream: htmlnano master with this parser and posthtml master (incl. posthtml/posthtml#421): all 6 CDATA/SVG tests that failed with 0.13.0 pass. The remaining 15 failures are <plaintext> rendering (the renderer emits end tags that never existed in the source), to be handled in posthtml-render.

Proposed as 0.13.1.

🤖 Generated with Claude Code

htmlparser2 12 reports a CDATA section in foreign content (SVG) as plain
text without oncdatastart/oncdataend, so the adapter dropped the markers
and <svg><style><![CDATA[...]]></style></svg> lost its wrapper on round
trip. Restore the markers when the text token starts at a CDATA section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant