From bd75650bb6c4fb173321be3c55dc3500bba1831d Mon Sep 17 00:00:00 2001 From: Ivan Voischev Date: Thu, 26 Nov 2026 15:11:37 +0300 Subject: [PATCH] fix: keep CDATA markers inside SVG in HTML mode htmlparser2 12 reports a CDATA section in foreign content (SVG) as plain text without oncdatastart/oncdataend, so the adapter dropped the markers and 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 --- changelog.md | 4 ++++ src/index.ts | 13 ++++++++++++ test/core.test.cjs | 49 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+) diff --git a/changelog.md b/changelog.md index ec0998b..564e74c 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,9 @@ ## Unreleased +### Bug Fixes + +* Keep `` markers inside SVG in HTML mode. With htmlparser2 12 the markers were dropped, so `` rendered as `` and CDATA in SVG `` lost its wrapper. CDATA outside foreign content is still a comment, and `xmlMode`/`recognizeCDATA` still expose plain text. + ## 0.13.0 (2026-10-28) ### Breaking Changes diff --git a/src/index.ts b/src/index.ts index e26b2ee..f96f118 100644 --- a/src/index.ts +++ b/src/index.ts @@ -226,6 +226,19 @@ export const parser = (html: string, options: Options = {}): Node[] => { } function ontext(text: string) { + // In HTML mode htmlparser2 reports a CDATA section inside foreign content + // (SVG) as plain text without its markers. Restore them so the section + // renders back as written. Raw text such as ", + ); + const expected = [ + { + tag: "svg", + content: [ + { tag: "style", content: [""] }, + { tag: "script", content: ['/*"/*]]>*/'] }, + ], + }, + ]; + assert.deepEqual(tree, expected); +}); + +test("should keep CDATA markers inside SVG text content", () => { + const tree = parser("a b<c d"); + const expected = [{ tag: "svg", content: [{ tag: "text", content: ["a d"] }] }]; + assert.deepEqual(tree, expected); +}); + +test("should not duplicate CDATA markers in raw text elements", () => { + const tree = parser(""); + const expected = [ + { tag: "script", content: [""] }, + { tag: "svg", content: [{ tag: "style", content: [""] }] }, + ]; + assert.deepEqual(tree, expected); +}); + +test("should parse CDATA outside foreign content as a comment", () => { + assert.deepEqual(parser("
"), [{ tag: "div", content: [""] }]); + assert.deepEqual(parser("x<y"), [ + { tag: "math", content: [{ tag: "mi", content: [""] }] }, + ]); +}); + +test("should expose CDATA text without markers with recognizeCDATA", () => { + const tree = parser("
", { + recognizeCDATA: true, + }); + const expected = [ + { tag: "div", content: ["a { const html = '';