All files index.js

100% Statements 23/23
100% Branches 24/24
100% Functions 2/2
100% Lines 23/23
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42  1x     10x     1x   9x   1x   8x 1x   7x 7x 2x   5x 5x 1x   4x 4x 4x 1x   3x 3x 5x   3x 1x   2x          
export default function({types: t }) {
  return {
    visitor: {
      MemberExpression(path) {
        if (!t.isIdentifier(path.node.object) ||
            path.node.object.name !== "Variant" ||
            path.scope.hasBinding("Variant")) {
          return;
        }
        if (!t.isIdentifier(path.node.property) ||
            path.node.property.name !== "select") {
          throw path.buildCodeFrameError("Variant does not have this member, did you mean Variant.select?");
        }
        if (!t.isCallExpression(path.parent)) {
          throw path.buildCodeFrameError("Variant.select can only be called directly.");
        }
        const args = path.parent.arguments;
        if (args.length !== 2) {
          throw path.buildCodeFrameError("Variant.select must receive exactly 2 arguments.");
        }
        const variantNameNode = args[0];
        if (!t.isStringLiteral(variantNameNode)) {
          throw path.buildCodeFrameError("The first argument of Variant.select must be a string literal.");
        }
        const variantName = variantNameNode.value;
        const variants = args[1];
        if (!t.isObjectExpression(variants)) {
          throw path.buildCodeFrameError("The second argument of Variant.select must be an object literal.");
        }
        const variantValue = process.env[`VARIANT_${variantName}`] || "default";
        const properties = variants.properties.filter((property) =>
          t.isProperty(property) && t.isIdentifier(property.key) && property.key.name === variantValue
        );
        if (properties.length !== 1) {
          throw path.buildCodeFrameError(`Argument of Variant.select does not contain key for ${variantName} value of ${variantValue}.`);
        }
        path.parentPath.replaceWith(properties[0].value);
      }
    }
  };
}