optimize.ts 8.5 KB
Newer Older
I
isidor 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

J
Joao Moreno 已提交
6 7
'use strict';

8
import * as es from 'event-stream';
9
import * as gulp from 'gulp';
10 11
import * as concat from 'gulp-concat';
import * as filter from 'gulp-filter';
A
Alex Dima 已提交
12 13
import * as fancyLog from 'fancy-log';
import * as ansiColors from 'ansi-colors';
14 15
import * as path from 'path';
import * as pump from 'pump';
16 17
import * as VinylFile from 'vinyl';
import * as bundle from './bundle';
18 19
import { Language, processNlsFiles } from './i18n';
import { createStatsStream } from './stats';
20
import * as util from './util';
21

22 23
const REPO_ROOT_PATH = path.join(__dirname, '../..');

24
function log(prefix: string, message: string): void {
A
Alex Dima 已提交
25
	fancyLog(ansiColors.cyan('[' + prefix + ']'), message);
26
}
D
Dirk Baeumer 已提交
27

28
export function loaderConfig() {
M
Matt Bierner 已提交
29
	const result: any = {
I
isidor 已提交
30 31
		paths: {
			'vs': 'out-build/vs',
J
Joao Moreno 已提交
32
			'vscode': 'empty:'
I
isidor 已提交
33
		},
34
		amdModulesPattern: /^vs\//
I
isidor 已提交
35 36
	};

B
Benjamin Pasero 已提交
37 38
	result['vs/css'] = { inlineResources: true };

I
isidor 已提交
39
	return result;
40
}
I
isidor 已提交
41

J
Joao Moreno 已提交
42
const IS_OUR_COPYRIGHT_REGEXP = /Copyright \(C\) Microsoft Corporation/i;
I
isidor 已提交
43

44
function loader(src: string, bundledFileHeader: string, bundleLoader: boolean): NodeJS.ReadWriteStream {
A
Alex Dima 已提交
45
	let sources = [
46
		`${src}/vs/loader.js`
A
Alex Dima 已提交
47 48 49
	];
	if (bundleLoader) {
		sources = sources.concat([
50 51
			`${src}/vs/css.js`,
			`${src}/vs/nls.js`
A
Alex Dima 已提交
52 53 54
		]);
	}

J
Joao Moreno 已提交
55
	let isFirst = true;
A
Alex Dima 已提交
56 57
	return (
		gulp
58
			.src(sources, { base: `${src}` })
59 60 61 62 63
			.pipe(es.through(function (data) {
				if (isFirst) {
					isFirst = false;
					this.emit('data', new VinylFile({
						path: 'fake',
64
						base: '.',
65
						contents: Buffer.from(bundledFileHeader)
66 67 68 69 70 71 72
					}));
					this.emit('data', data);
				} else {
					this.emit('data', data);
				}
			}))
			.pipe(concat('vs/loader.js'))
A
Alex Dima 已提交
73
	);
I
isidor 已提交
74 75
}

76
function toConcatStream(src: string, bundledFileHeader: string, sources: bundle.IFile[], dest: string, fileContentMapper: (contents: string, path: string) => string): NodeJS.ReadWriteStream {
J
Joao Moreno 已提交
77
	const useSourcemaps = /\.js$/.test(dest) && !/\.nls\.js$/.test(dest);
I
isidor 已提交
78 79 80

	// If a bundle ends up including in any of the sources our copyright, then
	// insert a fake source at the beginning of each bundle with our copyright
J
Joao Moreno 已提交
81 82 83
	let containsOurCopyright = false;
	for (let i = 0, len = sources.length; i < len; i++) {
		const fileContents = sources[i].contents;
I
isidor 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96
		if (IS_OUR_COPYRIGHT_REGEXP.test(fileContents)) {
			containsOurCopyright = true;
			break;
		}
	}

	if (containsOurCopyright) {
		sources.unshift({
			path: null,
			contents: bundledFileHeader
		});
	}

97
	const treatedSources = sources.map(function (source) {
98
		const root = source.path ? REPO_ROOT_PATH.replace(/\\/g, '/') : '';
99
		const base = source.path ? root + `/${src}` : '.';
100 101
		const path = source.path ? root + '/' + source.path.replace(/\\/g, '/') : 'fake';
		const contents = source.path ? fileContentMapper(source.contents, path) : source.contents;
I
isidor 已提交
102

103
		return new VinylFile({
104
			path: path,
I
isidor 已提交
105
			base: base,
106
			contents: Buffer.from(contents)
I
isidor 已提交
107 108 109 110 111
		});
	});

	return es.readArray(treatedSources)
		.pipe(useSourcemaps ? util.loadSourcemaps() : es.through())
112
		.pipe(concat(dest))
113
		.pipe(createStatsStream(dest));
I
isidor 已提交
114 115
}

