Code coverage report for 6to5/util.js

Statements: 94.62% (176 / 186)      Branches: 86.73% (85 / 98)      Functions: 100% (24 / 24)      Lines: 94.64% (159 / 168)      Ignored: none     

All files » 6to5/ » util.js
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 2981   1 1 1 1 1 1 1 1   1   1 10 10 10     1 6     1 1 1   1       1 7085     1 8     1 8 4 4 2 1     1 722 718 716 1     1 15   15 1 14 11     15   15   15     1 6 4 3 2     1 1 1 1     1 18   18 18 18             18 18 5   13   18   18 18 1     18     1 12   12 13   13   13   13 45   31 31 31   31 31 31 31     13     12     1 324 324   323         323   323 237   3428 583           323   323 144     323     1 17   17   17 17 17   17         17 42   42   42 42   42   42 14 14 14     42       1 38310 38310     1 492 492           1 493 493 493   493                       492   492   492 354   138     18 18 18   18 18 17 17     18 18     18       1 39 39     1 1   1 1           1 40   39 39 39   39     1     1 1   1   1    
require("./patch");
 
var estraverse = require("estraverse");
var traverse   = require("./traverse");
var acorn      = require("acorn-6to5");
var path       = require("path");
var util       = require("util");
var fs         = require("fs");
var t          = require("./types");
var _          = require("lodash");
 
exports.inherits = util.inherits;
 
exports.canCompile = function (filename, altExts) {
  var exts = altExts || [".js", ".jsx", ".es6"];
  var ext = path.extname(filename);
  return _.contains(exts, ext);
};
 
exports.isInteger = function (i) {
  return _.isNumber(i) && i % 1 === 0;
};
 
exports.resolve = function (loc) {
  try {
    return require.resolve(loc);
  } catch (err) {
    return null;
  }
};
 
exports.trimRight = function (str) {
  return str.replace(/[\n\s]+$/g, "");
};
 
exports.list = function (val) {
  return val ? val.split(",") : [];
};
 
exports.regexify = function (val) {
  if (!val) return new RegExp(/.^/);
  if (_.isArray(val)) val = val.join("|");
  if (_.isString(val)) return new RegExp(val);
  if (_.isRegExp(val)) return val;
  throw new TypeError("illegal type for regexify");
};
 
exports.arrayify = function (val) {
  if (!val) return [];
  if (_.isString(val)) return exports.list(val);
  if (_.isArray(val)) return val;
  throw new TypeError("illegal type for arrayify");
};
 
exports.getUid = function (parent, file) {
  var node;
 
  if (t.isAssignmentExpression(parent)) {
    node = parent.left;
  } else if (t.isVariableDeclarator(parent)) {
    node = parent.id;
  }
 
  var id = "ref";
 
  if (t.isIdentifier(node)) id = node.name;
 
  return file.generateUidIdentifier(id);
};
 
exports.isAbsolute = function (loc) {
  if (!loc) return false;
  if (loc[0] === "/") return true; // unix
  if (loc[1] === ":" && loc[2] === "\\") return true; // windows
  return false;
};
 
exports.sourceMapToComment = function (map) {
  var json = JSON.stringify(map);
  var base64 = new Buffer(json).toString("base64");
  return "//# sourceMappingURL=data:application/json;base64," + base64;
};
 
exports.pushMutatorMap = function (mutatorMap, key, kind, method) {
  var alias;
 
  Eif (t.isIdentifier(key)) {
    alias = key.name;
    if (method.computed) alias = "computed:" + alias;
  } else if (t.isLiteral(key)) {
    alias = String(key.value);
  } else {
    alias = JSON.stringify(traverse.removeProperties(_.cloneDeep(key)));
  }
 
  var map;
  if (_.has(mutatorMap, alias)) {
    map = mutatorMap[alias];
  } else {
    map = {};
  }
  mutatorMap[alias] = map;
 
  map._key = key;
  if (method.computed) {
    map._computed = true;
  }
 
  map[kind] = method;
};
 
exports.buildDefineProperties = function (mutatorMap) {
  var objExpr = t.objectExpression([]);
 
  _.each(mutatorMap, function (map) {
    var mapNode = t.objectExpression([]);
 
    var propNode = t.property("init", map._key, mapNode, map._computed);
 
    map.enumerable = t.literal(true);
 
    _.each(map, function (node, key) {
      if (key[0] === "_") return;
 
      node = _.clone(node);
      var inheritNode = node;
      if (t.isMethodDefinition(node)) node = node.value;
 
      var prop = t.property("init", t.identifier(key), node);
      t.inheritsComments(prop, inheritNode);
      t.removeComments(inheritNode);
      mapNode.properties.push(prop);
    });
 
    objExpr.properties.push(propNode);
  });
 
  return objExpr;
};
 
