Socket
Socket
Sign inDemoInstall

istanbul-lib-instrument

Package Overview
Dependencies
31
Maintainers
3
Versions
74
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 2.3.1 to 2.3.2

8

CHANGELOG.md

@@ -6,2 +6,10 @@ # Change Log

<a name="2.3.2"></a>
## [2.3.2](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@2.3.1...istanbul-lib-instrument@2.3.2) (2018-07-24)
**Note:** Version bump only for package istanbul-lib-instrument
<a name="2.3.1"></a>

@@ -8,0 +16,0 @@ ## [2.3.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-lib-instrument@2.3.0...istanbul-lib-instrument@2.3.1) (2018-07-07)

6

dist/constants.js

@@ -15,9 +15,9 @@ "use strict";

// function to use for creating hashes
var SHA = 'sha1'; // name of coverage data magic key
const SHA = 'sha1'; // name of coverage data magic key
exports.SHA = SHA;
var MAGIC_KEY = '_coverageSchema'; // name of coverage data magic value
const MAGIC_KEY = '_coverageSchema'; // name of coverage data magic value
exports.MAGIC_KEY = MAGIC_KEY;
var MAGIC_VALUE = (0, _crypto.createHash)(SHA).update(_package.name + '@' + (0, _semver.major)(_package.version)).digest('hex');
const MAGIC_VALUE = (0, _crypto.createHash)(SHA).update(_package.name + '@' + (0, _semver.major)(_package.version)).digest('hex');
exports.MAGIC_VALUE = MAGIC_VALUE;

