instrumenter.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. /*
  2. Copyright 2012-2015, Yahoo Inc.
  3. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
  4. */
  5. const { transformSync } = require('@babel/core');
  6. const { defaults } = require('@istanbuljs/schema');
  7. const programVisitor = require('./visitor');
  8. const readInitialCoverage = require('./read-coverage');
  9. /**
  10. * Instrumenter is the public API for the instrument library.
  11. * It is typically used for ES5 code. For ES6 code that you
  12. * are already running under `babel` use the coverage plugin
  13. * instead.
  14. * @param {Object} opts optional.
  15. * @param {string} [opts.coverageVariable=__coverage__] name of global coverage variable.
  16. * @param {boolean} [opts.reportLogic=false] report boolean value of logical expressions.
  17. * @param {boolean} [opts.preserveComments=false] preserve comments in output.
  18. * @param {boolean} [opts.compact=true] generate compact code.
  19. * @param {boolean} [opts.esModules=false] set to true to instrument ES6 modules.
  20. * @param {boolean} [opts.autoWrap=false] set to true to allow `return` statements outside of functions.
  21. * @param {boolean} [opts.produceSourceMap=false] set to true to produce a source map for the instrumented code.
  22. * @param {Array} [opts.ignoreClassMethods=[]] set to array of class method names to ignore for coverage.
  23. * @param {Function} [opts.sourceMapUrlCallback=null] a callback function that is called when a source map URL
  24. * is found in the original code. This function is called with the source file name and the source map URL.
  25. * @param {boolean} [opts.debug=false] - turn debugging on.
  26. * @param {array} [opts.parserPlugins] - set babel parser plugins, see @istanbuljs/schema for defaults.
  27. * @param {string} [opts.coverageGlobalScope=this] the global coverage variable scope.
  28. * @param {boolean} [opts.coverageGlobalScopeFunc=true] use an evaluated function to find coverageGlobalScope.
  29. */
  30. class Instrumenter {
  31. constructor(opts = {}) {
  32. this.opts = {
  33. ...defaults.instrumenter,
  34. ...opts
  35. };
  36. this.fileCoverage = null;
  37. this.sourceMap = null;
  38. }
  39. /**
  40. * instrument the supplied code and track coverage against the supplied
  41. * filename. It throws if invalid code is passed to it. ES5 and ES6 syntax
  42. * is supported. To instrument ES6 modules, make sure that you set the
  43. * `esModules` property to `true` when creating the instrumenter.
  44. *
  45. * @param {string} code - the code to instrument
  46. * @param {string} filename - the filename against which to track coverage.
  47. * @param {object} [inputSourceMap] - the source map that maps the not instrumented code back to it's original form.
  48. * Is assigned to the coverage object and therefore, is available in the json output and can be used to remap the
  49. * coverage to the untranspiled source.
  50. * @returns {string} the instrumented code.
  51. */
  52. instrumentSync(code, filename, inputSourceMap) {
  53. if (typeof code !== 'string') {
  54. throw new Error('Code must be a string');
  55. }
  56. filename = filename || String(new Date().getTime()) + '.js';
  57. const { opts } = this;
  58. let output = {};
  59. const babelOpts = {
  60. configFile: false,
  61. babelrc: false,
  62. ast: true,
  63. filename: filename || String(new Date().getTime()) + '.js',
  64. inputSourceMap,
  65. sourceMaps: opts.produceSourceMap,
  66. compact: opts.compact,
  67. comments: opts.preserveComments,
  68. parserOpts: {
  69. allowReturnOutsideFunction: opts.autoWrap,
  70. sourceType: opts.esModules ? 'module' : 'script',
  71. plugins: opts.parserPlugins
  72. },
  73. plugins: [
  74. [
  75. ({ types }) => {
  76. const ee = programVisitor(types, filename, {
  77. coverageVariable: opts.coverageVariable,
  78. reportLogic: opts.reportLogic,
  79. coverageGlobalScope: opts.coverageGlobalScope,
  80. coverageGlobalScopeFunc:
  81. opts.coverageGlobalScopeFunc,
  82. ignoreClassMethods: opts.ignoreClassMethods,
  83. inputSourceMap
  84. });
  85. return {
  86. visitor: {
  87. Program: {
  88. enter: ee.enter,
  89. exit(path) {
  90. output = ee.exit(path);
  91. }
  92. }
  93. }
  94. };
  95. }
  96. ]
  97. ]
  98. };
  99. const codeMap = transformSync(code, babelOpts);
  100. if (!output || !output.fileCoverage) {
  101. const initialCoverage =
  102. readInitialCoverage(codeMap.ast) ||
  103. /* istanbul ignore next: paranoid check */ {};
  104. this.fileCoverage = initialCoverage.coverageData;
  105. this.sourceMap = inputSourceMap;
  106. return code;
  107. }
  108. this.fileCoverage = output.fileCoverage;
  109. this.sourceMap = codeMap.map;
  110. const cb = this.opts.sourceMapUrlCallback;
  111. if (cb && output.sourceMappingURL) {
  112. cb(filename, output.sourceMappingURL);
  113. }
  114. return codeMap.code;
  115. }
  116. /**
  117. * callback-style instrument method that calls back with an error
  118. * as opposed to throwing one. Note that in the current implementation,
  119. * the callback will be called in the same process tick and is not asynchronous.
  120. *
  121. * @param {string} code - the code to instrument
  122. * @param {string} filename - the filename against which to track coverage.
  123. * @param {Function} callback - the callback
  124. * @param {Object} inputSourceMap - the source map that maps the not instrumented code back to it's original form.
  125. * Is assigned to the coverage object and therefore, is available in the json output and can be used to remap the
  126. * coverage to the untranspiled source.
  127. */
  128. instrument(code, filename, callback, inputSourceMap) {
  129. if (!callback && typeof filename === 'function') {
  130. callback = filename;
  131. filename = null;
  132. }
  133. try {
  134. const out = this.instrumentSync(code, filename, inputSourceMap);
  135. callback(null, out);
  136. } catch (ex) {
  137. callback(ex);
  138. }
  139. }
  140. /**
  141. * returns the file coverage object for the last file instrumented.
  142. * @returns {Object} the file coverage object.
  143. */
  144. lastFileCoverage() {
  145. return this.fileCoverage;
  146. }
  147. /**
  148. * returns the source map produced for the last file instrumented.
  149. * @returns {null|Object} the source map object.
  150. */
  151. lastSourceMap() {
  152. return this.sourceMap;
  153. }
  154. }
  155. module.exports = Instrumenter;