/
npm-modules-parser.ts
57 lines (52 loc) · 1.65 KB
/
npm-modules-parser.ts
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
import * as path from 'path';
import * as fs from 'fs';
import * as resolveNodeDeps from 'snyk-resolve-deps';
import { PkgTree } from 'snyk-nodejs-lockfile-parser';
import * as spinner from '../../spinner';
import * as analytics from '../../analytics';
import { Options } from '../types';
export async function parse(
root: string,
targetFile: string,
options: Options,
): Promise<PkgTree> {
const nodeModulesPath = path.join(
path.dirname(path.resolve(root, targetFile)),
'node_modules',
);
const packageManager = options.packageManager || 'npm';
if (!fs.existsSync(nodeModulesPath)) {
// throw a custom error
throw new Error(
"Missing node_modules folder: we can't test " +
`without dependencies.\nPlease run '${packageManager} install' first.`,
);
}
analytics.add('local', true);
analytics.add('generating-node-dependency-tree', {
lockFile: false,
targetFile,
});
const resolveModuleSpinnerLabel =
'Analyzing npm dependencies for ' +
path.dirname(path.resolve(root, targetFile));
try {
await spinner(resolveModuleSpinnerLabel);
if (targetFile.endsWith('yarn.lock')) {
options.file =
options.file && options.file.replace('yarn.lock', 'package.json');
}
// package-lock.json falls back to package.json (used in wizard code)
if (targetFile.endsWith('package-lock.json')) {
options.file =
options.file &&
options.file.replace('package-lock.json', 'package.json');
}
return resolveNodeDeps(
root,
Object.assign({}, options, { noFromArrays: true }),
);
} finally {
await spinner.clear<void>(resolveModuleSpinnerLabel)();
}
}