Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/build/lib/optimize.js
3520 views
1
"use strict";
2
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
if (k2 === undefined) k2 = k;
4
var desc = Object.getOwnPropertyDescriptor(m, k);
5
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
desc = { enumerable: true, get: function() { return m[k]; } };
7
}
8
Object.defineProperty(o, k2, desc);
9
}) : (function(o, m, k, k2) {
10
if (k2 === undefined) k2 = k;
11
o[k2] = m[k];
12
}));
13
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
Object.defineProperty(o, "default", { enumerable: true, value: v });
15
}) : function(o, v) {
16
o["default"] = v;
17
});
18
var __importStar = (this && this.__importStar) || (function () {
19
var ownKeys = function(o) {
20
ownKeys = Object.getOwnPropertyNames || function (o) {
21
var ar = [];
22
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
return ar;
24
};
25
return ownKeys(o);
26
};
27
return function (mod) {
28
if (mod && mod.__esModule) return mod;
29
var result = {};
30
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
__setModuleDefault(result, mod);
32
return result;
33
};
34
})();
35
var __importDefault = (this && this.__importDefault) || function (mod) {
36
return (mod && mod.__esModule) ? mod : { "default": mod };
37
};
38
Object.defineProperty(exports, "__esModule", { value: true });
39
exports.bundleTask = bundleTask;
40
exports.minifyTask = minifyTask;
41
/*---------------------------------------------------------------------------------------------
42
* Copyright (c) Microsoft Corporation. All rights reserved.
43
* Licensed under the MIT License. See License.txt in the project root for license information.
44
*--------------------------------------------------------------------------------------------*/
45
const event_stream_1 = __importDefault(require("event-stream"));
46
const gulp_1 = __importDefault(require("gulp"));
47
const gulp_filter_1 = __importDefault(require("gulp-filter"));
48
const path_1 = __importDefault(require("path"));
49
const fs_1 = __importDefault(require("fs"));
50
const pump_1 = __importDefault(require("pump"));
51
const vinyl_1 = __importDefault(require("vinyl"));
52
const bundle = __importStar(require("./bundle"));
53
const esbuild_1 = __importDefault(require("esbuild"));
54
const gulp_sourcemaps_1 = __importDefault(require("gulp-sourcemaps"));
55
const fancy_log_1 = __importDefault(require("fancy-log"));
56
const ansi_colors_1 = __importDefault(require("ansi-colors"));
57
const REPO_ROOT_PATH = path_1.default.join(__dirname, '../..');
58
const DEFAULT_FILE_HEADER = [
59
'/*!--------------------------------------------------------',
60
' * Copyright (C) Microsoft Corporation. All rights reserved.',
61
' *--------------------------------------------------------*/'
62
].join('\n');
63
function bundleESMTask(opts) {
64
const resourcesStream = event_stream_1.default.through(); // this stream will contain the resources
65
const bundlesStream = event_stream_1.default.through(); // this stream will contain the bundled files
66
const entryPoints = opts.entryPoints.map(entryPoint => {
67
if (typeof entryPoint === 'string') {
68
return { name: path_1.default.parse(entryPoint).name };
69
}
70
return entryPoint;
71
});
72
const bundleAsync = async () => {
73
const files = [];
74
const tasks = [];
75
for (const entryPoint of entryPoints) {
76
(0, fancy_log_1.default)(`Bundled entry point: ${ansi_colors_1.default.yellow(entryPoint.name)}...`);
77
// support for 'dest' via esbuild#in/out
78
const dest = entryPoint.dest?.replace(/\.[^/.]+$/, '') ?? entryPoint.name;
79
// banner contents
80
const banner = {
81
js: DEFAULT_FILE_HEADER,
82
css: DEFAULT_FILE_HEADER
83
};
84
// TS Boilerplate
85
if (!opts.skipTSBoilerplateRemoval?.(entryPoint.name)) {
86
const tslibPath = path_1.default.join(require.resolve('tslib'), '../tslib.es6.js');
87
banner.js += await fs_1.default.promises.readFile(tslibPath, 'utf-8');
88
}
89
const contentsMapper = {
90
name: 'contents-mapper',
91
setup(build) {
92
build.onLoad({ filter: /\.js$/ }, async ({ path }) => {
93
const contents = await fs_1.default.promises.readFile(path, 'utf-8');
94
// TS Boilerplate
95
let newContents;
96
if (!opts.skipTSBoilerplateRemoval?.(entryPoint.name)) {
97
newContents = bundle.removeAllTSBoilerplate(contents);
98
}
99
else {
100
newContents = contents;
101
}
102
// File Content Mapper
103
const mapper = opts.fileContentMapper?.(path.replace(/\\/g, '/'));
104
if (mapper) {
105
newContents = await mapper(newContents);
106
}
107
return { contents: newContents };
108
});
109
}
110
};
111
const externalOverride = {
112
name: 'external-override',
113
setup(build) {
114
// We inline selected modules that are we depend on on startup without
115
// a conditional `await import(...)` by hooking into the resolution.
116
build.onResolve({ filter: /^minimist$/ }, () => {
117
return { path: path_1.default.join(REPO_ROOT_PATH, 'node_modules', 'minimist', 'index.js'), external: false };
118
});
119
},
120
};
121
const task = esbuild_1.default.build({
122
bundle: true,
123
packages: 'external', // "external all the things", see https://esbuild.github.io/api/#packages
124
platform: 'neutral', // makes esm
125
format: 'esm',
126
sourcemap: 'external',
127
plugins: [contentsMapper, externalOverride],
128
target: ['es2022'],
129
loader: {
130
'.ttf': 'file',
131
'.svg': 'file',
132
'.png': 'file',
133
'.sh': 'file',
134
},
135
assetNames: 'media/[name]', // moves media assets into a sub-folder "media"
136
banner: entryPoint.name === 'vs/workbench/workbench.web.main' ? undefined : banner, // TODO@esm remove line when we stop supporting web-amd-esm-bridge
137
entryPoints: [
138
{
139
in: path_1.default.join(REPO_ROOT_PATH, opts.src, `${entryPoint.name}.js`),
140
out: dest,
141
}
142
],
143
outdir: path_1.default.join(REPO_ROOT_PATH, opts.src),
144
write: false, // enables res.outputFiles
145
metafile: true, // enables res.metafile
146
// minify: NOT enabled because we have a separate minify task that takes care of the TSLib banner as well
147
}).then(res => {
148
for (const file of res.outputFiles) {
149
let sourceMapFile = undefined;
150
if (file.path.endsWith('.js')) {
151
sourceMapFile = res.outputFiles.find(f => f.path === `${file.path}.map`);
152
}
153
const fileProps = {
154
contents: Buffer.from(file.contents),
155
sourceMap: sourceMapFile ? JSON.parse(sourceMapFile.text) : undefined, // support gulp-sourcemaps
156
path: file.path,
157
base: path_1.default.join(REPO_ROOT_PATH, opts.src)
158
};
159
files.push(new vinyl_1.default(fileProps));
160
}
161
});
162
tasks.push(task);
163
}
164
await Promise.all(tasks);
165
return { files };
166
};
167
bundleAsync().then((output) => {
168
// bundle output (JS, CSS, SVG...)
169
event_stream_1.default.readArray(output.files).pipe(bundlesStream);
170
// forward all resources
171
gulp_1.default.src(opts.resources ?? [], { base: `${opts.src}`, allowEmpty: true }).pipe(resourcesStream);
172
});
173
const result = event_stream_1.default.merge(bundlesStream, resourcesStream);
174
return result
175
.pipe(gulp_sourcemaps_1.default.write('./', {
176
sourceRoot: undefined,
177
addComment: true,
178
includeContent: true
179
}));
180
}
181
function bundleTask(opts) {
182
return function () {
183
return bundleESMTask(opts.esm).pipe(gulp_1.default.dest(opts.out));
184
};
185
}
186
function minifyTask(src, sourceMapBaseUrl) {
187
const sourceMappingURL = sourceMapBaseUrl ? ((f) => `${sourceMapBaseUrl}/${f.relative}.map`) : undefined;
188
return cb => {
189
const svgmin = require('gulp-svgmin');
190
const esbuildFilter = (0, gulp_filter_1.default)('**/*.{js,css}', { restore: true });
191
const svgFilter = (0, gulp_filter_1.default)('**/*.svg', { restore: true });
192
(0, pump_1.default)(gulp_1.default.src([src + '/**', '!' + src + '/**/*.map']), esbuildFilter, gulp_sourcemaps_1.default.init({ loadMaps: true }), event_stream_1.default.map((f, cb) => {
193
esbuild_1.default.build({
194
entryPoints: [f.path],
195
minify: true,
196
sourcemap: 'external',
197
outdir: '.',
198
packages: 'external', // "external all the things", see https://esbuild.github.io/api/#packages
199
platform: 'neutral', // makes esm
200
target: ['es2022'],
201
write: false,
202
}).then(res => {
203
const jsOrCSSFile = res.outputFiles.find(f => /\.(js|css)$/.test(f.path));
204
const sourceMapFile = res.outputFiles.find(f => /\.(js|css)\.map$/.test(f.path));
205
const contents = Buffer.from(jsOrCSSFile.contents);
206
const unicodeMatch = contents.toString().match(/[^\x00-\xFF]+/g);
207
if (unicodeMatch) {
208
cb(new Error(`Found non-ascii character ${unicodeMatch[0]} in the minified output of ${f.path}. Non-ASCII characters in the output can cause performance problems when loading. Please review if you have introduced a regular expression that esbuild is not automatically converting and convert it to using unicode escape sequences.`));
209
}
210
else {
211
f.contents = contents;
212
f.sourceMap = JSON.parse(sourceMapFile.text);
213
cb(undefined, f);
214
}
215
}, cb);
216
}), esbuildFilter.restore, svgFilter, svgmin(), svgFilter.restore, gulp_sourcemaps_1.default.write('./', {
217
sourceMappingURL,
218
sourceRoot: undefined,
219
includeContent: true,
220
addComment: true
221
}), gulp_1.default.dest(src + '-min'), (err) => cb(err));
222
};
223
}
224
//# sourceMappingURL=optimize.js.map
225