All files babel_file.ts

99.38% Statements 159/160
95.65% Branches 44/46
100% Functions 46/46
100% Lines 113/113

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 2141x 1x   1x 1x 1x   1x 1x   26x           24x 24x   1x 11x     1x 1x   1x   1x                                     1x 1x 58x   1x 71x   1x 29x   1x 1x 1x     14x 14x 14x     1x 1x 1x     10x 10x 10x     1x 1x 1x     10x 10x 10x     1x 18x 18x           1x 17x 16x       16x     32x 32x 32x 15x 15x 15x                             23x           15x 24x 7x   17x   15x 15x     1x   35x   14x 14x   24x 24x 1x 7x   1x 19x   1x 14x 14x   32x 32x 32x 23x   14x 28x 28x 14x 7x 7x 7x 5x 5x 10x       18x 9x     25x 25x 25x 25x     7x 7x 7x 7x       9x 9x 9x 9x 9x 9x 9x 8x 8x 7x   8x 8x 8x   8x     1x  
import * as path from 'path';
import babelTraverse from '@babel/traverse';
import {File as BabelNodes} from '@babel/types';
import * as babelParser from '@babel/parser';
import {ParseableFile} from './parsable_file';
import {PackageJSON} from './package_json';
 
const defaults = {readonly: true};
export class BabelFile extends ParseableFile<BabelNodes> {
  constructor(
    public props: ConstructorParameters<typeof ParseableFile>[0] & {
      plugins?: babelParser.ParserPlugin[];
      // modifyDependency?: (dep: string) => string;
      pkg?: PackageJSON;
    } = defaults
  ) {
    super({...props, ...defaults});
    this.props = {...props, ...defaults};
  }
  get pkg() {
    return this.props.pkg ?? new PackageJSON({cwd: this.cwd});
  }
  /** @see https://stackoverflow.com/a/54003496/340688 */
  static getBuiltins() {
    try {
      // eslint-disable-next-line @typescript-eslint/no-var-requires
      const result = require('module');
      // eslint-disable-next-line node/no-unsupported-features/node-builtins
      return result.builtinModules;
    } catch (e) {
      /* istanbul ignore next */
      // prettier-ignore
      return [
        'assert',         'buffer',   'child_process',
        'cluster',        'console',  'constants',
        'crypto',         'dgram',    'dns',
        'domain',         'events',   'fs',
        'http',           'https',    'module',
        'net',            'os',       'path',
        'process',        'punycode', 'querystring',
        'readline',       'repl',     'stream',
        'string_decoder', 'sys',      'timers',
        'tls',            'tty',      'url',
        'util',           'vm',       'zlib'
      ];
    }
  }
  static builtins = BabelFile.getBuiltins();
  static isNativeImport(pkg: string) {
    return BabelFile.builtins.includes(pkg);
  }
  static isLocalImport(pkg: string) {
    return Boolean(pkg.match('^/|^./|^../'));
  }
  static isNodePackageImport(pkg: string) {
    return !BabelFile.isNativeImport(pkg) && !BabelFile.isLocalImport(pkg);
  }
  get packageImports() {
    return (async () => {
      return (await this.imports).filter(BabelFile.isNodePackageImport);
    })();
  }
  get localImports() {
    return (async () => {
      return (await this.imports).filter(BabelFile.isLocalImport);
    })();
  }
  get nativeImports() {
    return (async () => {
      return (await this.imports).filter(BabelFile.isNativeImport);
    })();
  }
  get packageRecursiveImports() {
    return (async () => {
      return (await this.recursiveImports).filter(BabelFile.isNodePackageImport);
    })();
  }
  get localRecursiveImports() {
    return (async () => {
      return (await this.recursiveImports).filter(BabelFile.isLocalImport);
    })();
  }
  get nativeRecursiveImports() {
    return (async () => {
      return (await this.recursiveImports).filter(BabelFile.isNativeImport);
    })();
  }
  get plugins(): babelParser.ParserPlugin[] {
    Iif (this.props.plugins && this.props.plugins.length) return this.props.plugins;
    return ['typescript', 'classProperties', 'classPrivateProperties'];
  }
  // get modifyDependency() {
  //   return this.props?.modifyDependency;
  // }
  private cacheParsedContent?: BabelNodes;
  parse(content: string): BabelNodes {
    if (this.cacheParsedContent) return this.cacheParsedContent;
    this.cacheParsedContent = babelParser.parse(content, {
      sourceType: 'module',
      plugins: this.plugins,
    });
    return this.cacheParsedContent;
  }
  private cacheImports?: string[];
  get imports(): Promise<string[]> {
    return (async () => {
      if (this.cacheImports) return this.cacheImports;
      let imports: string[] = [];
      const content = await this.parsedContent;
      babelTraverse(content, {
        CallExpression: astPath => {
          /* istanbul ignore next */
          if ('name' in astPath.node?.callee) {
            if (astPath.node?.callee?.name === 'require') {
              const arg = astPath.node.arguments[0];
              /* istanbul ignore next */
              if ('value' in arg && typeof arg.value === 'string') {
                imports.push(arg.value);
                // if (this.modifyDependency) arg.value = this.modifyDependency(arg.value);
              }
            }
          }
        },
        ImportDeclaration: astPath => {
          imports.push(astPath.node.source.value);
          // if (this.modifyDependency) {
          //   astPath.node.source.value = this.modifyDependency(astPath.node.source.value);
          // }
        },
      });
      imports = imports.map(i => {
        if (BabelFile.isLocalImport(i)) {
          return path.join(this.dirname, `${i}${this.extname}`);
        }
        return i;
      });
      this.cacheImports = imports;
      return this.cacheImports;
    })();
  }
  static uniqueString(a: string[]) {
    function onlyUnique(value: string, index: number, self: string[]) {
      return self.indexOf(value) === index;
    }
    const unique = a.filter(onlyUnique); // returns ['a', 1, 2, '1']
    return unique;
  }
  private cacheSiblingFiles: {[key: string]: BabelFile} = {};
  private cacheRecursiveImports: string[] = [];
  private fileCacheCheck(path: string) {
    return typeof this.cacheSiblingFiles[path] !== 'undefined';
  }
  private fileCacheAdd(file: BabelFile) {
    this.cacheSiblingFiles[file.path] = file;
  }
  private async recursiveImportAdd(file: BabelFile) {
    const imports = await file.imports;
    this.cacheRecursiveImports = BabelFile.uniqueString([...this.cacheRecursiveImports, ...imports]);
  }
  get recursiveDependencies(): Promise<[string[], {[key: string]: BabelFile}]> {
    return (async (): Promise<[string[], {[key: string]: BabelFile}]> => {
      if (this.cacheRecursiveImports.length !== 0) {
        return [this.cacheRecursiveImports, this.cacheSiblingFiles];
      }
      const recursive = async (babelFile: BabelFile) => {
        await this.fileCacheAdd(babelFile);
        await this.recursiveImportAdd(babelFile);
        return (await babelFile.localImports).reduce((promise, path) => {
          return promise.then(async () => {
            const isCached = this.fileCacheCheck(path);
            if (isCached) return;
            const file = new BabelFile({path});
            this.fileCacheAdd(file);
            await recursive(file);
          });
        }, Promise.resolve());
      };
      await recursive(this);
      return [this.cacheRecursiveImports, this.cacheSiblingFiles];
    })();
  }
  get recursiveImports() {
    return (async () => {
      const [imports] = await this.recursiveDependencies;
      return imports;
    })();
  }
  get recursiveSiblings() {
    return (async () => {
      const [, siblings] = await this.recursiveDependencies;
      return Object.values(siblings);
    })();
  }
  /** Given a package json file, will pluck all npm dependencies */
  get dependencies(): Promise<{[k: string]: string}> {
    return (async () => {
      const imports = await this.packageRecursiveImports;
      const nativeImports = await this.nativeRecursiveImports;
      const allDependencies = await this.pkg.dependencies;
      const dependencies = {};
      imports.forEach(i => {
        const version = allDependencies[i];
        if (!version) throw new Error(`Dependency "${i}" is not found in package.json.`);
        Object.assign(dependencies, {[i]: version});
      });
      nativeImports.forEach(i => {
        const version = allDependencies[i];
        if (version) Object.assign(dependencies, {[i]: version});
      });
      return dependencies;
    })();
  }
}