exports.template = function (name, nodes, keepExpression) {
  var template = exports.templates[name];
  if (!template) throw new ReferenceError("unknown template " + name);
 
  Iif (nodes === true) {
    keepExpression = true;
    nodes = null;
  }
 
  template = _.cloneDeep(template);
 
  if (!_.isEmpty(nodes)) {
    traverse(template, {
      enter: function (node) {
        if (t.isIdentifier(node) && _.has(nodes, node.name)) {
          return nodes[node.name];
        }
      }
    });
  }
 
  var node = template.body[0];
 
  if (!keepExpression && t.isExpressionStatement(node)) {
    node = node.expression;
  }
 
  return node;
};
 
exports.codeFrame = function (lines, lineNumber, colNumber) {
  colNumber = Math.max(colNumber, 0);
 
  lines = lines.split("\n");
 
  var start = Math.max(lineNumber - 3, 0);
  var end   = Math.min(lines.length, lineNumber + 3);
  var width = (end + "").length;
 
  Iif (!lineNumber && !colNumber) {
    start = 0;
    end = lines.length;
  }
 
  return "\n" + lines.slice(start, end).map(function (line, i) {
    var curr = i + start + 1;
 
    var gutter = curr === lineNumber ? "> " : "  ";
 
    var sep = curr + exports.repeat(width + 1);
    gutter += sep + "| ";
 
    var str = gutter + line;
 
    if (colNumber && curr === lineNumber) {
      str += "\n";
      str += exports.repeat(gutter.length - 2);
      str += "|" + exports.repeat(colNumber) + "^";
    }
 
    return str;
  }).join("\n");
};
 
exports.repeat = function (width, cha) {
  cha = cha || " ";
  return new Array(width + 1).join(cha);
};
 
exports.normaliseAst = function (ast, comments, tokens) {
  Eif (ast && ast.type === "Program") {
    return t.file(ast, comments || [], tokens || []);
  } else {
    throw new Error("Not a valid ast?");
  }
};
 
exports.parse = function (opts, code, callback) {
  try {
    var comments = [];
    var tokens   = [];
 
    var ast = acorn.parse(code, {
      allowImportExportEverywhere: true,
      allowReturnOutsideFunction:  true,
      ecmaVersion:                 opts.experimental ? 7 : 6,
      playground:                  opts.playground,
      strictMode:                  true,
      onComment:                   comments,
      locations:                   true,
      onToken:                     tokens,
      ranges:                      true
    });
 
    estraverse.attachComments(ast, comments, tokens);
 
    ast = exports.normaliseAst(ast, comments, tokens);
 
    if (callback) {
      return callback(ast);
    } else {
      return ast;
    }
  } catch (err) {
    Eif (!err._6to5) {
      err._6to5 = true;
      var message = opts.filename + ": " + err.message;
 
      var loc = err.loc;
      if (loc) {
        var frame = exports.codeFrame(code, loc.line, loc.column);
        message += frame;
      }
 
      Eif (err.stack) err.stack = err.stack.replace(err.message, message);
      err.message = message;
    }
 
    throw err;
  }
};
 
exports.parseTemplate = function (loc, code) {
  var ast = exports.parse({ filename: loc }, code).program;
  return traverse.removeProperties(ast);
};
 
var loadTemplates = function () {
  var templates = {};
 
  var templatesLoc = __dirname + "/transformation/templates";
  Iif (!fs.existsSync(templatesLoc)) {
    throw new Error("no templates directory - this is most likely the " +
                    "result of a broken `npm publish`. Please report to " +
                    "https://githut.com/6to5/6to5/issues");
  }
 
  _.each(fs.readdirSync(templatesLoc), function (name) {
    if (name[0] === ".") return;
 
    var key  = path.basename(name, path.extname(name));
    var loc  = templatesLoc + "/" + name;
    var code = fs.readFileSync(loc, "utf8");
 
    templates[key] = exports.parseTemplate(loc, code);
  });
 
  return templates;
};
 
try {
  exports.templates = require("../../templates.json");
} catch (err) {
  Iif (err.code !== "MODULE_NOT_FOUND") throw err;
 
  exports.templates = loadTemplates();
}