116
function toBundleStream(src: string, bundledFileHeader: string, bundles: bundle.IConcatFile[], fileContentMapper: (contents: string, path: string) => string): NodeJS.ReadWriteStream {
117
	return es.merge(bundles.map(function (bundle) {
118
		return toConcatStream(src, bundledFileHeader, bundle.sources, bundle.dest, fileContentMapper);
I
isidor 已提交
119 120 121
	}));
}

122
export interface IOptimizeTaskOpts {
123 124 125 126
	/**
	 * The folder to read files from.
	 */
	src: string;
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
	/**
	 * (for AMD files, will get bundled and get Copyright treatment)
	 */
	entryPoints: bundle.IEntryPoint[];
	/**
	 * (svg, etc.)
	 */
	resources: string[];
	loaderConfig: any;
	/**
	 * (true by default - append css and nls to loader)
	 */
	bundleLoader?: boolean;
	/**
	 * (basically the Copyright treatment)
	 */
B
Benjamin Pasero 已提交
143
	header?: string;
144 145 146 147 148 149 150 151
	/**
	 * (emit bundleInfo.json file)
	 */
	bundleInfo: boolean;
	/**
	 * (out folder name)
	 */
	out: string;
152 153 154 155
	/**
	 * (out folder name)
	 */
	languages?: Language[];
156 157 158 159 160 161
	/**
	 * File contents interceptor
	 * @param contents The contens of the file
	 * @param path The absolute file path, always using `/`, even on Windows
	 */
	fileContentMapper?: (contents: string, path: string) => string;
162
}
163

B
Benjamin Pasero 已提交
164 165 166 167 168 169
const DEFAULT_FILE_HEADER = [
	'/*!--------------------------------------------------------',
	' * Copyright (C) Microsoft Corporation. All rights reserved.',
	' *--------------------------------------------------------*/'
].join('\n');

170
export function optimizeTask(opts: IOptimizeTaskOpts): () => NodeJS.ReadWriteStream {
171
	const src = opts.src;
J
Joao Moreno 已提交
172 173 174
	const entryPoints = opts.entryPoints;
	const resources = opts.resources;
	const loaderConfig = opts.loaderConfig;
B
Benjamin Pasero 已提交
175
	const bundledFileHeader = opts.header || DEFAULT_FILE_HEADER;
A
Alex Dima 已提交
176
	const bundleLoader = (typeof opts.bundleLoader === 'undefined' ? true : opts.bundleLoader);
J
Joao Moreno 已提交
177
	const out = opts.out;
178
	const fileContentMapper = opts.fileContentMapper || ((contents: string, _path: string) => contents);
I
isidor 已提交
179

180
	return function () {
J
João Moreno 已提交
181
		const sourcemaps = require('gulp-sourcemaps') as typeof import('gulp-sourcemaps');
182

J
Joao Moreno 已提交
183 184 185
		const bundlesStream = es.through(); // this stream will contain the bundled files
		const resourcesStream = es.through(); // this stream will contain the resources
		const bundleInfoStream = es.through(); // this stream will contain bundleInfo.json
I
isidor 已提交
186

187
		bundle.bundle(entryPoints, loaderConfig, function (err, result) {
188
			if (err || !result) { return bundlesStream.emit('error', JSON.stringify(err)); }
I
isidor 已提交
189

190
			toBundleStream(src, bundledFileHeader, result.files, fileContentMapper).pipe(bundlesStream);
191 192

			// Remove css inlined resources
J
Joao Moreno 已提交
193
			const filteredResources = resources.slice();
194
			result.cssInlinedResources.forEach(function (resource) {
J
Joao Moreno 已提交
195 196 197
				if (process.env['VSCODE_BUILD_VERBOSE']) {
					log('optimizer', 'excluding inlined: ' + resource);
				}
198 199
				filteredResources.push('!' + resource);
			});
A
Alex Dima 已提交
200
			gulp.src(filteredResources, { base: `${src}`, allowEmpty: true }).pipe(resourcesStream);
201

202
			const bundleInfoArray: VinylFile[] = [];
203
			if (opts.bundleInfo) {
204
				bundleInfoArray.push(new VinylFile({
205 206
					path: 'bundleInfo.json',
					base: '.',
207
					contents: Buffer.from(JSON.stringify(result.bundleData, null, '\t'))
208 209 210
				}));
			}
			es.readArray(bundleInfoArray).pipe(bundleInfoStream);
I
isidor 已提交
211 212
		});

J
Joao Moreno 已提交
213
		const result = es.merge(
214
			loader(src, bundledFileHeader, bundleLoader),
I
isidor 已提交
215
			bundlesStream,
216 217
			resourcesStream,
			bundleInfoStream
I
isidor 已提交
218 219 220 221
		);

		return result
			.pipe(sourcemaps.write('./', {
222
				sourceRoot: undefined,
I
isidor 已提交
223 224 225
				addComment: true,
				includeContent: true
			}))
226 227 228 229
			.pipe(opts.languages && opts.languages.length ? processNlsFiles({
				fileHeader: bundledFileHeader,
				languages: opts.languages
			}) : es.through())
I
isidor 已提交
230 231
			.pipe(gulp.dest(out));
	};
D
Dirk Baeumer 已提交
232
}
I
isidor 已提交
233

