-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnpmCommand.ts
More file actions
281 lines (247 loc) · 8.69 KB
/
npmCommand.ts
File metadata and controls
281 lines (247 loc) · 8.69 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*
* Copyright 2025, Salesforce, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import os from 'node:os';
import path from 'node:path';
import { createRequire } from 'node:module';
import fs from 'node:fs';
import npmRunPath from 'npm-run-path';
import shelljs, { ShellString } from 'shelljs';
import { SfError } from '@salesforce/core';
import { sleep, parseJson } from '@salesforce/kit';
import { Ux } from '@salesforce/sf-plugins-core';
import { setErrorName } from './errors.js';
export type NpmMeta = {
tarballUrl?: string;
signatureUrl?: string;
publicKeyUrl?: string;
tarballLocalPath?: string;
verified?: boolean;
moduleName?: string;
version?: string;
tarballFilename?: string;
};
export type NpmShowResults = {
versions: string[];
'dist-tags': {
[name: string]: string;
};
sfdx?: {
publicKeyUrl: string;
signatureUrl: string;
};
dist?: {
[name: string]: string;
};
};
type NpmCommandOptions = shelljs.ExecOptions & {
json?: boolean;
registry?: string;
cliRoot?: string;
};
type NpmCommandResult = shelljs.ShellString;
type NpmPackage = {
bin: {
[name: string]: string;
};
};
export class NpmCommand {
public static runNpmCmd(cmd: string, options = {} as NpmCommandOptions): NpmCommandResult {
const nodeExecutable = NpmCommand.findNode(options.cliRoot);
const npmCli = NpmCommand.npmCli();
const command = `"${nodeExecutable}" "${npmCli}" ${cmd} --registry=${options.registry ?? ''}`;
const npmCmdResult = shelljs.exec(command, {
...options,
silent: true,
async: false,
env: npmRunPath.env({ env: process.env }),
});
if (npmCmdResult.code !== 0) {
throw new SfError(npmCmdResult.stderr, 'ShellExecError');
}
return npmCmdResult;
}
public static npxCli(): string {
const require = createRequire(import.meta.url);
const pkgPath = require.resolve('npm/package.json');
const fileData = fs.readFileSync(pkgPath, 'utf8');
const pkgJson = parseJson(fileData, pkgPath) as NpmPackage;
const prjPath = pkgPath.substring(0, pkgPath.lastIndexOf(path.sep));
return path.join(prjPath, pkgJson.bin['npx']);
}
/**
* Locate node executable and return its absolute path
* First it tries to locate the node executable on the root path passed in
* If not found then tries to use whatver 'node' resolves to on the user's PATH
* If found return absolute path to the executable
* If the node executable cannot be found, an error is thrown
*
* @private
*/
public static findNode(root?: string): string {
const isExecutable = (filepath: string): boolean => {
if (os.type() === 'Windows_NT') return filepath.endsWith('node.exe');
try {
if (filepath.endsWith('node')) {
// This checks if the filepath is executable on Mac or Linux, if it is not it errors.
fs.accessSync(filepath, fs.constants.X_OK);
return true;
}
} catch {
return false;
}
return false;
};
if (root) {
const sfdxBinDirs = NpmCommand.findSfdxBinDirs(root);
if (sfdxBinDirs.length > 0) {
// Find the node executable
const node = shelljs.find(sfdxBinDirs).filter((file) => isExecutable(file))[0];
if (node) {
return fs.realpathSync(node);
}
}
}
// Check to see if node is installed
const nodeShellString = shelljs.which('node');
if (nodeShellString?.code === 0 && nodeShellString?.stdout) return nodeShellString.stdout;
throw setErrorName(
new SfError('Cannot locate node executable.', 'CannotFindNodeExecutable'),
'CannotFindNodeExecutable'
);
}
/**
* Returns the path to the npm-cli.js file in this package's node_modules
*
* @private
*/
private static npmCli(): string {
const require = createRequire(import.meta.url);
const pkgPath = require.resolve('npm/package.json');
const fileData = fs.readFileSync(pkgPath, 'utf8');
const pkgJson = parseJson(fileData, pkgPath) as NpmPackage;
const prjPath = pkgPath.substring(0, pkgPath.lastIndexOf(path.sep));
return path.join(prjPath, pkgJson.bin['npm']);
}
/**
* Finds the bin directory in the sfdx installation root path
*
* @param sfdxPath
* @private
*/
private static findSfdxBinDirs(sfdxPath: string): string[] {
return sfdxPath
? [path.join(sfdxPath, 'bin'), path.join(sfdxPath, 'client', 'bin')].filter((p) => fs.existsSync(p))
: [];
}
}
export class NpmModule {
public npmMeta: NpmMeta;
public constructor(private module: string, private version: string = 'latest', private cliRoot?: string) {
this.npmMeta = {
moduleName: module,
};
}
public ping(registry?: string): { registry: string; time: number; details: Record<string, unknown> } {
return JSON.parse(NpmCommand.runNpmCmd(`ping ${registry ?? ''} --json`, { json: true, cliRoot: this.cliRoot })) as {
registry: string;
time: number;
details: Record<string, unknown>;
};
}
public run(command: string): ShellString {
return NpmCommand.runNpmCmd(command, { cliRoot: this.cliRoot, json: command.includes('--json') });
}
public show(registry: string): NpmShowResults {
const showCmd = NpmCommand.runNpmCmd(`show ${this.module}@${this.version} --json`, {
registry,
cliRoot: this.cliRoot,
});
// `npm show` doesn't return exit code 1 when it fails to get a specific package version
// If `stdout` is empty then no info was found in the registry.
if (showCmd.stdout === '') {
throw setErrorName(
new SfError(`Failed to find ${this.module}@${this.version} in the registry`, 'NpmError'),
'NpmError'
);
}
try {
// `npm show` returns an array of results when the version is a range
const raw = JSON.parse(showCmd.stdout) as NpmShowResults | NpmShowResults[];
if (Array.isArray(raw)) {
// Return the last result in the array since that will be the highest version
// NOTE: .at() possibly returns undefined so instead directly index the array for the last element
return raw[raw.length - 1];
}
return raw;
} catch (error) {
if (error instanceof Error) {
throw setErrorName(new SfError(error.message, 'ShellParseError'), 'ShellParseError');
}
throw error;
}
}
public pack(registry: string, options?: shelljs.ExecOptions): void {
try {
NpmCommand.runNpmCmd(`pack ${this.module}@${this.version}`, {
...options,
registry,
cliRoot: this.cliRoot,
});
} catch (err) {
if (err instanceof Error) {
const sfErr = SfError.wrap(err);
const e = new SfError(`Failed to fetch tarball from the registry: \n${sfErr.message}`, 'NpmError');
throw setErrorName(e, 'NpmError');
}
}
return;
}
public async fetchTarball(registry: string, options?: shelljs.ExecOptions): Promise<void> {
await this.pollForAvailability(() => {
this.pack(registry, options);
});
this.pack(registry, options);
}
// leave it because it's stubbed in the test
// eslint-disable-next-line class-methods-use-this
public async pollForAvailability(checkFn: () => void): Promise<void> {
const isNonTTY = process.env.CI !== undefined || process.env.CIRCLECI !== undefined;
let found = false;
let attempts = 0;
const maxAttempts = 300;
const ux = new Ux({ jsonEnabled: isNonTTY });
const start = isNonTTY ? (msg: string): void => ux.log(msg) : (msg: string): void => ux.spinner.start(msg);
const update = isNonTTY ? (msg: string): void => ux.log(msg) : (msg: string): string => (ux.spinner.status = msg);
const stop = isNonTTY ? (msg: string): void => ux.log(msg) : (msg: string): void => ux.spinner.stop(msg);
start('Polling for new version(s) to become available on npm');
while (!found && attempts < maxAttempts) {
attempts += 1;
update(`attempt: ${attempts} of ${maxAttempts}`);
try {
checkFn();
found = true;
} catch (error) {
if (attempts === maxAttempts) {
throw error;
}
found = false;
}
// eslint-disable-next-line no-await-in-loop
await sleep(1000);
}
stop(attempts >= maxAttempts ? 'failed' : 'done');
}
}