optimize.ts 9.0 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
import * as concat from 'gulp-concat';
11
import * as minifyCSS from 'gulp-cssnano';
12 13 14
import * as filter from 'gulp-filter';
import * as flatmap from 'gulp-flatmap';
import * as sourcemaps from 'gulp-sourcemaps';
15
import * as uglify from 'gulp-uglify';
J
Joao Moreno 已提交
16
import * as composer from 'gulp-uglify/composer';
A
Alex Dima 已提交
17 18
import * as fancyLog from 'fancy-log';
import * as ansiColors from 'ansi-colors';
19 20 21
import * as path from 'path';
import * as pump from 'pump';
import * as sm from 'source-map';
22
import * as terser from 'terser';
23 24
import * as VinylFile from 'vinyl';
import * as bundle from './bundle';
25 26
import { Language, processNlsFiles } from './i18n';
import { createStatsStream } from './stats';
27
import * as util from './util';
28

29 30
const REPO_ROOT_PATH = path.join(__dirname, '../..');

31
function log(prefix: string, message: string): void {
A
Alex Dima 已提交
32
	fancyLog(ansiColors.cyan('[' + prefix + ']'), message);
33
}
D
Dirk Baeumer 已提交
34

E
Erich Gamma 已提交
35
export function loaderConfig(emptyPaths?: string[]) {
M
Matt Bierner 已提交
36
	const result: any = {
I
isidor 已提交
37 38
		paths: {
			'vs': 'out-build/vs',
J
Joao Moreno 已提交
39
			'vscode': 'empty:'
I
isidor 已提交
40
		},
41
		nodeModules: emptyPaths || []
I
isidor 已提交
42 43
	};

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

I
isidor 已提交
46
	return result;
47
}
I
isidor 已提交
48

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

51 52 53 54
declare class FileSourceMap extends VinylFile {
	public sourceMap: sm.RawSourceMap;
}

55
function loader(src: string, bundledFileHeader: string, bundleLoader: boolean): NodeJS.ReadWriteStream {
A
Alex Dima 已提交
56
	let sources = [
57
		`${src}/vs/loader.js`
A
Alex Dima 已提交
58 59 60
	];
	if (bundleLoader) {
		sources = sources.concat([
61 62
			`${src}/vs/css.js`,
			`${src}/vs/nls.js`
A
Alex Dima 已提交
63 64 65
		]);
	}

J
Joao Moreno 已提交
66
	let isFirst = true;
A
Alex Dima 已提交
67 68
	return (
		gulp
69
			.src(sources, { base: `${src}` })
70 71 72 73 74 75
			.pipe(es.through(function (data) {
				if (isFirst) {
					isFirst = false;
					this.emit('data', new VinylFile({
						path: 'fake',
						base: '',
76
						contents: Buffer.from(bundledFileHeader)
77 78 79 80 81 82 83
					}));
					this.emit('data', data);
				} else {
					this.emit('data', data);
				}
			}))
			.pipe(concat('vs/loader.js'))
A
Alex Dima 已提交
84
	);
I
isidor 已提交
85 86
}

87
function toConcatStream(src: string, bundledFileHeader: string, sources: bundle.IFile[], dest: string): NodeJS.ReadWriteStream {
J
Joao Moreno 已提交
88
	const useSourcemaps = /\.js$/.test(dest) && !/\.nls\.js$/.test(dest);
I
isidor 已提交
89 90 91

	// 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 已提交
92 93 94
	let containsOurCopyright = false;
	for (let i = 0, len = sources.length; i < len; i++) {
		const fileContents = sources[i].contents;
I
isidor 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107
		if (IS_OUR_COPYRIGHT_REGEXP.test(fileContents)) {
			containsOurCopyright = true;
			break;
		}
	}

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

108
	const treatedSources = sources.map(function (source) {
109
		const root = source.path ? REPO_ROOT_PATH.replace(/\\/g, '/') : '';
110
		const base = source.path ? root + `/${src}` : '';
I
isidor 已提交
111

112
		return new VinylFile({
I
isidor 已提交
113 114
			path: source.path ? root + '/' + source.path.replace(/\\/g, '/') : 'fake',
			base: base,
115
			contents: Buffer.from(source.contents)
I
isidor 已提交
116 117 118 119 120
		});
	});

	return es.readArray(treatedSources)
		.pipe(useSourcemaps ? util.loadSourcemaps() : es.through())
121
		.pipe(concat(dest))
122
		.pipe(createStatsStream(dest));
I
isidor 已提交
123 124
}

