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 16 17 18 19 20 21
//#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)
process.on('SIGPIPE', () => {
	console.error(new Error('Unexpected SIGPIPE'));
});

//#endregion

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

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

	const Module = require('module');
	const path = require('path');

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

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

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

49
		return paths;
50 51
	};
};
52

53 54
//#endregion

A
Alex Dima 已提交
55 56
//#region Remove global paths from the node lookup paths

57
exports.removeGlobalNodeModuleLookupPaths = function () {
A
Alex Dima 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
	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);
	};
};
75

A
Alex Dima 已提交
76 77
//#endregion

A
Alex Dima 已提交
78
//#region Add support for using node_modules.asar
79

B
Benjamin Pasero 已提交
80 81 82 83
/**
 * @param {string=} nodeModulesPath
 */
exports.enableASARSupport = function (nodeModulesPath) {
A
Alex Dima 已提交
84
	const Module = require('module');
85
	const path = require('path');
86

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

A
Alex Dima 已提交
92 93
	const NODE_MODULES_ASAR_PATH = NODE_MODULES_PATH + '.asar';

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

97 98 99
	// @ts-ignore
	Module._resolveLookupPaths = function (request, parent) {
		const paths = originalResolveLookupPaths(request, parent);
100 101 102 103 104 105
		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 已提交
106 107 108
			}
		}

109
		return paths;
A
Alex Dima 已提交
110
	};
111
};
112

A
Alex Dima 已提交
113
//#endregion
114

115
//#region URI helpers
116

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

140
//#endregion
E
Erich Gamma 已提交
141

142
//#region FS helpers
143

144 145
/**
 * @param {string} file
146
 * @returns {Promise<string>}
147
 */
148 149
exports.readFile = function (file) {
	const fs = require('fs');
E
Erich Gamma 已提交
150

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

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

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

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

188
	return new Promise((c, e) => fs.mkdir(dir, { recursive: true }, err => (err && err.code !== 'EEXIST') ? e(err) : c(dir)));
189
};
190

191
//#endregion
E
Erich Gamma 已提交
192

193
//#region NLS helpers
194

195 196 197
/**
 * @returns {{locale?: string, availableLanguages: {[lang: string]: string;}, pseudo?: boolean }}
 */
198 199
exports.setupNLS = function () {
	const path = require('path');
E
Erich Gamma 已提交
200

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

211 212
	if (nlsConfig._resolvedLanguagePackCoreLocation) {
		const bundles = Object.create(null);
213

214
		nlsConfig.loadBundle = function (bundle, language, cb) {
M
Max Belsky 已提交
215
			const result = bundles[bundle];
216 217 218 219 220 221 222 223
			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 已提交
224
				const json = JSON.parse(content);
225 226 227 228 229 230 231 232 233 234 235 236 237
				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 已提交
238
	}
239

240 241
	return nlsConfig;
};
242

243
//#endregion
E
Erich Gamma 已提交
244

245
//#region Portable helpers
246

247 248 249
/**
 * @returns {{ portableDataPath: string, isPortable: boolean }}
 */
250
exports.configurePortable = function () {
251
	const product = require('../product.json');
252 253
	const path = require('path');
	const fs = require('fs');
254

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

257 258 259 260
	function getApplicationPath() {
		if (process.env['VSCODE_DEV']) {
			return appRoot;
		}
261

262 263 264
		if (process.platform === 'darwin') {
			return path.dirname(path.dirname(path.dirname(appRoot)));
		}
265

266
		return path.dirname(path.dirname(appRoot));
J
Joao Moreno 已提交
267
	}
268 269 270 271 272 273 274 275

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

		if (process.platform === 'win32' || process.platform === 'linux') {
			return path.join(getApplicationPath(), 'data');
276
		}
277

278
		// @ts-ignore
279 280
		const portableDataName = product.portable || `${product.applicationName}-portable-data`;
		return path.join(path.dirname(getApplicationPath()), portableDataName);
281 282
	}

283
	const portableDataPath = getPortableDataPath();
J
Joao Moreno 已提交
284
	const isPortable = !('target' in product) && fs.existsSync(portableDataPath);
285 286 287 288 289 290 291 292 293 294
	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 已提交
295 296 297 298 299 300
		if (process.platform === 'win32') {
			process.env['TMP'] = portableTempPath;
			process.env['TEMP'] = portableTempPath;
		} else {
			process.env['TMPDIR'] = portableTempPath;
		}
301
	}
302

303 304 305 306 307
	return {
		portableDataPath,
		isPortable
	};
};
308

R
Ramya Rao 已提交
309 310 311
//#endregion

//#region ApplicationInsights
312 313 314

// Prevents appinsights from monkey patching modules.
// This should be called before importing the applicationinsights module
R
Ramya Rao 已提交
315
exports.avoidMonkeyPatchFromAppInsights = function () {
316
	// @ts-ignore
R
Ramya Rao 已提交
317 318 319
	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
};
320

M
Max Belsky 已提交
321
//#endregion