From bd4590e546faab5238b95a41ffc8bef995e16352 Mon Sep 17 00:00:00 2001 From: Chris West Date: Wed, 13 Jan 2021 01:40:23 +0000 Subject: [PATCH] fix: cloneNode(deep, withoutLoc) handles absent comments (#12602) This fragment (maybe all fragments?) throw during cloning, as 'comments' is unset here. Handle it being unset, by returning undefined. --- packages/babel-types/src/clone/cloneNode.ts | 14 +++++++++++--- packages/babel-types/test/cloning.js | 8 ++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/packages/babel-types/src/clone/cloneNode.ts b/packages/babel-types/src/clone/cloneNode.ts index 1ef270afe2..826d54c53e 100644 --- a/packages/babel-types/src/clone/cloneNode.ts +++ b/packages/babel-types/src/clone/cloneNode.ts @@ -102,7 +102,9 @@ export default function cloneNode( return newNode; } -function cloneCommentsWithoutLoc(comments: T[]): T[] { +function cloneCommentsWithoutLoc( + comments: ReadonlyArray, +): T[] { return comments.map( ({ type, value }) => ({ @@ -113,6 +115,12 @@ function cloneCommentsWithoutLoc(comments: T[]): T[] { ); } -function maybeCloneComments(comments, deep, withoutLoc) { - return deep && withoutLoc ? cloneCommentsWithoutLoc(comments) : comments; +function maybeCloneComments( + comments: ReadonlyArray | null, + deep: boolean, + withoutLoc: boolean, +): ReadonlyArray | null { + return deep && withoutLoc && comments + ? cloneCommentsWithoutLoc(comments) + : comments; } diff --git a/packages/babel-types/test/cloning.js b/packages/babel-types/test/cloning.js index c8c3955157..6cbb1cfe05 100644 --- a/packages/babel-types/test/cloning.js +++ b/packages/babel-types/test/cloning.js @@ -42,6 +42,14 @@ describe("cloneNode", function () { expect(t.isNodesEquivalent(node, cloned)).toBe(true); }); + it("should handle deep cloning without loc of fragments", function () { + const program = "foo();"; + const node = parse(program); + const cloned = t.cloneNode(node, /* deep */ true, /* withoutLoc */ true); + expect(node).not.toBe(cloned); + expect(t.isNodesEquivalent(node, cloned)).toBe(true); + }); + it("should handle missing array element", function () { const node = parse("[,0]"); const cloned = t.cloneNode(node);