read-coverage.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = readInitialCoverage;
  6. var _parser = require("@babel/parser");
  7. var _traverse = _interopRequireDefault(require("@babel/traverse"));
  8. var t = _interopRequireWildcard(require("@babel/types"));
  9. var _constants = require("./constants");
  10. var _instrumenter = require("./instrumenter");
  11. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. function readInitialCoverage(code) {
  14. if (typeof code !== 'string') {
  15. throw new Error('Code must be a string');
  16. } // Parse as leniently as possible
  17. const ast = (0, _parser.parse)(code, {
  18. allowImportExportEverywhere: true,
  19. allowReturnOutsideFunction: true,
  20. allowSuperOutsideMethod: true,
  21. sourceType: 'script',
  22. plugins: (0, _instrumenter.defaultOpts)().plugins
  23. });
  24. let covScope;
  25. (0, _traverse.default)(ast, {
  26. ObjectProperty(path) {
  27. const node = path.node;
  28. if (!node.computed && t.isIdentifier(node.key) && node.key.name === _constants.MAGIC_KEY) {
  29. const magicValue = path.get('value').evaluate();
  30. if (!magicValue.confident || magicValue.value !== _constants.MAGIC_VALUE) {
  31. return;
  32. }
  33. covScope = path.scope.getFunctionParent() || path.scope.getProgramParent();
  34. path.stop();
  35. }
  36. }
  37. });
  38. if (!covScope) {
  39. return null;
  40. }
  41. const result = {};
  42. for (var _i = 0, _arr = ['path', 'hash', 'gcv', 'coverageData']; _i < _arr.length; _i++) {
  43. const key = _arr[_i];
  44. const binding = covScope.getOwnBinding(key);
  45. if (!binding) {
  46. return null;
  47. }
  48. const valuePath = binding.path.get('init');
  49. const value = valuePath.evaluate();
  50. if (!value.confident) {
  51. return null;
  52. }
  53. result[key] = value.value;
  54. }
  55. delete result.coverageData[_constants.MAGIC_KEY];
  56. return result;
  57. }