fix: set start and end indices on the text inside CDATA nodes
BA
1d ago+68+68+01234567890123456789-0-0-0123456789
With withStartIndices, the text node inside a CDATA node always has startIndex: null.
import { parseDocument } from "htmlparser2";
const doc = parseDocument("<a><![CDATA[x]]></a>", {
xmlMode: true,
withStartIndices: true,
withEndIndices: true,
});
const cdata = doc.children[0].children[0];
console.log(cdata.startIndex, cdata.endIndex); // 3 15
const text = cdata.children[0];
console.log(text.startIndex, text.endIndex); // null 15 (expected 3 15)
oncdatastart creates the text child itself and never passes it through addNode, so the start index is never set. The end index only works because ontext updates endIndex on the last text node. Same with recognizeCDATA in HTML mode.
Fix: copy both indices from the CDATA node to its text child. That matches how a comment's text gets the comment's range.
Test: new fixture 28-cdata-indices.json (runs both char-by-char and in one go). It fails on main (expected null to be 3) and passes with the fix. npm test (vitest + lint) is green.
Found while fuzzing node indices from htmlparser2.
Summary by CodeRabbit
- Bug Fixes
- Text inside CDATA sections now reports the same start and end positions as its enclosing CDATA node when index tracking is enabled, in both XML and HTML parsing.
- Tests
- Added coverage for CDATA and text-node positions, along with the enclosing element’s positions, in XML and HTML modes.