Skip to content

Commit

Permalink
Only allow safe identifiers as object keys (Fixes #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 d38cdff
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 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,12 @@
"use strict";

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

function isSafeKeyIdentifier(value) {
return !safeIdentifierRegExp.test(value)
}


module.exports = function({ types: t }) {
return {
name: "transform-property-literals",
Expand All @@ -8,14 +15,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(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(key.value)) {
node.key = t.identifier(key.value);
node.computed = false;
}
Expand Down

0 comments on commit d38cdff

Please sign in to comment.