forked from eslint/create-config
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnpm-utils.js
238 lines (197 loc) · 7.9 KB
/
npm-utils.js
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/**
* @fileoverview Utility for executing npm commands.
* @author Ian VanSchooten
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import fs from "node:fs";
import spawn from "cross-spawn";
import path from "node:path";
import * as log from "./logging.js";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Find the closest package.json file, starting at process.cwd (by default),
* and working up to root.
* @param {string} [startDir=process.cwd()] Starting directory
* @returns {string} Absolute path to closest package.json file
*/
function findPackageJson(startDir) {
let dir = path.resolve(startDir || process.cwd());
do {
const pkgFile = path.join(dir, "package.json");
if (!fs.existsSync(pkgFile) || !fs.statSync(pkgFile).isFile()) {
dir = path.join(dir, "..");
continue;
}
return pkgFile;
} while (dir !== path.resolve(dir, ".."));
return null;
}
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
/**
* Install node modules synchronously and save to devDependencies in package.json
* @param {string|string[]} packages Node module or modules to install
* @param {string} packageManager Package manager to use for installation.
* @param {string[]} installFlags Flags to pass to the package manager.
* @returns {void}
*/
function installSyncSaveDev(packages, packageManager = "npm", installFlags = ["-D"]) {
const packageList = Array.isArray(packages) ? packages : [packages];
const installCmd = packageManager === "yarn" ? "add" : "install";
const installProcess = spawn.sync(packageManager, [installCmd, ...installFlags].concat(packageList), { stdio: "inherit" });
const error = installProcess.error;
if (error && error.code === "ENOENT") {
const pluralS = packageList.length > 1 ? "s" : "";
log.error(`Could not execute ${packageManager}. Please install the following package${pluralS} with a package manager of your choice: ${packageList.join(", ")}`);
}
}
/**
* Parses a package name string into its name and version components.
* @param {string} packageName The package name to parse.
* @returns {Object} An object with 'name' and 'version' properties.
*/
function parsePackageName(packageName) {
const atIndex = packageName.lastIndexOf("@");
if (atIndex > 0) {
const name = packageName.slice(0, atIndex);
const version = packageName.slice(atIndex + 1) || "latest";
return { name, version };
}
return { name: packageName, version: "latest" };
}
/**
* Fetch `peerDependencies` of the given package by `npm show` command.
* @param {string} packageName The package name to fetch peerDependencies.
* @returns {Object} Gotten peerDependencies. Returns null if npm was not found.
*/
async function fetchPeerDependencies(packageName) {
const npmProcess = spawn.sync(
"npm",
["show", "--json", packageName, "peerDependencies"],
{ encoding: "utf8" }
);
const error = npmProcess.error;
if (error && error.code === "ENOENT") {
// Fallback to using the npm registry API directly when npm is not available.
const { name, version } = parsePackageName(packageName);
try {
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- Fallback using built-in fetch
const response = await fetch(`https://registry.npmjs.org/${name}`);
const data = await response.json();
const resolvedVersion =
version === "latest" ? data["dist-tags"]?.latest : version;
const packageVersion = data.versions[resolvedVersion];
if (!packageVersion) {
throw new Error(
`Version "${version}" not found for package "${name}".`
);
}
return Object.entries(packageVersion.peerDependencies).map(
([pkgName, pkgVersion]) => `${pkgName}@${pkgVersion}`
);
} catch {
// TODO: should throw an error instead of returning null
return null;
}
}
const fetchedText = npmProcess.stdout.trim();
const peers = JSON.parse(fetchedText || "{}");
const dependencies = [];
Object.keys(peers).forEach(pkgName => {
dependencies.push(`${pkgName}@${peers[pkgName]}`);
});
return dependencies;
}
/**
* Check whether node modules are include in a project's package.json.
* @param {string[]} packages Array of node module names
* @param {Object} opt Options Object
* @param {boolean} opt.dependencies Set to true to check for direct dependencies
* @param {boolean} opt.devDependencies Set to true to check for development dependencies
* @param {boolean} opt.startdir Directory to begin searching from
* @throws {Error} If cannot find valid `package.json` file.
* @returns {Object} An object whose keys are the module names
* and values are booleans indicating installation.
*/
function check(packages, opt) {
const deps = new Set();
const pkgJson = (opt) ? findPackageJson(opt.startDir) : findPackageJson();
if (!pkgJson) {
throw new Error("Could not find a package.json file. Run 'npm init' to create one.");
}
const fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
["dependencies", "devDependencies"].forEach(key => {
if (opt[key] && typeof fileJson[key] === "object") {
Object.keys(fileJson[key]).forEach(dep => deps.add(dep));
}
});
return packages.reduce((status, pkg) => {
status[pkg] = deps.has(pkg);
return status;
}, {});
}
/**
* Check whether node modules are included in the dependencies of a project's
* package.json.
*
* Convenience wrapper around check().
* @param {string[]} packages Array of node modules to check.
* @param {string} rootDir The directory containing a package.json
* @returns {Object} An object whose keys are the module names
* and values are booleans indicating installation.
*/
function checkDeps(packages, rootDir) {
return check(packages, { dependencies: true, startDir: rootDir });
}
/**
* Check whether node modules are included in the devDependencies of a project's
* package.json.
*
* Convenience wrapper around check().
* @param {string[]} packages Array of node modules to check.
* @returns {Object} An object whose keys are the module names
* and values are booleans indicating installation.
*/
function checkDevDeps(packages) {
return check(packages, { devDependencies: true });
}
/**
* Check whether package.json is found in current path.
* @param {string} [startDir] Starting directory
* @returns {boolean} Whether a package.json is found in current path.
*/
function checkPackageJson(startDir) {
return !!findPackageJson(startDir);
}
/**
* check if the package.type === "module"
* @param {string} pkgJSONPath path to package.json
* @returns {boolean} return true if the package.type === "module"
*/
function isPackageTypeModule(pkgJSONPath) {
if (pkgJSONPath) {
const pkgJSONContents = JSON.parse(fs.readFileSync(pkgJSONPath, "utf8"));
if (pkgJSONContents.type === "module") {
return true;
}
}
return false;
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export {
installSyncSaveDev,
parsePackageName,
fetchPeerDependencies,
findPackageJson,
checkDeps,
checkDevDeps,
checkPackageJson,
isPackageTypeModule
};