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