-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnpm-interactions.ts
83 lines (67 loc) · 1.97 KB
/
npm-interactions.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
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
/**
* Rotten Deps NPM Interactions library
* @module
*/
import * as proc from 'child_process';
export interface PackageDetails {
time: Record<string, string>;
name: string;
}
export interface OutdatedPackage {
current: string;
wanted: string;
latest: string;
location: string;
}
export interface OutdatedData {
[key: string]: OutdatedPackage;
}
interface OutdatedRequest {
(): Promise<OutdatedData|Error>;
}
interface DetailsRequest {
(): Promise<PackageDetails|Error>;
}
/**
* Creates a function for running `npm outdated`
*/
export const createOutdatedRequest = (): OutdatedRequest => {
const command = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const args = ['outdated', '--json'];
/* NPM 7.x included a breaking change to the exit codes for the `outdated` command.
Prior to v7 the command would exit 1 if you had any outdated dependencies.
After v7 it exits 0 */
return () => new Promise(resolve => {
proc.execFile(command, args, { encoding: 'utf8' }, (err, stdout) => {
if (err) {
if (!err.message.includes('Command failed')) resolve(err);
if (err.code !== 1) resolve(err);
// hail mary attempt to parse the stdout in spite of the error
try {
resolve(JSON.parse(stdout));
} catch {
resolve(err);
}
}
resolve(JSON.parse(stdout));
});
});
};
/**
* Creates a function to run the `npm view` command for a specific dependency
* @param dependencyName
*/
export const createDetailsRequest = (dependencyName: string): DetailsRequest => {
const command = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const args = ['view', '--json', dependencyName];
return (): Promise<PackageDetails | Error> => new Promise(resolve => {
proc.execFile(command, args, { encoding: 'utf8' }, (err, stdout) => {
if (err) resolve(err);
resolve(JSON.parse(stdout));
});
});
};
export default {
createOutdatedRequest,
createDetailsRequest,
};