/
validate-build.ts
402 lines (360 loc) · 12.3 KB
/
validate-build.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import fs from 'fs-extra';
import { dirname, join, relative } from 'path';
import { rollup } from 'rollup';
import ts from 'typescript';
import { BuildOptions, getOptions } from '../utils/options';
import { PackageData } from '../utils/write-pkg-json';
/**
* Used to triple check that the final build files
* ready to be published are good to go
*/
const pkgs: TestPackage[] = [
{
// cli
packageJson: 'cli/package.json',
},
{
// compiler
packageJson: 'compiler/package.json',
files: ['compiler/lib.d.ts', 'compiler/lib.dom.d.ts'],
},
{
// dev-server
packageJson: 'dev-server/package.json',
files: [
'dev-server/static/favicon.ico',
'dev-server/templates/directory-index.html',
'dev-server/templates/initial-load.html',
'dev-server/connector.html',
'dev-server/open-in-editor-api.js',
'dev-server/server-process.js',
'dev-server/server-worker-thread.js',
'dev-server/visualstudio.vbs',
'dev-server/ws.js',
'dev-server/xdg-open',
],
},
{
// internal/app-data
packageJson: 'internal/app-data/package.json',
},
{
// internal/client
packageJson: 'internal/client/package.json',
files: ['internal/client/polyfills/'],
},
{
// internal/hydrate
packageJson: 'internal/hydrate/package.json',
files: ['internal/hydrate/runner.d.ts', 'internal/hydrate/runner.js'],
},
{
// internal/testing
packageJson: 'internal/testing/package.json',
},
{
// internal
packageJson: 'internal/package.json',
files: [
'internal/stencil-core/index.cjs',
'internal/stencil-core/index.js',
'internal/stencil-core/index.d.ts',
'internal/stencil-ext-modules.d.ts',
'internal/stencil-private.d.ts',
'internal/stencil-public-compiler.d.ts',
'internal/stencil-public-docs.d.ts',
'internal/stencil-public-runtime.d.ts',
],
},
{
// mock-doc
packageJson: 'mock-doc/package.json',
},
{
// screenshot
packageJson: 'screenshot/package.json',
files: [
'screenshot/compare/',
'screenshot/connector.js',
'screenshot/local-connector.js',
'screenshot/pixel-match.js',
],
},
{
// sys/node
packageJson: 'sys/node/package.json',
files: ['sys/node/autoprefixer.js', 'sys/node/graceful-fs.js', 'sys/node/node-fetch.js'],
},
{
// testing
packageJson: 'testing/package.json',
files: [
'testing/jest-environment.js',
'testing/jest-preprocessor.js',
'testing/jest-preset.js',
'testing/jest-runner.js',
'testing/jest-setuptestframework.js',
],
},
{
// @stencil/core
packageJson: 'package.json',
packageJsonFiles: [
'bin/',
'cli/',
'compiler/',
'dev-server/',
'internal/',
'mock-doc/',
'screenshot/',
'sys/',
'testing/',
],
files: ['CHANGELOG.md', 'LICENSE.md', 'readme.md'],
hasBin: true,
},
];
/**
*
* @param rootDir the root of the Stencil repository
*/
export async function validateBuild(rootDir: string): Promise<void> {
const dtsEntries: string[] = [];
const opts = getOptions(rootDir);
pkgs.forEach((testPkg) => {
validatePackage(opts, testPkg, dtsEntries);
});
console.log(`🐡 Validated packages`);
validateDts(opts, dtsEntries);
await validateCompiler(opts);
await validateTreeshaking(opts);
}
/**
* Validates a bundled package/sub-module. Validation steps include verifying that various fields in `package.json` are
* filled out and file references are valid.
* @param opts build options to be used to validate a package
* @param testPkg the package to validate
* @param dtsEntries a reference to .d.ts files to collect while validating the package
*/
function validatePackage(opts: BuildOptions, testPkg: TestPackage, dtsEntries: string[]): void {
const rootDir = opts.rootDir;
if (testPkg.packageJson) {
testPkg.packageJson = join(rootDir, testPkg.packageJson);
const pkgDir = dirname(testPkg.packageJson);
const pkgJson: PackageData = require(testPkg.packageJson);
if (!pkgJson.name) {
throw new Error('missing package.json name: ' + testPkg.packageJson);
}
if (!pkgJson.main) {
throw new Error('missing package.json main: ' + testPkg.packageJson);
}
if (testPkg.packageJsonFiles) {
if (!Array.isArray(pkgJson.files)) {
throw new Error(testPkg.packageJson + ' missing "files" property');
}
pkgJson.files.forEach((f) => {
if (f === '!**/*.map' || f === '!**/*.stub.ts' || f === '!**/*.stub.tsx') {
// skip sourcemaps, stub files
return;
}
const pkgFile = join(pkgDir, f);
fs.accessSync(pkgFile);
});
testPkg.packageJsonFiles.forEach((testPkgFile) => {
if (!pkgJson.files.includes(testPkgFile)) {
throw new Error(testPkg.packageJson + ' missing file ' + testPkgFile);
}
const filePath = join(pkgDir, testPkgFile);
fs.accessSync(filePath);
});
}
if (testPkg.hasBin && !pkgJson.bin) {
throw new Error(testPkg.packageJson + ' missing bin');
}
if (pkgJson.bin) {
Object.keys(pkgJson.bin).forEach((k) => {
const binExe = join(pkgDir, pkgJson.bin[k]);
fs.accessSync(binExe);
});
}
const mainIndex = join(pkgDir, pkgJson.main);
fs.accessSync(mainIndex);
if (pkgJson.module) {
const moduleIndex = join(pkgDir, pkgJson.module);
fs.accessSync(moduleIndex);
}
if (pkgJson.browser) {
const browserIndex = join(pkgDir, pkgJson.browser);
fs.accessSync(browserIndex);
}
if (pkgJson.types) {
const pkgTypes = join(pkgDir, pkgJson.types);
fs.accessSync(pkgTypes);
dtsEntries.push(pkgTypes);
}
}
if (testPkg.files) {
testPkg.files.forEach((file) => {
const filePath = join(rootDir, file);
fs.statSync(filePath);
});
}
}
/**
* Validate the the .d.ts files used in the output are semantically and syntactically correct
* @param opts build options to be used to validate .d.ts files
* @param dtsEntries the .d.ts files to validate
*/
function validateDts(opts: BuildOptions, dtsEntries: string[]): void {
const program = ts.createProgram(dtsEntries, {
baseUrl: '.',
paths: {
'@stencil/core/mock-doc': [join(opts.rootDir, 'mock-doc', 'index.d.ts')],
'@stencil/core/internal': [join(opts.rootDir, 'internal', 'index.d.ts')],
'@stencil/core/internal/testing': [join(opts.rootDir, 'internal', 'testing', 'index.d.ts')],
},
});
const tsDiagnostics = program.getSemanticDiagnostics().concat(program.getSyntacticDiagnostics());
if (tsDiagnostics.length > 0) {
const host = {
getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
getNewLine: () => ts.sys.newLine,
getCanonicalFileName: (f: string) => f,
};
throw new Error('🧨 ' + ts.formatDiagnostics(tsDiagnostics, host));
}
console.log(`🐟 Validated dts files`);
}
/**
* Validates the Stencil compiler. This includes verifying that the compiler, CLI and sys API can be instantiated,
* smoke testing the compiler's transpilation, and running a small task in the CLI.
* @param opts build options to be used to validate the compiler
*/
async function validateCompiler(opts: BuildOptions): Promise<void> {
const compilerPath = join(opts.output.compilerDir, 'stencil.js');
const cliPath = join(opts.output.cliDir, 'index.cjs');
const sysNodePath = join(opts.output.sysNodeDir, 'index.js');
const compiler = await import(compilerPath);
const cli = await import(cliPath);
const sysNodeApi = await import(sysNodePath);
const nodeLogger = sysNodeApi.createNodeLogger({ process });
const nodeSys = sysNodeApi.createNodeSys({ process });
if (!nodeSys || nodeSys.name !== 'node' || nodeSys.version.length < 4) {
throw new Error(`🧨 unable to validate sys node`);
}
console.log(`🐳 Validated sys node, current ${nodeSys.name} version: ${nodeSys.version}`);
const validated = await compiler.loadConfig({
config: {
logger: nodeLogger,
sys: nodeSys,
},
});
console.log(`${compiler.vermoji} Validated compiler: ${compiler.version}`);
const transpileResults = compiler.transpileSync('const m: string = `transpile!`;', {
target: 'es5',
});
if (
!transpileResults ||
transpileResults.diagnostics.length > 0 ||
!transpileResults.code.startsWith(`var m = "transpile!";`)
) {
console.error(transpileResults);
throw new Error(`🧨 transpileSync error`);
}
console.log(`🐋 Validated compiler.transpileSync()`);
const orgConsoleLog = console.log;
let loggedVersion = null;
console.log = (value: string) => (loggedVersion = value);
// this runTask is intentionally not wrapped in telemetry helpers
await cli.runTask(compiler, validated.config, 'version');
console.log = orgConsoleLog;
if (typeof loggedVersion !== 'string' || loggedVersion.length < 4) {
throw new Error(`🧨 unable to validate compiler. loggedVersion: "${loggedVersion}"`);
}
console.log(`🐬 Validated cli`);
}
/**
* Validate tree shaking for various modules in the output
* @param opts build options to be used to validate treeshaking
*/
async function validateTreeshaking(opts: BuildOptions) {
await validateModuleTreeshake(opts, 'app-data', join(opts.output.internalDir, 'app-data', 'index.js'));
await validateModuleTreeshake(opts, 'client', join(opts.output.internalDir, 'client', 'index.js'));
await validateModuleTreeshake(opts, 'patch-browser', join(opts.output.internalDir, 'client', 'patch-browser.js'));
await validateModuleTreeshake(opts, 'patch-esm', join(opts.output.internalDir, 'client', 'patch-esm.js'));
await validateModuleTreeshake(opts, 'shadow-css', join(opts.output.internalDir, 'client', 'shadow-css.js'));
await validateModuleTreeshake(opts, 'hydrate', join(opts.output.internalDir, 'hydrate', 'index.js'));
await validateModuleTreeshake(opts, 'stencil-core', join(opts.output.internalDir, 'stencil-core', 'index.js'));
await validateModuleTreeshake(opts, 'cli', join(opts.output.cliDir, 'index.js'));
}
/**
* Validates treeshaking for a single module & entrypoint
* @param opts build options to be used to validate treeshaking for a specific module
* @param moduleName the module to validate
* @param entryModulePath the entrypoint to validate
*/
async function validateModuleTreeshake(opts: BuildOptions, moduleName: string, entryModulePath: string): Promise<void> {
// this is a song, 'agadoo' by Black Lace
const virtualInputId = `@g@doo`;
const entryId = `@entry-module`;
const outputFile = join(opts.scriptsBuildDir, `treeshake_${moduleName}.js`);
const bundle = await rollup({
input: virtualInputId,
treeshake: 'smallest',
plugins: [
{
name: 'stencilResolver',
resolveId(id) {
if (id === '@stencil/core/internal/client' || id === '@stencil/core') {
return join(opts.output.internalDir, 'client', 'index.js');
}
if (id === '@stencil/core/internal/app-data') {
return join(opts.output.internalDir, 'app-data', 'index.js');
}
if (id === '@stencil/core/internal/app-globals') {
return id;
}
if (id === virtualInputId) {
return id;
}
if (id === entryId) {
return entryModulePath;
}
},
load(id) {
if (id === '@stencil/core/internal/app-globals') {
return 'export const globalScripts = () => {};';
}
if (id === virtualInputId) {
return `import "${entryId}";`;
}
},
},
],
onwarn(warning) {
if (warning.code !== 'EMPTY_BUNDLE') {
throw warning;
}
},
});
const o = await bundle.generate({
format: 'es',
});
const output = o.output[0];
const outputCode = output.code.trim();
await fs.writeFile(outputFile, outputCode);
if (outputCode !== '') {
console.error(`\nTreeshake output: ${outputFile}\n`);
throw new Error(`🧨 Not all code was not treeshaken (treeshooken? treeshaked?)`);
}
console.log(`🌳 validated treeshake: ${relative(opts.rootDir, entryModulePath)}`);
}
/**
* Represents a package/submodule of the bundled Stencil output to validate
*/
interface TestPackage {
packageJson?: string;
packageJsonFiles?: string[];
files?: string[];
hasBin?: boolean;
}