From 2821b6d416b9393094554cae0f78eb155351c8b7 Mon Sep 17 00:00:00 2001 From: Pionxzh Date: Fri, 15 Dec 2023 03:20:58 +0800 Subject: [PATCH] fix(smart-rename): handle invalid/reserved identifier --- .../__tests__/smart-rename.spec.ts | 17 +++++++++++++++++ .../src/transformations/smart-rename.ts | 15 +++++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/packages/unminify/src/transformations/__tests__/smart-rename.spec.ts b/packages/unminify/src/transformations/__tests__/smart-rename.spec.ts index 0ebe2189..768bd56e 100644 --- a/packages/unminify/src/transformations/__tests__/smart-rename.spec.ts +++ b/packages/unminify/src/transformations/__tests__/smart-rename.spec.ts @@ -164,6 +164,23 @@ function foo({ `, ) +inlineTest('object destructuring with reserved identifier', + ` +const { + static: t, + default: o, +} = n; +o.delete(t); +`, + ` +const { + static: _static, + default: _default, +} = n; +_default.delete(_static); +`, +) + inlineTest('react rename - createContext', ` const d = createContext(null); diff --git a/packages/unminify/src/transformations/smart-rename.ts b/packages/unminify/src/transformations/smart-rename.ts index f2213ca9..13bc2ce5 100644 --- a/packages/unminify/src/transformations/smart-rename.ts +++ b/packages/unminify/src/transformations/smart-rename.ts @@ -1,6 +1,6 @@ import { assertScopeExists } from '@wakaru/ast-utils/assert' import { pascalCase } from '@wakaru/ast-utils/case' -import { generateName } from '@wakaru/ast-utils/identifier' +import { generateName, isValidIdentifier } from '@wakaru/ast-utils/identifier' import { renameIdentifier } from '@wakaru/ast-utils/reference' import { isDeclared } from '@wakaru/ast-utils/scope' import { wrapAstTransformation } from '@wakaru/ast-utils/wrapAstTransformation' @@ -119,10 +119,17 @@ function handlePropertyRename(j: JSCodeshift, objectPattern: ObjectPattern, scop // If the key is longer than the value, rename the value if (key.name.length > value.name.length) { - if (isDeclared(scope, key.name)) return + let newName = key.name - renameIdentifier(j, scope, value.name, key.name) - property.shorthand = key.name === value.name + // if the newName is not a valid identifier, _{newName} is used instead + if (!isValidIdentifier(newName)) { + newName = generateName(`_${newName}`) + } + + if (isDeclared(scope, newName)) return + + renameIdentifier(j, scope, value.name, newName) + property.shorthand = newName === value.name } }) }