E
Erich Gamma 已提交
234
export function minifyTask(src: string, sourceMapBaseUrl?: string): (cb: any) => void {
J
João Moreno 已提交
235
	const esbuild = require('esbuild') as typeof import('esbuild');
236
	const sourceMappingURL = sourceMapBaseUrl ? ((f: any) => `${sourceMapBaseUrl}/${f.relative}.map`) : undefined;
J
Joao Moreno 已提交
237

238
	return cb => {
J
João Moreno 已提交
239 240
		const minifyCSS = require('gulp-cssnano') as typeof import('gulp-cssnano');
		const sourcemaps = require('gulp-sourcemaps') as typeof import('gulp-sourcemaps');
241

J
Joao Moreno 已提交
242 243
		const jsFilter = filter('**/*.js', { restore: true });
		const cssFilter = filter('**/*.css', { restore: true });
I
isidor 已提交
244

245 246 247 248
		pump(
			gulp.src([src + '/**', '!' + src + '/**/*.map']),
			jsFilter,
			sourcemaps.init({ loadMaps: true }),
J
João Moreno 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
			es.map((f: any, cb) => {
				esbuild.build({
					entryPoints: [f.path],
					minify: true,
					sourcemap: 'external',
					outdir: '.',
					platform: 'node',
					target: ['node12.18'],
					write: false
				}).then(res => {
					const jsFile = res.outputFiles.find(f => /\.js$/.test(f.path))!;
					const sourceMapFile = res.outputFiles.find(f => /\.js\.map$/.test(f.path))!;

					f.contents = Buffer.from(jsFile.contents);
					f.sourceMap = JSON.parse(sourceMapFile.text);

					cb(undefined, f);
				}, cb);
			}),
268 269 270 271
			jsFilter.restore,
			cssFilter,
			minifyCSS({ reduceIdents: false }),
			cssFilter.restore,
R
Rob Lourens 已提交
272 273 274 275 276 277 278
			(<any>sourcemaps).mapSources((sourcePath: string) => {
				if (sourcePath === 'bootstrap-fork.js') {
					return 'bootstrap-fork.orig.js';
				}

				return sourcePath;
			}),
279
			sourcemaps.write('./', {
J
Joao Moreno 已提交
280
				sourceMappingURL,
281
				sourceRoot: undefined,
I
isidor 已提交
282
				includeContent: true,
J
Joao Moreno 已提交
283
				addComment: true
284
			} as any),
J
João Moreno 已提交
285 286
			gulp.dest(src + '-min'),
			(err: any) => cb(err));
I
isidor 已提交
287
	};
D
Dirk Baeumer 已提交
288
}