bootstrap.js 7.9 KB
Newer Older
E
Erich Gamma 已提交
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.
 *--------------------------------------------------------------------------------------------*/

6 7 8
//@ts-check
'use strict';

9 10 11 12 13 14 15
//#region global bootstrapping

// increase number of stack frames(from 10, https://github.com/v8/v8/wiki/Stack-Trace-API)
Error.stackTraceLimit = 100;

// Workaround for Electron not installing a handler to ignore SIGPIPE
// (https://github.com/electron/electron/issues/13254)
16
// @ts-ignore
17 18 19 20 21 22
process.on('SIGPIPE', () => {
	console.error(new Error('Unexpected SIGPIPE'));
});

//#endregion

23
//#region Add support for redirecting the loading of node modules
24

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
exports.injectNodeModuleLookupPath = function (injectPath) {
	if (!injectPath) {
		throw new Error('Missing injectPath');
	}

	// @ts-ignore
	const Module = require('module');
	const path = require('path');

	const nodeModulesPath = path.join(__dirname, '../node_modules');

	// @ts-ignore
	const originalResolveLookupPaths = Module._resolveLookupPaths;

	// @ts-ignore
40 41
	Module._resolveLookupPaths = function (moduleName, parent) {
		const paths = originalResolveLookupPaths(moduleName, parent);
42 43 44 45 46 47
		if (Array.isArray(paths)) {
			for (let i = 0, len = paths.length; i < len; i++) {
				if (paths[i] === nodeModulesPath) {
					paths.splice(i, 0, injectPath);
					break;
				}
48 49 50
			}
		}

51
		return paths;
52 53 54 55
	};
};
//#endregion

A
Alex Dima 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
//#region Remove global paths from the node lookup paths

exports.removeGlobalNodeModuleLookupPaths = function() {
	// @ts-ignore
	const Module = require('module');
	// @ts-ignore
	const globalPaths = Module.globalPaths;

	// @ts-ignore
	const originalResolveLookupPaths = Module._resolveLookupPaths;

	// @ts-ignore
	Module._resolveLookupPaths = function (moduleName, parent) {
		const paths = originalResolveLookupPaths(moduleName, parent);
		let commonSuffixLength = 0;
		while (commonSuffixLength < paths.length && paths[paths.length - 1 - commonSuffixLength] === globalPaths[globalPaths.length - 1 - commonSuffixLength]) {
			commonSuffixLength++;
		}
		return paths.slice(0, paths.length - commonSuffixLength);
	};
};
//#endregion

A
Alex Dima 已提交
79
//#region Add support for using node_modules.asar
B
Benjamin Pasero 已提交
80 81 82 83
/**
 * @param {string=} nodeModulesPath
 */
exports.enableASARSupport = function (nodeModulesPath) {
84

85
	// @ts-ignore
A
Alex Dima 已提交
86
	const Module = require('module');
87
	const path = require('path');
88

B
Benjamin Pasero 已提交
89 90 91 92 93
	let NODE_MODULES_PATH = nodeModulesPath;
	if (!NODE_MODULES_PATH) {
		NODE_MODULES_PATH = path.join(__dirname, '../node_modules');
	}

A
Alex Dima 已提交
94 95
	const NODE_MODULES_ASAR_PATH = NODE_MODULES_PATH + '.asar';

96
	// @ts-ignore
A
Alex Dima 已提交
97
	const originalResolveLookupPaths = Module._resolveLookupPaths;
98

99 100 101
	// @ts-ignore
	Module._resolveLookupPaths = function (request, parent) {
		const paths = originalResolveLookupPaths(request, parent);
102 103 104 105 106 107
		if (Array.isArray(paths)) {
			for (let i = 0, len = paths.length; i < len; i++) {
				if (paths[i] === NODE_MODULES_PATH) {
					paths.splice(i, 0, NODE_MODULES_ASAR_PATH);
					break;
				}
A
Alex Dima 已提交
108 109 110
			}
		}

111
		return paths;
A
Alex Dima 已提交
112
	};
113
};
A
Alex Dima 已提交
114
//#endregion
115

116
//#region URI helpers
117 118 119 120
/**
 * @param {string} _path
 * @returns {string}
 */
