forked from jupyterlab/jupyterlab
/
ensure-package.ts
236 lines (210 loc) · 6.38 KB
/
ensure-package.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
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
/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import * as fs from 'fs-extra';
import * as glob from 'glob';
import * as path from 'path';
import * as ts from 'typescript';
import { getDependency } from './get-dependency';
import * as utils from './utils';
/**
* Ensure the integrity of a package.
*
* @param options - The options used to ensure the package.
*
* @returns A list of changes that were made to ensure the package.
*/
export async function ensurePackage(
options: IEnsurePackageOptions
): Promise<string[]> {
let { data, pkgPath } = options;
let deps: { [key: string]: string } = data.dependencies || {};
let devDeps: { [key: string]: string } = data.devDependencies || {};
let seenDeps = options.depCache || {};
let missing = options.missing || [];
let unused = options.unused || [];
let messages: string[] = [];
let locals = options.locals || {};
// Verify dependencies are consistent.
let promises = Object.keys(deps).map(async name => {
if (!(name in seenDeps)) {
seenDeps[name] = await getDependency(name);
}
if (deps[name] !== seenDeps[name]) {
messages.push(`Updated dependency: ${name}@${seenDeps[name]}`);
}
deps[name] = seenDeps[name];
});
await Promise.all(promises);
// Verify devDependencies are consistent.
promises = Object.keys(devDeps).map(async name => {
if (!(name in seenDeps)) {
seenDeps[name] = await getDependency(name);
}
if (devDeps[name] !== seenDeps[name]) {
messages.push(`Updated devDependency: ${name}@${seenDeps[name]}`);
}
devDeps[name] = seenDeps[name];
});
await Promise.all(promises);
// For TypeScript files, verify imports match dependencies.
let filenames: string[] = [];
filenames = glob.sync(path.join(pkgPath, 'src/*.ts*'));
filenames = filenames.concat(glob.sync(path.join(pkgPath, 'src/**/*.ts*')));
if (!fs.existsSync(path.join(pkgPath, 'src', 'tsconfig.json'))) {
if (utils.writePackageData(path.join(pkgPath, 'package.json'), data)) {
messages.push('Updated package.json');
}
return messages;
}
let imports: string[] = [];
// Extract all of the imports from the TypeScript files.
filenames.forEach(fileName => {
let sourceFile = ts.createSourceFile(
fileName,
fs.readFileSync(fileName).toString(),
(ts.ScriptTarget as any).ES6,
/*setParentNodes */ true
);
imports = imports.concat(getImports(sourceFile));
});
let names: string[] = Array.from(new Set(imports)).sort();
names = names.map(function(name) {
let parts = name.split('/');
if (name.indexOf('@') === 0) {
return parts[0] + '/' + parts[1];
}
return parts[0];
});
// Look for imports with no dependencies.
promises = names.map(async name => {
if (missing.indexOf(name) !== -1) {
return;
}
if (name === '.' || name === '..') {
return;
}
if (!deps[name]) {
if (!(name in seenDeps)) {
seenDeps[name] = await getDependency(name);
}
deps[name] = seenDeps[name];
messages.push(`Added dependency: ${name}@${seenDeps[name]}`);
}
});
await Promise.all(promises);
// Look for unused packages
Object.keys(deps).forEach(name => {
if (options.noUnused === false) {
return;
}
if (unused.indexOf(name) !== -1) {
return;
}
if (names.indexOf(name) === -1) {
let version = data.dependencies[name];
messages.push(
`Unused dependency: ${name}@${version}: remove or add to list of known unused dependencies for this package`
);
}
});
// Handle references.
let references: { [key: string]: string } = Object.create(null);
Object.keys(deps).forEach(name => {
if (!(name in locals)) {
return;
}
const target = path.join(locals[name], 'src');
if (!fs.existsSync(target)) {
return;
}
let ref = path.relative(path.join(pkgPath, 'src'), locals[name]);
ref = path.join(ref, 'src');
references[name] = ref.split(path.sep).join('/');
});
if (
data.name.indexOf('test-') === -1 &&
data.name.indexOf('example-') === -1 &&
Object.keys(references).length > 0
) {
const tsConfigPath = path.join(pkgPath, 'src', 'tsconfig.json');
const tsConfigData = utils.readJSONFile(tsConfigPath);
tsConfigData.references = [];
Object.keys(references).forEach(name => {
tsConfigData.references.push({ path: references[name] });
});
utils.writeJSONFile(tsConfigPath, tsConfigData);
}
// Ensure dependencies and dev dependencies.
data.dependencies = deps;
data.devDependencies = devDeps;
if (Object.keys(data.dependencies).length === 0) {
delete data.dependencies;
}
if (Object.keys(data.devDependencies).length === 0) {
delete data.devDependencies;
}
if (utils.writePackageData(path.join(pkgPath, 'package.json'), data)) {
messages.push('Updated package.json');
}
return messages;
}
/**
* The options used to ensure a package.
*/
export interface IEnsurePackageOptions {
/**
* The path to the package.
*/
pkgPath: string;
/**
* The package data.
*/
data: any;
/**
* The cache of dependency versions by package.
*/
depCache?: { [key: string]: string };
/**
* A list of dependencies that can be unused.
*/
unused?: string[];
/**
* A list of dependencies that can be missing.
*/
missing?: string[];
/**
* A map of local package names and their relative path.
*/
locals?: { [key: string]: string };
/**
* Whether to enforce that dependencies get used. Default is true.
*/
noUnused?: boolean;
}
/**
* Extract the module imports from a TypeScript source file.
*
* @param sourceFile - The path to the source file.
*
* @returns An array of package names.
*/
function getImports(sourceFile: ts.SourceFile): string[] {
let imports: string[] = [];
handleNode(sourceFile);
function handleNode(node: any): void {
switch (node.kind) {
case ts.SyntaxKind.ImportDeclaration:
imports.push(node.moduleSpecifier.text);
break;
case ts.SyntaxKind.ImportEqualsDeclaration:
imports.push(node.moduleReference.expression.text);
break;
default:
// no-op
}
ts.forEachChild(node, handleNode);
}
return imports;
}