forked from jestjs/jest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbundleTs.mjs
236 lines (199 loc) · 5.92 KB
/
bundleTs.mjs
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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {createRequire} from 'module';
import * as path from 'path';
import {fileURLToPath} from 'url';
import {
CompilerState,
Extractor,
ExtractorConfig,
} from '@microsoft/api-extractor';
import chalk from 'chalk';
import {ESLint} from 'eslint';
import {glob} from 'glob';
import fs from 'graceful-fs';
import pkgDir from 'pkg-dir';
import {rimraf} from 'rimraf';
import {copyrightSnippet, getPackagesWithTsConfig} from './buildUtils.mjs';
const require = createRequire(import.meta.url);
const typescriptCompilerFolder = await pkgDir(require.resolve('typescript'));
const typesNodeReferenceDirective = '/// <reference types="node" />';
const excludedPackages = new Set(['@jest/globals', '@jest/test-globals']);
const packagesToBundle = getPackagesWithTsConfig().filter(
p => !excludedPackages.has(p.pkg.name),
);
console.log(chalk.inverse(' Extracting TypeScript definition files '));
const sharedExtractorConfig = {
$schema:
'https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json',
apiReport: {
enabled: false,
},
/**
* A list of NPM package names whose exports should be treated as part of this package.
*/
bundledPackages: [],
compiler: {
skipLibCheck: true,
},
docModel: {
enabled: false,
},
dtsRollup: {
enabled: true,
untrimmedFilePath: '<projectFolder>/dist/index.d.ts',
},
messages: {
compilerMessageReporting: {
default: {
logLevel: 'warning',
},
},
extractorMessageReporting: {
'ae-forgotten-export': {
logLevel: 'none',
},
'ae-missing-release-tag': {
logLevel: 'none',
},
default: {
logLevel: 'warning',
},
},
tsdocMessageReporting: {
default: {
logLevel: 'none',
},
},
},
tsdocMetadata: {
enabled: false,
},
};
await fs.promises.writeFile(
path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../api-extractor.json',
),
JSON.stringify(sharedExtractorConfig, null, 2),
);
const eslint = new ESLint({
cwd: process.cwd(),
fix: true,
overrideConfig: {
rules: {
// `d.ts` files are by nature `type` only imports, so it's just noise when looking at the file
'@typescript-eslint/consistent-type-imports': [
'error',
{prefer: 'no-type-imports'},
],
},
},
});
let compilerState;
await Promise.all(
packagesToBundle.map(async ({packageDir, pkg}) => {
const configFile = path.resolve(packageDir, 'api-extractor.json');
await fs.promises.writeFile(
configFile,
JSON.stringify(
{
extends: '../../api-extractor.json',
mainEntryPointFilePath: path.resolve(packageDir, pkg.types),
projectFolder: packageDir,
},
null,
2,
),
);
const extractorConfig = ExtractorConfig.loadFileAndPrepare(configFile);
if (!compilerState) {
compilerState = CompilerState.create(extractorConfig, {
additionalEntryPoints: packagesToBundle.map(({pkg, packageDir}) =>
path.resolve(packageDir, pkg.types),
),
typescriptCompilerFolder,
});
}
const extractorResult = Extractor.invoke(extractorConfig, {
compilerState,
localBuild: true,
showVerboseMessages: true,
typescriptCompilerFolder,
});
if (!extractorResult.succeeded || extractorResult.warningCount > 0) {
console.error(
chalk.inverse.red(' Unable to extract TypeScript definition files '),
);
throw new Error(
`API Extractor completed with ${extractorResult.errorCount} errors and ${extractorResult.warningCount} warnings`,
);
}
const filepath = extractorResult.extractorConfig.untrimmedFilePath;
let definitionFile = await fs.promises.readFile(filepath, 'utf8');
await rimraf(path.resolve(packageDir, 'build/**/*.d.ts'), {glob: true});
await fs.promises.rm(path.resolve(packageDir, 'dist/'), {
force: true,
recursive: true,
});
// this is invalid now, so remove it to not confuse `tsc`
await fs.promises.rm(path.resolve(packageDir, 'tsconfig.tsbuildinfo'), {
force: true,
recursive: true,
});
const dirsInBuild = await glob('**/', {
cwd: path.resolve(packageDir, 'build'),
});
await Promise.all(
dirsInBuild
.filter(dir => dir !== '.')
// reverse to delete deep directories first
.reverse()
.map(async dir => {
const dirToDelete = path.resolve(packageDir, 'build', dir);
try {
await fs.promises.rmdir(dirToDelete);
} catch (error) {
// e.g. `jest-jasmine2/build/jasmine` is not empty - ignore those errors
if (error.code !== 'ENOTEMPTY') {
throw error;
}
}
}),
);
definitionFile = definitionFile.replaceAll('\r\n', '\n');
const hasNodeTypesReference = definitionFile.includes(
typesNodeReferenceDirective,
);
if (hasNodeTypesReference) {
definitionFile = [
typesNodeReferenceDirective,
...definitionFile.split(typesNodeReferenceDirective),
].join('\n');
}
definitionFile = [
copyrightSnippet,
'',
...definitionFile.split(copyrightSnippet),
].join('\n');
const [lintResult] = await eslint.lintText(definitionFile, {
filePath: 'some-file.ts',
});
// if the autofixer did anything, the result is in `output`
const formattedContent = lintResult.output || definitionFile;
await fs.promises.writeFile(
filepath.replace(
`${path.sep}dist${path.sep}`,
`${path.sep}build${path.sep}`,
),
formattedContent,
);
}),
);
console.log(
chalk.inverse.green(' Successfully extracted TypeScript definition files '),
);