121 122
exports.uriFromPath = function (_path) {
	const path = require('path');
123

124 125 126 127
	let pathName = path.resolve(_path).replace(/\\/g, '/');
	if (pathName.length > 0 && pathName.charAt(0) !== '/') {
		pathName = '/' + pathName;
	}
128

129 130
	/** @type {string} */
	let uri;
B
Benjamin Pasero 已提交
131
	if (process.platform === 'win32' && pathName.startsWith('//')) { // specially handle Windows UNC paths
132 133 134 135 136 137
		uri = encodeURI('file:' + pathName);
	} else {
		uri = encodeURI('file://' + pathName);
	}

	return uri.replace(/#/g, '%23');
138 139
};
//#endregion
E
Erich Gamma 已提交
140

141
//#region FS helpers
142 143
/**
 * @param {string} file
144
 * @returns {Promise<string>}
145
 */
146 147
exports.readFile = function (file) {
	const fs = require('fs');
E
Erich Gamma 已提交
148

149 150 151 152 153 154 155 156 157 158
	return new Promise(function (resolve, reject) {
		fs.readFile(file, 'utf8', function (err, data) {
			if (err) {
				reject(err);
				return;
			}
			resolve(data);
		});
	});
};
E
Erich Gamma 已提交
159

160 161 162
/**
 * @param {string} file
 * @param {string} content
163
 * @returns {Promise<void>}
164
 */
165 166
exports.writeFile = function (file, content) {
	const fs = require('fs');
E
Erich Gamma 已提交
167

168 169 170 171 172 173 174 175 176 177
	return new Promise(function (resolve, reject) {
		fs.writeFile(file, content, 'utf8', function (err) {
			if (err) {
				reject(err);
				return;
			}
			resolve();
		});
	});
};
178 179 180 181 182 183

/**
 * @param {string} dir
 * @returns {Promise<string>}
 */
exports.mkdirp = function mkdirp(dir) {
184
	const fs = require('fs');
185

186
	return new Promise((c, e) => fs.mkdir(dir, { recursive: true }, err => (err && err.code !== 'EEXIST') ? e(err) : c(dir)));
187
};
188
//#endregion
E
Erich Gamma 已提交
189

190
//#region NLS helpers
191 192 193
/**
 * @returns {{locale?: string, availableLanguages: {[lang: string]: string;}, pseudo?: boolean }}
 */
194 195
exports.setupNLS = function () {
	const path = require('path');
E
Erich Gamma 已提交
196

197 198 199
	// Get the nls configuration into the process.env as early as possible.
	let nlsConfig = { availableLanguages: {} };
	if (process.env['VSCODE_NLS_CONFIG']) {
200
		try {
201 202 203
			nlsConfig = JSON.parse(process.env['VSCODE_NLS_CONFIG']);
		} catch (e) {
			// Ignore
204 205 206
		}
	}

207 208
	if (nlsConfig._resolvedLanguagePackCoreLocation) {
		const bundles = Object.create(null);
209

210
		nlsConfig.loadBundle = function (bundle, language, cb) {
M
Max Belsky 已提交
211
			const result = bundles[bundle];
212 213 214 215 216 217 218 219
			if (result) {
				cb(undefined, result);

				return;
			}

			const bundleFile = path.join(nlsConfig._resolvedLanguagePackCoreLocation, bundle.replace(/\//g, '!') + '.nls.json');
			exports.readFile(bundleFile).then(function (content) {
M
Max Belsky 已提交
220
				const json = JSON.parse(content);
221 222 223 224 225 226 227 228 229 230 231 232 233
				bundles[bundle] = json;

				cb(undefined, json);
			}).catch((error) => {
				try {
					if (nlsConfig._corruptedFile) {
						exports.writeFile(nlsConfig._corruptedFile, 'corrupted').catch(function (error) { console.error(error); });
					}
				} finally {
					cb(error, undefined);
				}
			});
		};
E
Erich Gamma 已提交
234
	}
235

236 237 238
	return nlsConfig;
};
//#endregion
E
Erich Gamma 已提交
239

240
//#region Portable helpers
241 242 243
/**
 * @returns {{ portableDataPath: string, isPortable: boolean }}
 */
244
exports.configurePortable = function () {
245 246
	// @ts-ignore
	const product = require('../product.json');
247 248
	const path = require('path');
	const fs = require('fs');
249

250
	const appRoot = path.dirname(__dirname);
J
Joao Moreno 已提交
251

252 253 254 255
	function getApplicationPath() {
		if (process.env['VSCODE_DEV']) {
			return appRoot;
		}
256

257 258 259
		if (process.platform === 'darwin') {
			return path.dirname(path.dirname(path.dirname(appRoot)));
		}
260

261
		return path.dirname(path.dirname(appRoot));
J
Joao Moreno 已提交
262
	}
263 264 265 266 267 268 269 270

	function getPortableDataPath() {
		if (process.env['VSCODE_PORTABLE']) {
			return process.env['VSCODE_PORTABLE'];
		}

		if (process.platform === 'win32' || process.platform === 'linux') {
			return path.join(getApplicationPath(), 'data');
271
		}
272 273 274

		const portableDataName = product.portable || `${product.applicationName}-portable-data`;
		return path.join(path.dirname(getApplicationPath()), portableDataName);
275 276
	}

277
	const portableDataPath = getPortableDataPath();
J
Joao Moreno 已提交
278
	const isPortable = !('target' in product) && fs.existsSync(portableDataPath);
279 280 281 282 283 284 285 286 287 288
	const portableTempPath = path.join(portableDataPath, 'tmp');
	const isTempPortable = isPortable && fs.existsSync(portableTempPath);

	if (isPortable) {
		process.env['VSCODE_PORTABLE'] = portableDataPath;
	} else {
		delete process.env['VSCODE_PORTABLE'];
	}

	if (isTempPortable) {
J
Joao Moreno 已提交
289 290 291 292 293 294
		if (process.platform === 'win32') {
			process.env['TMP'] = portableTempPath;
			process.env['TEMP'] = portableTempPath;
		} else {
			process.env['TMPDIR'] = portableTempPath;
		}
295
	}
296

297 298 299 300 301
	return {
		portableDataPath,
		isPortable
	};
};
R
Ramya Rao 已提交
302 303 304 305 306 307 308 309
//#endregion

//#region ApplicationInsights
/**
 * Prevents appinsights from monkey patching modules.
 * This should be called before importing the applicationinsights module
 */
exports.avoidMonkeyPatchFromAppInsights = function () {
310
	// @ts-ignore
R
Ramya Rao 已提交
311 312 313
	process.env['APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL'] = true; // Skip monkey patching of 3rd party modules by appinsights
	global['diagnosticsSource'] = {}; // Prevents diagnostic channel (which patches "require") from initializing entirely
};
M
Max Belsky 已提交
314
//#endregion