1const { resolve } = require('path')
2const localeCompare = require('@isaacs/string-locale-compare')('en')
3
4const installedDeep = async (npm) => {
5  const Arborist = require('@npmcli/arborist')
6  const {
7    depth,
8    global,
9    prefix,
10    workspacesEnabled,
11  } = npm.flatOptions
12
13  const getValues = (tree) =>
14    [...tree.inventory.values()]
15      .filter(i => i.location !== '' && !i.isRoot)
16      .map(i => {
17        return i
18      })
19      .filter(i => (i.depth - 1) <= depth)
20      .sort((a, b) => (a.depth - b.depth) || localeCompare(a.name, b.name))
21
22  const res = new Set()
23  const gArb = new Arborist({
24    global: true,
25    path: resolve(npm.globalDir, '..'),
26    workspacesEnabled,
27  })
28  const gTree = await gArb.loadActual({ global: true })
29
30  for (const node of getValues(gTree)) {
31    res.add(global ? node.name : [node.name, '-g'])
32  }
33
34  if (!global) {
35    const arb = new Arborist({ global: false, path: prefix, workspacesEnabled })
36    const tree = await arb.loadActual()
37    for (const node of getValues(tree)) {
38      res.add(node.name)
39    }
40  }
41
42  return [...res]
43}
44
45module.exports = installedDeep
46