125
function toBundleStream(src: string, bundledFileHeader: string, bundles: bundle.IConcatFile[]): NodeJS.ReadWriteStream {
126
	return es.merge(bundles.map(function (bundle) {
127
		return toConcatStream(src, bundledFileHeader, bundle.sources, bundle.dest);
I
isidor 已提交
128 129 130
	}));
}

131
export interface IOptimizeTaskOpts {
132 133 134 135
	/**
	 * The folder to read files from.
	 */
	src: string;
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
	/**
	 * (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 已提交
152
	header?: string;
153 154 155 156 157 158 159 160
	/**
	 * (emit bundleInfo.json file)
	 */
	bundleInfo: boolean;
	/**
	 * (out folder name)
	 */
	out: string;
161 162 163 164
	/**
	 * (out folder name)
	 */
	languages?: Language[];
165
}
166

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

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

182
	return function () {
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).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

234 235 236
declare class FileWithCopyright extends VinylFile {
	public __hasOurCopyright: boolean;
}
I
isidor 已提交
237
/**
J
Joao Moreno 已提交
238 239
 * Wrap around uglify and allow the preserveComments function
 * to have a file "context" to include our copyright only once per file.
I
isidor 已提交
240
 */
241 242
function uglifyWithCopyrights(): NodeJS.ReadWriteStream {
	const preserveComments = (f: FileWithCopyright) => {
M
Matt Bierner 已提交
243
		return (_node: any, comment: { value: string; type: string; }) => {
244 245
			const text = comment.value;
			const type = comment.type;
I
isidor 已提交
246

247 248 249
			if (/@minifier_do_not_preserve/.test(text)) {
				return false;
			}
I
isidor 已提交
250

251
			const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
I
isidor 已提交
252

253 254 255 256 257 258
			if (isOurCopyright) {
				if (f.__hasOurCopyright) {
					return false;
				}
				f.__hasOurCopyright = true;
				return true;
I
isidor 已提交
259 260
			}

261 262 263 264 265 266 267 268
			if ('comment2' === type) {
				// check for /*!. Note that text doesn't contain leading /*
				return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
			} else if ('comment1' === type) {
				return /license|copyright/i.test(text);
			}
			return false;
		};
I
isidor 已提交
269 270
	};

271
	const minify = (composer as any)(terser);
272 273 274
	const input = es.through();
	const output = input
		.pipe(flatmap((stream, f) => {
J
Joao Moreno 已提交
275
			return stream.pipe(minify({
J
Joao Moreno 已提交
276
				output: {
J
Joao Moreno 已提交
277
					comments: preserveComments(<FileWithCopyright>f),
278
					max_line_len: 1024
J
Joao Moreno 已提交
279
				}
280
			}));
281
		}));
I
isidor 已提交
282

283
	return es.duplex(input, output);
I
isidor 已提交
284 285
}

E
Erich Gamma 已提交
286
export function minifyTask(src: string, sourceMapBaseUrl?: string): (cb: any) => void {
287
	const sourceMappingURL = sourceMapBaseUrl ? ((f: any) => `${sourceMapBaseUrl}/${f.relative}.map`) : undefined;
J
Joao Moreno 已提交
288

289
	return cb => {
J
Joao Moreno 已提交
290 291
		const jsFilter = filter('**/*.js', { restore: true });
		const cssFilter = filter('**/*.css', { restore: true });
I
isidor 已提交
292

293 294 295 296 297 298 299 300 301
		pump(
			gulp.src([src + '/**', '!' + src + '/**/*.map']),
			jsFilter,
			sourcemaps.init({ loadMaps: true }),
			uglifyWithCopyrights(),
			jsFilter.restore,
			cssFilter,
			minifyCSS({ reduceIdents: false }),
			cssFilter.restore,
R
Rob Lourens 已提交
302 303 304 305 306 307 308
			(<any>sourcemaps).mapSources((sourcePath: string) => {
				if (sourcePath === 'bootstrap-fork.js') {
					return 'bootstrap-fork.orig.js';
				}

				return sourcePath;
			}),
309
			sourcemaps.write('./', {
J
Joao Moreno 已提交
310
				sourceMappingURL,
311
				sourceRoot: undefined,
I
isidor 已提交
312
				includeContent: true,
J
Joao Moreno 已提交
313
				addComment: true
314
			} as any),
315
			gulp.dest(src + '-min')
316
			, (err: any) => {
M
Matt Bierner 已提交
317
				if (err instanceof (uglify as any).GulpUglifyError) {
318 319
					console.error(`Uglify error in '${err.cause && err.cause.filename}'`);
				}
320

321 322
				cb(err);
			});
I
isidor 已提交
323
	};
D
Dirk Baeumer 已提交
324
}