All files index.js

100% Statements 22/22
100% Branches 8/8
100% Functions 7/7
100% Lines 21/21
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    1x 1x     996x 3x   16x 16x   993x       1x 1011x 1011x 1011x 1011x 1010x 1010x 1010x 103x 103x 1004x 996x 1009x     1011x    
'use strict'
 
const fs = require('fs')
const path = require('path')
 
function mergeScopes (basePath, packages, dir) {
  if (/^@/.test(dir)) {
    const scopedSuffixPackages = fs
      .readdirSync(path.join(basePath, dir))
      .filter(packageName => !/^\./.test(packageName))
    return packages.concat(scopedSuffixPackages.map(p => path.join(dir, p)))
  } else {
    return packages.concat(dir)
  }
}
 
module.exports = function nmTree (basePath, tree) {
  tree = tree || {}
  const packageJsonPath = path.join(basePath, 'package.json')
  const nodeModulesPath = path.join(basePath, 'node_modules')
  if (fs.existsSync(packageJsonPath)) {
    const packageJson = JSON.parse(fs.readFileSync(packageJsonPath))
    tree[basePath] = packageJson
    if (fs.existsSync(nodeModulesPath)) { // TODO: and is dir
      const nodeModulesPackages = fs.readdirSync(nodeModulesPath)
      nodeModulesPackages
      .filter(dir => !/^\./.test(dir)) // no hidden directories (eg. .bin)
      .reduce((packages, dir) => mergeScopes(nodeModulesPath, packages, dir), [])
      .forEach(nmPackage => nmTree(path.join(nodeModulesPath, nmPackage), tree))
    }
  }
  return tree
}