fix: clone deeply nested nodes without overflowing the stack
Merged
FB
7h ago+252+252+012345678901234567890123456789-25-25-01234567890123456789
Deeply nested DOM trees made cloneNode(node, true) overflow the call stack and throw RangeError (for example, around 2,000 nested elements through Cheerio's .clone()).
The cloned node and the 31 levels below it are cloned recursively, as before; parents below them are cloned with explicit frames on a stack. Output nodes, attributes, data, links and read order are preserved: each parent is cloned after its children, so descendants are read before the parent's attributes, which matters when attributes or text come from getters. Each child list is read once, and children appended to it during the clone are left out.
- Plain arrays: each cloned node's
childrenis a plainArray. When anArraysubclass was passed to a node's constructor, the recursive clone'sArray#mapreturned that subclass.cloneNode's comment states this. - Tests: a 100,000-level clone fails on master with
RangeError. The read-order and child-list tests run once through recursion and once 32 levels down, on the explicit stack; the stack fixture includes a document, a CDATA section and sibling links. - Cost: cloning a 100 KB page is 4.9% faster than on master, a small fragment takes the same time (ratio 0.999), and a single element is 3.5% faster (medians of twenty processes, ten in each load order; master against a copy of itself: 0.995, 0.996 and 1.008).
🤖 Generated with Claude Code, using Opus 5.5.
Summary by CodeRabbit
- Bug Fixes
- Deeply nested node trees can now be cloned without running into recursion limits.
- Cloned trees retain descendant values, child positions, and parent and sibling relationships, including when source attributes change during cloning.
- Cloning also handles customized child lists consistently and reads each child list only once.