Skip to content

Commit

Permalink
fix(smart-rename): handle invalid/reserved identifier
Browse files Browse the repository at this point in the history
  • Loading branch information
pionxzh committed Dec 14, 2023
1 parent 8182f99 commit 2821b6d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
15 changes: 11 additions & 4 deletions packages/unminify/src/transformations/smart-rename.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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
}
})
}
Expand Down

0 comments on commit 2821b6d

Please sign in to comment.