-
Notifications
You must be signed in to change notification settings - Fork 820
/
update-ts-configs.js
308 lines (282 loc) · 8.98 KB
/
update-ts-configs.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
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/*
* Copyright The OpenTelemetry Authors
*
* 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
*
* https://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.
*/
/**
* This script generates per-package tsconfig.*.json from the definition in
* package/package.json.
*
* Specifically,
* 1. If the package.json has fields `main`, `module` and `esnext`, targets
* like ESM and ESNEXT tsconfig.json are generated. Otherwise only one
* default CJS target is generated.
* 2. References in tsconfig.json are generated from the package.json fields
* `dependencies`, `devDependencies` and `peerDependencies`.
*/
const fs = require('fs');
const path = require('path');
const {
getDefaultTsConfig,
getEsmTsConfig,
getEsnextTsConfig,
toPosix
} = require('./update-ts-configs-constants');
const packageJsonDependencyFields = ['dependencies', 'peerDependencies', 'devDependencies'];
const tsConfigMergeKeys = [
'compilerOptions',
'include',
'files',
];
// Make `extends` the first field.
const tsConfigPriorityKeys = ['extends'];
const ignoredLernaProjects = [
'experimental/examples/*',
'experimental/backwards-compatibility/*',
'integration-tests/*',
'selenium-tests',
'examples/otlp-exporter-node',
'examples/opentelemetry-web',
'examples/http',
'examples/https',
'examples/esm-http-ts',
];
let dryRun = false;
const argv = process.argv.slice(2);
while (argv.length) {
switch (argv[0]) {
case '--dry': {
dryRun = true;
}
default: {}
}
argv.shift();
}
main();
function main() {
const pkgRoot = process.cwd();
const projectRoot = findProjectRoot(pkgRoot);
const workspacePackages = resolveWorkspacePackages(projectRoot);
generateTsConfig(projectRoot, workspacePackages, pkgRoot, true);
for (const packageMeta of workspacePackages.values()) {
generateTsConfig(projectRoot, workspacePackages, path.join(projectRoot, packageMeta.dir), false, packageMeta);
}
}
function generateTsConfig(projectRoot, workspacePackages, pkgRoot, isLernaRoot, packageMeta) {
// Root tsconfig.json
if (isLernaRoot) {
writeRootTsConfigJson(pkgRoot, projectRoot, workspacePackages);
return;
}
const otelDependencies = getOtelDependencies(packageMeta.pkgJson);
const dependenciesDir = resolveDependencyDirs(workspacePackages, otelDependencies);
const references = dependenciesDir.map(it => path.relative(pkgRoot, path.join(projectRoot, it))).sort();
if (packageMeta.hasMultiTarget) {
writeMultiTargetTsConfigs(pkgRoot, projectRoot, references);
return;
}
writeSingleTargetTsConfig(pkgRoot, projectRoot, references);
}
function writeRootTsConfigJson(pkgRoot, projectRoot, workspacePackages) {
const tsconfigPath = path.join(pkgRoot, 'tsconfig.json');
const tsconfig = readJSON(tsconfigPath);
const references = Array.from(workspacePackages.values())
.filter(it => it.isTsProject)
.map(it => toPosix(path.relative(pkgRoot, path.join(projectRoot, it.dir)))).sort();
tsconfig.references = references.map(path => {
return { path: toPosix(path) }
});
tsconfig.typedocOptions.entryPoints = Array.from(workspacePackages.values())
.filter(it => !it.private && it.isTsProject)
.map(it => toPosix(path.relative(pkgRoot, path.join(projectRoot, it.dir)))).sort();
writeJSON(tsconfigPath, tsconfig, dryRun);
for (const tsconfigName of ['tsconfig.esm.json', 'tsconfig.esnext.json']) {
const tsconfigPath = path.join(pkgRoot, tsconfigName);
const tsconfig = readJSON(tsconfigPath);
const references = Array.from(workspacePackages.values())
.filter(it => it.isTsProject && it.hasMultiTarget)
.map(it => toPosix(path.relative(pkgRoot, path.join(projectRoot, it.dir)))).sort();
tsconfig.references = references.map(pkgPath => {
return { path: toPosix(path.join(pkgPath, tsconfigName)), }
});
writeJSON(tsconfigPath, tsconfig, dryRun);
}
}
function writeMultiTargetTsConfigs(pkgRoot, projectRoot, references) {
const pairs = [
['tsconfig.json', getDefaultTsConfig],
['tsconfig.esm.json', getEsmTsConfig],
['tsconfig.esnext.json', getEsnextTsConfig]
];
for (const [tsconfigName, getTsConfig] of pairs) {
const tsconfigPath = path.join(pkgRoot, tsconfigName);
let tsconfig = getTsConfig(pkgRoot, projectRoot);
tsconfig.references = references.map(path => {
return { path: toPosix(path) };
});
tsconfig = readAndMaybeMergeTsConfig(tsconfigPath, tsconfig);
writeJSON(tsconfigPath, tsconfig, dryRun);
}
}
function writeSingleTargetTsConfig(pkgRoot, projectRoot, references) {
const tsconfigPath = path.join(pkgRoot, 'tsconfig.json');
let tsconfig = getDefaultTsConfig(pkgRoot, projectRoot);
tsconfig.references = references.map(path => {
return { path: toPosix(path) }
});
tsconfig = readAndMaybeMergeTsConfig(tsconfigPath, tsconfig);
writeJSON(tsconfigPath, tsconfig, dryRun);
}
function findProjectRoot(pkgRoot) {
let dir;
let parent = pkgRoot;
do {
dir = parent;
try {
const stat = fs.statSync(path.join(dir, 'lerna.json'));
if (stat.isFile()) {
return dir;
}
} catch (e) {
/* ignore */
}
parent = path.dirname(dir);
} while (dir !== parent)
}
function getOtelDependencies(packageJson) {
const deps = new Set();
for (const type of packageJsonDependencyFields) {
if (packageJson[type] == null) {
continue;
}
Object.keys(packageJson[type]).filter(it => it.startsWith('@opentelemetry'))
.forEach(it => deps.add(it))
}
return Array.from(deps.values());
}
function resolveWorkspacePackages(projectRoot) {
const map = new Map();
const packageJson = readJSON(`${projectRoot}/package.json`);
for (const pkgDefinition of packageJson.workspaces) {
if (ignoredLernaProjects.includes(pkgDefinition)) {
continue;
}
if (pkgDefinition.endsWith('*')) {
const relDir = path.dirname(pkgDefinition)
const pkgs = fs.readdirSync(path.join(projectRoot, relDir)).filter(it => !it.startsWith('.'));
for (const pkg of pkgs) {
const pkgDir = path.join(relDir, pkg);
const meta = resolvePackageMeta(path.join(projectRoot, pkgDir));
if (meta == null) {
continue;
}
map.set(meta.name, {
...meta,
dir: pkgDir,
});
}
} else {
const meta = resolvePackageMeta(path.join(projectRoot, pkgDefinition));
if (meta == null) {
continue;
}
map.set(meta.name, {
...meta,
dir: pkgDefinition,
});
}
}
return map;
}
function resolveDependencyDirs(lernaProjectMap, deps) {
const results = [];
for (const dep of deps) {
const meta = lernaProjectMap.get(dep);
if (meta == null) {
continue;
}
results.push(meta.dir);
}
return results;
}
function resolvePackageMeta(pkgDir) {
try {
const pkgJson = readJSON(path.join(pkgDir, 'package.json'));
let isTsProject = false;
try {
isTsProject = fs.statSync(path.join(pkgDir, 'tsconfig.json')).isFile()
} catch {/** ignore */}
return {
name: pkgJson.name,
private: pkgJson.private,
isTsProject,
hasMultiTarget: hasEsTargets(pkgJson),
pkgJson,
};
} catch (e) {
return null
}
}
function readAndMaybeMergeTsConfig(tsconfigPath, updates) {
const tsconfig = readJSON(tsconfigPath);
updates = mergeTsConfig(tsconfig, updates);
return updates;
}
function mergeTsConfig(existing, updates) {
for (const key of tsConfigMergeKeys) {
const value = existing[key];
if (value === undefined) {
continue;
}
if (updates[key] === undefined) {
updates[key] = value;
continue;
}
if (Array.isArray(value)) {
updates[key] = Array.from(new Set([...value, ...updates[key]]));
} else {
updates[key] = sortObjectKeys({ ...updates[key], ...value });
}
}
// Make `extends` the first field.
updates = sortObjectKeys(updates, tsConfigPriorityKeys);
return updates;
}
function hasEsTargets(pjson) {
return typeof pjson.module === 'string';
}
function readJSON(filepath) {
const fileContent = fs.readFileSync(filepath, 'utf8');
try {
return JSON.parse(fileContent);
} catch (e) {
throw new Error(`Invalid JSON ${filepath}: ${e.message}`);
}
}
function writeJSON(filepath, content, dry) {
const text = JSON.stringify(content, null, 2);
if (dry) {
console.log(text);
} else {
fs.writeFileSync(filepath, text + '\n', 'utf8');
}
}
function sortObjectKeys(obj, priorityKeys = []) {
let keys = Object.keys(obj).sort();
keys = Array.from(new Set([...priorityKeys, ...keys]));
const ret = {};
keys.forEach(key => {
ret[key] = obj[key];
});
return ret;
}