Skip to content

Commit

Permalink
Only allow safe identifiers as object keys (Fixes babel#416)
Browse files Browse the repository at this point in the history
  • Loading branch information
patrick-steele-idem committed Feb 28, 2017
1 parent ca9c3fe commit 1dd1486
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion packages/babel-plugin-transform-property-literals/src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
"use strict";

const safeIdentifierRegExp = /[^a-z0-9$_]/i;

function isSafeKeyIdentifier(t, value) {
return !safeIdentifierRegExp.test(value) && t.isValidIdentifier(value);
}

module.exports = function({ types: t }) {
return {
name: "transform-property-literals",
Expand All @@ -8,14 +14,24 @@ module.exports = function({ types: t }) {
ObjectProperty: {
exit({ node }) {
const key = node.key;

// Handle the case where the incoming property key may not be a safe
// identifier that works in all browsers
if (t.isIdentifier(key)) {
if (!isSafeKeyIdentifier(t, key.name)) {
node.key = t.stringLiteral(key.name);
}
return;
}

if (!t.isStringLiteral(key)) {
return;
}

if (key.value.match(/^\d+$/)) {
node.key = t.numericLiteral(parseInt(node.key.value, 10));
node.computed = false;
} else if (t.isValidIdentifier(key.value)) {
} else if (isSafeKeyIdentifier(t, key.value)) {
node.key = t.identifier(key.value);
node.computed = false;
}
Expand Down

0 comments on commit 1dd1486

Please sign in to comment.