/
npm.ts
193 lines (160 loc) · 5.38 KB
/
npm.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
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
import * as path from 'path';
import * as fs from 'fs';
import * as cp from 'child_process';
import * as parseSemver from 'parse-semver';
import * as _ from 'lodash';
import { CancellationToken, ERROR } from './util';
interface IOptions {
cwd?: string;
stdio?: any;
customFds?: any;
env?: any;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
}
function parseStdout({ stdout }: { stdout: string }): string {
return stdout.split(/[\r\n]/).filter(line => !!line)[0];
}
function exec(command: string, options: IOptions = {}, cancellationToken?: CancellationToken): Promise<{ stdout: string; stderr: string; }> {
return new Promise((c, e) => {
let disposeCancellationListener: Function = null;
const child = cp.exec(command, { ...options, encoding: 'utf8' } as any, (err, stdout: string, stderr: string) => {
if (disposeCancellationListener) {
disposeCancellationListener();
disposeCancellationListener = null;
}
if (err) { return e(err); }
c({ stdout, stderr });
});
if (cancellationToken) {
disposeCancellationListener = cancellationToken.subscribe(err => {
child.kill();
e(err);
});
}
});
}
function checkNPM(cancellationToken?: CancellationToken): Promise<void> {
return exec('npm -v', {}, cancellationToken).then(({ stdout }) => {
const version = stdout.trim();
if (/^3\.7\.[0123]$/.test(version)) {
return Promise.reject(`npm@${version} doesn't work with vsce. Please update npm: npm install -g npm`);
}
});
}
function getNpmDependencies(cwd: string): Promise<string[]> {
return checkNPM()
.then(() => exec('npm list --production --parseable --depth=99999', { cwd }))
.then(({ stdout }) => stdout
.split(/[\r\n]/)
.filter(dir => path.isAbsolute(dir)));
}
interface YarnTreeNode {
name: string;
children: YarnTreeNode[];
}
export interface YarnDependency {
name: string;
version: string;
path: string;
children: YarnDependency[];
}
function asYarnDependency(prefix: string, tree: YarnTreeNode, prune: boolean): YarnDependency | null {
if (prune && /@[\^~]/.test(tree.name)) {
return null;
}
let name: string, version: string;
try {
const parseResult = parseSemver(tree.name);
name = parseResult.name;
version = parseResult.version;
} catch (err) {
console.error(`${ERROR} Failed to parse dependency:`, tree.name);
return null;
}
const dependencyPath = path.join(prefix, name);
const children: YarnDependency[] = [];
for (const child of (tree.children || [])) {
const dep = asYarnDependency(path.join(prefix, name, 'node_modules'), child, prune);
if (dep) {
children.push(dep);
}
}
return { name, version, path: dependencyPath, children };
}
function selectYarnDependencies(deps: YarnDependency[], packagedDependencies: string[]): YarnDependency[] {
const index = new class {
private data: { [name: string]: YarnDependency } = Object.create(null);
constructor() {
for (const dep of deps) {
if (this.data[dep.name]) {
throw Error(`Dependency seen more than once: ${dep.name}`);
}
this.data[dep.name] = dep;
}
}
find(name: string): YarnDependency {
let result = this.data[name];
if (!result) {
throw new Error(`Could not find dependency: ${name}`);
}
return result;
}
};
const reached = new class {
values: YarnDependency[] = [];
add(dep: YarnDependency): boolean {
if (this.values.indexOf(dep) < 0) {
this.values.push(dep);
return true;
}
return false;
}
};
const visit = (name: string) => {
let dep = index.find(name);
if (!reached.add(dep)) {
// already seen -> done
return;
}
for (const child of dep.children) {
visit(child.name);
}
};
packagedDependencies.forEach(visit);
return reached.values;
}
async function getYarnProductionDependencies(cwd: string, packagedDependencies?: string[]): Promise<YarnDependency[]> {
const raw = await new Promise<string>((c, e) => cp.exec('yarn list --prod --json', { cwd, encoding: 'utf8', env: { ...process.env } }, (err, stdout) => err ? e(err) : c(stdout)));
const match = /^{"type":"tree".*$/m.exec(raw);
if (!match || match.length !== 1) {
throw new Error('Could not parse result of `yarn list --json`');
}
const usingPackagedDependencies = Array.isArray(packagedDependencies);
const trees = JSON.parse(match[0]).data.trees as YarnTreeNode[];
let result = trees
.map(tree => asYarnDependency(path.join(cwd, 'node_modules'), tree, !usingPackagedDependencies))
.filter(dep => !!dep);
if (usingPackagedDependencies) {
result = selectYarnDependencies(result, packagedDependencies);
}
return result;
}
async function getYarnDependencies(cwd: string, packagedDependencies?: string[]): Promise<string[]> {
const result: string[] = [cwd];
if (await new Promise(c => fs.exists(path.join(cwd, 'yarn.lock'), c))) {
const deps = await getYarnProductionDependencies(cwd, packagedDependencies);
const flatten = (dep: YarnDependency) => { result.push(dep.path); dep.children.forEach(flatten); };
deps.forEach(flatten);
}
return _.uniq(result);
}
export function getDependencies(cwd: string, useYarn = false, packagedDependencies?: string[]): Promise<string[]> {
return useYarn ? getYarnDependencies(cwd, packagedDependencies) : getNpmDependencies(cwd);
}
export function getLatestVersion(name: string, cancellationToken?: CancellationToken): Promise<string> {
return checkNPM(cancellationToken)
.then(() => exec(`npm show ${name} version`, {}, cancellationToken))
.then(parseStdout);
}