1 | "use strict";
|
---|
2 |
|
---|
3 | Object.defineProperty(exports, "__esModule", {
|
---|
4 | value: true
|
---|
5 | });
|
---|
6 | exports.default = readInitialCoverage;
|
---|
7 |
|
---|
8 | var _core = require("@babel/core");
|
---|
9 |
|
---|
10 | var _schema = require("@istanbuljs/schema");
|
---|
11 |
|
---|
12 | var _constants = require("./constants");
|
---|
13 |
|
---|
14 | function getAst(code) {
|
---|
15 | if (typeof code === 'object' && typeof code.type === 'string') {
|
---|
16 | // Assume code is already a babel ast.
|
---|
17 | return code;
|
---|
18 | }
|
---|
19 |
|
---|
20 | if (typeof code !== 'string') {
|
---|
21 | throw new Error('Code must be a string');
|
---|
22 | } // Parse as leniently as possible
|
---|
23 |
|
---|
24 |
|
---|
25 | return (0, _core.parseSync)(code, {
|
---|
26 | babelrc: false,
|
---|
27 | configFile: false,
|
---|
28 | parserOpts: {
|
---|
29 | allowImportExportEverywhere: true,
|
---|
30 | allowReturnOutsideFunction: true,
|
---|
31 | allowSuperOutsideMethod: true,
|
---|
32 | sourceType: 'script',
|
---|
33 | plugins: _schema.defaults.instrumenter.parserPlugins
|
---|
34 | }
|
---|
35 | });
|
---|
36 | }
|
---|
37 |
|
---|
38 | function readInitialCoverage(code) {
|
---|
39 | const ast = getAst(code);
|
---|
40 | let covScope;
|
---|
41 | (0, _core.traverse)(ast, {
|
---|
42 | ObjectProperty(path) {
|
---|
43 | const {
|
---|
44 | node
|
---|
45 | } = path;
|
---|
46 |
|
---|
47 | if (!node.computed && path.get('key').isIdentifier() && node.key.name === _constants.MAGIC_KEY) {
|
---|
48 | const magicValue = path.get('value').evaluate();
|
---|
49 |
|
---|
50 | if (!magicValue.confident || magicValue.value !== _constants.MAGIC_VALUE) {
|
---|
51 | return;
|
---|
52 | }
|
---|
53 |
|
---|
54 | covScope = path.scope.getFunctionParent() || path.scope.getProgramParent();
|
---|
55 | path.stop();
|
---|
56 | }
|
---|
57 | }
|
---|
58 |
|
---|
59 | });
|
---|
60 |
|
---|
61 | if (!covScope) {
|
---|
62 | return null;
|
---|
63 | }
|
---|
64 |
|
---|
65 | const result = {};
|
---|
66 |
|
---|
67 | for (const key of ['path', 'hash', 'gcv', 'coverageData']) {
|
---|
68 | const binding = covScope.getOwnBinding(key);
|
---|
69 |
|
---|
70 | if (!binding) {
|
---|
71 | return null;
|
---|
72 | }
|
---|
73 |
|
---|
74 | const valuePath = binding.path.get('init');
|
---|
75 | const value = valuePath.evaluate();
|
---|
76 |
|
---|
77 | if (!value.confident) {
|
---|
78 | return null;
|
---|
79 | }
|
---|
80 |
|
---|
81 | result[key] = value.value;
|
---|
82 | }
|
---|
83 |
|
---|
84 | delete result.coverageData[_constants.MAGIC_KEY];
|
---|
85 | delete result.coverageData.hash;
|
---|
86 | return result;
|
---|
87 | } |
---|