@@ -22,8 +22,6 @@ "use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
function defaultOpts() {

@@ -61,10 +59,4 @@ return {

var Instrumenter =
/*#__PURE__*/
function () {
function Instrumenter() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultOpts();
_classCallCheck(this, Instrumenter);
class Instrumenter {
constructor(opts = defaultOpts()) {
this.opts = this.normalizeOpts(opts);

@@ -81,131 +73,123 @@ this.fileCoverage = null;

_createClass(Instrumenter, [{
key: "normalizeOpts",
value: function normalizeOpts(opts) {
var normalize = function normalize(name, defaultValue) {
if (!opts.hasOwnProperty(name)) {
opts[name] = defaultValue;
}
};
var defOpts = defaultOpts();
Object.keys(defOpts).forEach(function (k) {
normalize(k, defOpts[k]);
});
return opts;
}
/**
* instrument the supplied code and track coverage against the supplied
* filename. It throws if invalid code is passed to it. ES5 and ES6 syntax
* is supported. To instrument ES6 modules, make sure that you set the
* `esModules` property to `true` when creating the instrumenter.
*
* @param {string} code - the code to instrument
* @param {string} filename - the filename against which to track coverage.
* @param {object} [inputSourceMap] - the source map that maps the not instrumented code back to it's original form.
* Is assigned to the coverage object and therefore, is available in the json output and can be used to remap the
* coverage to the untranspiled source.
* @returns {string} the instrumented code.
*/
}, {
key: "instrumentSync",
value: function instrumentSync(code, filename, inputSourceMap) {
if (typeof code !== 'string') {
throw new Error('Code must be a string');
normalizeOpts(opts) {
const normalize = (name, defaultValue) => {
if (!opts.hasOwnProperty(name)) {
opts[name] = defaultValue;
}
};
filename = filename || String(new Date().getTime()) + '.js';
var opts = this.opts;
var ast = parser.parse(code, {
allowReturnOutsideFunction: opts.autoWrap,
sourceType: opts.esModules ? "module" : "script",
plugins: ['asyncGenerators', 'dynamicImport', 'objectRestSpread', 'optionalCatchBinding', 'flow', 'jsx']
});
var ee = (0, _visitor.default)(t, filename, {
coverageVariable: opts.coverageVariable,
ignoreClassMethods: opts.ignoreClassMethods,
inputSourceMap: inputSourceMap
});
var output = {};
var visitor = {
Program: {
enter: ee.enter,
exit: function exit(path) {
output = ee.exit(path);
}
}
};
(0, _traverse.default)(ast, visitor);
var generateOptions = {
compact: opts.compact,
comments: opts.preserveComments,
sourceMaps: opts.produceSourceMap,
sourceFileName: filename
};
var codeMap = (0, _generator.default)(ast, generateOptions, code);
this.fileCoverage = output.fileCoverage;
this.sourceMap = codeMap.map;
var cb = this.opts.sourceMapUrlCallback;
const defOpts = defaultOpts();
Object.keys(defOpts).forEach(function (k) {
normalize(k, defOpts[k]);
});
return opts;
}
/**
* instrument the supplied code and track coverage against the supplied
* filename. It throws if invalid code is passed to it. ES5 and ES6 syntax
* is supported. To instrument ES6 modules, make sure that you set the
* `esModules` property to `true` when creating the instrumenter.
*
* @param {string} code - the code to instrument
* @param {string} filename - the filename against which to track coverage.
* @param {object} [inputSourceMap] - the source map that maps the not instrumented code back to it's original form.
* Is assigned to the coverage object and therefore, is available in the json output and can be used to remap the
* coverage to the untranspiled source.
* @returns {string} the instrumented code.
*/
if (cb && output.sourceMappingURL) {
cb(filename, output.sourceMappingURL);
}
return codeMap.code;
instrumentSync(code, filename, inputSourceMap) {
if (typeof code !== 'string') {
throw new Error('Code must be a string');
}
/**
* callback-style instrument method that calls back with an error
* as opposed to throwing one. Note that in the current implementation,
* the callback will be called in the same process tick and is not asynchronous.
*
* @param {string} code - the code to instrument
* @param {string} filename - the filename against which to track coverage.
* @param {Function} callback - the callback
* @param {Object} inputSourceMap - the source map that maps the not instrumented code back to it's original form.
* Is assigned to the coverage object and therefore, is available in the json output and can be used to remap the
* coverage to the untranspiled source.
*/
}, {
key: "instrument",
value: function instrument(code, filename, callback, inputSourceMap) {
if (!callback && typeof filename === 'function') {
callback = filename;
filename = null;
filename = filename || String(new Date().getTime()) + '.js';
const opts = this.opts;
const ast = parser.parse(code, {
allowReturnOutsideFunction: opts.autoWrap,
sourceType: opts.esModules ? "module" : "script",
plugins: ['asyncGenerators', 'dynamicImport', 'objectRestSpread', 'optionalCatchBinding', 'flow', 'jsx']
});
const ee = (0, _visitor.default)(t, filename, {
coverageVariable: opts.coverageVariable,
ignoreClassMethods: opts.ignoreClassMethods,
inputSourceMap: inputSourceMap
});
let output = {};
const visitor = {
Program: {
enter: ee.enter,
exit: function exit(path) {
output = ee.exit(path);
}
}
};
(0, _traverse.default)(ast, visitor);
const generateOptions = {
compact: opts.compact,
comments: opts.preserveComments,
sourceMaps: opts.produceSourceMap,
sourceFileName: filename
};
const codeMap = (0, _generator.default)(ast, generateOptions, code);
this.fileCoverage = output.fileCoverage;
this.sourceMap = codeMap.map;
const cb = this.opts.sourceMapUrlCallback;
try {
var out = this.instrumentSync(code, filename, inputSourceMap);
callback(null, out);
} catch (ex) {
callback(ex);
}
if (cb && output.sourceMappingURL) {
cb(filename, output.sourceMappingURL);
}
/**
* returns the file coverage object for the last file instrumented.
* @returns {Object} the file coverage object.
*/
}, {
key: "lastFileCoverage",
value: function lastFileCoverage() {
return this.fileCoverage;
return codeMap.code;
}
/**
* callback-style instrument method that calls back with an error
* as opposed to throwing one. Note that in the current implementation,
* the callback will be called in the same process tick and is not asynchronous.
*
* @param {string} code - the code to instrument
* @param {string} filename - the filename against which to track coverage.
* @param {Function} callback - the callback
* @param {Object} inputSourceMap - the source map that maps the not instrumented code back to it's original form.
* Is assigned to the coverage object and therefore, is available in the json output and can be used to remap the
* coverage to the untranspiled source.
*/
instrument(code, filename, callback, inputSourceMap) {
if (!callback && typeof filename === 'function') {
callback = filename;
filename = null;
}
/**
* returns the source map produced for the last file instrumented.
* @returns {null|Object} the source map object.
*/
}, {
key: "lastSourceMap",
value: function lastSourceMap() {
return this.sourceMap;
try {
var out = this.instrumentSync(code, filename, inputSourceMap);
callback(null, out);
} catch (ex) {
callback(ex);
}
}]);
}
/**
* returns the file coverage object for the last file instrumented.
* @returns {Object} the file coverage object.
*/
return Instrumenter;
}();
lastFileCoverage() {
return this.fileCoverage;
}
/**
* returns the source map produced for the last file instrumented.
* @returns {null|Object} the source map object.
*/
lastSourceMap() {
return this.sourceMap;
}
}
var _default = Instrumenter;
exports.default = _default;

@@ -26,3 +26,3 @@ "use strict";

var ast = (0, _parser.parse)(code, {
const ast = (0, _parser.parse)(code, {
allowImportExportEverywhere: true,

@@ -35,9 +35,9 @@ allowReturnOutsideFunction: true,

});
var covScope;
let covScope;
(0, _traverse.default)(ast, {
ObjectProperty: function ObjectProperty(path) {
var node = path.node;
const node = path.node;
if (!node.computed && t.isIdentifier(node.key) && node.key.name === _constants.MAGIC_KEY) {
var magicValue = path.get('value').evaluate();
const magicValue = path.get('value').evaluate();

@@ -58,8 +58,8 @@ if (!magicValue.confident || magicValue.value !== _constants.MAGIC_VALUE) {

var result = {};
const result = {};
var _arr = ['path', 'hash', 'gcv', 'coverageData'];
for (var _i = 0; _i < _arr.length; _i++) {
var key = _arr[_i];
var binding = covScope.getOwnBinding(key);
const key = _arr[_i];
const binding = covScope.getOwnBinding(key);

@@ -70,4 +70,4 @@ if (!binding) {

var valuePath = binding.path.get('init');
var value = valuePath.evaluate();
const valuePath = binding.path.get('init');
const value = valuePath.evaluate();

@@ -74,0 +74,0 @@ if (!value.confident) {

@@ -10,20 +10,2 @@ "use strict";

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function cloneLocation(loc) {

@@ -53,14 +35,6 @@ return {

var SourceCoverage =
/*#__PURE__*/
function (_classes$FileCoverage) {
_inherits(SourceCoverage, _classes$FileCoverage);
function SourceCoverage(pathOrObj) {
var _this;
_classCallCheck(this, SourceCoverage);
_this = _possibleConstructorReturn(this, _getPrototypeOf(SourceCoverage).call(this, pathOrObj));
_this.meta = {
class SourceCoverage extends _istanbulLibCoverage.classes.FileCoverage {
constructor(pathOrObj) {
super(pathOrObj);
this.meta = {
last: {

@@ -72,89 +46,79 @@ s: 0,

};
return _this;
}
_createClass(SourceCoverage, [{
key: "newStatement",
value: function newStatement(loc) {
var s = this.meta.last.s;
this.data.statementMap[s] = cloneLocation(loc);
this.data.s[s] = 0;
this.meta.last.s += 1;
return s;
}
}, {
key: "newFunction",
value: function newFunction(name, decl, loc) {
var f = this.meta.last.f;
name = name || '(anonymous_' + f + ')';
this.data.fnMap[f] = {
name: name,
decl: cloneLocation(decl),
loc: cloneLocation(loc),
// DEPRECATED: some legacy reports require this info.
line: loc && loc.start.line
};
this.data.f[f] = 0;
this.meta.last.f += 1;
return f;
}
}, {
key: "newBranch",
value: function newBranch(type, loc) {
var b = this.meta.last.b;
this.data.b[b] = [];
this.data.branchMap[b] = {
loc: cloneLocation(loc),
type: type,
locations: [],
// DEPRECATED: some legacy reports require this info.
line: loc && loc.start.line
};
this.meta.last.b += 1;
return b;
}
}, {
key: "addBranchPath",
value: function addBranchPath(name, location) {
var bMeta = this.data.branchMap[name],
counts = this.data.b[name];
/* istanbul ignore if: paranoid check */
newStatement(loc) {
var s = this.meta.last.s;
this.data.statementMap[s] = cloneLocation(loc);
this.data.s[s] = 0;
this.meta.last.s += 1;
return s;
}
if (!bMeta) {
throw new Error("Invalid branch " + name);
}
newFunction(name, decl, loc) {
var f = this.meta.last.f;
name = name || '(anonymous_' + f + ')';
this.data.fnMap[f] = {
name: name,
decl: cloneLocation(decl),
loc: cloneLocation(loc),
// DEPRECATED: some legacy reports require this info.
line: loc && loc.start.line
};
this.data.f[f] = 0;
this.meta.last.f += 1;
return f;
}
bMeta.locations.push(cloneLocation(location));
counts.push(0);
return counts.length - 1;
}
/**
* Assigns an input source map to the coverage that can be used
* to remap the coverage output to the original source
* @param sourceMap {object} the source map
*/
newBranch(type, loc) {
var b = this.meta.last.b;
this.data.b[b] = [];
this.data.branchMap[b] = {
loc: cloneLocation(loc),
type: type,
locations: [],
// DEPRECATED: some legacy reports require this info.
line: loc && loc.start.line
};
this.meta.last.b += 1;
return b;
}
}, {
key: "inputSourceMap",
value: function inputSourceMap(sourceMap) {
this.data.inputSourceMap = sourceMap;
addBranchPath(name, location) {
var bMeta = this.data.branchMap[name],
counts = this.data.b[name];
/* istanbul ignore if: paranoid check */
if (!bMeta) {
throw new Error("Invalid branch " + name);
}
}, {
key: "freeze",
value: function freeze() {
// prune empty branches
var map = this.data.branchMap,
branches = this.data.b;
Object.keys(map).forEach(function (b) {
if (map[b].locations.length === 0) {
delete map[b];
delete branches[b];
}
});
}
}]);
return SourceCoverage;
}(_istanbulLibCoverage.classes.FileCoverage);
bMeta.locations.push(cloneLocation(location));
counts.push(0);
return counts.length - 1;
}
/**
* Assigns an input source map to the coverage that can be used
* to remap the coverage output to the original source
* @param sourceMap {object} the source map
*/
inputSourceMap(sourceMap) {
this.data.inputSourceMap = sourceMap;
}
freeze() {
// prune empty branches
var map = this.data.branchMap,
branches = this.data.b;
Object.keys(map).forEach(function (b) {
if (map[b].locations.length === 0) {
delete map[b];
delete branches[b];
}
});
}
}
exports.SourceCoverage = SourceCoverage;

@@ -18,14 +18,8 @@ "use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
// pattern for istanbul to ignore a section
var COMMENT_RE = /^\s*istanbul\s+ignore\s+(if|else|next)(?=\W|$)/; // pattern for istanbul to ignore the whole file
const COMMENT_RE = /^\s*istanbul\s+ignore\s+(if|else|next)(?=\W|$)/; // pattern for istanbul to ignore the whole file
var COMMENT_FILE_RE = /^\s*istanbul\s+ignore\s+(file)(?=\W|$)/; // source map URL pattern
const COMMENT_FILE_RE = /^\s*istanbul\s+ignore\s+(file)(?=\W|$)/; // source map URL pattern
var SOURCE_MAP_RE = /[#@]\s*sourceMappingURL=(.*)\s*$/m; // generate a variable name from hashing the supplied file path
const SOURCE_MAP_RE = /[#@]\s*sourceMappingURL=(.*)\s*$/m; // generate a variable name from hashing the supplied file path

@@ -40,10 +34,4 @@ function genVar(filename) {

var VisitState =
/*#__PURE__*/
function () {
function VisitState(types, sourceFilePath, inputSourceMap) {
var ignoreClassMethods = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
_classCallCheck(this, VisitState);
class VisitState {
constructor(types, sourceFilePath, inputSourceMap, ignoreClassMethods = []) {
this.varName = genVar(sourceFilePath);

@@ -65,276 +53,250 @@ this.attrs = {};

_createClass(VisitState, [{
key: "shouldIgnore",
value: function shouldIgnore(path) {
return this.nextIgnore || !path.node.loc;
} // extract the ignore comment hint (next|if|else) or null
shouldIgnore(path) {
return this.nextIgnore || !path.node.loc;
} // extract the ignore comment hint (next|if|else) or null
}, {
key: "hintFor",
value: function hintFor(node) {
var hint = null;
if (node.leadingComments) {
node.leadingComments.forEach(function (c) {
var v = (c.value ||
/* istanbul ignore next: paranoid check */
"").trim();
var groups = v.match(COMMENT_RE);
hintFor(node) {
let hint = null;
if (groups) {
hint = groups[1];
}
});
if (node.leadingComments) {
node.leadingComments.forEach(function (c) {
const v = (c.value ||
/* istanbul ignore next: paranoid check */
"").trim();
const groups = v.match(COMMENT_RE);
if (groups) {
hint = groups[1];
}
});
}
return hint;
} // extract a source map URL from comments and keep track of it
maybeAssignSourceMapURL(node) {
const that = this;
const extractURL = comments => {
if (!comments) {
return;
}
return hint;
} // extract a source map URL from comments and keep track of it
comments.forEach(function (c) {
const v = (c.value ||
/* istanbul ignore next: paranoid check */
"").trim();
const groups = v.match(SOURCE_MAP_RE);
}, {
key: "maybeAssignSourceMapURL",
value: function maybeAssignSourceMapURL(node) {
var that = this;
var extractURL = function extractURL(comments) {
if (!comments) {
return;
if (groups) {
that.sourceMappingURL = groups[1];
}
});
};
comments.forEach(function (c) {
var v = (c.value ||
/* istanbul ignore next: paranoid check */
"").trim();
var groups = v.match(SOURCE_MAP_RE);
extractURL(node.leadingComments);
extractURL(node.trailingComments);
} // for these expressions the statement counter needs to be hoisted, so
// function name inference can be preserved
if (groups) {
that.sourceMappingURL = groups[1];
}
});
};
extractURL(node.leadingComments);
extractURL(node.trailingComments);
} // for these expressions the statement counter needs to be hoisted, so
// function name inference can be preserved
counterNeedsHoisting(path) {
return path.isFunctionExpression() || path.isArrowFunctionExpression() || path.isClassExpression();
} // all the generic stuff that needs to be done on enter for every node
}, {
key: "counterNeedsHoisting",
value: function counterNeedsHoisting(path) {
return path.isFunctionExpression() || path.isArrowFunctionExpression() || path.isClassExpression();
} // all the generic stuff that needs to be done on enter for every node
}, {
key: "onEnter",
value: function onEnter(path) {
var n = path.node;
this.maybeAssignSourceMapURL(n); // if already ignoring, nothing more to do
onEnter(path) {
const n = path.node;
this.maybeAssignSourceMapURL(n); // if already ignoring, nothing more to do
if (this.nextIgnore !== null) {
return;
} // check hint to see if ignore should be turned on
if (this.nextIgnore !== null) {
return;
} // check hint to see if ignore should be turned on
var hint = this.hintFor(n);
const hint = this.hintFor(n);
if (hint === 'next') {
this.nextIgnore = n;
return;
} // else check custom node attribute set by a prior visitor
if (hint === 'next') {
this.nextIgnore = n;
return;
} // else check custom node attribute set by a prior visitor
if (this.getAttr(path.node, 'skip-all') !== null) {
this.nextIgnore = n;
} // else check for ignored class methods
if (this.getAttr(path.node, 'skip-all') !== null) {
this.nextIgnore = n;
} // else check for ignored class methods
if (path.isFunctionExpression() && this.ignoreClassMethods.some(function (name) {
return path.node.id && name === path.node.id.name;
})) {
this.nextIgnore = n;
return;
}
if (path.isFunctionExpression() && this.ignoreClassMethods.some(name => path.node.id && name === path.node.id.name)) {
this.nextIgnore = n;
return;
}
if (path.isClassMethod() && this.ignoreClassMethods.some(function (name) {
return name === path.node.key.name;
})) {
this.nextIgnore = n;
return;
}
} // all the generic stuff on exit of a node,
// including reseting ignores and custom node attrs
if (path.isClassMethod() && this.ignoreClassMethods.some(name => name === path.node.key.name)) {
this.nextIgnore = n;
return;
}
} // all the generic stuff on exit of a node,
// including reseting ignores and custom node attrs
}, {
key: "onExit",
value: function onExit(path) {
// restore ignore status, if needed
if (path.node === this.nextIgnore) {
this.nextIgnore = null;
} // nuke all attributes for the node
onExit(path) {
// restore ignore status, if needed
if (path.node === this.nextIgnore) {
this.nextIgnore = null;
} // nuke all attributes for the node
delete path.node.__cov__;
} // set a node attribute for the supplied node
}, {
key: "setAttr",
value: function setAttr(node, name, value) {
node.__cov__ = node.__cov__ || {};
node.__cov__[name] = value;
} // retrieve a node attribute for the supplied node or null
delete path.node.__cov__;
} // set a node attribute for the supplied node
}, {
key: "getAttr",
value: function getAttr(node, name) {
var c = node.__cov__;
if (!c) {
return null;
}
setAttr(node, name, value) {
node.__cov__ = node.__cov__ || {};
node.__cov__[name] = value;
} // retrieve a node attribute for the supplied node or null
return c[name];
} //
}, {
key: "increase",
value: function increase(type, id, index) {
var T = this.types;
var wrap = index !== null // If `index` present, turn `x` into `x[index]`.
? function (x) {
return T.memberExpression(x, T.numericLiteral(index), true);
} : function (x) {
return x;
};
return T.updateExpression('++', wrap(T.memberExpression(T.memberExpression(T.identifier(this.varName), T.identifier(type)), T.numericLiteral(id), true)));
getAttr(node, name) {
const c = node.__cov__;
if (!c) {
return null;
}
}, {
key: "insertCounter",
value: function insertCounter(path, increment) {
var T = this.types;
if (path.isBlockStatement()) {
path.node.body.unshift(T.expressionStatement(increment));
} else if (path.isStatement()) {
path.insertBefore(T.expressionStatement(increment));
} else if (this.counterNeedsHoisting(path) && T.isVariableDeclarator(path.parentPath)) {
// make an attempt to hoist the statement counter, so that
// function names are maintained.
var parent = path.parentPath.parentPath;
return c[name];
} //
if (parent && T.isExportNamedDeclaration(parent.parentPath)) {
parent.parentPath.insertBefore(T.expressionStatement(increment));
} else if (parent && (T.isProgram(parent.parentPath) || T.isBlockStatement(parent.parentPath))) {
parent.insertBefore(T.expressionStatement(increment));
} else {
path.replaceWith(T.sequenceExpression([increment, path.node]));
}
} else
/* istanbul ignore else: not expected */
if (path.isExpression()) {
path.replaceWith(T.sequenceExpression([increment, path.node]));
} else {
console.error('Unable to insert counter for node type:', path.node.type);
}
}
}, {
key: "insertStatementCounter",
value: function insertStatementCounter(path) {
/* istanbul ignore if: paranoid check */
if (!(path.node && path.node.loc)) {
return;
increase(type, id, index) {
const T = this.types;
const wrap = index !== null // If `index` present, turn `x` into `x[index]`.
? x => T.memberExpression(x, T.numericLiteral(index), true) : x => x;
return T.updateExpression('++', wrap(T.memberExpression(T.memberExpression(T.identifier(this.varName), T.identifier(type)), T.numericLiteral(id), true)));
}
insertCounter(path, increment) {
const T = this.types;
if (path.isBlockStatement()) {
path.node.body.unshift(T.expressionStatement(increment));
} else if (path.isStatement()) {
path.insertBefore(T.expressionStatement(increment));
} else if (this.counterNeedsHoisting(path) && T.isVariableDeclarator(path.parentPath)) {
// make an attempt to hoist the statement counter, so that
// function names are maintained.
const parent = path.parentPath.parentPath;
if (parent && T.isExportNamedDeclaration(parent.parentPath)) {
parent.parentPath.insertBefore(T.expressionStatement(increment));
} else if (parent && (T.isProgram(parent.parentPath) || T.isBlockStatement(parent.parentPath))) {
parent.insertBefore(T.expressionStatement(increment));
} else {
path.replaceWith(T.sequenceExpression([increment, path.node]));
}
} else
/* istanbul ignore else: not expected */
if (path.isExpression()) {
path.replaceWith(T.sequenceExpression([increment, path.node]));
} else {
console.error('Unable to insert counter for node type:', path.node.type);
}
}
var index = this.cov.newStatement(path.node.loc);
var increment = this.increase('s', index, null);
this.insertCounter(path, increment);
insertStatementCounter(path) {
/* istanbul ignore if: paranoid check */
if (!(path.node && path.node.loc)) {
return;
}
}, {
key: "insertFunctionCounter",
value: function insertFunctionCounter(path) {
var T = this.types;
/* istanbul ignore if: paranoid check */
if (!(path.node && path.node.loc)) {
return;
}
const index = this.cov.newStatement(path.node.loc);
const increment = this.increase('s', index, null);
this.insertCounter(path, increment);
}
var n = path.node;
var dloc = null; // get location for declaration
insertFunctionCounter(path) {
const T = this.types;
/* istanbul ignore if: paranoid check */
switch (n.type) {
case "FunctionDeclaration":
/* istanbul ignore else: paranoid check */
if (n.id) {
dloc = n.id.loc;
}
if (!(path.node && path.node.loc)) {
return;
}
break;
const n = path.node;
let dloc = null; // get location for declaration
case "FunctionExpression":
if (n.id) {
dloc = n.id.loc;
}
switch (n.type) {
case "FunctionDeclaration":
/* istanbul ignore else: paranoid check */
if (n.id) {
dloc = n.id.loc;
}
break;
}
break;
if (!dloc) {
dloc = {
start: n.loc.start,
end: {
line: n.loc.start.line,
column: n.loc.start.column + 1
}
};
}
case "FunctionExpression":
if (n.id) {
dloc = n.id.loc;
}
var name = path.node.id ? path.node.id.name : path.node.name;
var index = this.cov.newFunction(name, dloc, path.node.body.loc);
var increment = this.increase('f', index, null);
var body = path.get('body');
/* istanbul ignore else: not expected */
break;
}
if (body.isBlockStatement()) {
body.node.body.unshift(T.expressionStatement(increment));
} else {
console.error('Unable to process function body node type:', path.node.type);
}
if (!dloc) {
dloc = {
start: n.loc.start,
end: {
line: n.loc.start.line,
column: n.loc.start.column + 1
}
};
}
}, {
key: "getBranchIncrement",
value: function getBranchIncrement(branchName, loc) {
var index = this.cov.addBranchPath(branchName, loc);
return this.increase('b', branchName, index);
const name = path.node.id ? path.node.id.name : path.node.name;
const index = this.cov.newFunction(name, dloc, path.node.body.loc);
const increment = this.increase('f', index, null);
const body = path.get('body');
/* istanbul ignore else: not expected */
if (body.isBlockStatement()) {
body.node.body.unshift(T.expressionStatement(increment));
} else {
console.error('Unable to process function body node type:', path.node.type);
}
}, {
key: "insertBranchCounter",
value: function insertBranchCounter(path, branchName, loc) {
var increment = this.getBranchIncrement(branchName, loc || path.node.loc);
this.insertCounter(path, increment);
}
getBranchIncrement(branchName, loc) {
const index = this.cov.addBranchPath(branchName, loc);
return this.increase('b', branchName, index);
}
insertBranchCounter(path, branchName, loc) {
const increment = this.getBranchIncrement(branchName, loc || path.node.loc);
this.insertCounter(path, increment);
}
findLeaves(node, accumulator, parent, property) {
if (!node) {
return;
}
}, {
key: "findLeaves",
value: function findLeaves(node, accumulator, parent, property) {
if (!node) {
return;
}
if (node.type === "LogicalExpression") {
var hint = this.hintFor(node);
if (node.type === "LogicalExpression") {
const hint = this.hintFor(node);
if (hint !== 'next') {
this.findLeaves(node.left, accumulator, node, 'left');
this.findLeaves(node.right, accumulator, node, 'right');
}
} else {
accumulator.push({
node: node,
parent: parent,
property: property
});
if (hint !== 'next') {
this.findLeaves(node.left, accumulator, node, 'left');
this.findLeaves(node.right, accumulator, node, 'right');
}
} else {
accumulator.push({
node: node,
parent: parent,
property: property
});
}
}]);
}
return VisitState;
}(); // generic function that takes a set of visitor methods and
} // generic function that takes a set of visitor methods and
// returns a visitor object with `enter` and `exit` properties,

@@ -351,5 +313,5 @@ // such that:

function entries() {
var enter = Array.prototype.slice.call(arguments); // the enter function
const enter = Array.prototype.slice.call(arguments); // the enter function
var wrappedEntry = function wrappedEntry(path, node) {
const wrappedEntry = function wrappedEntry(path, node) {
this.onEnter(path);

@@ -361,3 +323,3 @@

var that = this;
const that = this;
enter.forEach(function (e) {

@@ -368,3 +330,3 @@ e.call(that, path, node);

var exit = function exit(path, node) {
const exit = function exit(path, node) {
this.onExit(path, node);

@@ -386,4 +348,4 @@ };

function coverAssignmentPattern(path) {
var n = path.node;
var b = this.cov.newBranch('default-arg', n.loc);
const n = path.node;
const b = this.cov.newBranch('default-arg', n.loc);
this.insertBranchCounter(path.get('right'), b);

@@ -407,3 +369,3 @@ }

function makeBlock(path) {
var T = this.types;
const T = this.types;

@@ -441,7 +403,7 @@ if (!path.node) {

function convertArrowExpression(path) {
var n = path.node;
var T = this.types;
const n = path.node;
const T = this.types;
if (!T.isBlockStatement(n.body)) {
var bloc = n.body.loc;
const bloc = n.body.loc;

@@ -462,7 +424,7 @@ if (n.expression === true) {

function coverIfBranches(path) {
var n = path.node,
hint = this.hintFor(n),
ignoreIf = hint === 'if',
ignoreElse = hint === 'else',
branch = this.cov.newBranch('if', n.loc);
const n = path.node,
hint = this.hintFor(n),
ignoreIf = hint === 'if',
ignoreElse = hint === 'else',
branch = this.cov.newBranch('if', n.loc);

@@ -483,3 +445,3 @@ if (ignoreIf) {

function createSwitchBranch(path) {
var b = this.cov.newBranch('switch', path.node.loc);
const b = this.cov.newBranch('switch', path.node.loc);
this.setAttr(path.node, 'branchName', b);

@@ -489,4 +451,4 @@ }

function coverSwitchCase(path) {
var T = this.types;
var b = this.getAttr(path.parentPath.node, 'branchName');
const T = this.types;
const b = this.getAttr(path.parentPath.node, 'branchName');
/* istanbul ignore if: paranoid check */

@@ -498,3 +460,3 @@

var increment = this.getBranchIncrement(b, path.node.loc);
const increment = this.getBranchIncrement(b, path.node.loc);
path.node.consequent.unshift(T.expressionStatement(increment));

@@ -504,6 +466,6 @@ }

function coverTernary(path) {
var n = path.node,
branch = this.cov.newBranch('cond-expr', path.node.loc),
cHint = this.hintFor(n.consequent),
aHint = this.hintFor(n.alternate);
const n = path.node,
branch = this.cov.newBranch('cond-expr', path.node.loc),
cHint = this.hintFor(n.consequent),
aHint = this.hintFor(n.alternate);

@@ -520,3 +482,3 @@ if (cHint !== 'next') {

function coverLogicalExpression(path) {
var T = this.types;
const T = this.types;

@@ -527,9 +489,9 @@ if (path.parentPath.node.type === "LogicalExpression") {

var leaves = [];
let leaves = [];
this.findLeaves(path.node, leaves);
var b = this.cov.newBranch("binary-expr", path.node.loc);
const b = this.cov.newBranch("binary-expr", path.node.loc);
for (var i = 0; i < leaves.length; i += 1) {
var leaf = leaves[i];
var hint = this.hintFor(leaf.node);
for (let i = 0; i < leaves.length; i += 1) {
const leaf = leaves[i];
const hint = this.hintFor(leaf.node);

@@ -540,3 +502,3 @@ if (hint === 'next') {

var increment = this.getBranchIncrement(b, leaf.node.loc);
const increment = this.getBranchIncrement(b, leaf.node.loc);

@@ -551,3 +513,3 @@ if (!increment) {

var codeVisitor = {
const codeVisitor = {
ArrowFunctionExpression: entries(convertArrowExpression, coverFunction),

@@ -586,3 +548,18 @@ AssignmentPattern: entries(coverAssignmentPattern),

var coverageTemplate = (0, _template.default)("\n var COVERAGE_VAR = (function () {\n var path = PATH,\n hash = HASH,\n Function = (function(){}).constructor,\n global = (new Function('return this'))(),\n gcv = GLOBAL_COVERAGE_VAR,\n coverageData = INITIAL,\n coverage = global[gcv] || (global[gcv] = {});\n if (coverage[path] && coverage[path].hash === hash) {\n return coverage[path];\n }\n coverageData.hash = hash;\n return coverage[path] = coverageData;\n })();\n"); // the rewire plugin (and potentially other babel middleware)
const coverageTemplate = (0, _template.default)(`
var COVERAGE_VAR = (function () {
var path = PATH,
hash = HASH,
Function = (function(){}).constructor,
global = (new Function('return this'))(),
gcv = GLOBAL_COVERAGE_VAR,
coverageData = INITIAL,
coverage = global[gcv] || (global[gcv] = {});
if (coverage[path] && coverage[path].hash === hash) {
return coverage[path];
}
coverageData.hash = hash;
return coverage[path] = coverageData;
})();
`); // the rewire plugin (and potentially other babel middleware)
// may cause files to be instrumented twice, see:

@@ -598,8 +575,6 @@ // https://github.com/istanbuljs/babel-plugin-istanbul/issues/94

function shouldIgnoreFile(programNode) {
return programNode.parent && programNode.parent.comments.some(function (c) {
return COMMENT_FILE_RE.test(c.value);
});
return programNode.parent && programNode.parent.comments.some(c => COMMENT_FILE_RE.test(c.value));
}
var defaultProgramVisitorOpts = {
const defaultProgramVisitorOpts = {
coverageVariable: '__coverage__',

@@ -631,12 +606,8 @@ ignoreClassMethods: [],

function programVisitor(types) {
var sourceFilePath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'unknown.js';
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultProgramVisitorOpts;
var T = types;
var visitState = new VisitState(types, sourceFilePath, opts.inputSourceMap, opts.ignoreClassMethods);
function programVisitor(types, sourceFilePath = 'unknown.js', opts = defaultProgramVisitorOpts) {
const T = types;
const visitState = new VisitState(types, sourceFilePath, opts.inputSourceMap, opts.ignoreClassMethods);
return {
enter: function enter(path) {
if (shouldIgnoreFile(path.find(function (p) {
return p.isProgram();
}))) {
enter(path) {
if (shouldIgnoreFile(path.find(p => p.isProgram()))) {
return;

@@ -651,3 +622,4 @@ }

},
exit: function exit(path) {
exit(path) {
if (alreadyInstrumented(path, visitState)) {

@@ -658,7 +630,5 @@ return;

visitState.cov.freeze();
var coverageData = visitState.cov.toJSON();
const coverageData = visitState.cov.toJSON();
if (shouldIgnoreFile(path.find(function (p) {
return p.isProgram();
}))) {
if (shouldIgnoreFile(path.find(p => p.isProgram()))) {
return {

@@ -671,6 +641,6 @@ fileCoverage: coverageData,

coverageData[_constants.MAGIC_KEY] = _constants.MAGIC_VALUE;
var hash = (0, _crypto.createHash)(_constants.SHA).update(JSON.stringify(coverageData)).digest('hex');
var coverageNode = T.valueToNode(coverageData);
const hash = (0, _crypto.createHash)(_constants.SHA).update(JSON.stringify(coverageData)).digest('hex');
const coverageNode = T.valueToNode(coverageData);
delete coverageData[_constants.MAGIC_KEY];
var cv = coverageTemplate({
const cv = coverageTemplate({
GLOBAL_COVERAGE_VAR: T.stringLiteral(opts.coverageVariable),

@@ -689,2 +659,3 @@ COVERAGE_VAR: T.identifier(visitState.varName),

}
};

@@ -691,0 +662,0 @@ }

{
"name": "istanbul-lib-instrument",
"version": "2.3.1",
"version": "2.3.2",
"description": "Core istanbul API for JS code coverage",

@@ -5,0 +5,0 @@ "author": "Krishnan Anantheswaran <kananthmail-github@yahoo.com>",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc