fix(devtools): avoid mutating recorded frames when merging a frame range

When a later frame has a directive that the first selected frame doesn't,
`mergeFrames` added that frame's directive object to the merged result
by reference. Merging the next frame then added its timings into the
recorded frame, so selecting three or more frames inflated the stored
change detection and lifecycle times, and they grew each time the range
was selected again.

Copy the directive before adding it to the merged result.

Tested by adding a spec that merges three frames and checks that the
input frames are unchanged.
This commit is contained in:
Shuaib Hasan Akib
2026-10-28 11:41:50 -07:00
committed by Matthew Beck
parent cd9d0aea3f
commit 5f47c3c972
2 changed files with 38 additions and 1 deletions
@@ -183,4 +183,40 @@ describe('mergeFrames', () => {
source: '',
});
});
it('should not mutate the merged frames', () => {
const createElement = (name: string): ElementProfile => ({
children: [],
directives: [
{
isComponent: false,
isElement: false,
lifecycle: {},
outputs: {},
changeDetection: 10,
name,
},
],
type: 'element',
});
const createFrame = (directives: ElementProfile[]): ProfilerFrame => ({
directives,
duration: 5,
source: 'foo',
});
// Only the later frames have the `Bar` element, e.g. because it was created after the first one.
const frames = [
createFrame([createElement('Foo')]),
createFrame([createElement('Foo'), createElement('Bar')]),
createFrame([createElement('Foo'), createElement('Bar')]),
];
const framesBefore = structuredClone(frames);
const result = mergeFrames(frames);
expect(frames).toEqual(framesBefore);
expect(mergeFrames(frames)).toEqual(result);
expect(result!.directives[1].directives[0].changeDetection).toBe(20);
});
});
@@ -45,7 +45,8 @@ const mergeDirectives = (mergeIn: ElementProfile[], second: ElementProfile[]) =>
if (mergeInDirective && mergeInDirective.name === d.name) {
mergeDirective(mergeInDirective, d);
} else {
mergeIn[i].directives.push(d);
// Copy, so merging later frames into it doesn't change the recorded frame.
mergeIn[i].directives.push(structuredClone(d));
}
});
mergeDirectives(mergeIn[i].children, second[i].children);