vscode.patch 142.2 KB
Newer Older
A
Asher 已提交
1
diff --git a/.gitignore b/.gitignore
A
Asher 已提交
2
index e73dd4d9e8..e3192b3a0d 100644
A
Asher 已提交
3 4
--- a/.gitignore
+++ b/.gitignore
A
Asher 已提交
5
@@ -24,7 +24,6 @@ out-vscode-reh-web-min/
A
Asher 已提交
6 7 8 9 10 11 12
 out-vscode-reh-web-pkg/
 out-vscode-web/
 out-vscode-web-min/
-src/vs/server
 resources/server
 build/node_modules
 coverage/
A
Asher 已提交
13
diff --git a/.yarnrc b/.yarnrc
A
Anmol Sethi 已提交
14
deleted file mode 100644
A
Asher 已提交
15
index 1406d749d7..0000000000
A
Asher 已提交
16
--- a/.yarnrc
A
Anmol Sethi 已提交
17 18
+++ /dev/null
@@ -1,3 +0,0 @@
A
Asher 已提交
19
-disturl "https://atom.io/download/electron"
A
Asher 已提交
20
-target "7.3.1"
A
Asher 已提交
21
-runtime "electron"
A
Anmol Sethi 已提交
22
diff --git a/build/gulpfile.reh.js b/build/gulpfile.reh.js
A
Asher 已提交
23
index f2ea1bd370..3f660f9981 100644
A
Anmol Sethi 已提交
24 25 26 27 28 29
--- a/build/gulpfile.reh.js
+++ b/build/gulpfile.reh.js
@@ -52,6 +52,7 @@ gulp.task('vscode-reh-web-linux-x64-min', noop);
 gulp.task('vscode-reh-web-linux-alpine-min', noop);
 
 function getNodeVersion() {
A
Asher 已提交
30
+	return process.versions.node;
A
Anmol Sethi 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
 	const yarnrc = fs.readFileSync(path.join(REPO_ROOT, 'remote', '.yarnrc'), 'utf8');
 	const target = /^target "(.*)"$/m.exec(yarnrc)[1];
 	return target;
diff --git a/build/lib/node.js b/build/lib/node.js
index 403ae3d965..738ee8cee0 100644
--- a/build/lib/node.js
+++ b/build/lib/node.js
@@ -5,11 +5,8 @@
  *--------------------------------------------------------------------------------------------*/
 Object.defineProperty(exports, "__esModule", { value: true });
 const path = require("path");
-const fs = require("fs");
 const root = path.dirname(path.dirname(__dirname));
-const yarnrcPath = path.join(root, 'remote', '.yarnrc');
-const yarnrc = fs.readFileSync(yarnrcPath, 'utf8');
-const version = /^target\s+"([^"]+)"$/m.exec(yarnrc)[1];
+const version = process.versions.node;
 const node = process.platform === 'win32' ? 'node.exe' : 'node';
 const nodePath = path.join(root, '.build', 'node', `v${version}`, `${process.platform}-${process.arch}`, node);
 console.log(nodePath);
diff --git a/build/lib/node.ts b/build/lib/node.ts
index 6439703446..c53dccf4dc 100644
--- a/build/lib/node.ts
+++ b/build/lib/node.ts
@@ -4,13 +4,10 @@
  *--------------------------------------------------------------------------------------------*/
 
 import * as path from 'path';
-import * as fs from 'fs';
 
 const root = path.dirname(path.dirname(__dirname));
-const yarnrcPath = path.join(root, 'remote', '.yarnrc');
-const yarnrc = fs.readFileSync(yarnrcPath, 'utf8');
-const version = /^target\s+"([^"]+)"$/m.exec(yarnrc)![1];
+const version = process.versions.node;
 const node = process.platform === 'win32' ? 'node.exe' : 'node';
 const nodePath = path.join(root, '.build', 'node', `v${version}`, `${process.platform}-${process.arch}`, node);
 
-console.log(nodePath);
\ No newline at end of file
+console.log(nodePath);
A
Asher 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
diff --git a/build/lib/util.js b/build/lib/util.js
index 8b70b534b2..76d68fd318 100644
--- a/build/lib/util.js
+++ b/build/lib/util.js
@@ -257,6 +257,7 @@ function streamToPromise(stream) {
 }
 exports.streamToPromise = streamToPromise;
 function getElectronVersion() {
+    return process.versions.node;
     const yarnrc = fs.readFileSync(path.join(root, '.yarnrc'), 'utf8');
     const target = /^target "(.*)"$/m.exec(yarnrc)[1];
     return target;
diff --git a/build/lib/util.ts b/build/lib/util.ts
index e379b47d8e..2ff4e2b7cc 100644
--- a/build/lib/util.ts
+++ b/build/lib/util.ts
@@ -322,6 +322,7 @@ export function streamToPromise(stream: NodeJS.ReadWriteStream): Promise<void> {
 }
 
 export function getElectronVersion(): string {
+	return process.versions.node;
 	const yarnrc = fs.readFileSync(path.join(root, '.yarnrc'), 'utf8');
 	const target = /^target "(.*)"$/m.exec(yarnrc)![1];
 	return target;
A
Asher 已提交
96
diff --git a/build/npm/postinstall.js b/build/npm/postinstall.js
A
Asher 已提交
97
index 7b8b710636..3f6609cedf 100644
A
Asher 已提交
98 99
--- a/build/npm/postinstall.js
+++ b/build/npm/postinstall.js
A
Asher 已提交
100
@@ -33,10 +33,11 @@ function yarnInstall(location, opts) {
A
Asher 已提交
101 102 103
 
 yarnInstall('extensions'); // node modules shared by all extensions
 
A
Asher 已提交
104 105 106 107 108 109 110 111 112
-if (!(process.platform === 'win32' && process.env['npm_config_arch'] === 'arm64')) {
-	yarnInstall('remote'); // node modules used by vscode server
-	yarnInstall('remote/web'); // node modules used by vscode web
-}
+// NOTE@coder: Skip these dependencies since we don't use them.
+// if (!(process.platform === 'win32' && process.env['npm_config_arch'] === 'arm64')) {
+// 	yarnInstall('remote'); // node modules used by vscode server
+// 	yarnInstall('remote/web'); // node modules used by vscode web
+// }
A
Asher 已提交
113 114 115
 
 const allExtensionFolders = fs.readdirSync('extensions');
 const extensions = allExtensionFolders.filter(e => {
A
Asher 已提交
116
@@ -69,7 +70,7 @@ runtime "${runtime}"`;
A
Asher 已提交
117 118 119 120 121 122 123 124 125 126
 }
 
 yarnInstall(`build`); // node modules required for build
-yarnInstall('test/automation'); // node modules required for smoketest
-yarnInstall('test/smoke'); // node modules required for smoketest
-yarnInstall('test/integration/browser'); // node modules required for integration
+// yarnInstall('test/automation'); // node modules required for smoketest
+// yarnInstall('test/smoke'); // node modules required for smoketest
+// yarnInstall('test/integration/browser'); // node modules required for integration
 yarnInstallBuildDependencies(); // node modules for watching, specific to host node version, not electron
A
Anmol Sethi 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
diff --git a/build/npm/preinstall.js b/build/npm/preinstall.js
index cb88d37ade..6b3253af0a 100644
--- a/build/npm/preinstall.js
+++ b/build/npm/preinstall.js
@@ -8,8 +8,9 @@ let err = false;
 const majorNodeVersion = parseInt(/^(\d+)\./.exec(process.versions.node)[1]);
 
 if (majorNodeVersion < 10 || majorNodeVersion >= 13) {
-	console.error('\033[1;31m*** Please use node >=10 and <=12.\033[0;0m');
-	err = true;
+	// We are ok building above Node 12.
+	// console.error('\033[1;31m*** Please use node >=10 and <=12.\033[0;0m');
+	// err = true;
 }
 
 const cp = require('child_process');
A
Asher 已提交
143 144
diff --git a/coder.js b/coder.js
new file mode 100644
A
Asher 已提交
145
index 0000000000..ce7d4f175f
A
Asher 已提交
146 147
--- /dev/null
+++ b/coder.js
A
Asher 已提交
148
@@ -0,0 +1,68 @@
A
Asher 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
+// This must be ran from VS Code's root.
+const gulp = require("gulp");
+const path = require("path");
+const _ = require("underscore");
+const buildfile = require("./src/buildfile");
+const common = require("./build/lib/optimize");
+const util = require("./build/lib/util");
+const deps = require("./build/dependencies");
+
+const vscodeEntryPoints = _.flatten([
+	buildfile.entrypoint("vs/workbench/workbench.web.api"),
+	buildfile.entrypoint("vs/server/entry"),
+	buildfile.base,
+	buildfile.workbenchWeb,
+	buildfile.workerExtensionHost,
+	buildfile.keyboardMaps,
A
Asher 已提交
165 166 167
+	buildfile.entrypoint("vs/platform/files/node/watcher/unix/watcherApp", ["vs/css", "vs/nls"]),
+	buildfile.entrypoint("vs/platform/files/node/watcher/nsfw/watcherApp", ["vs/css", "vs/nls"]),
+	buildfile.entrypoint("vs/workbench/services/extensions/node/extensionHostProcess", ["vs/css", "vs/nls"]),
A
Asher 已提交
168 169 170 171 172 173 174 175 176 177
+]);
+
+const vscodeResources = [
+	"out-build/vs/server/fork.js",
+	"!out-build/vs/server/doc/**",
+	"out-build/vs/workbench/services/extensions/worker/extensionHostWorkerMain.js",
+	"out-build/bootstrap.js",
+	"out-build/bootstrap-fork.js",
+	"out-build/bootstrap-amd.js",
+	"out-build/paths.js",
178
+	'out-build/vs/**/*.{svg,png,html,ttf}',
A
Asher 已提交
179 180 181 182
+	"!out-build/vs/code/browser/workbench/*.html",
+	'!out-build/vs/code/electron-browser/**',
+	"out-build/vs/base/common/performance.js",
+	"out-build/vs/base/node/languagePacks.js",
A
Asher 已提交
183
+	'out-build/vs/base/browser/ui/codicons/codicon/**',
A
Asher 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
+	"out-build/vs/workbench/browser/media/*-theme.css",
+	"out-build/vs/workbench/contrib/debug/**/*.json",
+	"out-build/vs/workbench/contrib/externalTerminal/**/*.scpt",
+	"out-build/vs/workbench/contrib/webview/browser/pre/*.js",
+	"out-build/vs/**/markdown.css",
+	"out-build/vs/workbench/contrib/tasks/**/*.json",
+	"out-build/vs/platform/files/**/*.md",
+	"!**/test/**"
+];
+
+const rootPath = __dirname;
+const nodeModules = ["electron", "original-fs"]
+	.concat(_.uniq(deps.getProductionDependencies(rootPath).map((d) => d.name)))
+	.concat(_.uniq(deps.getProductionDependencies(path.join(rootPath, "src/vs/server")).map((d) => d.name)))
+	.concat(Object.keys(process.binding("natives")).filter((n) => !/^_|\//.test(n)));
+
+gulp.task("optimize", gulp.series(
+	util.rimraf("out-vscode"),
+	common.optimizeTask({
+		src: "out-build",
+		entryPoints: vscodeEntryPoints,
+		resources: vscodeResources,
+		loaderConfig: common.loaderConfig(nodeModules),
+		out: "out-vscode",
+		inlineAmdImages: true,
+		bundleInfo: undefined
+	}),
+));
+
+gulp.task("minify", gulp.series(
+	util.rimraf("out-vscode-min"),
+	common.minifyTask("out-vscode")
+));
diff --git a/package.json b/package.json
A
Asher 已提交
218
index 37e3623fac..19482438bc 100644
A
Asher 已提交
219 220
--- a/package.json
+++ b/package.json
A
Asher 已提交
221 222
@@ -36,6 +36,9 @@
     "eslint": "eslint -c .eslintrc.json --rulesdir ./build/lib/eslint --ext .ts --ext .js ./src/vs ./extensions"
A
Asher 已提交
223 224
   },
   "dependencies": {
A
Asher 已提交
225
+    "@coder/logger": "^1.1.12",
A
Asher 已提交
226
+    "@coder/node-browser": "^1.0.8",
227
+    "@coder/requirefs": "^1.1.5",
A
Asher 已提交
228 229
     "applicationinsights": "1.0.8",
     "chokidar": "3.2.3",
A
Asher 已提交
230
     "graceful-fs": "4.2.3",
C
cmoog 已提交
231
diff --git a/product.json b/product.json
A
Asher 已提交
232
index d586d2fc06..d08cab5456 100644
C
cmoog 已提交
233 234
--- a/product.json
+++ b/product.json
A
Asher 已提交
235
@@ -20,7 +20,7 @@
C
cmoog 已提交
236 237 238 239 240 241 242
 	"darwinBundleIdentifier": "com.visualstudio.code.oss",
 	"linuxIconName": "com.visualstudio.code.oss",
 	"licenseFileName": "LICENSE.txt",
-	"reportIssueUrl": "https://github.com/Microsoft/vscode/issues/new",
+	"reportIssueUrl": "https://github.com/cdr/code-server/issues/new",
 	"urlProtocol": "code-oss",
 	"extensionAllowedProposedApi": [
A
Asher 已提交
243
 		"ms-vscode.vscode-js-profile-flame",
A
Anmol Sethi 已提交
244 245 246 247 248 249 250 251 252
diff --git a/remote/.yarnrc b/remote/.yarnrc
deleted file mode 100644
index 1e16cde724..0000000000
--- a/remote/.yarnrc
+++ /dev/null
@@ -1,3 +0,0 @@
-disturl "http://nodejs.org/dist"
-target "12.4.0"
-runtime "node"
A
Asher 已提交
253
diff --git a/src/vs/base/common/network.ts b/src/vs/base/common/network.ts
A
Asher 已提交
254
index b99dcbbb33..2bc1f2afe6 100644
A
Asher 已提交
255 256
--- a/src/vs/base/common/network.ts
+++ b/src/vs/base/common/network.ts
A
Asher 已提交
257
@@ -98,16 +98,17 @@ class RemoteAuthoritiesImpl {
A
Asher 已提交
258 259 260
 		if (host && host.indexOf(':') !== -1) {
 			host = `[${host}]`;
 		}
A
Asher 已提交
261
-		const port = this._ports[authority];
A
Asher 已提交
262
+		// const port = this._ports[authority];
A
Asher 已提交
263
 		const connectionToken = this._connectionTokens[authority];
264
 		let query = `path=${encodeURIComponent(uri.path)}`;
A
Asher 已提交
265 266 267 268
 		if (typeof connectionToken === 'string') {
 			query += `&tkn=${encodeURIComponent(connectionToken)}`;
 		}
+		// NOTE@coder: Changed this to work against the current path.
A
Asher 已提交
269 270 271 272 273 274
 		return URI.from({
 			scheme: platform.isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource,
-			authority: `${host}:${port}`,
-			path: `/vscode-remote-resource`,
+			authority: window.location.host,
+			path: `${window.location.pathname.replace(/\/+$/, '')}/vscode-remote-resource`,
A
Asher 已提交
275
 			query
A
Asher 已提交
276 277
 		});
 	}
A
Asher 已提交
278
diff --git a/src/vs/base/common/platform.ts b/src/vs/base/common/platform.ts
A
Asher 已提交
279
index 2c30aaa188..a1e89578a8 100644
A
Asher 已提交
280 281
--- a/src/vs/base/common/platform.ts
+++ b/src/vs/base/common/platform.ts
A
Asher 已提交
282
@@ -59,6 +59,17 @@ if (typeof navigator === 'object' && !isElectronRenderer) {
A
Asher 已提交
283
 	_isWeb = true;
A
Asher 已提交
284 285
 	_locale = navigator.language;
 	_language = _locale;
A
Asher 已提交
286
+	// NOTE@coder: Make languages work.
A
Asher 已提交
287 288
+	const el = typeof document !== 'undefined' && document.getElementById('vscode-remote-nls-configuration');
+	const rawNlsConfig = el && el.getAttribute('data-settings');
A
Asher 已提交
289 290 291 292 293 294 295 296 297 298 299
+	if (rawNlsConfig) {
+		try {
+			const nlsConfig: NLSConfig = JSON.parse(rawNlsConfig);
+			_locale = nlsConfig.locale;
+			_translationsConfigFile = nlsConfig._translationsConfigFile;
+			_language = nlsConfig.availableLanguages['*'] || LANGUAGE_DEFAULT;
+		} catch (error) { /* Oh well. */ }
+	}
 } else if (typeof process === 'object') {
 	_isWindows = (process.platform === 'win32');
 	_isMacintosh = (process.platform === 'darwin');
A
Asher 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313
diff --git a/src/vs/base/common/processes.ts b/src/vs/base/common/processes.ts
index c52f7b3774..08a87fa970 100644
--- a/src/vs/base/common/processes.ts
+++ b/src/vs/base/common/processes.ts
@@ -110,7 +110,8 @@ export function sanitizeProcessEnvironment(env: IProcessEnvironment, ...preserve
 		/^ELECTRON_.+$/,
 		/^GOOGLE_API_KEY$/,
 		/^VSCODE_.+$/,
-		/^SNAP(|_.*)$/
+		/^SNAP(|_.*)$/,
+		/^CODE_SERVER_.+$/,
 	];
 	const envKeys = Object.keys(env);
 	envKeys
A
Asher 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
diff --git a/src/vs/base/common/uriIpc.ts b/src/vs/base/common/uriIpc.ts
index ef2291d49b..29b2f9dfc2 100644
--- a/src/vs/base/common/uriIpc.ts
+++ b/src/vs/base/common/uriIpc.ts
@@ -5,6 +5,7 @@
 
 import { URI, UriComponents } from 'vs/base/common/uri';
 import { MarshalledObject } from 'vs/base/common/marshalling';
+import { Schemas } from './network';
 
 export interface IURITransformer {
 	transformIncoming(uri: UriComponents): UriComponents;
@@ -31,29 +32,35 @@ function toJSON(uri: URI): UriComponents {
 
 export class URITransformer implements IURITransformer {
 
-	private readonly _uriTransformer: IRawURITransformer;
-
-	constructor(uriTransformer: IRawURITransformer) {
-		this._uriTransformer = uriTransformer;
+	constructor(private readonly remoteAuthority: string) {
 	}
 
+	// NOTE@coder: Coming in from the browser it'll be vscode-remote so it needs
+	// to be transformed into file.
 	public transformIncoming(uri: UriComponents): UriComponents {
-		const result = this._uriTransformer.transformIncoming(uri);
-		return (result === uri ? uri : toJSON(URI.from(result)));
+		return uri.scheme === Schemas.vscodeRemote
+			? toJSON(URI.file(uri.path))
+			: uri;
 	}
 
+	// NOTE@coder: Going out to the browser it'll be file so it needs to be
+	// transformed into vscode-remote.
 	public transformOutgoing(uri: UriComponents): UriComponents {
-		const result = this._uriTransformer.transformOutgoing(uri);
-		return (result === uri ? uri : toJSON(URI.from(result)));
+		return uri.scheme === Schemas.file
+			? toJSON(URI.from({ authority: this.remoteAuthority, scheme: Schemas.vscodeRemote, path: uri.path }))
+			: uri;
 	}
 
 	public transformOutgoingURI(uri: URI): URI {
-		const result = this._uriTransformer.transformOutgoing(uri);
-		return (result === uri ? uri : URI.from(result));
+		return uri.scheme === Schemas.file
+			? URI.from({ authority: this.remoteAuthority, scheme: Schemas.vscodeRemote, path:uri.path })
+			: uri;
 	}
 
 	public transformOutgoingScheme(scheme: string): string {
-		return this._uriTransformer.transformOutgoingScheme(scheme);
+		return scheme === Schemas.file
+			? Schemas.vscodeRemote
+			: scheme;
 	}
 }
 
@@ -152,4 +159,4 @@ export function transformAndReviveIncomingURIs<T>(obj: T, transformer: IURITrans
 		return obj;
 	}
 	return result;
-}
\ No newline at end of file
+}
380
diff --git a/src/vs/base/node/languagePacks.js b/src/vs/base/node/languagePacks.js
A
Asher 已提交
381
index 2c64061da7..c0ef8faedd 100644
382 383
--- a/src/vs/base/node/languagePacks.js
+++ b/src/vs/base/node/languagePacks.js
A
Asher 已提交
384
@@ -128,7 +128,10 @@ function factory(nodeRequire, path, fs, perf) {
385 386 387 388
 	function getLanguagePackConfigurations(userDataPath) {
 		const configFile = path.join(userDataPath, 'languagepacks.json');
 		try {
-			return nodeRequire(configFile);
A
Asher 已提交
389 390 391
+			// NOTE@coder: Swapped require with readFile since require is cached and
+			// we don't restart the server-side portion of code-server when the
+			// language changes.
392 393 394 395
+			return JSON.parse(fs.readFileSync(configFile, "utf8"));
 		} catch (err) {
 			// Do nothing. If we can't read the file we have no
 			// language pack config.
396
diff --git a/src/vs/code/browser/workbench/workbench.ts b/src/vs/code/browser/workbench/workbench.ts
A
Asher 已提交
397
index 556c03a03a..ac5d23ed8e 100644
398 399
--- a/src/vs/code/browser/workbench/workbench.ts
+++ b/src/vs/code/browser/workbench/workbench.ts
A
Asher 已提交
400 401 402 403 404
@@ -12,6 +12,8 @@ import { request } from 'vs/base/parts/request/browser/request';
 import { isFolderToOpen, isWorkspaceToOpen } from 'vs/platform/windows/common/windows';
 import { isEqual } from 'vs/base/common/resources';
 import { isStandalone } from 'vs/base/browser/browser';
+import { Schemas } from 'vs/base/common/network';
405 406 407 408
+import { encodePath } from 'vs/server/node/util';
 
 interface ICredential {
 	service: string;
A
Asher 已提交
409
@@ -242,12 +244,18 @@ class WorkspaceProvider implements IWorkspaceProvider {
A
Asher 已提交
410
 
411 412 413 414
 		// Folder
 		else if (isFolderToOpen(workspace)) {
-			targetHref = `${document.location.origin}${document.location.pathname}?${WorkspaceProvider.QUERY_PARAM_FOLDER}=${encodeURIComponent(workspace.folderUri.toString())}`;
+			const target = workspace.folderUri.scheme === Schemas.vscodeRemote
415
+				? encodePath(workspace.folderUri.path)
416 417 418
+				: encodeURIComponent(workspace.folderUri.toString());
+			targetHref = `${document.location.origin}${document.location.pathname}?${WorkspaceProvider.QUERY_PARAM_FOLDER}=${target}`;
 		}
A
Asher 已提交
419
 
420 421 422 423
 		// Workspace
 		else if (isWorkspaceToOpen(workspace)) {
-			targetHref = `${document.location.origin}${document.location.pathname}?${WorkspaceProvider.QUERY_PARAM_WORKSPACE}=${encodeURIComponent(workspace.workspaceUri.toString())}`;
+			const target = workspace.workspaceUri.scheme === Schemas.vscodeRemote
424
+				? encodePath(workspace.workspaceUri.path)
425 426 427
+				: encodeURIComponent(workspace.workspaceUri.toString());
+			targetHref = `${document.location.origin}${document.location.pathname}?${WorkspaceProvider.QUERY_PARAM_WORKSPACE}=${target}`;
 		}
A
Asher 已提交
428
 
429
 		// Append payload if any
A
Asher 已提交
430 431 432
@@ -284,7 +292,22 @@ class WorkspaceProvider implements IWorkspaceProvider {
 		throw new Error('Missing web configuration element');
 	}
A
Asher 已提交
433
 
A
Asher 已提交
434 435
-	const config: IWorkbenchConstructionOptions & { folderUri?: UriComponents, workspaceUri?: UriComponents } = JSON.parse(configElementAttribute);
+	const config: IWorkbenchConstructionOptions & { folderUri?: UriComponents, workspaceUri?: UriComponents } = {
A
Asher 已提交
436
+		webviewEndpoint: `${window.location.origin}${window.location.pathname.replace(/\/+$/, '')}/webview`,
A
Asher 已提交
437 438 439
+		...JSON.parse(configElementAttribute),
+	};
+
A
Asher 已提交
440
+	// Strip the protocol from the authority if it exists.
A
Asher 已提交
441
+	const normalizeAuthority = (authority: string): string => authority.replace(/^https?:\/\//, "");
A
Asher 已提交
442 443 444
+	if (config.remoteAuthority) {
+		(config as any).remoteAuthority = normalizeAuthority(config.remoteAuthority);
+	}
A
Asher 已提交
445
+	if (config.workspaceUri && config.workspaceUri.authority) {
A
Asher 已提交
446 447
+		config.workspaceUri.authority = normalizeAuthority(config.workspaceUri.authority);
+	}
A
Asher 已提交
448
+	if (config.folderUri && config.folderUri.authority) {
A
Asher 已提交
449 450
+		config.folderUri.authority = normalizeAuthority(config.folderUri.authority);
+	}
A
Asher 已提交
451
 
A
Asher 已提交
452 453
 	// Revive static extension locations
 	if (Array.isArray(config.staticExtensions)) {
A
Asher 已提交
454
@@ -296,40 +319,7 @@ class WorkspaceProvider implements IWorkspaceProvider {
455 456
 	// Find workspace to open and payload
 	let foundWorkspace = false;
457
 	let workspace: IWorkspace;
458 459
-	let payload = Object.create(null);
-
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
-	const query = new URL(document.location.href).searchParams;
-	query.forEach((value, key) => {
-		switch (key) {
-
-			// Folder
-			case WorkspaceProvider.QUERY_PARAM_FOLDER:
-				workspace = { folderUri: URI.parse(value) };
-				foundWorkspace = true;
-				break;
-
-			// Workspace
-			case WorkspaceProvider.QUERY_PARAM_WORKSPACE:
-				workspace = { workspaceUri: URI.parse(value) };
-				foundWorkspace = true;
-				break;
-
-			// Empty
-			case WorkspaceProvider.QUERY_PARAM_EMPTY_WINDOW:
-				workspace = undefined;
-				foundWorkspace = true;
-				break;
-
-			// Payload
-			case WorkspaceProvider.QUERY_PARAM_PAYLOAD:
A
Asher 已提交
484 485 486 487 488
-				try {
-					payload = JSON.parse(value);
-				} catch (error) {
-					console.error(error); // possible invalid JSON
-				}
489 490 491
-				break;
-		}
-	});
492 493
+	let payload = config.workspaceProvider?.payload || Object.create(null);
 
494 495
 	// If no workspace is provided through the URL, check for config attribute from server
 	if (!foundWorkspace) {
A
Asher 已提交
496
diff --git a/src/vs/platform/environment/common/environment.ts b/src/vs/platform/environment/common/environment.ts
A
Asher 已提交
497
index 3627ab2855..fa4f63472d 100644
A
Asher 已提交
498 499
--- a/src/vs/platform/environment/common/environment.ts
+++ b/src/vs/platform/environment/common/environment.ts
A
Asher 已提交
500 501 502 503 504 505 506 507 508 509
@@ -65,6 +65,9 @@ export interface IEnvironmentService {
 	disableTelemetry: boolean;
 	serviceMachineIdResource: URI;
 
+	// NOTE@coder: vscodevim makes use of this.
+	globalStorageHome: string;
+
 	// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 	// NOTE: DO NOT ADD ANY OTHER PROPERTY INTO THE COLLECTION HERE
 	// UNLESS THIS PROPERTY IS SUPPORTED BOTH IN WEB AND DESKTOP!!!!
A
Asher 已提交
510
diff --git a/src/vs/platform/environment/node/argv.ts b/src/vs/platform/environment/node/argv.ts
A
Asher 已提交
511
index e3aee68c8a..9e9240057c 100644
A
Asher 已提交
512 513
--- a/src/vs/platform/environment/node/argv.ts
+++ b/src/vs/platform/environment/node/argv.ts
A
Asher 已提交
514 515
@@ -8,6 +8,8 @@ import * as os from 'os';
 import { localize } from 'vs/nls';
A
Asher 已提交
516
 
A
Asher 已提交
517 518 519 520 521 522
 export interface ParsedArgs {
+	'extra-extensions-dir'?: string[];
+	'extra-builtin-extensions-dir'?: string[];
 	_: string[];
 	'folder-uri'?: string[]; // undefined or array of 1 or more
 	'file-uri'?: string[]; // undefined or array of 1 or more
A
Asher 已提交
523
@@ -139,6 +141,8 @@ export const OPTIONS: OptionDescriptions<Required<ParsedArgs>> = {
A
Asher 已提交
524
 	'extensions-dir': { type: 'string', deprecates: 'extensionHomePath', cat: 'e', args: 'dir', description: localize('extensionHomePath', "Set the root path for extensions.") },
A
Asher 已提交
525
 	'extensions-download-dir': { type: 'string' },
A
Asher 已提交
526 527 528 529 530 531
 	'builtin-extensions-dir': { type: 'string' },
+	'extra-builtin-extensions-dir': { type: 'string[]', cat: 'o', description: 'Path to an extra builtin extension directory.' },
+	'extra-extensions-dir': { type: 'string[]', cat: 'o', description: 'Path to an extra user extension directory.' },
 	'list-extensions': { type: 'boolean', cat: 'e', description: localize('listExtensions', "List the installed extensions.") },
 	'show-versions': { type: 'boolean', cat: 'e', description: localize('showVersions', "Show versions of installed extensions, when using --list-extension.") },
 	'category': { type: 'string', cat: 'e', description: localize('category', "Filters installed extensions by provided category, when using --list-extension.") },
A
Asher 已提交
532
@@ -399,4 +403,3 @@ export function buildHelpMessage(productName: string, executableName: string, ve
A
Asher 已提交
533 534 535 536
 export function buildVersionMessage(version: string | undefined, commit: string | undefined): string {
 	return `${version || localize('unknownVersion', "Unknown version")}\n${commit || localize('unknownCommit', "Unknown commit")}\n${process.arch}`;
 }
-
A
Asher 已提交
537
diff --git a/src/vs/platform/environment/node/environmentService.ts b/src/vs/platform/environment/node/environmentService.ts
A
Asher 已提交
538
index 283b4b325b..0733d21728 100644
A
Asher 已提交
539 540
--- a/src/vs/platform/environment/node/environmentService.ts
+++ b/src/vs/platform/environment/node/environmentService.ts
A
Asher 已提交
541 542 543 544 545 546 547 548 549 550 551 552 553
@@ -38,8 +38,9 @@ export interface INativeEnvironmentService extends IEnvironmentService {
 	extensionsPath?: string;
 	extensionsDownloadPath?: string;
 	builtinExtensionsPath: string;
+	extraExtensionPaths: string[];
+	extraBuiltinExtensionPaths: string[];
 
-	globalStorageHome: string;
 	workspaceStorageHome: string;
 
 	driverHandle?: string;
@@ -176,6 +177,13 @@ export class EnvironmentService implements INativeEnvironmentService {
 		return resources.joinPath(this.userHome, product.dataFolderName, 'extensions').fsPath;
A
Asher 已提交
554
 	}
A
Asher 已提交
555
 
A
Asher 已提交
556
+	@memoize get extraExtensionPaths(): string[] {
A
Asher 已提交
557
+		return (this._args['extra-extensions-dir'] || []).map((p) => <string>parsePathArg(p, process));
A
Asher 已提交
558
+	}
A
Asher 已提交
559 560 561
+	@memoize get extraBuiltinExtensionPaths(): string[] {
+		return (this._args['extra-builtin-extensions-dir'] || []).map((p) => <string>parsePathArg(p, process));
+	}
A
Asher 已提交
562 563 564 565
+
 	@memoize
 	get extensionDevelopmentLocationURI(): URI[] | undefined {
 		const s = this._args.extensionDevelopmentPath;
A
Asher 已提交
566 567 568 569 570 571 572 573 574 575
diff --git a/src/vs/platform/extensionManagement/node/extensionsScanner.ts b/src/vs/platform/extensionManagement/node/extensionsScanner.ts
index 8c9d4ce94d..5035763c08 100644
--- a/src/vs/platform/extensionManagement/node/extensionsScanner.ts
+++ b/src/vs/platform/extensionManagement/node/extensionsScanner.ts
@@ -88,7 +88,7 @@ export class ExtensionsScanner extends Disposable {
 	}
 
 	async scanAllUserExtensions(): Promise<ILocalExtension[]> {
-		return this.scanExtensionsInDir(this.extensionsPath, ExtensionType.User);
+		return this.scanExtensionsInDirs(this.extensionsPath, this.environmentService.extraExtensionPaths, ExtensionType.User);
A
Asher 已提交
576
 	}
A
Asher 已提交
577
 
A
Asher 已提交
578 579 580 581
 	async extractUserExtension(identifierWithVersion: ExtensionIdentifierWithVersion, zipPath: string, token: CancellationToken): Promise<ILocalExtension> {
@@ -214,7 +214,13 @@ export class ExtensionsScanner extends Disposable {
 
 	private async scanExtensionsInDir(dir: string, type: ExtensionType): Promise<ILocalExtension[]> {
A
Asher 已提交
582
 		const limiter = new Limiter<any>(10);
A
Asher 已提交
583 584
-		const extensionsFolders = await pfs.readdir(dir);
+		const extensionsFolders = await pfs.readdir(dir)
A
Asher 已提交
585 586 587 588
+			.catch((error) => {
+				if (error.code !== 'ENOENT') {
+					throw error;
+				}
A
Asher 已提交
589
+				return <string[]>[];
A
Asher 已提交
590 591 592
+			});
 		const extensions = await Promise.all<ILocalExtension>(extensionsFolders.map(extensionFolder => limiter.queue(() => this.scanExtension(extensionFolder, dir, type))));
 		return extensions.filter(e => e && e.identifier);
A
Asher 已提交
593
 	}
A
Asher 已提交
594
@@ -244,7 +250,7 @@ export class ExtensionsScanner extends Disposable {
A
Asher 已提交
595
 	}
A
Asher 已提交
596
 
A
Asher 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
 	private async scanDefaultSystemExtensions(): Promise<ILocalExtension[]> {
-		const result = await this.scanExtensionsInDir(this.systemExtensionsPath, ExtensionType.System);
+		const result = await this.scanExtensionsInDirs(this.systemExtensionsPath, this.environmentService.extraBuiltinExtensionPaths, ExtensionType.System);
 		this.logService.trace('Scanned system extensions:', result.length);
 		return result;
 	}
@@ -348,4 +354,9 @@ export class ExtensionsScanner extends Disposable {
 			}
 		});
 	}
+
+	private async scanExtensionsInDirs(dir: string, dirs: string[], type: ExtensionType): Promise<ILocalExtension[]>{
+		const results = await Promise.all([dir, ...dirs].map((path) => this.scanExtensionsInDir(path, type)));
+		return results.reduce((flat, current) => flat.concat(current), []);
+	}
 }
A
Asher 已提交
613
diff --git a/src/vs/platform/product/common/product.ts b/src/vs/platform/product/common/product.ts
A
Asher 已提交
614
index c413616e47..ed2adf482f 100644
A
Asher 已提交
615 616
--- a/src/vs/platform/product/common/product.ts
+++ b/src/vs/platform/product/common/product.ts
A
Asher 已提交
617
@@ -26,6 +26,12 @@ if (isWeb) {
A
Asher 已提交
618 619 620 621 622 623 624
 			urlProtocol: 'code-oss'
 		});
 	}
+	// NOTE@coder: Add the ability to inject settings from the server.
+	const el = document.getElementById('vscode-remote-product-configuration');
+	const rawProductConfiguration = el && el.getAttribute('data-settings');
+	if (rawProductConfiguration) {
A
Asher 已提交
625
+		Object.assign(product, JSON.parse(rawProductConfiguration));
A
Asher 已提交
626 627
+	}
 }
A
Asher 已提交
628
 
A
Asher 已提交
629
 // Node: AMD loader
630 631 632 633 634 635 636 637 638 639 640 641 642
diff --git a/src/vs/platform/product/common/productService.ts b/src/vs/platform/product/common/productService.ts
index 266aa69fc6..e9b51f5fde 100644
--- a/src/vs/platform/product/common/productService.ts
+++ b/src/vs/platform/product/common/productService.ts
@@ -25,6 +25,8 @@ export interface IBuiltInExtension {
 export type ConfigurationSyncStore = { url: string, authenticationProviders: IStringDictionary<{ scopes: string[] }> };
 
 export interface IProductConfiguration {
+	readonly codeServerVersion?: string;
+
 	readonly version: string;
 	readonly date?: string;
 	readonly quality?: string;
A
Asher 已提交
643 644 645 646 647 648
diff --git a/src/vs/platform/remote/browser/browserSocketFactory.ts b/src/vs/platform/remote/browser/browserSocketFactory.ts
index d0f6e6b18a..1966fd297d 100644
--- a/src/vs/platform/remote/browser/browserSocketFactory.ts
+++ b/src/vs/platform/remote/browser/browserSocketFactory.ts
@@ -205,7 +205,8 @@ export class BrowserSocketFactory implements ISocketFactory {
 	}
A
Asher 已提交
649
 
A
Asher 已提交
650 651 652 653 654 655 656 657 658 659 660 661 662 663
 	connect(host: string, port: number, query: string, callback: IConnectCallback): void {
-		const socket = this._webSocketFactory.create(`ws://${host}:${port}/?${query}&skipWebSocketFrames=false`);
+		// NOTE@coder: Modified to work against the current path.
+		const socket = this._webSocketFactory.create(`${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}${window.location.pathname}?${query}&skipWebSocketFrames=false`);
 		const errorListener = socket.onError((err) => callback(err, undefined));
 		socket.onOpen(() => {
 			errorListener.dispose();
@@ -213,6 +214,3 @@ export class BrowserSocketFactory implements ISocketFactory {
 		});
 	}
 }
-
-
-
664 665 666 667 668 669 670 671 672 673 674 675 676
diff --git a/src/vs/platform/remote/common/remoteAgentConnection.ts b/src/vs/platform/remote/common/remoteAgentConnection.ts
index eab8591492..26668701f7 100644
--- a/src/vs/platform/remote/common/remoteAgentConnection.ts
+++ b/src/vs/platform/remote/common/remoteAgentConnection.ts
@@ -88,7 +88,7 @@ async function connectToRemoteExtensionHostAgent(options: ISimpleConnectionOptio
 		options.socketFactory.connect(
 			options.host,
 			options.port,
-			`reconnectionToken=${options.reconnectionToken}&reconnection=${options.reconnectionProtocol ? 'true' : 'false'}`,
+			`type=${connectionTypeToString(connectionType)}&reconnectionToken=${options.reconnectionToken}&reconnection=${options.reconnectionProtocol ? 'true' : 'false'}`,
 			(err: any, socket: ISocket | undefined) => {
 				if (err || !socket) {
 					options.logService.error(`${logPrefix} socketFactory.connect() failed. Error:`);
A
Asher 已提交
677 678
diff --git a/src/vs/server/browser/client.ts b/src/vs/server/browser/client.ts
new file mode 100644
A
Asher 已提交
679
index 0000000000..649cf32f0a
A
Asher 已提交
680 681
--- /dev/null
+++ b/src/vs/server/browser/client.ts
A
Asher 已提交
682
@@ -0,0 +1,264 @@
A
Asher 已提交
683 684 685 686 687 688 689
+import { Emitter } from 'vs/base/common/event';
+import { URI } from 'vs/base/common/uri';
+import { localize } from 'vs/nls';
+import { Extensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
+import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
+import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
+import { ILocalizationsService } from 'vs/platform/localizations/common/localizations';
690
+import { ILogService } from 'vs/platform/log/common/log';
A
Asher 已提交
691 692 693 694 695 696 697 698 699
+import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
+import { Registry } from 'vs/platform/registry/common/platform';
+import { PersistentConnectionEventType } from 'vs/platform/remote/common/remoteAgentConnection';
+import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
+import { INodeProxyService, NodeProxyChannelClient } from 'vs/server/common/nodeProxy';
+import { TelemetryChannelClient } from 'vs/server/common/telemetry';
+import 'vs/workbench/contrib/localizations/browser/localizations.contribution';
+import { LocalizationsService } from 'vs/workbench/services/localizations/electron-browser/localizationsService';
+import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
700
+import { Options } from 'vs/server/ipc.d';
A
Asher 已提交
701
+import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
A
Asher 已提交
702 703 704 705 706 707 708 709 710
+
+class TelemetryService extends TelemetryChannelClient {
+	public constructor(
+		@IRemoteAgentService remoteAgentService: IRemoteAgentService,
+	) {
+		super(remoteAgentService.getConnection()!.getChannel('telemetry'));
+	}
+}
+
711 712 713 714 715 716
+/**
+ * Remove extra slashes in a URL.
+ */
+export const normalize = (url: string, keepTrailing = false): string => {
+	return url.replace(/\/\/+/g, "/").replace(/\/+$/, keepTrailing ? "/" : "");
+};
A
Asher 已提交
717
+
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
+/**
+ * Get options embedded in the HTML from the server.
+ */
+export const getOptions = <T extends Options>(): T => {
+	if (typeof document === "undefined") {
+		return {} as T;
+	}
+	const el = document.getElementById("coder-options");
+	try {
+		if (!el) {
+			throw new Error("no options element");
+		}
+		const value = el.getAttribute("data-settings");
+		if (!value) {
+			throw new Error("no options value");
+		}
+		const options = JSON.parse(value);
+		const parts = window.location.pathname.replace(/^\//g, "").split("/");
+		parts[parts.length - 1] = options.base;
+		const url = new URL(window.location.origin + "/" + parts.join("/"));
+		return {
+			...options,
+			base: normalize(url.pathname, true),
+		};
+	} catch (error) {
+		console.warn(error);
+		return {} as T;
+	}
+};
747
+
748 749 750
+const options = getOptions();
+
+const TELEMETRY_SECTION_ID = 'telemetry';
A
Asher 已提交
751 752 753 754 755 756 757 758 759
+Registry.as<IConfigurationRegistry>(Extensions.Configuration).registerConfiguration({
+	'id': TELEMETRY_SECTION_ID,
+	'order': 110,
+	'type': 'object',
+	'title': localize('telemetryConfigurationTitle', 'Telemetry'),
+	'properties': {
+		'telemetry.enableTelemetry': {
+			'type': 'boolean',
+			'description': localize('telemetry.enableTelemetry', 'Enable usage data and errors to be sent to a Microsoft online service.'),
760
+			'default': !options.disableTelemetry,
A
Asher 已提交
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
+			'tags': ['usesOnlineServices']
+		}
+	}
+});
+
+class NodeProxyService extends NodeProxyChannelClient implements INodeProxyService {
+	private readonly _onClose = new Emitter<void>();
+	public readonly onClose = this._onClose.event;
+	private readonly _onDown = new Emitter<void>();
+	public readonly onDown = this._onDown.event;
+	private readonly _onUp = new Emitter<void>();
+	public readonly onUp = this._onUp.event;
+
+	public constructor(
+		@IRemoteAgentService remoteAgentService: IRemoteAgentService,
+	) {
+		super(remoteAgentService.getConnection()!.getChannel('nodeProxy'));
+		remoteAgentService.getConnection()!.onDidStateChange((state) => {
+			switch (state.type) {
+				case PersistentConnectionEventType.ConnectionGain:
+					return this._onUp.fire();
+				case PersistentConnectionEventType.ConnectionLost:
+					return this._onDown.fire();
+				case PersistentConnectionEventType.ReconnectionPermanentFailure:
+					return this._onClose.fire();
+			}
+		});
+	}
+}
+
+registerSingleton(ILocalizationsService, LocalizationsService);
+registerSingleton(INodeProxyService, NodeProxyService);
+registerSingleton(ITelemetryService, TelemetryService);
+
+/**
+ * This is called by vs/workbench/browser/web.main.ts after the workbench has
+ * been initialized so we can initialize our own client-side code.
+ */
+export const initialize = async (services: ServiceCollection): Promise<void> => {
+	const event = new CustomEvent('ide-ready');
+	window.dispatchEvent(event);
+
+	if (parent) {
+		// Tell the parent loading has completed.
+		parent.postMessage({ event: 'loaded' }, window.location.origin);
+
+		// Proxy or stop proxing events as requested by the parent.
+		const listeners = new Map<string, (event: Event) => void>();
+		window.addEventListener('message', (parentEvent) => {
+			const eventName = parentEvent.data.bind || parentEvent.data.unbind;
+			if (eventName) {
+				const oldListener = listeners.get(eventName);
+				if (oldListener) {
+					document.removeEventListener(eventName, oldListener);
+				}
+			}
+
+			if (parentEvent.data.bind && parentEvent.data.prop) {
+				const listener = (event: Event) => {
+					parent.postMessage({
+						event: parentEvent.data.event,
+						[parentEvent.data.prop]: event[parentEvent.data.prop as keyof Event]
+					}, window.location.origin);
+				};
+				listeners.set(parentEvent.data.bind, listener);
+				document.addEventListener(parentEvent.data.bind, listener);
+			}
+		});
+	}
+
+	if (!window.isSecureContext) {
+		(services.get(INotificationService) as INotificationService).notify({
+			severity: Severity.Warning,
834
+			message: 'code-server is being accessed over an insecure domain. Web views, the clipboard, and other functionality will not work as expected.',
A
Asher 已提交
835 836
+			actions: {
+				primary: [{
A
Asher 已提交
837 838 839
+					id: 'understand',
+					label: 'I understand',
+					tooltip: '',
A
Asher 已提交
840 841 842 843 844 845 846 847 848 849 850
+					class: undefined,
+					enabled: true,
+					checked: true,
+					dispose: () => undefined,
+					run: () => {
+						return Promise.resolve();
+					}
+				}],
+			}
+		});
+	}
851 852 853 854
+
+	const applyUpdate = async (): Promise<void> => {
+		(services.get(ILogService) as ILogService).debug("Applying update...");
+
855
+		const response = await fetch(normalize(`${options.base}/update/apply`), {
856 857 858
+			headers: { "content-type": "application/json" },
+		});
+		const json = await response.json();
A
Asher 已提交
859 860 861
+		if (response.status !== 200 || json.error) {
+			throw new Error(json.error || response.statusText);
+		}
862 863 864 865 866 867
+		(services.get(INotificationService) as INotificationService).info(`Updated to ${json.version}`);
+	};
+
+	const getUpdate = async (): Promise<void> => {
+		(services.get(ILogService) as ILogService).debug("Checking for update...");
+
868
+		const response = await fetch(normalize(`${options.base}/update`), {
869 870 871
+			headers: { "content-type": "application/json" },
+		});
+		const json = await response.json();
A
Asher 已提交
872 873 874
+		if (response.status !== 200 || json.error) {
+			throw new Error(json.error || response.statusText);
+		}
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
+		if (json.isLatest) {
+			return;
+		}
+
+		(services.get(INotificationService) as INotificationService).notify({
+			severity: Severity.Info,
+			message: `code-server has an update: ${json.version}`,
+			actions: {
+				primary: [{
+					id: 'update',
+					label: 'Apply Update',
+					tooltip: '',
+					class: undefined,
+					enabled: true,
+					checked: true,
+					dispose: () => undefined,
+					run: applyUpdate,
+				}],
+			}
+		});
+	};
+
+	const updateLoop = (): void => {
+		getUpdate().catch((error) => {
+			(services.get(ILogService) as ILogService).warn(error);
+		}).finally(() => {
+			setTimeout(updateLoop, 300000);
+		});
+	};
+
+	updateLoop();
A
Asher 已提交
906 907 908 909 910 911
+
+	// This will be used to set the background color while VS Code loads.
+	const theme = (services.get(IStorageService) as IStorageService).get("colorThemeData", StorageScope.GLOBAL);
+	if (theme) {
+		localStorage.setItem("colorThemeData", theme);
+	}
A
Asher 已提交
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
+};
+
+export interface Query {
+	[key: string]: string | undefined;
+}
+
+/**
+ * Split a string up to the delimiter. If the delimiter doesn't exist the first
+ * item will have all the text and the second item will be an empty string.
+ */
+export const split = (str: string, delimiter: string): [string, string] => {
+	const index = str.indexOf(delimiter);
+	return index !== -1 ? [str.substring(0, index).trim(), str.substring(index + 1)] : [str, ''];
+};
+
+/**
+ * Return the URL modified with the specified query variables. It's pretty
+ * stupid so it probably doesn't cover any edge cases. Undefined values will
+ * unset existing values. Doesn't allow duplicates.
+ */
+export const withQuery = (url: string, replace: Query): string => {
+	const uri = URI.parse(url);
+	const query = { ...replace };
+	uri.query.split('&').forEach((kv) => {
+		const [key, value] = split(kv, '=');
+		if (!(key in query)) {
+			query[key] = value;
+		}
+	});
+	return uri.with({
+		query: Object.keys(query)
+			.filter((k) => typeof query[k] !== 'undefined')
+			.map((k) => `${k}=${query[k]}`).join('&'),
+	}).toString(true);
+};
diff --git a/src/vs/server/browser/extHostNodeProxy.ts b/src/vs/server/browser/extHostNodeProxy.ts
new file mode 100644
index 0000000000..ed7c078077
--- /dev/null
+++ b/src/vs/server/browser/extHostNodeProxy.ts
@@ -0,0 +1,46 @@
+import { Emitter } from 'vs/base/common/event';
+import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
+import { ExtHostNodeProxyShape, MainContext, MainThreadNodeProxyShape } from 'vs/workbench/api/common/extHost.protocol';
+import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
+
+export class ExtHostNodeProxy implements ExtHostNodeProxyShape {
+	_serviceBrand: any;
+
+	private readonly _onMessage = new Emitter<string>();
+	public readonly onMessage = this._onMessage.event;
+	private readonly _onClose = new Emitter<void>();
+	public readonly onClose = this._onClose.event;
+	private readonly _onDown = new Emitter<void>();
+	public readonly onDown = this._onDown.event;
+	private readonly _onUp = new Emitter<void>();
+	public readonly onUp = this._onUp.event;
+
+	private readonly proxy: MainThreadNodeProxyShape;
+
+	constructor(@IExtHostRpcService rpc: IExtHostRpcService) {
+		this.proxy = rpc.getProxy(MainContext.MainThreadNodeProxy);
+	}
+
+	public $onMessage(message: string): void {
+		this._onMessage.fire(message);
+	}
+
+	public $onClose(): void {
+		this._onClose.fire();
+	}
+
+	public $onUp(): void {
+		this._onUp.fire();
+	}
+
+	public $onDown(): void {
+		this._onDown.fire();
+	}
+
+	public send(message: string): void {
+		this.proxy.$send(message);
+	}
+}
+
+export interface IExtHostNodeProxy extends ExtHostNodeProxy { }
+export const IExtHostNodeProxy = createDecorator<IExtHostNodeProxy>('IExtHostNodeProxy');
diff --git a/src/vs/server/browser/mainThreadNodeProxy.ts b/src/vs/server/browser/mainThreadNodeProxy.ts
new file mode 100644
index 0000000000..0d2e93edae
--- /dev/null
+++ b/src/vs/server/browser/mainThreadNodeProxy.ts
@@ -0,0 +1,37 @@
+import { IDisposable } from 'vs/base/common/lifecycle';
+import { INodeProxyService } from 'vs/server/common/nodeProxy';
+import { ExtHostContext, IExtHostContext, MainContext, MainThreadNodeProxyShape } from 'vs/workbench/api/common/extHost.protocol';
+import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
+
+@extHostNamedCustomer(MainContext.MainThreadNodeProxy)
+export class MainThreadNodeProxy implements MainThreadNodeProxyShape {
+	private disposed = false;
+	private disposables = <IDisposable[]>[];
+
+	constructor(
+		extHostContext: IExtHostContext,
+		@INodeProxyService private readonly proxyService: INodeProxyService,
+	) {
+		if (!extHostContext.remoteAuthority) { // HACK: A terrible way to detect if running in the worker.
+			const proxy = extHostContext.getProxy(ExtHostContext.ExtHostNodeProxy);
+			this.disposables = [
+				this.proxyService.onMessage((message: string) => proxy.$onMessage(message)),
+				this.proxyService.onClose(() => proxy.$onClose()),
+				this.proxyService.onDown(() => proxy.$onDown()),
+				this.proxyService.onUp(() => proxy.$onUp()),
+			];
+		}
+	}
+
+	$send(message: string): void {
+		if (!this.disposed) {
+			this.proxyService.send(message);
+		}
+	}
+
+	dispose(): void {
+		this.disposables.forEach((d) => d.dispose());
+		this.disposables = [];
+		this.disposed = true;
+	}
+}
diff --git a/src/vs/server/browser/worker.ts b/src/vs/server/browser/worker.ts
new file mode 100644
1044
index 0000000000..a93381631a
A
Asher 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
--- /dev/null
+++ b/src/vs/server/browser/worker.ts
@@ -0,0 +1,57 @@
+import { Client } from '@coder/node-browser';
+import { fromTar } from '@coder/requirefs';
+import { URI } from 'vs/base/common/uri';
+import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
+import { ILogService } from 'vs/platform/log/common/log';
+import { ExtensionActivationTimesBuilder } from 'vs/workbench/api/common/extHostExtensionActivator';
+import { IExtHostNodeProxy } from './extHostNodeProxy';
+
+export const loadCommonJSModule = async <T>(
+	module: IExtensionDescription,
+	activationTimesBuilder: ExtensionActivationTimesBuilder,
+	nodeProxy: IExtHostNodeProxy,
+	logService: ILogService,
+	vscode: any,
+): Promise<T> => {
+	const fetchUri = URI.from({
+		scheme: self.location.protocol.replace(':', ''),
+		authority: self.location.host,
1066
+		path: self.location.pathname.replace(/\/static\/([^\/]+)\/.*$/, '/static/$1\/'),
1067
+		query: `tar=${encodeURIComponent(module.extensionLocation.path)}`,
A
Asher 已提交
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
+	});
+	const response = await fetch(fetchUri.toString(true));
+	if (response.status !== 200) {
+		throw new Error(`Failed to download extension "${module.extensionLocation.path}"`);
+	}
+	const client = new Client(nodeProxy, { logger: logService });
+	const init = await client.handshake();
+	const buffer = new Uint8Array(await response.arrayBuffer());
+	const rfs = fromTar(buffer);
+	(<any>self).global = self;
+	rfs.provide('vscode', vscode);
+	Object.keys(client.modules).forEach((key) => {
+		const mod = (client.modules as any)[key];
+		if (key === 'process') {
+			(<any>self).process = mod;
+			(<any>self).process.env = init.env;
+			return;
+		}
+
+		rfs.provide(key, mod);
+		switch (key) {
+			case 'buffer':
+				(<any>self).Buffer = mod.Buffer;
+				break;
+			case 'timers':
+				(<any>self).setImmediate = mod.setImmediate;
+				break;
+		}
+	});
+
+	try {
+		activationTimesBuilder.codeLoadingStart();
+		return rfs.require('.');
+	} finally {
+		activationTimesBuilder.codeLoadingStop();
+	}
+};
diff --git a/src/vs/server/common/nodeProxy.ts b/src/vs/server/common/nodeProxy.ts
new file mode 100644
index 0000000000..14b9de879c
--- /dev/null
+++ b/src/vs/server/common/nodeProxy.ts
@@ -0,0 +1,47 @@
+import { ReadWriteConnection } from '@coder/node-browser';
+import { Event } from 'vs/base/common/event';
+import { IChannel, IServerChannel } from 'vs/base/parts/ipc/common/ipc';
+import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
+
+export const INodeProxyService = createDecorator<INodeProxyService>('nodeProxyService');
+
+export interface INodeProxyService extends ReadWriteConnection {
+	_serviceBrand: any;
+	send(message: string): void;
+	onMessage: Event<string>;
+	onUp: Event<void>;
+	onClose: Event<void>;
+	onDown: Event<void>;
+}
+
+export class NodeProxyChannel implements IServerChannel {
+	constructor(private service: INodeProxyService) {}
+
+	listen(_: unknown, event: string): Event<any> {
+		switch (event) {
+			case 'onMessage': return this.service.onMessage;
+		}
+		throw new Error(`Invalid listen ${event}`);
+	}
+
+	async call(_: unknown, command: string, args?: any): Promise<any> {
+		switch (command) {
+			case 'send': return this.service.send(args[0]);
+		}
+		throw new Error(`Invalid call ${command}`);
+	}
+}
+
+export class NodeProxyChannelClient {
+	_serviceBrand: any;
+
+	public readonly onMessage: Event<string>;
+
+	constructor(private readonly channel: IChannel) {
+		this.onMessage = this.channel.listen<string>('onMessage');
+	}
+
+	public send(data: string): void {
+		this.channel.call('send', [data]);
+	}
+}
diff --git a/src/vs/server/common/telemetry.ts b/src/vs/server/common/telemetry.ts
new file mode 100644
A
Asher 已提交
1160
index 0000000000..4cd0d91657
A
Asher 已提交
1161 1162
--- /dev/null
+++ b/src/vs/server/common/telemetry.ts
A
Asher 已提交
1163
@@ -0,0 +1,60 @@
A
Asher 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
+import { ITelemetryData } from 'vs/base/common/actions';
+import { Event } from 'vs/base/common/event';
+import { IChannel, IServerChannel } from 'vs/base/parts/ipc/common/ipc';
+import { ClassifiedEvent, GDPRClassification, StrictPropertyCheck } from 'vs/platform/telemetry/common/gdprTypings';
+import { ITelemetryInfo, ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
+
+export class TelemetryChannel implements IServerChannel {
+	constructor(private service: ITelemetryService) {}
+
+	listen(_: unknown, event: string): Event<any> {
+		throw new Error(`Invalid listen ${event}`);
+	}
+
+	call(_: unknown, command: string, args?: any): Promise<any> {
+		switch (command) {
+			case 'publicLog': return this.service.publicLog(args[0], args[1], args[2]);
+			case 'publicLog2': return this.service.publicLog2(args[0], args[1], args[2]);
A
Asher 已提交
1181 1182
+			case 'publicLogError': return this.service.publicLogError(args[0], args[1]);
+			case 'publicLogError2': return this.service.publicLogError2(args[0], args[1]);
A
Asher 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
+			case 'setEnabled': return Promise.resolve(this.service.setEnabled(args[0]));
+			case 'getTelemetryInfo': return this.service.getTelemetryInfo();
+		}
+		throw new Error(`Invalid call ${command}`);
+	}
+}
+
+export class TelemetryChannelClient implements ITelemetryService {
+	_serviceBrand: any;
+
A
Asher 已提交
1193 1194 1195 1196 1197
+	// These don't matter; telemetry is sent to the Node side which decides
+	// whether to send the telemetry event.
+	public isOptedIn = true;
+	public sendErrorTelemetry = true;
+
A
Asher 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
+	constructor(private readonly channel: IChannel) {}
+
+	public publicLog(eventName: string, data?: ITelemetryData, anonymizeFilePaths?: boolean): Promise<void> {
+		return this.channel.call('publicLog', [eventName, data, anonymizeFilePaths]);
+	}
+
+	public publicLog2<E extends ClassifiedEvent<T> = never, T extends GDPRClassification<T> = never>(eventName: string, data?: StrictPropertyCheck<T, E>, anonymizeFilePaths?: boolean): Promise<void> {
+		return this.channel.call('publicLog2', [eventName, data, anonymizeFilePaths]);
+	}
+
A
Asher 已提交
1208 1209 1210 1211 1212 1213 1214 1215
+	public publicLogError(errorEventName: string, data?: ITelemetryData): Promise<void> {
+		return this.channel.call('publicLogError', [errorEventName, data]);
+	}
+
+	public publicLogError2<E extends ClassifiedEvent<T> = never, T extends GDPRClassification<T> = never>(eventName: string, data?: StrictPropertyCheck<T, E>): Promise<void> {
+		return this.channel.call('publicLogError2', [eventName, data]);
+	}
+
A
Asher 已提交
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
+	public setEnabled(value: boolean): void {
+		this.channel.call('setEnable', [value]);
+	}
+
+	public getTelemetryInfo(): Promise<ITelemetryInfo> {
+		return this.channel.call('getTelemetryInfo');
+	}
+}
diff --git a/src/vs/server/entry.ts b/src/vs/server/entry.ts
new file mode 100644
A
Asher 已提交
1226
index 0000000000..ab020fbb4e
A
Asher 已提交
1227 1228
--- /dev/null
+++ b/src/vs/server/entry.ts
A
Asher 已提交
1229
@@ -0,0 +1,78 @@
A
Asher 已提交
1230 1231 1232 1233 1234 1235 1236
+import { field } from '@coder/logger';
+import { setUnexpectedErrorHandler } from 'vs/base/common/errors';
+import { CodeServerMessage, VscodeMessage } from 'vs/server/ipc';
+import { logger } from 'vs/server/node/logger';
+import { enableCustomMarketplace } from 'vs/server/node/marketplace';
+import { Vscode } from 'vs/server/node/server';
+
A
Asher 已提交
1237
+setUnexpectedErrorHandler((error) => logger.warn(error instanceof Error ? error.message : error));
A
Asher 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
+enableCustomMarketplace();
+
+/**
+ * Ensure we control when the process exits.
+ */
+const exit = process.exit;
+process.exit = function(code?: number) {
+	logger.warn(`process.exit() was prevented: ${code || 'unknown code'}.`);
+} as (code?: number) => never;
+
+// Kill VS Code if the parent process dies.
+if (typeof process.env.CODE_SERVER_PARENT_PID !== 'undefined') {
+	const parentPid = parseInt(process.env.CODE_SERVER_PARENT_PID, 10);
+	setInterval(() => {
+		try {
+			process.kill(parentPid, 0); // Throws an exception if the process doesn't exist anymore.
+		} catch (e) {
+			exit();
+		}
+	}, 5000);
+} else {
+	logger.error('no parent process');
+	exit(1);
+}
+
+const vscode = new Vscode();
+const send = (message: VscodeMessage): void => {
+	if (!process.send) {
+		throw new Error('not spawned with IPC');
+	}
+	process.send(message);
+};
+
1271 1272
+// Wait for the init message then start up VS Code. Subsequent messages will
+// return new workbench options without starting a new instance.
A
Asher 已提交
1273 1274 1275 1276 1277 1278 1279 1280 1281
+process.on('message', async (message: CodeServerMessage, socket) => {
+	logger.debug('got message from code-server', field('message', message));
+	switch (message.type) {
+		case 'init':
+			try {
+				const options = await vscode.initialize(message.options);
+				send({ type: 'options', id: message.id, options });
+			} catch (error) {
+				logger.error(error.message);
A
Asher 已提交
1282
+				logger.error(error.stack);
A
Asher 已提交
1283 1284 1285
+				exit(1);
+			}
+			break;
A
Asher 已提交
1286 1287 1288 1289 1290 1291
+		case 'cli':
+			try {
+				await vscode.cli(message.args);
+				exit(0);
+			} catch (error) {
+				logger.error(error.message);
A
Asher 已提交
1292
+				logger.error(error.stack);
A
Asher 已提交
1293 1294 1295
+				exit(1);
+			}
+			break;
A
Asher 已提交
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
+		case 'socket':
+			vscode.handleWebSocket(socket, message.query);
+			break;
+	}
+});
+if (!process.send) {
+	logger.error('not spawned with IPC');
+	exit(1);
+} else {
+	// This lets the parent know the child is ready to receive messages.
+	send({ type: 'ready' });
+}
diff --git a/src/vs/server/fork.js b/src/vs/server/fork.js
new file mode 100644
index 0000000000..56331ff1fc
--- /dev/null
+++ b/src/vs/server/fork.js
@@ -0,0 +1,3 @@
+// This must be a JS file otherwise when it gets compiled it turns into AMD
+// syntax which will not work without the right loader.
+require('../../bootstrap-amd').load('vs/server/entry');
diff --git a/src/vs/server/ipc.d.ts b/src/vs/server/ipc.d.ts
new file mode 100644
1319
index 0000000000..0a9c95d50e
A
Asher 已提交
1320 1321
--- /dev/null
+++ b/src/vs/server/ipc.d.ts
1322
@@ -0,0 +1,117 @@
A
Asher 已提交
1323 1324 1325 1326
+/**
+ * External interfaces for integration into code-server over IPC. No vs imports
+ * should be made in this file.
+ */
1327 1328 1329 1330 1331
+export interface Options {
+	base: string
+	commit: string
+	disableTelemetry: boolean
+}
A
Asher 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
+
+export interface InitMessage {
+	type: 'init';
+	id: string;
+	options: VscodeOptions;
+}
+
+export type Query = { [key: string]: string | string[] | undefined };
+
+export interface SocketMessage {
+	type: 'socket';
+	query: Query;
+}
+
A
Asher 已提交
1346 1347 1348 1349 1350 1351
+export interface CliMessage {
+	type: 'cli';
+	args: Args;
+}
+
+export type CodeServerMessage = InitMessage | SocketMessage | CliMessage;
A
Asher 已提交
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
+
+export interface ReadyMessage {
+	type: 'ready';
+}
+
+export interface OptionsMessage {
+	id: string;
+	type: 'options';
+	options: WorkbenchOptions;
+}
+
+export type VscodeMessage = ReadyMessage | OptionsMessage;
+
+export interface StartPath {
1366 1367
+	url: string;
+	workspace: boolean;
A
Asher 已提交
1368 1369
+}
+
1370
+export interface Args {
1371 1372 1373 1374 1375 1376 1377
+	'user-data-dir'?: string;
+
+	'extensions-dir'?: string;
+	'builtin-extensions-dir'?: string;
+	'extra-extensions-dir'?: string[];
+	'extra-builtin-extensions-dir'?: string[];
+
A
Asher 已提交
1378 1379
+	locale?: string
+
1380 1381 1382
+	log?: string;
+	verbose?: boolean;
+
1383
+	_: string[];
A
Asher 已提交
1384 1385 1386
+}
+
+export interface VscodeOptions {
1387
+	readonly args: Args;
A
Asher 已提交
1388
+	readonly remoteAuthority: string;
1389
+	readonly startPath?: StartPath;
A
Asher 已提交
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
+}
+
+export interface VscodeOptionsMessage extends VscodeOptions {
+	readonly id: string;
+}
+
+export interface UriComponents {
+	readonly scheme: string;
+	readonly authority: string;
+	readonly path: string;
+	readonly query: string;
+	readonly fragment: string;
+}
+
+export interface NLSConfiguration {
+	locale: string;
+	availableLanguages: {
+		[key: string]: string;
+	};
+	pseudo?: boolean;
+	_languagePackSupport?: boolean;
+}
+
+export interface WorkbenchOptions {
+	readonly workbenchWebConfiguration: {
+		readonly remoteAuthority?: string;
+		readonly folderUri?: UriComponents;
+		readonly workspaceUri?: UriComponents;
+		readonly logLevel?: number;
1419 1420 1421
+		readonly workspaceProvider?: {
+			payload: [["userDataPath", string]];
+		};
A
Asher 已提交
1422 1423 1424
+	};
+	readonly remoteUserDataUri: UriComponents;
+	readonly productConfiguration: {
1425
+		codeServerVersion?: string;
A
Asher 已提交
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
+		readonly extensionsGallery?: {
+			readonly serviceUrl: string;
+			readonly itemUrl: string;
+			readonly controlUrl: string;
+			readonly recommendationsUrl: string;
+		};
+	};
+	readonly nlsConfiguration: NLSConfiguration;
+	readonly commit: string;
+}
+
+export interface WorkbenchOptionsMessage {
+	id: string;
+}
diff --git a/src/vs/server/node/channel.ts b/src/vs/server/node/channel.ts
new file mode 100644
1442
index 0000000000..1166835371
A
Asher 已提交
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
--- /dev/null
+++ b/src/vs/server/node/channel.ts
@@ -0,0 +1,343 @@
+import { Server } from '@coder/node-browser';
+import * as path from 'path';
+import { VSBuffer, VSBufferReadableStream } from 'vs/base/common/buffer';
+import { Emitter, Event } from 'vs/base/common/event';
+import { IDisposable } from 'vs/base/common/lifecycle';
+import { OS } from 'vs/base/common/platform';
+import { ReadableStreamEventPayload } from 'vs/base/common/stream';
+import { URI, UriComponents } from 'vs/base/common/uri';
+import { transformOutgoingURIs } from 'vs/base/common/uriIpc';
+import { IServerChannel } from 'vs/base/parts/ipc/common/ipc';
+import { IDiagnosticInfo } from 'vs/platform/diagnostics/common/diagnostics';
A
Asher 已提交
1457
+import { INativeEnvironmentService } from 'vs/platform/environment/node/environmentService';
A
Asher 已提交
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
+import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
+import { FileDeleteOptions, FileOpenOptions, FileOverwriteOptions, FileReadStreamOptions, FileType, FileWriteOptions, IStat, IWatchOptions } from 'vs/platform/files/common/files';
+import { createReadStream } from 'vs/platform/files/common/io';
+import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider';
+import { ILogService } from 'vs/platform/log/common/log';
+import product from 'vs/platform/product/common/product';
+import { IRemoteAgentEnvironment, RemoteAgentConnectionContext } from 'vs/platform/remote/common/remoteAgentEnvironment';
+import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
+import { INodeProxyService } from 'vs/server/common/nodeProxy';
+import { getTranslations } from 'vs/server/node/nls';
+import { getUriTransformer } from 'vs/server/node/util';
+import { IFileChangeDto } from 'vs/workbench/api/common/extHost.protocol';
+import { ExtensionScanner, ExtensionScannerInput } from 'vs/workbench/services/extensions/node/extensionPoints';
+
+/**
+ * Extend the file provider to allow unwatching.
+ */
+class Watcher extends DiskFileSystemProvider {
+	public readonly watches = new Map<number, IDisposable>();
+
+	public dispose(): void {
+		this.watches.forEach((w) => w.dispose());
+		this.watches.clear();
+		super.dispose();
+	}
+
+	public _watch(req: number, resource: URI, opts: IWatchOptions): void {
+		this.watches.set(req, this.watch(resource, opts));
+	}
+
+	public unwatch(req: number): void {
+		this.watches.get(req)!.dispose();
+		this.watches.delete(req);
+	}
+}
+
+export class FileProviderChannel implements IServerChannel<RemoteAgentConnectionContext>, IDisposable {
+	private readonly provider: DiskFileSystemProvider;
+	private readonly watchers = new Map<string, Watcher>();
+
+	public constructor(
A
Asher 已提交
1499
+		private readonly environmentService: INativeEnvironmentService,
A
Asher 已提交
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
+		private readonly logService: ILogService,
+	) {
+		this.provider = new DiskFileSystemProvider(this.logService);
+	}
+
+	public listen(context: RemoteAgentConnectionContext, event: string, args?: any): Event<any> {
+		switch (event) {
+			case 'filechange': return this.filechange(context, args[0]);
+			case 'readFileStream': return this.readFileStream(args[0], args[1]);
+		}
+
+		throw new Error(`Invalid listen '${event}'`);
+	}
+
+	private filechange(context: RemoteAgentConnectionContext, session: string): Event<IFileChangeDto[]> {
+		const emitter = new Emitter<IFileChangeDto[]>({
+			onFirstListenerAdd: () => {
+				const provider = new Watcher(this.logService);
+				this.watchers.set(session, provider);
+				const transformer = getUriTransformer(context.remoteAuthority);
+				provider.onDidChangeFile((events) => {
+					emitter.fire(events.map((event) => ({
+						...event,
+						resource: transformer.transformOutgoing(event.resource),
+					})));
+				});
+				provider.onDidErrorOccur((event) => this.logService.error(event));
+			},
+			onLastListenerRemove: () => {
+				this.watchers.get(session)!.dispose();
+				this.watchers.delete(session);
+			},
+		});
+
+		return emitter.event;
+	}
+
+	private readFileStream(resource: UriComponents, opts: FileReadStreamOptions): Event<ReadableStreamEventPayload<VSBuffer>> {
+		let fileStream: VSBufferReadableStream | undefined;
+		const emitter = new Emitter<ReadableStreamEventPayload<VSBuffer>>({
+			onFirstListenerAdd: () => {
+				if (!fileStream) {
+					fileStream = createReadStream(this.provider, this.transform(resource), {
+						...opts,
+						bufferSize: 64 * 1024, // From DiskFileSystemProvider
+					});
+					fileStream.on('data', (data) => emitter.fire(data));
+					fileStream.on('error', (error) => emitter.fire(error));
+					fileStream.on('end', () => emitter.fire('end'));
+				}
+			},
+			onLastListenerRemove: () => fileStream && fileStream.destroy(),
+		});
+
+		return emitter.event;
+	}
+
+	public call(_: unknown, command: string, args?: any): Promise<any> {
+		switch (command) {
+			case 'stat': return this.stat(args[0]);
+			case 'open': return this.open(args[0], args[1]);
+			case 'close': return this.close(args[0]);
+			case 'read': return this.read(args[0], args[1], args[2]);
+			case 'readFile': return this.readFile(args[0]);
+			case 'write': return this.write(args[0], args[1], args[2], args[3], args[4]);
+			case 'writeFile': return this.writeFile(args[0], args[1], args[2]);
+			case 'delete': return this.delete(args[0], args[1]);
+			case 'mkdir': return this.mkdir(args[0]);
+			case 'readdir': return this.readdir(args[0]);
+			case 'rename': return this.rename(args[0], args[1], args[2]);
+			case 'copy': return this.copy(args[0], args[1], args[2]);
+			case 'watch': return this.watch(args[0], args[1], args[2], args[3]);
+			case 'unwatch': return this.unwatch(args[0], args[1]);
+		}
+
+		throw new Error(`Invalid call '${command}'`);
+	}
+
+	public dispose(): void {
+		this.watchers.forEach((w) => w.dispose());
+		this.watchers.clear();
+	}
+
+	private async stat(resource: UriComponents): Promise<IStat> {
+		return this.provider.stat(this.transform(resource));
+	}
+
+	private async open(resource: UriComponents, opts: FileOpenOptions): Promise<number> {
+		return this.provider.open(this.transform(resource), opts);
+	}
+
+	private async close(fd: number): Promise<void> {
+		return this.provider.close(fd);
+	}
+
+	private async read(fd: number, pos: number, length: number): Promise<[VSBuffer, number]> {
+		const buffer = VSBuffer.alloc(length);
+		const bytesRead = await this.provider.read(fd, pos, buffer.buffer, 0, length);
+		return [buffer, bytesRead];
+	}
+
+	private async readFile(resource: UriComponents): Promise<VSBuffer> {
+		return VSBuffer.wrap(await this.provider.readFile(this.transform(resource)));
+	}
+
+	private write(fd: number, pos: number, buffer: VSBuffer, offset: number, length: number): Promise<number> {
+		return this.provider.write(fd, pos, buffer.buffer, offset, length);
+	}
+
+	private writeFile(resource: UriComponents, buffer: VSBuffer, opts: FileWriteOptions): Promise<void> {
+		return this.provider.writeFile(this.transform(resource), buffer.buffer, opts);
+	}
+
+	private async delete(resource: UriComponents, opts: FileDeleteOptions): Promise<void> {
+		return this.provider.delete(this.transform(resource), opts);
+	}
+
+	private async mkdir(resource: UriComponents): Promise<void> {
+		return this.provider.mkdir(this.transform(resource));
+	}
+
+	private async readdir(resource: UriComponents): Promise<[string, FileType][]> {
+		return this.provider.readdir(this.transform(resource));
+	}
+
+	private async rename(resource: UriComponents, target: UriComponents, opts: FileOverwriteOptions): Promise<void> {
+		return this.provider.rename(this.transform(resource), URI.from(target), opts);
+	}
+
+	private copy(resource: UriComponents, target: UriComponents, opts: FileOverwriteOptions): Promise<void> {
+		return this.provider.copy(this.transform(resource), URI.from(target), opts);
+	}
+
+	private async watch(session: string, req: number, resource: UriComponents, opts: IWatchOptions): Promise<void> {
+		this.watchers.get(session)!._watch(req, this.transform(resource), opts);
+	}
+
+	private async unwatch(session: string, req: number): Promise<void> {
+		this.watchers.get(session)!.unwatch(req);
+	}
+
+	private transform(resource: UriComponents): URI {
+		// Used for walkthrough content.
+		if (/^\/static[^/]*\//.test(resource.path)) {
+			return URI.file(this.environmentService.appRoot + resource.path.replace(/^\/static[^/]*\//, '/'));
+		// Used by the webview service worker to load resources.
+		} else if (resource.path === '/vscode-resource' && resource.query) {
+			try {
+				const query = JSON.parse(resource.query);
+				if (query.requestResourcePath) {
+					return URI.file(query.requestResourcePath);
+				}
+			} catch (error) { /* Carry on. */ }
+		}
+		return URI.from(resource);
+	}
+}
+
+export class ExtensionEnvironmentChannel implements IServerChannel {
+	public constructor(
A
Asher 已提交
1660
+		private readonly environment: INativeEnvironmentService,
A
Asher 已提交
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
+		private readonly log: ILogService,
+		private readonly telemetry: ITelemetryService,
+		private readonly connectionToken: string,
+	) {}
+
+	public listen(_: unknown, event: string): Event<any> {
+		throw new Error(`Invalid listen '${event}'`);
+	}
+
+	public async call(context: any, command: string, args?: any): Promise<any> {
+		switch (command) {
+			case 'getEnvironmentData':
+				return transformOutgoingURIs(
+					await this.getEnvironmentData(args.language),
+					getUriTransformer(context.remoteAuthority),
+				);
+			case 'getDiagnosticInfo': return this.getDiagnosticInfo();
+			case 'disableTelemetry': return this.disableTelemetry();
+		}
+		throw new Error(`Invalid call '${command}'`);
+	}
+
+	private async getEnvironmentData(locale: string): Promise<IRemoteAgentEnvironment> {
+		return {
+			pid: process.pid,
+			connectionToken: this.connectionToken,
+			appRoot: URI.file(this.environment.appRoot),
+			appSettingsHome: this.environment.appSettingsHome,
1689
+			settingsPath: this.environment.settingsResource,
A
Asher 已提交
1690 1691 1692 1693
+			logsPath: URI.file(this.environment.logsPath),
+			extensionsPath: URI.file(this.environment.extensionsPath!),
+			extensionHostLogsPath: URI.file(path.join(this.environment.logsPath, 'extension-host')),
+			globalStorageHome: URI.file(this.environment.globalStorageHome),
A
Asher 已提交
1694
+			userHome: this.environment.userHome,
A
Asher 已提交
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
+			extensions: await this.scanExtensions(locale),
+			os: OS,
+		};
+	}
+
+	private async scanExtensions(locale: string): Promise<IExtensionDescription[]> {
+		const translations = await getTranslations(locale, this.environment.userDataPath);
+
+		const scanMultiple = (isBuiltin: boolean, isUnderDevelopment: boolean, paths: string[]): Promise<IExtensionDescription[][]> => {
+			return Promise.all(paths.map((path) => {
+				return ExtensionScanner.scanExtensions(new ExtensionScannerInput(
+					product.version,
+					product.commit,
+					locale,
+					!!process.env.VSCODE_DEV,
+					path,
+					isBuiltin,
+					isUnderDevelopment,
+					translations,
+				), this.log);
+			}));
+		};
+
+		const scanBuiltin = async (): Promise<IExtensionDescription[][]> => {
+			return scanMultiple(true, false, [this.environment.builtinExtensionsPath, ...this.environment.extraBuiltinExtensionPaths]);
+		};
+
+		const scanInstalled = async (): Promise<IExtensionDescription[][]> => {
+			return scanMultiple(false, true, [this.environment.extensionsPath!, ...this.environment.extraExtensionPaths]);
+		};
+
+		return Promise.all([scanBuiltin(), scanInstalled()]).then((allExtensions) => {
+			const uniqueExtensions = new Map<string, IExtensionDescription>();
+			allExtensions.forEach((multipleExtensions) => {
+				multipleExtensions.forEach((extensions) => {
+					extensions.forEach((extension) => {
+						const id = ExtensionIdentifier.toKey(extension.identifier);
+						if (uniqueExtensions.has(id)) {
+							const oldPath = uniqueExtensions.get(id)!.extensionLocation.fsPath;
+							const newPath = extension.extensionLocation.fsPath;
+							this.log.warn(`${oldPath} has been overridden ${newPath}`);
+						}
+						uniqueExtensions.set(id, extension);
+					});
+				});
+			});
+			return Array.from(uniqueExtensions.values());
+		});
+	}
+
+	private getDiagnosticInfo(): Promise<IDiagnosticInfo> {
+		throw new Error('not implemented');
+	}
+
+	private async disableTelemetry(): Promise<void> {
+		this.telemetry.setEnabled(false);
+	}
+}
+
+export class NodeProxyService implements INodeProxyService {
+	public _serviceBrand = undefined;
+
+	public readonly server: Server;
+
+	private readonly _onMessage = new Emitter<string>();
+	public readonly onMessage = this._onMessage.event;
+	private readonly _$onMessage = new Emitter<string>();
+	public readonly $onMessage = this._$onMessage.event;
+	public readonly _onDown = new Emitter<void>();
+	public readonly onDown = this._onDown.event;
+	public readonly _onUp = new Emitter<void>();
+	public readonly onUp = this._onUp.event;
+
+	// Unused because the server connection will never permanently close.
+	private readonly _onClose = new Emitter<void>();
+	public readonly onClose = this._onClose.event;
+
+	public constructor() {
+		// TODO: down/up
+		this.server = new Server({
+			onMessage: this.$onMessage,
+			onClose: this.onClose,
+			onDown: this.onDown,
+			onUp: this.onUp,
+			send: (message: string): void => {
+				this._onMessage.fire(message);
+			}
+		});
+	}
+
+	public send(message: string): void {
+		this._$onMessage.fire(message);
+	}
+}
diff --git a/src/vs/server/node/connection.ts b/src/vs/server/node/connection.ts
new file mode 100644
1791
index 0000000000..36e80fb696
A
Asher 已提交
1792 1793
--- /dev/null
+++ b/src/vs/server/node/connection.ts
A
Asher 已提交
1794
@@ -0,0 +1,157 @@
A
Asher 已提交
1795 1796 1797 1798 1799 1800
+import * as cp from 'child_process';
+import { getPathFromAmdModule } from 'vs/base/common/amd';
+import { VSBuffer } from 'vs/base/common/buffer';
+import { Emitter } from 'vs/base/common/event';
+import { ISocket } from 'vs/base/parts/ipc/common/ipc.net';
+import { NodeSocket } from 'vs/base/parts/ipc/node/ipc.net';
A
Asher 已提交
1801
+import { INativeEnvironmentService } from 'vs/platform/environment/node/environmentService';
A
Asher 已提交
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
+import { ILogService } from 'vs/platform/log/common/log';
+import { getNlsConfiguration } from 'vs/server/node/nls';
+import { Protocol } from 'vs/server/node/protocol';
+import { IExtHostReadyMessage } from 'vs/workbench/services/extensions/common/extensionHostProtocol';
+
+export abstract class Connection {
+	private readonly _onClose = new Emitter<void>();
+	public readonly onClose = this._onClose.event;
+	private disposed = false;
+	private _offline: number | undefined;
+
+	public constructor(protected protocol: Protocol, public readonly token: string) {}
+
+	public get offline(): number | undefined {
+		return this._offline;
+	}
+
+	public reconnect(socket: ISocket, buffer: VSBuffer): void {
+		this._offline = undefined;
+		this.doReconnect(socket, buffer);
+	}
+
+	public dispose(): void {
+		if (!this.disposed) {
+			this.disposed = true;
+			this.doDispose();
+			this._onClose.fire();
+		}
+	}
+
+	protected setOffline(): void {
+		if (!this._offline) {
+			this._offline = Date.now();
+		}
+	}
+
+	/**
+	 * Set up the connection on a new socket.
+	 */
+	protected abstract doReconnect(socket: ISocket, buffer: VSBuffer): void;
+	protected abstract doDispose(): void;
+}
+
+/**
+ * Used for all the IPC channels.
+ */
+export class ManagementConnection extends Connection {
+	public constructor(protected protocol: Protocol, token: string) {
+		super(protocol, token);
+		protocol.onClose(() => this.dispose()); // Explicit close.
+		protocol.onSocketClose(() => this.setOffline()); // Might reconnect.
+	}
+
+	protected doDispose(): void {
+		this.protocol.sendDisconnect();
+		this.protocol.dispose();
1858
+		this.protocol.getUnderlyingSocket().destroy();
A
Asher 已提交
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
+	}
+
+	protected doReconnect(socket: ISocket, buffer: VSBuffer): void {
+		this.protocol.beginAcceptReconnection(socket, buffer);
+		this.protocol.endAcceptReconnection();
+	}
+}
+
+export class ExtensionHostConnection extends Connection {
+	private process?: cp.ChildProcess;
+
+	public constructor(
+		locale:string, protocol: Protocol, buffer: VSBuffer, token: string,
+		private readonly log: ILogService,
A
Asher 已提交
1873
+		private readonly environment: INativeEnvironmentService,
A
Asher 已提交
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
+	) {
+		super(protocol, token);
+		this.protocol.dispose();
+		this.spawn(locale, buffer).then((p) => this.process = p);
+		this.protocol.getUnderlyingSocket().pause();
+	}
+
+	protected doDispose(): void {
+		if (this.process) {
+			this.process.kill();
+		}
1885
+		this.protocol.getUnderlyingSocket().destroy();
A
Asher 已提交
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
+	}
+
+	protected doReconnect(socket: ISocket, buffer: VSBuffer): void {
+		// This is just to set the new socket.
+		this.protocol.beginAcceptReconnection(socket, null);
+		this.protocol.dispose();
+		this.sendInitMessage(buffer);
+	}
+
+	private sendInitMessage(buffer: VSBuffer): void {
+		const socket = this.protocol.getUnderlyingSocket();
+		socket.pause();
+		this.process!.send({ // Process must be set at this point.
+			type: 'VSCODE_EXTHOST_IPC_SOCKET',
+			initialDataChunk: (buffer.buffer as Buffer).toString('base64'),
+			skipWebSocketFrames: this.protocol.getSocket() instanceof NodeSocket,
+		}, socket);
+	}
+
+	private async spawn(locale: string, buffer: VSBuffer): Promise<cp.ChildProcess> {
+		const config = await getNlsConfiguration(locale, this.environment.userDataPath);
+		const proc = cp.fork(
+			getPathFromAmdModule(require, 'bootstrap-fork'),
A
Asher 已提交
1909
+			[ '--type=extensionHost' ],
A
Asher 已提交
1910 1911 1912 1913 1914 1915 1916 1917 1918
+			{
+				env: {
+					...process.env,
+					AMD_ENTRYPOINT: 'vs/workbench/services/extensions/node/extensionHostProcess',
+					PIPE_LOGGING: 'true',
+					VERBOSE_LOGGING: 'true',
+					VSCODE_EXTHOST_WILL_SEND_SOCKET: 'true',
+					VSCODE_HANDLES_UNCAUGHT_ERRORS: 'true',
+					VSCODE_LOG_STACK: 'false',
A
Asher 已提交
1919
+					VSCODE_LOG_LEVEL: process.env.LOG_LEVEL,
A
Asher 已提交
1920 1921 1922 1923 1924 1925 1926 1927
+					VSCODE_NLS_CONFIG: JSON.stringify(config),
+				},
+				silent: true,
+			},
+		);
+
+		proc.on('error', () => this.dispose());
+		proc.on('exit', () => this.dispose());
A
Asher 已提交
1928 1929 1930 1931
+		if (proc.stdout && proc.stderr) {
+			proc.stdout.setEncoding('utf8').on('data', (d) => this.log.info('Extension host stdout', d));
+			proc.stderr.setEncoding('utf8').on('data', (d) => this.log.error('Extension host stderr', d));
+		}
A
Asher 已提交
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
+		proc.on('message', (event) => {
+			if (event && event.type === '__$console') {
+				const severity = (<any>this.log)[event.severity] ? event.severity : 'info';
+				(<any>this.log)[severity]('Extension host', event.arguments);
+			}
+			if (event && event.type === 'VSCODE_EXTHOST_DISCONNECTED') {
+				this.setOffline();
+			}
+		});
+
+		const listen = (message: IExtHostReadyMessage) => {
+			if (message.type === 'VSCODE_EXTHOST_IPC_READY') {
+				proc.removeListener('message', listen);
+				this.sendInitMessage(buffer);
+			}
+		};
+
+		return proc.on('message', listen);
+	}
+}
diff --git a/src/vs/server/node/insights.ts b/src/vs/server/node/insights.ts
new file mode 100644
index 0000000000..a0ece345f2
--- /dev/null
+++ b/src/vs/server/node/insights.ts
@@ -0,0 +1,124 @@
+import * as appInsights from 'applicationinsights';
+import * as https from 'https';
+import * as http from 'http';
+import * as os from 'os';
+
+class Channel {
+	public get _sender() {
+		throw new Error('unimplemented');
+	}
+	public get _buffer() {
+		throw new Error('unimplemented');
+	}
+
+	public setUseDiskRetryCaching(): void {
+		throw new Error('unimplemented');
+	}
+	public send(): void {
+		throw new Error('unimplemented');
+	}
+	public triggerSend(): void {
+		throw new Error('unimplemented');
+	}
+}
+
+export class TelemetryClient  {
+	public context: any = undefined;
+	public commonProperties: any = undefined;
+	public config: any = {};
+
+	public channel: any = new Channel();
+
+	public addTelemetryProcessor(): void {
+		throw new Error('unimplemented');
+	}
+
+	public clearTelemetryProcessors(): void {
+		throw new Error('unimplemented');
+	}
+
+	public runTelemetryProcessors(): void {
+		throw new Error('unimplemented');
+	}
+
+	public trackTrace(): void {
+		throw new Error('unimplemented');
+	}
+
+	public trackMetric(): void {
+		throw new Error('unimplemented');
+	}
+
+	public trackException(): void {
+		throw new Error('unimplemented');
+	}
+
+	public trackRequest(): void {
+		throw new Error('unimplemented');
+	}
+
+	public trackDependency(): void {
+		throw new Error('unimplemented');
+	}
+
+	public track(): void {
+		throw new Error('unimplemented');
+	}
+
+	public trackNodeHttpRequestSync(): void {
+		throw new Error('unimplemented');
+	}
+
+	public trackNodeHttpRequest(): void {
+		throw new Error('unimplemented');
+	}
+
+	public trackNodeHttpDependency(): void {
+		throw new Error('unimplemented');
+	}
+
+	public trackEvent(options: appInsights.Contracts.EventTelemetry): void {
+		if (!options.properties) {
+			options.properties = {};
+		}
+		if (!options.measurements) {
+			options.measurements = {};
+		}
+
+		try {
+			const cpus = os.cpus();
+			options.measurements.cores = cpus.length;
+			options.properties['common.cpuModel'] = cpus[0].model;
+		} catch (error) {}
+
+		try {
+			options.measurements.memoryFree = os.freemem();
+			options.measurements.memoryTotal = os.totalmem();
+		} catch (error) {}
+
+		try {
+			options.properties['common.shell'] = os.userInfo().shell;
+			options.properties['common.release'] = os.release();
+			options.properties['common.arch'] = os.arch();
+		} catch (error) {}
+
+		try {
+			const url = process.env.TELEMETRY_URL || 'https://v1.telemetry.coder.com/track';
+			const request = (/^http:/.test(url) ? http : https).request(url, {
+				method: 'POST',
+				headers: {
+					'Content-Type': 'application/json',
+				},
+			});
+			request.on('error', () => { /* We don't care. */ });
+			request.write(JSON.stringify(options));
+			request.end();
+		} catch (error) {}
+	}
+
+	public flush(options: { callback: (v: string) => void }): void {
+		if (options.callback) {
+			options.callback('');
+		}
+	}
+}
diff --git a/src/vs/server/node/ipc.ts b/src/vs/server/node/ipc.ts
new file mode 100644
index 0000000000..5e560eb46e
--- /dev/null
+++ b/src/vs/server/node/ipc.ts
@@ -0,0 +1,61 @@
+import * as cp from 'child_process';
+import { Emitter } from 'vs/base/common/event';
+
+enum ControlMessage {
+	okToChild = 'ok>',
+	okFromChild = 'ok<',
+}
+
+interface RelaunchMessage {
+	type: 'relaunch';
+	version: string;
+}
+
+export type Message = RelaunchMessage;
+
+class IpcMain {
+	protected readonly _onMessage = new Emitter<Message>();
+	public readonly onMessage = this._onMessage.event;
+
+	public handshake(child?: cp.ChildProcess): Promise<void> {
+		return new Promise((resolve, reject) => {
+			const target = child || process;
+			if (!target.send) {
+				throw new Error('Not spawned with IPC enabled');
+			}
+			target.on('message', (message) => {
+				if (message === child ? ControlMessage.okFromChild : ControlMessage.okToChild) {
+					target.removeAllListeners();
+					target.on('message', (msg) => this._onMessage.fire(msg));
+					if (child) {
+						target.send!(ControlMessage.okToChild);
+					}
+					resolve();
+				}
+			});
+			if (child) {
+				child.once('error', reject);
+				child.once('exit', (code) => {
+					const error = new Error(`Unexpected exit with code ${code}`);
+					(error as any).code = code;
+					reject(error);
+				});
+			} else {
+				target.send(ControlMessage.okFromChild);
+			}
+		});
+	}
+
+	public relaunch(version: string): void {
+		this.send({ type: 'relaunch', version });
+	}
+
+	private send(message: Message): void {
+		if (!process.send) {
+			throw new Error('Not a child process with IPC enabled');
+		}
+		process.send(message);
+	}
+}
+
+export const ipcMain = new IpcMain();
diff --git a/src/vs/server/node/logger.ts b/src/vs/server/node/logger.ts
new file mode 100644
index 0000000000..2a39c524aa
--- /dev/null
+++ b/src/vs/server/node/logger.ts
@@ -0,0 +1,2 @@
+import { logger as baseLogger } from '@coder/logger';
+export const logger = baseLogger.named('vscode');
diff --git a/src/vs/server/node/marketplace.ts b/src/vs/server/node/marketplace.ts
new file mode 100644
A
Asher 已提交
2159
index 0000000000..8956fc40d4
A
Asher 已提交
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
--- /dev/null
+++ b/src/vs/server/node/marketplace.ts
@@ -0,0 +1,174 @@
+import * as fs from 'fs';
+import * as path from 'path';
+import * as tarStream from 'tar-stream';
+import * as util from 'util';
+import { CancellationToken } from 'vs/base/common/cancellation';
+import { mkdirp } from 'vs/base/node/pfs';
+import * as vszip from 'vs/base/node/zip';
+import * as nls from 'vs/nls';
+import product from 'vs/platform/product/common/product';
+
+// We will be overriding these, so keep a reference to the original.
+const vszipExtract = vszip.extract;
+const vszipBuffer = vszip.buffer;
+
+export interface IExtractOptions {
+	overwrite?: boolean;
+	/**
+	 * Source path within the TAR/ZIP archive. Only the files
+	 * contained in this path will be extracted.
+	 */
+	sourcePath?: string;
+}
+
+export interface IFile {
+	path: string;
+	contents?: Buffer | string;
+	localPath?: string;
+}
+
+export const tar = async (tarPath: string, files: IFile[]): Promise<string> => {
+	const pack = tarStream.pack();
+	const chunks: Buffer[] = [];
+	const ended = new Promise<Buffer>((resolve) => {
+		pack.on('end', () => resolve(Buffer.concat(chunks)));
+	});
+	pack.on('data', (chunk: Buffer) => chunks.push(chunk));
+	for (let i = 0; i < files.length; i++) {
+		const file = files[i];
+		pack.entry({ name: file.path }, file.contents);
+	}
+	pack.finalize();
+	await util.promisify(fs.writeFile)(tarPath, await ended);
+	return tarPath;
+};
+
+export const extract = async (archivePath: string, extractPath: string, options: IExtractOptions = {}, token: CancellationToken): Promise<void> => {
+	try {
+		await extractTar(archivePath, extractPath, options, token);
+	} catch (error) {
+		if (error.toString().includes('Invalid tar header')) {
+			await vszipExtract(archivePath, extractPath, options, token);
+		}
+	}
+};
+
+export const buffer = (targetPath: string, filePath: string): Promise<Buffer> => {
+	return new Promise<Buffer>(async (resolve, reject) => {
+		try {
+			let done: boolean = false;
+			await extractAssets(targetPath, new RegExp(filePath), (assetPath: string, data: Buffer) => {
+				if (path.normalize(assetPath) === path.normalize(filePath)) {
+					done = true;
+					resolve(data);
+				}
+			});
+			if (!done) {
+				throw new Error('couldn\'t find asset ' + filePath);
+			}
+		} catch (error) {
+			if (error.toString().includes('Invalid tar header')) {
+				vszipBuffer(targetPath, filePath).then(resolve).catch(reject);
+			} else {
+				reject(error);
+			}
+		}
+	});
+};
+
+const extractAssets = async (tarPath: string, match: RegExp, callback: (path: string, data: Buffer) => void): Promise<void> => {
+	return new Promise<void>((resolve, reject): void => {
+		const extractor = tarStream.extract();
+		const fail = (error: Error) => {
+			extractor.destroy();
+			reject(error);
+		};
+		extractor.once('error', fail);
+		extractor.on('entry', async (header, stream, next) => {
+			const name = header.name;
+			if (match.test(name)) {
+				extractData(stream).then((data) => {
+					callback(name, data);
+					next();
+				}).catch(fail);
+			} else {
+				stream.on('end', () => next());
+				stream.resume(); // Just drain it.
+			}
+		});
+		extractor.on('finish', resolve);
+		fs.createReadStream(tarPath).pipe(extractor);
+	});
+};
+
+const extractData = (stream: NodeJS.ReadableStream): Promise<Buffer> => {
+	return new Promise((resolve, reject): void => {
+		const fileData: Buffer[] = [];
+		stream.on('error', reject);
+		stream.on('end', () => resolve(Buffer.concat(fileData)));
+		stream.on('data', (data) => fileData.push(data));
+	});
+};
+
+const extractTar = async (tarPath: string, targetPath: string, options: IExtractOptions = {}, token: CancellationToken): Promise<void> => {
+	return new Promise<void>((resolve, reject): void => {
+		const sourcePathRegex = new RegExp(options.sourcePath ? `^${options.sourcePath}` : '');
+		const extractor = tarStream.extract();
+		const fail = (error: Error) => {
+			extractor.destroy();
+			reject(error);
+		};
+		extractor.once('error', fail);
+		extractor.on('entry', async (header, stream, next) => {
+			const nextEntry = (): void => {
+				stream.on('end', () => next());
+				stream.resume();
+			};
+
+			const rawName = path.normalize(header.name);
+			if (token.isCancellationRequested || !sourcePathRegex.test(rawName)) {
+				return nextEntry();
+			}
+
+			const fileName = rawName.replace(sourcePathRegex, '');
+			const targetFileName = path.join(targetPath, fileName);
+			if (/\/$/.test(fileName)) {
+				return mkdirp(targetFileName).then(nextEntry);
+			}
+
+			const dirName = path.dirname(fileName);
+			const targetDirName = path.join(targetPath, dirName);
+			if (targetDirName.indexOf(targetPath) !== 0) {
+				return fail(new Error(nls.localize('invalid file', 'Error extracting {0}. Invalid file.', fileName)));
+			}
+
+			await mkdirp(targetDirName, undefined);
+
+			const fstream = fs.createWriteStream(targetFileName, { mode: header.mode });
+			fstream.once('close', () => next());
+			fstream.once('error', fail);
+			stream.pipe(fstream);
+		});
+		extractor.once('finish', resolve);
+		fs.createReadStream(tarPath).pipe(extractor);
+	});
+};
+
+/**
+ * Override original functionality so we can use a custom marketplace with
+ * either tars or zips.
+ */
+export const enableCustomMarketplace = (): void => {
+	(<any>product).extensionsGallery = { // Use `any` to override readonly.
A
Asher 已提交
2325
+		serviceUrl: process.env.SERVICE_URL || 'https://extensions.coder.com/api',
A
Asher 已提交
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
+		itemUrl: process.env.ITEM_URL || '',
+		controlUrl: '',
+		recommendationsUrl: '',
+		...(product.extensionsGallery || {}),
+	};
+
+	const target = vszip as typeof vszip;
+	target.zip = tar;
+	target.extract = extract;
+	target.buffer = buffer;
+};
diff --git a/src/vs/server/node/nls.ts b/src/vs/server/node/nls.ts
new file mode 100644
A
Asher 已提交
2339
index 0000000000..3d428a57d3
A
Asher 已提交
2340 2341
--- /dev/null
+++ b/src/vs/server/node/nls.ts
A
Asher 已提交
2342
@@ -0,0 +1,88 @@
A
Asher 已提交
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
+import * as fs from 'fs';
+import * as path from 'path';
+import * as util from 'util';
+import { getPathFromAmdModule } from 'vs/base/common/amd';
+import * as lp from 'vs/base/node/languagePacks';
+import product from 'vs/platform/product/common/product';
+import { Translations } from 'vs/workbench/services/extensions/common/extensionPoints';
+
+const configurations = new Map<string, Promise<lp.NLSConfiguration>>();
+const metadataPath = path.join(getPathFromAmdModule(require, ''), 'nls.metadata.json');
+
+export const isInternalConfiguration = (config: lp.NLSConfiguration): config is lp.InternalNLSConfiguration => {
+	return config && !!(<lp.InternalNLSConfiguration>config)._languagePackId;
+};
+
+const DefaultConfiguration = {
+	locale: 'en',
+	availableLanguages: {},
+};
+
+export const getNlsConfiguration = async (locale: string, userDataPath: string): Promise<lp.NLSConfiguration> => {
+	const id = `${locale}: ${userDataPath}`;
+	if (!configurations.has(id)) {
+		configurations.set(id, new Promise(async (resolve) =>  {
+			const config = product.commit && await util.promisify(fs.exists)(metadataPath)
+				? await lp.getNLSConfiguration(product.commit, userDataPath, metadataPath, locale)
+				: DefaultConfiguration;
+			if (isInternalConfiguration(config)) {
+				config._languagePackSupport = true;
+			}
+			// If the configuration has no results keep trying since code-server
+			// doesn't restart when a language is installed so this result would
+			// persist (the plugin might not be installed yet or something).
+			if (config.locale !== 'en' && config.locale !== 'en-us' && Object.keys(config.availableLanguages).length === 0) {
+				configurations.delete(id);
+			}
+			resolve(config);
+		}));
+	}
+	return configurations.get(id)!;
+};
+
+export const getTranslations = async (locale: string, userDataPath: string): Promise<Translations> => {
+	const config = await getNlsConfiguration(locale, userDataPath);
+	if (isInternalConfiguration(config)) {
+		try {
+			return JSON.parse(await util.promisify(fs.readFile)(config._translationsConfigFile, 'utf8'));
+		} catch (error) { /* Nothing yet. */}
+	}
+	return {};
+};
+
+export const getLocaleFromConfig = async (userDataPath: string): Promise<string> => {
A
Asher 已提交
2396 2397 2398 2399 2400 2401 2402 2403 2404
+	const files = ['locale.json', 'argv.json'];
+	for (let i = 0; i < files.length; ++i) {
+		try {
+			const localeConfigUri = path.join(userDataPath, 'User', files[i]);
+			const content = stripComments(await util.promisify(fs.readFile)(localeConfigUri, 'utf8'));
+			return JSON.parse(content).locale;
+		} catch (error) { /* Ignore. */ }
+	}
+	return 'en';
A
Asher 已提交
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
+};
+
+// Taken from src/main.js in the main VS Code source.
+const stripComments = (content: string): string => {
+	const regexp = /('(?:[^\\']*(?:\\.)?)*')|('(?:[^\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
+
+	return content.replace(regexp, (match, _m1, _m2, m3, m4) => {
+		// Only one of m1, m2, m3, m4 matches
+		if (m3) {
+			// A block comment. Replace with nothing
+			return '';
+		} else if (m4) {
+			// A line comment. If it ends in \r?\n then keep it.
+			const length_1 = m4.length;
+			if (length_1 > 2 && m4[length_1 - 1] === '\n') {
+				return m4[length_1 - 2] === '\r' ? '\r\n' : '\n';
+			}
+			else {
+				return '';
+			}
+		} else {
+			// We match a string
+			return match;
+		}
+	});
+};
diff --git a/src/vs/server/node/protocol.ts b/src/vs/server/node/protocol.ts
new file mode 100644
index 0000000000..3c74512192
--- /dev/null
+++ b/src/vs/server/node/protocol.ts
@@ -0,0 +1,73 @@
+import * as net from 'net';
+import { VSBuffer } from 'vs/base/common/buffer';
+import { PersistentProtocol } from 'vs/base/parts/ipc/common/ipc.net';
+import { NodeSocket, WebSocketNodeSocket } from 'vs/base/parts/ipc/node/ipc.net';
+import { AuthRequest, ConnectionTypeRequest, HandshakeMessage } from 'vs/platform/remote/common/remoteAgentConnection';
+
+export interface SocketOptions {
+	readonly reconnectionToken: string;
+	readonly reconnection: boolean;
+	readonly skipWebSocketFrames: boolean;
+}
+
+export class Protocol extends PersistentProtocol {
+	public constructor(socket: net.Socket, public readonly options: SocketOptions) {
+		super(
+			options.skipWebSocketFrames
+				? new NodeSocket(socket)
+				: new WebSocketNodeSocket(new NodeSocket(socket)),
+		);
A
Asher 已提交
2456
+	}
A
Asher 已提交
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
+
+	public getUnderlyingSocket(): net.Socket {
+		const socket = this.getSocket();
+		return socket instanceof NodeSocket
+			? socket.socket
+			: (socket as WebSocketNodeSocket).socket.socket;
+	}
+
+	/**
+	 * Perform a handshake to get a connection request.
+	 */
+	public handshake(): Promise<ConnectionTypeRequest> {
+		return new Promise((resolve, reject) => {
+			const handler = this.onControlMessage((rawMessage) => {
+				try {
+					const message = JSON.parse(rawMessage.toString());
+					switch (message.type) {
+						case 'auth': return this.authenticate(message);
+						case 'connectionType':
+							handler.dispose();
+							return resolve(message);
+						default: throw new Error('Unrecognized message type');
+					}
+				} catch (error) {
+					handler.dispose();
+					reject(error);
+				}
+			});
A
Asher 已提交
2485 2486 2487
+		});
+	}
+
A
Asher 已提交
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
+	/**
+	 * TODO: This ignores the authentication process entirely for now.
+	 */
+	private authenticate(_message: AuthRequest): void {
+		this.sendMessage({ type: 'sign', data: '' });
+	}
+
+	/**
+	 * TODO: implement.
+	 */
+	public tunnel(): void {
+		throw new Error('Tunnel is not implemented yet');
+	}
+
+	/**
+	 * Send a handshake message. In the case of the extension host, it just sends
+	 * back a debug port.
+	 */
+	public sendMessage(message: HandshakeMessage | { debugPort?: number } ): void {
+		this.sendControl(VSBuffer.fromString(JSON.stringify(message)));
+	}
+}
diff --git a/src/vs/server/node/server.ts b/src/vs/server/node/server.ts
new file mode 100644
A
Asher 已提交
2512
index 0000000000..433646424e
A
Asher 已提交
2513 2514
--- /dev/null
+++ b/src/vs/server/node/server.ts
A
Asher 已提交
2515 2516
@@ -0,0 +1,282 @@
+import * as fs from 'fs';
A
Asher 已提交
2517 2518 2519 2520 2521 2522
+import * as net from 'net';
+import * as path from 'path';
+import { Emitter } from 'vs/base/common/event';
+import { Schemas } from 'vs/base/common/network';
+import { URI } from 'vs/base/common/uri';
+import { getMachineId } from 'vs/base/node/id';
A
Asher 已提交
2523
+import { ClientConnectionEvent, createChannelReceiver, IPCServer, IServerChannel } from 'vs/base/parts/ipc/common/ipc';
A
Asher 已提交
2524
+import { LogsDataCleaner } from 'vs/code/electron-browser/sharedProcess/contrib/logsDataCleaner';
A
Asher 已提交
2525
+import { main } from "vs/code/node/cliProcessMain";
A
Asher 已提交
2526
+import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
A
Asher 已提交
2527
+import { ConfigurationService } from 'vs/platform/configuration/common/configurationService';
A
Asher 已提交
2528
+import { ExtensionHostDebugBroadcastChannel } from 'vs/platform/debug/common/extensionHostDebugIpc';
A
Asher 已提交
2529 2530 2531
+import { IEnvironmentService } from 'vs/platform/environment/common/environment';
+import { ParsedArgs } from 'vs/platform/environment/node/argv';
+import { EnvironmentService, INativeEnvironmentService } from 'vs/platform/environment/node/environmentService';
A
Asher 已提交
2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555
+import { ExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionGalleryService';
+import { IExtensionGalleryService, IExtensionManagementService } from 'vs/platform/extensionManagement/common/extensionManagement';
+import { ExtensionManagementChannel } from 'vs/platform/extensionManagement/common/extensionManagementIpc';
+import { ExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService';
+import { IFileService } from 'vs/platform/files/common/files';
+import { FileService } from 'vs/platform/files/common/fileService';
+import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider';
+import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
+import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
+import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
+import { ILocalizationsService } from 'vs/platform/localizations/common/localizations';
+import { LocalizationsService } from 'vs/platform/localizations/node/localizations';
+import { getLogLevel, ILogService } from 'vs/platform/log/common/log';
+import { LoggerChannel } from 'vs/platform/log/common/logIpc';
+import { SpdLogService } from 'vs/platform/log/node/spdlogService';
+import product from 'vs/platform/product/common/product';
+import { IProductService } from 'vs/platform/product/common/productService';
+import { ConnectionType, ConnectionTypeRequest } from 'vs/platform/remote/common/remoteAgentConnection';
+import { RemoteAgentConnectionContext } from 'vs/platform/remote/common/remoteAgentEnvironment';
+import { IRequestService } from 'vs/platform/request/common/request';
+import { RequestChannel } from 'vs/platform/request/common/requestIpc';
+import { RequestService } from 'vs/platform/request/node/requestService';
+import ErrorTelemetry from 'vs/platform/telemetry/browser/errorTelemetry';
+import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
A
Asher 已提交
2556
+import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService';
A
Asher 已提交
2557 2558 2559 2560 2561
+import { combinedAppender, LogAppender, NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
+import { AppInsightsAppender } from 'vs/platform/telemetry/node/appInsightsAppender';
+import { resolveCommonProperties } from 'vs/platform/telemetry/node/commonProperties';
+import { INodeProxyService, NodeProxyChannel } from 'vs/server/common/nodeProxy';
+import { TelemetryChannel } from 'vs/server/common/telemetry';
2562
+import { Query, VscodeOptions, WorkbenchOptions } from 'vs/server/ipc';
A
Asher 已提交
2563 2564 2565
+import { ExtensionEnvironmentChannel, FileProviderChannel, NodeProxyService } from 'vs/server/node/channel';
+import { Connection, ExtensionHostConnection, ManagementConnection } from 'vs/server/node/connection';
+import { TelemetryClient } from 'vs/server/node/insights';
2566
+import { logger } from 'vs/server/node/logger';
A
Asher 已提交
2567 2568 2569
+import { getLocaleFromConfig, getNlsConfiguration } from 'vs/server/node/nls';
+import { Protocol } from 'vs/server/node/protocol';
+import { getUriTransformer } from 'vs/server/node/util';
A
Asher 已提交
2570
+import { REMOTE_FILE_SYSTEM_CHANNEL_NAME } from "vs/workbench/services/remote/common/remoteAgentFileSystemChannel";
A
Asher 已提交
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583
+import { RemoteExtensionLogFileName } from 'vs/workbench/services/remote/common/remoteAgentService';
+
+export class Vscode {
+	public readonly _onDidClientConnect = new Emitter<ClientConnectionEvent>();
+	public readonly onDidClientConnect = this._onDidClientConnect.event;
+	private readonly ipc = new IPCServer<RemoteAgentConnectionContext>(this.onDidClientConnect);
+
+	private readonly maxExtraOfflineConnections = 0;
+	private readonly connections = new Map<ConnectionType, Map<string, Connection>>();
+
+	private readonly services = new ServiceCollection();
+	private servicesPromise?: Promise<void>;
+
A
Asher 已提交
2584 2585 2586 2587
+	public async cli(args: ParsedArgs): Promise<void> {
+		return main(args);
+	}
+
A
Asher 已提交
2588 2589 2590
+	public async initialize(options: VscodeOptions): Promise<WorkbenchOptions> {
+		const transformer = getUriTransformer(options.remoteAuthority);
+		if (!this.servicesPromise) {
2591
+			this.servicesPromise = this.initializeServices(options.args);
A
Asher 已提交
2592 2593
+		}
+		await this.servicesPromise;
A
Asher 已提交
2594
+		const environment = this.services.get(IEnvironmentService) as INativeEnvironmentService;
2595
+		const startPath = options.startPath;
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
+		const parseUrl = (url: string): URI => {
+			// This might be a fully-specified URL or just a path.
+			try {
+				return URI.parse(url, true);
+			} catch (error) {
+				return URI.from({
+					scheme: Schemas.vscodeRemote,
+					authority: options.remoteAuthority,
+					path: url,
+				});
+			}
+		};
A
Asher 已提交
2608 2609
+		return {
+			workbenchWebConfiguration: {
2610 2611
+				workspaceUri: startPath && startPath.workspace ? parseUrl(startPath.url) : undefined,
+				folderUri: startPath && !startPath.workspace ? parseUrl(startPath.url) : undefined,
A
Asher 已提交
2612 2613
+				remoteAuthority: options.remoteAuthority,
+				logLevel: getLogLevel(environment),
2614 2615 2616
+				workspaceProvider: {
+					payload: [["userDataPath", environment.userDataPath]],
+				},
A
Asher 已提交
2617 2618
+			},
+			remoteUserDataUri: transformer.transformOutgoing(URI.file(environment.userDataPath)),
2619
+			productConfiguration: product,
A
Asher 已提交
2620
+			nlsConfiguration: await getNlsConfiguration(environment.args.locale || await getLocaleFromConfig(environment.userDataPath), environment.userDataPath),
2621
+			commit: product.commit || 'development',
A
Asher 已提交
2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
+		};
+	}
+
+	public async handleWebSocket(socket: net.Socket, query: Query): Promise<true> {
+		if (!query.reconnectionToken) {
+			throw new Error('Reconnection token is missing from query parameters');
+		}
+		const protocol = new Protocol(socket, {
+			reconnectionToken: <string>query.reconnectionToken,
+			reconnection: query.reconnection === 'true',
+			skipWebSocketFrames: query.skipWebSocketFrames === 'true',
+		});
+		try {
+			await this.connect(await protocol.handshake(), protocol);
+		} catch (error) {
+			protocol.sendMessage({ type: 'error', reason: error.message });
+			protocol.dispose();
+			protocol.getSocket().dispose();
+		}
+		return true;
+	}
+
+	private async connect(message: ConnectionTypeRequest, protocol: Protocol): Promise<void> {
+		if (product.commit && message.commit !== product.commit) {
2646
+			logger.warn(`Version mismatch (${message.commit} instead of ${product.commit})`);
A
Asher 已提交
2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694
+		}
+
+		switch (message.desiredConnectionType) {
+			case ConnectionType.ExtensionHost:
+			case ConnectionType.Management:
+				if (!this.connections.has(message.desiredConnectionType)) {
+					this.connections.set(message.desiredConnectionType, new Map());
+				}
+				const connections = this.connections.get(message.desiredConnectionType)!;
+
+				const ok = async () => {
+					return message.desiredConnectionType === ConnectionType.ExtensionHost
+						? { debugPort: await this.getDebugPort() }
+						: { type: 'ok' };
+				};
+
+				const token = protocol.options.reconnectionToken;
+				if (protocol.options.reconnection && connections.has(token)) {
+					protocol.sendMessage(await ok());
+					const buffer = protocol.readEntireBuffer();
+					protocol.dispose();
+					return connections.get(token)!.reconnect(protocol.getSocket(), buffer);
+				} else if (protocol.options.reconnection || connections.has(token)) {
+					throw new Error(protocol.options.reconnection
+						? 'Unrecognized reconnection token'
+						: 'Duplicate reconnection token'
+					);
+				}
+
+				protocol.sendMessage(await ok());
+
+				let connection: Connection;
+				if (message.desiredConnectionType === ConnectionType.Management) {
+					connection = new ManagementConnection(protocol, token);
+					this._onDidClientConnect.fire({
+						protocol, onDidClientDisconnect: connection.onClose,
+					});
+					// TODO: Need a way to match clients with a connection. For now
+					// dispose everything which only works because no extensions currently
+					// utilize long-running proxies.
+					(this.services.get(INodeProxyService) as NodeProxyService)._onUp.fire();
+					connection.onClose(() => (this.services.get(INodeProxyService) as NodeProxyService)._onDown.fire());
+				} else {
+					const buffer = protocol.readEntireBuffer();
+					connection = new ExtensionHostConnection(
+						message.args ? message.args.language : 'en',
+						protocol, buffer, token,
+						this.services.get(ILogService) as ILogService,
A
Asher 已提交
2695
+						this.services.get(IEnvironmentService) as INativeEnvironmentService,
A
Asher 已提交
2696 2697 2698 2699 2700 2701 2702 2703 2704
+					);
+				}
+				connections.set(token, connection);
+				connection.onClose(() => connections.delete(token));
+				this.disposeOldOfflineConnections(connections);
+				break;
+			case ConnectionType.Tunnel: return protocol.tunnel();
+			default: throw new Error('Unrecognized connection type');
+		}
A
Asher 已提交
2705
+	}
A
Asher 已提交
2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716
+
+	private disposeOldOfflineConnections(connections: Map<string, Connection>): void {
+		const offline = Array.from(connections.values())
+			.filter((connection) => typeof connection.offline !== 'undefined');
+		for (let i = 0, max = offline.length - this.maxExtraOfflineConnections; i < max; ++i) {
+			offline[i].dispose();
+		}
+	}
+
+	private async initializeServices(args: ParsedArgs): Promise<void> {
+		const environmentService = new EnvironmentService(args, process.execPath);
2717 2718
+		// https://github.com/cdr/code-server/issues/1693
+		fs.mkdirSync(environmentService.globalStorageHome, { recursive: true });
A
Anmol Sethi 已提交
2719
+
A
Asher 已提交
2720 2721 2722 2723 2724 2725
+		const logService = new SpdLogService(RemoteExtensionLogFileName, environmentService.logsPath, getLogLevel(environmentService));
+		const fileService = new FileService(logService);
+		fileService.registerProvider(Schemas.file, new DiskFileSystemProvider(logService));
+
+		const piiPaths = [
+			path.join(environmentService.userDataPath, 'clp'), // Language packs.
A
Asher 已提交
2726
+			environmentService.appRoot,
A
Asher 已提交
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
+			environmentService.extensionsPath,
+			environmentService.builtinExtensionsPath,
+			...environmentService.extraExtensionPaths,
+			...environmentService.extraBuiltinExtensionPaths,
+		];
+
+		this.ipc.registerChannel('logger', new LoggerChannel(logService));
+		this.ipc.registerChannel(ExtensionHostDebugBroadcastChannel.ChannelName, new ExtensionHostDebugBroadcastChannel());
+
+		this.services.set(ILogService, logService);
+		this.services.set(IEnvironmentService, environmentService);
2738 2739 2740 2741 2742
+
+		const configurationService = new ConfigurationService(environmentService.settingsResource, fileService);
+		await configurationService.initialize();
+		this.services.set(IConfigurationService, configurationService);
+
A
Asher 已提交
2743 2744 2745 2746 2747 2748
+		this.services.set(IRequestService, new SyncDescriptor(RequestService));
+		this.services.set(IFileService, fileService);
+		this.services.set(IProductService, { _serviceBrand: undefined, ...product });
+		this.services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
+		this.services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));
+
A
Asher 已提交
2749 2750
+		if (!environmentService.disableTelemetry) {
+			this.services.set(ITelemetryService, new TelemetryService({
A
Asher 已提交
2751 2752 2753 2754
+				appender: combinedAppender(
+					new AppInsightsAppender('code-server', null, () => new TelemetryClient() as any, logService),
+					new LogAppender(logService),
+				),
A
Asher 已提交
2755
+				sendErrorTelemetry: true,
A
Asher 已提交
2756 2757 2758 2759 2760
+				commonProperties: resolveCommonProperties(
+					product.commit, product.version, await getMachineId(),
+					[], environmentService.installSourcePath, 'code-server',
+				),
+				piiPaths,
A
Asher 已提交
2761
+			}, configurationService));
A
Asher 已提交
2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
+		} else {
+			this.services.set(ITelemetryService, NullTelemetryService);
+		}
+
+		await new Promise((resolve) => {
+			const instantiationService = new InstantiationService(this.services);
+			this.services.set(ILocalizationsService, instantiationService.createInstance(LocalizationsService));
+			this.services.set(INodeProxyService, instantiationService.createInstance(NodeProxyService));
+
+			instantiationService.invokeFunction(() => {
+				instantiationService.createInstance(LogsDataCleaner);
+				const telemetryService = this.services.get(ITelemetryService) as ITelemetryService;
+				this.ipc.registerChannel('extensions', new ExtensionManagementChannel(
+					this.services.get(IExtensionManagementService) as IExtensionManagementService,
+					(context) => getUriTransformer(context.remoteAuthority),
+				));
+				this.ipc.registerChannel('remoteextensionsenvironment', new ExtensionEnvironmentChannel(
+					environmentService, logService, telemetryService, '',
+				));
+				this.ipc.registerChannel('request', new RequestChannel(this.services.get(IRequestService) as IRequestService));
+				this.ipc.registerChannel('telemetry', new TelemetryChannel(telemetryService));
+				this.ipc.registerChannel('nodeProxy', new NodeProxyChannel(this.services.get(INodeProxyService) as INodeProxyService));
+				this.ipc.registerChannel('localizations', <IServerChannel<any>>createChannelReceiver(this.services.get(ILocalizationsService) as ILocalizationsService));
+				this.ipc.registerChannel(REMOTE_FILE_SYSTEM_CHANNEL_NAME, new FileProviderChannel(environmentService, logService));
+				resolve(new ErrorTelemetry(telemetryService));
+			});
+		});
+	}
+
+	/**
+	 * TODO: implement.
+	 */
+	private async getDebugPort(): Promise<number | undefined> {
+		return undefined;
+	}
+}
diff --git a/src/vs/server/node/util.ts b/src/vs/server/node/util.ts
new file mode 100644
A
Asher 已提交
2800
index 0000000000..fa47e993b4
A
Asher 已提交
2801 2802
--- /dev/null
+++ b/src/vs/server/node/util.ts
A
Asher 已提交
2803 2804
@@ -0,0 +1,13 @@
+import { URITransformer } from 'vs/base/common/uriIpc';
A
Asher 已提交
2805 2806
+
+export const getUriTransformer = (remoteAuthority: string): URITransformer => {
A
Asher 已提交
2807
+	return new URITransformer(remoteAuthority);
A
Asher 已提交
2808
+};
2809 2810 2811 2812 2813 2814 2815 2816
+
+/**
+ * Encode a path for opening via the folder or workspace query parameter. This
+ * preserves slashes so it can be edited by hand more easily.
+ */
+export const encodePath = (path: string): string => {
+	return path.split("/").map((p) => encodeURIComponent(p)).join("/");
+};
2817
diff --git a/src/vs/workbench/api/browser/extensionHost.contribution.ts b/src/vs/workbench/api/browser/extensionHost.contribution.ts
A
Asher 已提交
2818
index 3f2de2c738..a967d8df69 100644
2819 2820
--- a/src/vs/workbench/api/browser/extensionHost.contribution.ts
+++ b/src/vs/workbench/api/browser/extensionHost.contribution.ts
A
Asher 已提交
2821 2822
@@ -59,6 +59,7 @@ import './mainThreadComments';
 import './mainThreadNotebook';
2823 2824
 import './mainThreadTask';
 import './mainThreadLabelService';
A
Asher 已提交
2825
+import 'vs/server/browser/mainThreadNodeProxy';
A
Asher 已提交
2826 2827 2828
 import './mainThreadTunnelService';
 import './mainThreadAuthentication';
 import './mainThreadTimeline';
2829
diff --git a/src/vs/workbench/api/common/extHost.api.impl.ts b/src/vs/workbench/api/common/extHost.api.impl.ts
A
Asher 已提交
2830
index 1c1e3efeae..b16b31a334 100644
2831 2832
--- a/src/vs/workbench/api/common/extHost.api.impl.ts
+++ b/src/vs/workbench/api/common/extHost.api.impl.ts
A
Asher 已提交
2833
@@ -68,6 +68,7 @@ import { IURITransformerService } from 'vs/workbench/api/common/extHostUriTransf
2834 2835
 import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
 import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
A
Asher 已提交
2836
 import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook';
A
Asher 已提交
2837
+import { IExtHostNodeProxy } from 'vs/server/browser/extHostNodeProxy';
A
Asher 已提交
2838 2839 2840
 import { ExtHostTheming } from 'vs/workbench/api/common/extHostTheming';
 import { IExtHostTunnelService } from 'vs/workbench/api/common/extHostTunnelService';
 import { IExtHostApiDeprecationService } from 'vs/workbench/api/common/extHostApiDeprecationService';
A
Asher 已提交
2841
@@ -95,6 +96,7 @@ export function createApiFactoryAndRegisterActors(accessor: ServicesAccessor): I
2842
 	const extHostStorage = accessor.get(IExtHostStorage);
A
Asher 已提交
2843
 	const extensionStoragePaths = accessor.get(IExtensionStoragePaths);
2844 2845
 	const extHostLogService = accessor.get(ILogService);
+	const extHostNodeProxy = accessor.get(IExtHostNodeProxy);
A
Asher 已提交
2846 2847
 	const extHostTunnelService = accessor.get(IExtHostTunnelService);
 	const extHostApiDeprecation = accessor.get(IExtHostApiDeprecationService);
A
Asher 已提交
2848
 
A
Asher 已提交
2849
@@ -104,6 +106,7 @@ export function createApiFactoryAndRegisterActors(accessor: ServicesAccessor): I
2850 2851 2852 2853
 	rpcProtocol.set(ExtHostContext.ExtHostConfiguration, extHostConfiguration);
 	rpcProtocol.set(ExtHostContext.ExtHostExtensionService, extensionService);
 	rpcProtocol.set(ExtHostContext.ExtHostStorage, extHostStorage);
+	rpcProtocol.set(ExtHostContext.ExtHostNodeProxy, extHostNodeProxy);
A
Asher 已提交
2854
 	rpcProtocol.set(ExtHostContext.ExtHostTunnelService, extHostTunnelService);
A
Asher 已提交
2855
 
2856 2857
 	// automatically create and register addressable instances
diff --git a/src/vs/workbench/api/common/extHost.protocol.ts b/src/vs/workbench/api/common/extHost.protocol.ts
A
Asher 已提交
2858
index b662b07ac0..b95fc537c5 100644
2859 2860
--- a/src/vs/workbench/api/common/extHost.protocol.ts
+++ b/src/vs/workbench/api/common/extHost.protocol.ts
A
Asher 已提交
2861
@@ -760,6 +760,16 @@ export interface MainThreadLabelServiceShape extends IDisposable {
2862 2863
 	$unregisterResourceLabelFormatter(handle: number): void;
 }
A
Asher 已提交
2864
 
2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
+export interface MainThreadNodeProxyShape extends IDisposable {
+	$send(message: string): void;
+}
+export interface ExtHostNodeProxyShape {
+	$onMessage(message: string): void;
+	$onClose(): void;
+	$onDown(): void;
+	$onUp(): void;
+}
+
A
Asher 已提交
2875 2876 2877
 export interface MainThreadSearchShape extends IDisposable {
 	$registerFileSearchProvider(handle: number, scheme: string): void;
 	$registerTextSearchProvider(handle: number, scheme: string): void;
A
Asher 已提交
2878
@@ -1659,6 +1669,7 @@ export const MainContext = {
2879
 	MainThreadWindow: createMainId<MainThreadWindowShape>('MainThreadWindow'),
A
Asher 已提交
2880
 	MainThreadLabelService: createMainId<MainThreadLabelServiceShape>('MainThreadLabelService'),
A
Asher 已提交
2881
 	MainThreadNotebook: createMainId<MainThreadNotebookShape>('MainThreadNotebook'),
A
Asher 已提交
2882 2883 2884 2885
+	MainThreadNodeProxy: createMainId<MainThreadNodeProxyShape>('MainThreadNodeProxy'),
 	MainThreadTheming: createMainId<MainThreadThemingShape>('MainThreadTheming'),
 	MainThreadTunnelService: createMainId<MainThreadTunnelServiceShape>('MainThreadTunnelService'),
 	MainThreadTimeline: createMainId<MainThreadTimelineShape>('MainThreadTimeline')
A
Asher 已提交
2886
@@ -1697,6 +1708,7 @@ export const ExtHostContext = {
2887
 	ExtHostOutputService: createMainId<ExtHostOutputServiceShape>('ExtHostOutputService'),
A
Asher 已提交
2888 2889
 	ExtHosLabelService: createMainId<ExtHostLabelServiceShape>('ExtHostLabelService'),
 	ExtHostNotebook: createMainId<ExtHostNotebookShape>('ExtHostNotebook'),
A
Asher 已提交
2890 2891 2892 2893
+	ExtHostNodeProxy: createMainId<ExtHostNodeProxyShape>('ExtHostNodeProxy'),
 	ExtHostTheming: createMainId<ExtHostThemingShape>('ExtHostTheming'),
 	ExtHostTunnelService: createMainId<ExtHostTunnelServiceShape>('ExtHostTunnelService'),
 	ExtHostAuthentication: createMainId<ExtHostAuthenticationShape>('ExtHostAuthentication'),
2894
diff --git a/src/vs/workbench/api/common/extHostExtensionService.ts b/src/vs/workbench/api/common/extHostExtensionService.ts
A
Asher 已提交
2895
index aef67f0ec9..756d591f62 100644
2896 2897
--- a/src/vs/workbench/api/common/extHostExtensionService.ts
+++ b/src/vs/workbench/api/common/extHostExtensionService.ts
A
Asher 已提交
2898 2899 2900 2901 2902 2903
@@ -5,7 +5,7 @@
 
 import * as nls from 'vs/nls';
 import * as path from 'vs/base/common/path';
-import { originalFSPath, joinPath } from 'vs/base/common/resources';
+import { originalFSPath } from 'vs/base/common/resources';
A
Asher 已提交
2904
 import { Barrier, timeout } from 'vs/base/common/async';
A
Asher 已提交
2905 2906
 import { dispose, toDisposable, DisposableStore } from 'vs/base/common/lifecycle';
 import { TernarySearchTree } from 'vs/base/common/map';
2907 2908 2909 2910
@@ -32,6 +32,7 @@ import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitData
 import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths';
 import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
 import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
A
Asher 已提交
2911
+import { IExtHostNodeProxy } from 'vs/server/browser/extHostNodeProxy';
A
Asher 已提交
2912
 import { IExtHostTunnelService } from 'vs/workbench/api/common/extHostTunnelService';
A
Asher 已提交
2913
 import { IExtHostTerminalService } from 'vs/workbench/api/common/extHostTerminalService';
A
Asher 已提交
2914
 
A
Asher 已提交
2915
@@ -78,6 +79,7 @@ export abstract class AbstractExtHostExtensionService implements ExtHostExtensio
2916 2917 2918 2919
 	protected readonly _extHostWorkspace: ExtHostWorkspace;
 	protected readonly _extHostConfiguration: ExtHostConfiguration;
 	protected readonly _logService: ILogService;
+	protected readonly _nodeProxy: IExtHostNodeProxy;
A
Asher 已提交
2920
 	protected readonly _extHostTunnelService: IExtHostTunnelService;
A
Asher 已提交
2921
 	protected readonly _extHostTerminalService: IExtHostTerminalService;
A
Asher 已提交
2922
 
A
Asher 已提交
2923
@@ -109,6 +111,7 @@ export abstract class AbstractExtHostExtensionService implements ExtHostExtensio
2924 2925
 		@ILogService logService: ILogService,
 		@IExtHostInitDataService initData: IExtHostInitDataService,
A
Asher 已提交
2926
 		@IExtensionStoragePaths storagePath: IExtensionStoragePaths,
2927
+		@IExtHostNodeProxy nodeProxy: IExtHostNodeProxy,
A
Asher 已提交
2928 2929
 		@IExtHostTunnelService extHostTunnelService: IExtHostTunnelService,
 		@IExtHostTerminalService extHostTerminalService: IExtHostTerminalService
2930
 	) {
A
Asher 已提交
2931
@@ -119,6 +122,7 @@ export abstract class AbstractExtHostExtensionService implements ExtHostExtensio
2932 2933 2934 2935
 		this._extHostWorkspace = extHostWorkspace;
 		this._extHostConfiguration = extHostConfiguration;
 		this._logService = logService;
+		this._nodeProxy = nodeProxy;
A
Asher 已提交
2936
 		this._extHostTunnelService = extHostTunnelService;
A
Asher 已提交
2937
 		this._extHostTerminalService = extHostTerminalService;
2938
 		this._disposables = new DisposableStore();
A
Asher 已提交
2939
@@ -345,14 +349,14 @@ export abstract class AbstractExtHostExtensionService implements ExtHostExtensio
A
Asher 已提交
2940
 
2941
 		const activationTimesBuilder = new ExtensionActivationTimesBuilder(reason.startup);
A
Asher 已提交
2942 2943
 		return Promise.all([
-			this._loadCommonJSModule<IExtensionModule>(joinPath(extensionDescription.extensionLocation, extensionDescription.main), activationTimesBuilder),
2944 2945 2946
+			this._loadCommonJSModule<IExtensionModule>(extensionDescription, activationTimesBuilder),
 			this._loadExtensionContext(extensionDescription)
 		]).then(values => {
A
Asher 已提交
2947
 			return AbstractExtHostExtensionService._callActivate(this._logService, extensionDescription.identifier, values[0], values[1], activationTimesBuilder);
2948 2949
 		});
 	}
A
Asher 已提交
2950
 
2951 2952
-	protected abstract _loadCommonJSModule<T>(module: URI, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T>;
+	protected abstract _loadCommonJSModule<T>(module: URI | IExtensionDescription, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T>;
A
Asher 已提交
2953
 
2954
 	private _loadExtensionContext(extensionDescription: IExtensionDescription): Promise<vscode.ExtensionContext> {
A
Asher 已提交
2955
 
2956
diff --git a/src/vs/workbench/api/node/extHost.services.ts b/src/vs/workbench/api/node/extHost.services.ts
A
Asher 已提交
2957
index 72ad75d63e..2dbc4a76d9 100644
2958 2959
--- a/src/vs/workbench/api/node/extHost.services.ts
+++ b/src/vs/workbench/api/node/extHost.services.ts
A
Asher 已提交
2960
@@ -24,11 +24,13 @@ import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePa
A
Asher 已提交
2961 2962
 import { IExtHostExtensionService } from 'vs/workbench/api/common/extHostExtensionService';
 import { ExtHostExtensionService } from 'vs/workbench/api/node/extHostExtensionService';
2963
 import { IExtHostStorage, ExtHostStorage } from 'vs/workbench/api/common/extHostStorage';
A
Asher 已提交
2964
+import { IExtHostNodeProxy } from 'vs/server/browser/extHostNodeProxy';
A
Asher 已提交
2965 2966 2967
 import { ILogService } from 'vs/platform/log/common/log';
 import { ExtHostLogService } from 'vs/workbench/api/node/extHostLogService';
 import { IExtHostTunnelService } from 'vs/workbench/api/common/extHostTunnelService';
A
Asher 已提交
2968 2969 2970 2971 2972 2973 2974
 import { ExtHostTunnelService } from 'vs/workbench/api/node/extHostTunnelService';
 import { IExtHostApiDeprecationService, ExtHostApiDeprecationService } from 'vs/workbench/api/common/extHostApiDeprecationService';
+import { NotImplementedProxy } from 'vs/base/common/types';
 
 // register singleton services
 registerSingleton(ILogService, ExtHostLogService);
@@ -47,3 +49,4 @@ registerSingleton(IExtensionStoragePaths, ExtensionStoragePaths);
2975 2976
 registerSingleton(IExtHostExtensionService, ExtHostExtensionService);
 registerSingleton(IExtHostStorage, ExtHostStorage);
A
Asher 已提交
2977
 registerSingleton(IExtHostTunnelService, ExtHostTunnelService);
A
Asher 已提交
2978
+registerSingleton(IExtHostNodeProxy, class extends NotImplementedProxy<IExtHostNodeProxy>(String(IExtHostNodeProxy)) { whenReady = Promise.resolve(); });
2979
diff --git a/src/vs/workbench/api/node/extHostExtensionService.ts b/src/vs/workbench/api/node/extHostExtensionService.ts
A
Asher 已提交
2980
index 3a02c5ce0b..3e1594129c 100644
2981 2982 2983 2984 2985 2986 2987 2988
--- a/src/vs/workbench/api/node/extHostExtensionService.ts
+++ b/src/vs/workbench/api/node/extHostExtensionService.ts
@@ -13,6 +13,8 @@ import { ExtHostDownloadService } from 'vs/workbench/api/node/extHostDownloadSer
 import { CLIServer } from 'vs/workbench/api/node/extHostCLIServer';
 import { URI } from 'vs/base/common/uri';
 import { Schemas } from 'vs/base/common/network';
+import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
+import { joinPath } from 'vs/base/common/resources';
A
Asher 已提交
2989
 
2990
 class NodeModuleRequireInterceptor extends RequireInterceptor {
A
Asher 已提交
2991
 
A
Asher 已提交
2992
@@ -76,7 +78,10 @@ export class ExtHostExtensionService extends AbstractExtHostExtensionService {
2993 2994
 		};
 	}
A
Asher 已提交
2995
 
2996 2997 2998 2999 3000 3001 3002 3003
-	protected _loadCommonJSModule<T>(module: URI, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T> {
+	protected _loadCommonJSModule<T>(module: URI | IExtensionDescription, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T> {
+		if (!URI.isUri(module)) {
+			module = joinPath(module.extensionLocation, module.main!);
+		}
 		if (module.scheme !== Schemas.file) {
 			throw new Error(`Cannot load URI: '${module}', must be of file-scheme`);
 		}
3004
diff --git a/src/vs/workbench/api/node/extHostStoragePaths.ts b/src/vs/workbench/api/node/extHostStoragePaths.ts
A
Asher 已提交
3005
index afdd6bf398..1633daf93d 100644
3006 3007 3008
--- a/src/vs/workbench/api/node/extHostStoragePaths.ts
+++ b/src/vs/workbench/api/node/extHostStoragePaths.ts
@@ -5,13 +5,14 @@
A
Asher 已提交
3009
 
3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
 import * as path from 'vs/base/common/path';
 import { URI } from 'vs/base/common/uri';
-import * as pfs from 'vs/base/node/pfs';
-import { IEnvironment, IStaticWorkspaceData } from 'vs/workbench/api/common/extHost.protocol';
+import { IEnvironment, IStaticWorkspaceData, MainContext } from 'vs/workbench/api/common/extHost.protocol';
 import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
 import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths';
 import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
 import { withNullAsUndefined } from 'vs/base/common/types';
 import { ILogService } from 'vs/platform/log/common/log';
+import { IExtHostRpcService } from '../common/extHostRpcService';
+import { VSBuffer } from 'vs/base/common/buffer';
A
Asher 已提交
3022
 
3023
 export class ExtensionStoragePaths implements IExtensionStoragePaths {
A
Asher 已提交
3024
 
3025 3026 3027 3028 3029 3030 3031 3032
@@ -26,6 +27,7 @@ export class ExtensionStoragePaths implements IExtensionStoragePaths {
 	constructor(
 		@IExtHostInitDataService initData: IExtHostInitDataService,
 		@ILogService private readonly _logService: ILogService,
+		@IExtHostRpcService private readonly _extHostRpc: IExtHostRpcService,
 	) {
 		this._workspace = withNullAsUndefined(initData.workspace);
 		this._environment = initData.environment;
A
Asher 已提交
3033
@@ -54,21 +56,26 @@ export class ExtensionStoragePaths implements IExtensionStoragePaths {
3034 3035
 		const storageName = this._workspace.id;
 		const storagePath = path.join(this._environment.appSettingsHome.fsPath, 'workspaceStorage', storageName);
A
Asher 已提交
3036
 
3037
-		const exists = await pfs.dirExists(storagePath);
A
Asher 已提交
3038 3039
-
-		if (exists) {
3040 3041
+		// NOTE@coder: Use the file system proxy so this will work in the browser.
+		const fileSystem = this._extHostRpc.getProxy(MainContext.MainThreadFileSystem);
A
Asher 已提交
3042 3043
+		try {
+			await fileSystem.$stat(URI.file(storagePath));
3044
 			return storagePath;
A
Asher 已提交
3045 3046
+		} catch (error) {
+			// Doesn't exist.
3047
 		}
A
Asher 已提交
3048
 
3049 3050 3051 3052 3053 3054 3055 3056 3057
 		try {
-			await pfs.mkdirp(storagePath);
-			await pfs.writeFile(
-				path.join(storagePath, 'meta.json'),
-				JSON.stringify({
-					id: this._workspace.id,
-					configuration: this._workspace.configuration && URI.revive(this._workspace.configuration).toString(),
-					name: this._workspace.name
-				}, undefined, 2)
A
Asher 已提交
3058
+			// NOTE@coder: $writeFile performs a mkdirp.
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
+			await fileSystem.$writeFile(
+				URI.file(path.join(storagePath, 'meta.json')),
+				VSBuffer.fromString(
+					JSON.stringify({
+						id: this._workspace.id,
+						configuration: this._workspace.configuration && URI.revive(this._workspace.configuration).toString(),
+						name: this._workspace.name
+					}, undefined, 2)
+				)
 			);
 			return storagePath;
A
Asher 已提交
3070
 
3071
diff --git a/src/vs/workbench/api/worker/extHostExtensionService.ts b/src/vs/workbench/api/worker/extHostExtensionService.ts
A
Asher 已提交
3072
index 681b279778..fb6eae3a99 100644
3073 3074
--- a/src/vs/workbench/api/worker/extHostExtensionService.ts
+++ b/src/vs/workbench/api/worker/extHostExtensionService.ts
A
Asher 已提交
3075 3076
@@ -8,6 +8,9 @@ import { ExtensionActivationTimesBuilder } from 'vs/workbench/api/common/extHost
 import { AbstractExtHostExtensionService } from 'vs/workbench/api/common/extHostExtensionService';
3077 3078
 import { URI } from 'vs/base/common/uri';
 import { RequireInterceptor } from 'vs/workbench/api/common/extHostRequireInterceptor';
A
Asher 已提交
3079
+import { joinPath } from 'vs/base/common/resources';
3080
+import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
A
Asher 已提交
3081
+import { loadCommonJSModule } from 'vs/server/browser/worker';
A
Anmol Sethi 已提交
3082
 
A
Asher 已提交
3083
 class WorkerRequireInterceptor extends RequireInterceptor {
A
Anmol Sethi 已提交
3084
 
A
Asher 已提交
3085
@@ -40,7 +43,14 @@ export class ExtHostExtensionService extends AbstractExtHostExtensionService {
3086 3087
 		await this._fakeModules.install();
 	}
A
Anmol Sethi 已提交
3088
 
A
Asher 已提交
3089
-	protected async _loadCommonJSModule<T>(module: URI, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T> {
3090 3091
+	protected async _loadCommonJSModule<T>(module: URI | IExtensionDescription, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T> {
+		if (!URI.isUri(module) && module.extensionKind !== 'web') {
A
Asher 已提交
3092
+			return loadCommonJSModule(module, activationTimesBuilder, this._nodeProxy, this._logService, this._fakeModules!.getModule('vscode', module.extensionLocation));
3093
+		}
A
Asher 已提交
3094
+
3095 3096 3097
+		if (!URI.isUri(module)) {
+			module = joinPath(module.extensionLocation, module.main!);
+		}
A
Anmol Sethi 已提交
3098
 
A
Asher 已提交
3099 3100
 		module = module.with({ path: ensureSuffix(module.path, '.js') });
 		const response = await fetch(module.toString(true));
A
Anmol Sethi 已提交
3101
@@ -57,7 +67,7 @@ export class ExtHostExtensionService extends AbstractExtHostExtensionService {
A
Asher 已提交
3102 3103 3104
 		const _exports = {};
 		const _module = { exports: _exports };
 		const _require = (request: string) => {
A
Asher 已提交
3105 3106
-			const result = this._fakeModules!.getModule(request, module);
+			const result = this._fakeModules!.getModule(request, <URI>module);
A
Asher 已提交
3107 3108 3109
 			if (result === undefined) {
 				throw new Error(`Cannot load module '${request}'`);
 			}
A
Asher 已提交
3110
diff --git a/src/vs/workbench/browser/web.main.ts b/src/vs/workbench/browser/web.main.ts
A
Asher 已提交
3111
index 8177f3d291..ee1355e25b 100644
A
Asher 已提交
3112 3113
--- a/src/vs/workbench/browser/web.main.ts
+++ b/src/vs/workbench/browser/web.main.ts
A
Asher 已提交
3114
@@ -47,6 +47,7 @@ import { IndexedDBLogProvider } from 'vs/workbench/services/log/browser/indexedD
A
Asher 已提交
3115
 import { InMemoryLogProvider } from 'vs/workbench/services/log/common/inMemoryLogProvider';
A
Asher 已提交
3116
 import { isWorkspaceToOpen, isFolderToOpen } from 'vs/platform/windows/common/windows';
A
Asher 已提交
3117
 import { getWorkspaceIdentifier } from 'vs/workbench/services/workspaces/browser/workspaces';
A
Asher 已提交
3118
+import { initialize } from 'vs/server/browser/client';
A
Asher 已提交
3119 3120
 import { coalesce } from 'vs/base/common/arrays';
 import { InMemoryFileSystemProvider } from 'vs/platform/files/common/inMemoryFilesystemProvider';
A
Asher 已提交
3121
 import { WebResourceIdentityService, IResourceIdentityService } from 'vs/platform/resource/common/resourceIdentityService';
A
Asher 已提交
3122
@@ -91,6 +92,8 @@ class BrowserMain extends Disposable {
A
Asher 已提交
3123
 		// Startup
A
Asher 已提交
3124
 		const instantiationService = workbench.startup();
A
Asher 已提交
3125
 
A
Asher 已提交
3126 3127 3128 3129 3130
+		await initialize(services.serviceCollection);
+
 		// Return API Facade
 		return instantiationService.invokeFunction(accessor => {
 			const commandService = accessor.get(ICommandService);
A
Asher 已提交
3131
diff --git a/src/vs/workbench/common/resources.ts b/src/vs/workbench/common/resources.ts
A
Asher 已提交
3132
index 2a7844da48..2812092983 100644
A
Asher 已提交
3133 3134 3135 3136 3137 3138 3139
--- a/src/vs/workbench/common/resources.ts
+++ b/src/vs/workbench/common/resources.ts
@@ -15,6 +15,7 @@ import { ParsedExpression, IExpression, parse } from 'vs/base/common/glob';
 import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
 import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
 import { withNullAsUndefined } from 'vs/base/common/types';
+import { Schemas } from 'vs/base/common/network';
A
Asher 已提交
3140
 
A
Asher 已提交
3141
 export class ResourceContextKey extends Disposable implements IContextKey<URI> {
A
Asher 已提交
3142
 
A
Asher 已提交
3143
@@ -67,7 +68,8 @@ export class ResourceContextKey extends Disposable implements IContextKey<URI> {
A
Asher 已提交
3144 3145 3146 3147
 	set(value: URI | null) {
 		if (!ResourceContextKey._uriEquals(this._resourceKey.get(), value)) {
 			this._resourceKey.set(value);
-			this._schemeKey.set(value ? value.scheme : null);
A
Asher 已提交
3148
+			// NOTE@coder: Fixes extensions matching against file schemas.
A
Asher 已提交
3149 3150 3151 3152
+			this._schemeKey.set(value ? (value.scheme === Schemas.vscodeRemote ? Schemas.file : value.scheme) : null);
 			this._filenameKey.set(value ? basename(value) : null);
 			this._langIdKey.set(value ? this._modeService.getModeIdByFilepathOrFirstLine(value) : null);
 			this._extensionKey.set(value ? extname(value) : null);
3153
diff --git a/src/vs/workbench/contrib/scm/browser/media/scmViewlet.css b/src/vs/workbench/contrib/scm/browser/media/scmViewlet.css
A
Asher 已提交
3154
index d07684c843..5c9e520ce4 100644
3155 3156 3157 3158 3159 3160 3161 3162 3163
--- a/src/vs/workbench/contrib/scm/browser/media/scmViewlet.css
+++ b/src/vs/workbench/contrib/scm/browser/media/scmViewlet.css
@@ -120,9 +120,11 @@
 	margin-right: 8px;
 }
 
-.scm-viewlet .monaco-list .monaco-list-row .resource > .name > .monaco-icon-label > .actions {
-	flex-grow: 100;
-}
A
Asher 已提交
3164
+/* NOTE@coder: Causes the label to shrink to zero width in Firefox due to
3165 3166 3167 3168 3169 3170 3171
+ * overflow:hidden. This isn't right anyway, as far as I can tell. */
+/* .scm-viewlet .monaco-list .monaco-list-row .resource > .name > .monaco-icon-label > .actions { */
+/* 	flex-grow: 100; */
+/* } */
 
 .scm-viewlet .monaco-list .monaco-list-row .resource-group > .actions,
 .scm-viewlet .monaco-list .monaco-list-row .resource > .name > .monaco-icon-label > .actions {
A
Asher 已提交
3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184
diff --git a/src/vs/workbench/contrib/webview/browser/pre/host.js b/src/vs/workbench/contrib/webview/browser/pre/host.js
index 99b4ecbb3a..91c1920bb3 100644
--- a/src/vs/workbench/contrib/webview/browser/pre/host.js
+++ b/src/vs/workbench/contrib/webview/browser/pre/host.js
@@ -97,7 +97,7 @@
 		fakeLoad: true,
 		rewriteCSP: (csp, endpoint) => {
 			const endpointUrl = new URL(endpoint);
-			csp.setAttribute('content', csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\s|;|$))/g, endpointUrl.origin));
+			return csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\s|;|$))/g, endpointUrl.origin);
 		}
 	});
 }());
3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203
diff --git a/src/vs/workbench/services/dialogs/browser/dialogService.ts b/src/vs/workbench/services/dialogs/browser/dialogService.ts
index 6b42535bff..88b7e3c3ea 100644
--- a/src/vs/workbench/services/dialogs/browser/dialogService.ts
+++ b/src/vs/workbench/services/dialogs/browser/dialogService.ts
@@ -124,11 +124,12 @@ export class DialogService implements IDialogService {
 	async about(): Promise<void> {
 		const detailString = (useAgo: boolean): string => {
 			return nls.localize('aboutDetail',
-				"Version: {0}\nCommit: {1}\nDate: {2}\nBrowser: {3}",
+				"code-server: v{4}\n VS Code: v{0}\nCommit: {1}\nDate: {2}\nBrowser: {3}",
 				this.productService.version || 'Unknown',
 				this.productService.commit || 'Unknown',
 				this.productService.date ? `${this.productService.date}${useAgo ? ' (' + fromNow(new Date(this.productService.date), true) + ')' : ''}` : 'Unknown',
-				navigator.userAgent
+				navigator.userAgent,
+				this.productService.codeServerVersion || 'Unknown',
 			);
 		};
 
A
Asher 已提交
3204
diff --git a/src/vs/workbench/services/environment/browser/environmentService.ts b/src/vs/workbench/services/environment/browser/environmentService.ts
A
Asher 已提交
3205
index 1060388040..a8f9646e25 100644
A
Asher 已提交
3206 3207
--- a/src/vs/workbench/services/environment/browser/environmentService.ts
+++ b/src/vs/workbench/services/environment/browser/environmentService.ts
A
Asher 已提交
3208
@@ -16,6 +16,7 @@ import { memoize } from 'vs/base/common/decorators';
A
Asher 已提交
3209
 import { onUnexpectedError } from 'vs/base/common/errors';
A
Asher 已提交
3210 3211
 import { LIGHT } from 'vs/platform/theme/common/themeService';
 import { parseLineAndColumnAware } from 'vs/base/common/extpath';
3212 3213
+import * as paths from 'vs/base/common/path';
 
A
Asher 已提交
3214
 export class BrowserEnvironmentConfiguration implements IEnvironmentConfiguration {
3215
 
A
Asher 已提交
3216
@@ -224,6 +225,20 @@ export class BrowserWorkbenchEnvironmentService implements IWorkbenchEnvironment
A
Asher 已提交
3217
 		return this.webviewExternalEndpoint.replace('{{uuid}}', '*');
A
Asher 已提交
3218
 	}
A
Asher 已提交
3219
 
A
Asher 已提交
3220
+	// NOTE@coder: vscodevim uses the global storage home.
3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
+	@memoize
+	get userDataPath(): string {
+		const dataPath = this.payload?.get("userDataPath");
+		if (!dataPath) {
+			throw new Error("userDataPath was not provided to environment service");
+		}
+		return dataPath;
+	}
+	@memoize
+	get appSettingsHome(): URI { return URI.file(paths.join(this.userDataPath, 'User')); }
A
Asher 已提交
3231 3232
+	@memoize
+	get globalStorageHome(): string { return paths.join(this.appSettingsHome.fsPath, 'globalStorage'); }
A
Asher 已提交
3233
+
A
Asher 已提交
3234 3235 3236
 	get disableTelemetry(): boolean { return false; }
 
 	get verbose(): boolean { return this.payload?.get('verbose') === 'true'; }
A
Asher 已提交
3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250
diff --git a/src/vs/workbench/services/extensionManagement/common/extensionEnablementService.ts b/src/vs/workbench/services/extensionManagement/common/extensionEnablementService.ts
index cfac383e8a..c535d38296 100644
--- a/src/vs/workbench/services/extensionManagement/common/extensionEnablementService.ts
+++ b/src/vs/workbench/services/extensionManagement/common/extensionEnablementService.ts
@@ -153,7 +153,7 @@ export class ExtensionEnablementService extends Disposable implements IWorkbench
 					}
 				}
 			}
-			return true;
+			return false; // NOTE@coder: Don't disable anything by extensionKind.
 		}
 		return false;
 	}
diff --git a/src/vs/workbench/services/extensionManagement/common/extensionManagementService.ts b/src/vs/workbench/services/extensionManagement/common/extensionManagementService.ts
A
Asher 已提交
3251
index 87e4b95906..0d598cf4f1 100644
A
Asher 已提交
3252 3253
--- a/src/vs/workbench/services/extensionManagement/common/extensionManagementService.ts
+++ b/src/vs/workbench/services/extensionManagement/common/extensionManagementService.ts
A
Asher 已提交
3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271
@@ -5,7 +5,7 @@
 
 import { Event, EventMultiplexer } from 'vs/base/common/event';
 import {
-	IExtensionManagementService, ILocalExtension, IGalleryExtension, InstallExtensionEvent, DidInstallExtensionEvent, IExtensionIdentifier, DidUninstallExtensionEvent, IReportedExtension, IGalleryMetadata, IExtensionGalleryService, INSTALL_ERROR_NOT_SUPPORTED
+	IExtensionManagementService, ILocalExtension, IGalleryExtension, InstallExtensionEvent, DidInstallExtensionEvent, IExtensionIdentifier, DidUninstallExtensionEvent, IReportedExtension, IGalleryMetadata, IExtensionGalleryService
 } from 'vs/platform/extensionManagement/common/extensionManagement';
 import { IExtensionManagementServer, IExtensionManagementServerService } from 'vs/workbench/services/extensionManagement/common/extensionManagement';
 import { ExtensionType, isLanguagePackExtension, IExtensionManifest } from 'vs/platform/extensions/common/extensions';
@@ -15,7 +15,7 @@ import { IConfigurationService } from 'vs/platform/configuration/common/configur
 import { CancellationToken } from 'vs/base/common/cancellation';
 import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
 import { localize } from 'vs/nls';
-import { prefersExecuteOnUI, canExecuteOnWorkspace } from 'vs/workbench/services/extensions/common/extensionsUtil';
+import { prefersExecuteOnUI } from 'vs/workbench/services/extensions/common/extensionsUtil';
 import { IProductService } from 'vs/platform/product/common/productService';
 import { Schemas } from 'vs/base/common/network';
 import { IDownloadService } from 'vs/platform/download/common/download';
A
Asher 已提交
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
@@ -208,11 +208,7 @@ export class ExtensionManagementService extends Disposable implements IExtension
 			if (!manifest) {
 				return Promise.reject(localize('Manifest is not found', "Installing Extension {0} failed: Manifest is not found.", gallery.displayName || gallery.name));
 			}
-			if (!isLanguagePackExtension(manifest) && !canExecuteOnWorkspace(manifest, this.productService, this.configurationService)) {
-				const error = new Error(localize('cannot be installed', "Cannot install '{0}' because this extension has defined that it cannot run on the remote server.", gallery.displayName || gallery.name));
-				error.name = INSTALL_ERROR_NOT_SUPPORTED;
-				return Promise.reject(error);
-			}
+			// NOTE@coder: Allow extensions of any kind.
 			return this.extensionManagementServerService.remoteExtensionManagementServer.extensionManagementService.installFromGallery(gallery);
 		}
 		return Promise.reject('No Servers to Install');
3285
diff --git a/src/vs/workbench/services/extensions/browser/extensionService.ts b/src/vs/workbench/services/extensions/browser/extensionService.ts
A
Asher 已提交
3286
index 5b6a15e820..0f93c896e2 100644
3287 3288 3289
--- a/src/vs/workbench/services/extensions/browser/extensionService.ts
+++ b/src/vs/workbench/services/extensions/browser/extensionService.ts
@@ -119,6 +119,7 @@ export class ExtensionService extends AbstractExtensionService implements IExten
A
Asher 已提交
3290
 
3291 3292
 		} else {
 			// remote: only enabled and none-web'ish extension
A
Asher 已提交
3293 3294
+			localExtensions.push(...remoteEnv.extensions.filter(extension => this._isEnabled(extension) && canExecuteOnWeb(extension, this._productService, this._configService)));
 			remoteEnv.extensions = remoteEnv.extensions.filter(extension => this._isEnabled(extension) && !canExecuteOnWeb(extension, this._productService, this._configService));
3295
 			this._checkEnableProposedApi(remoteEnv.extensions);
A
Asher 已提交
3296
 
3297
diff --git a/src/vs/workbench/services/extensions/browser/webWorkerExtensionHostStarter.ts b/src/vs/workbench/services/extensions/browser/webWorkerExtensionHostStarter.ts
A
Asher 已提交
3298
index 097a048793..b9f32b032d 100644
3299 3300
--- a/src/vs/workbench/services/extensions/browser/webWorkerExtensionHostStarter.ts
+++ b/src/vs/workbench/services/extensions/browser/webWorkerExtensionHostStarter.ts
A
Asher 已提交
3301
@@ -140,7 +140,7 @@ export class WebWorkerExtensionHostStarter implements IExtensionHostStarter {
3302 3303 3304 3305 3306 3307 3308 3309
 				appLanguage: platform.language,
 				extensionDevelopmentLocationURI: this._environmentService.extensionDevelopmentLocationURI,
 				extensionTestsLocationURI: this._environmentService.extensionTestsLocationURI,
-				globalStorageHome: URI.parse('fake:globalStorageHome'), //todo@joh URI.file(this._environmentService.globalStorageHome),
+				globalStorageHome: URI.file(this._environmentService.globalStorageHome),
 				userHome: URI.parse('fake:userHome'), //todo@joh URI.file(this._environmentService.userHome),
 				webviewResourceRoot: this._environmentService.webviewResourceRoot,
 				webviewCspSource: this._environmentService.webviewCspSource,
3310
diff --git a/src/vs/workbench/services/extensions/common/extensionsUtil.ts b/src/vs/workbench/services/extensions/common/extensionsUtil.ts
A
Asher 已提交
3311
index 9e8352ac88..22a2d296f9 100644
3312 3313
--- a/src/vs/workbench/services/extensions/common/extensionsUtil.ts
+++ b/src/vs/workbench/services/extensions/common/extensionsUtil.ts
A
Asher 已提交
3314
@@ -32,7 +32,8 @@ export function canExecuteOnWorkspace(manifest: IExtensionManifest, productServi
A
Asher 已提交
3315
 
A
Asher 已提交
3316 3317 3318
 export function canExecuteOnWeb(manifest: IExtensionManifest, productService: IProductService, configurationService: IConfigurationService): boolean {
 	const extensionKind = getExtensionKind(manifest, productService, configurationService);
-	return extensionKind.some(kind => kind === 'web');
A
Asher 已提交
3319
+	// NOTE@coder: Hardcode vim for now.
A
Asher 已提交
3320
+	return extensionKind.some(kind => kind === 'web') || manifest.name === 'vim';
3321
 }
A
Asher 已提交
3322
 
A
Asher 已提交
3323
 export function getExtensionKind(manifest: IExtensionManifest, productService: IProductService, configurationService: IConfigurationService): ExtensionKind[] {
A
Asher 已提交
3324
diff --git a/src/vs/workbench/services/extensions/node/extensionHostProcessSetup.ts b/src/vs/workbench/services/extensions/node/extensionHostProcessSetup.ts
A
Asher 已提交
3325
index 79dd77aeb2..1d93c0f922 100644
A
Asher 已提交
3326 3327
--- a/src/vs/workbench/services/extensions/node/extensionHostProcessSetup.ts
+++ b/src/vs/workbench/services/extensions/node/extensionHostProcessSetup.ts
A
Asher 已提交
3328 3329 3330 3331 3332 3333 3334 3335 3336
@@ -16,7 +16,7 @@ import { IInitData } from 'vs/workbench/api/common/extHost.protocol';
 import { MessageType, createMessageOfType, isMessageOfType, IExtHostSocketMessage, IExtHostReadyMessage, IExtHostReduceGraceTimeMessage } from 'vs/workbench/services/extensions/common/extensionHostProtocol';
 import { ExtensionHostMain, IExitFn } from 'vs/workbench/services/extensions/common/extensionHostMain';
 import { VSBuffer } from 'vs/base/common/buffer';
-import { IURITransformer, URITransformer, IRawURITransformer } from 'vs/base/common/uriIpc';
+import { IURITransformer, URITransformer } from 'vs/base/common/uriIpc';
 import { exists } from 'vs/base/node/pfs';
 import { realpath } from 'vs/base/node/extpath';
 import { IHostUtils } from 'vs/workbench/api/common/extHostExtensionService';
A
Asher 已提交
3337
@@ -55,12 +55,13 @@ const args = minimist(process.argv.slice(2), {
3338 3339
 	const Module = require.__$__nodeRequire('module') as any;
 	const originalLoad = Module._load;
A
Asher 已提交
3340
 
3341 3342 3343 3344 3345
-	Module._load = function (request: string) {
+	Module._load = function (request: string, parent: object, isMain: boolean) {
 		if (request === 'natives') {
 			throw new Error('Either the extension or a NPM dependency is using the "natives" node module which is unsupported as it can cause a crash of the extension host. Click [here](https://go.microsoft.com/fwlink/?linkid=871887) to find out more');
 		}
A
Asher 已提交
3346
 
3347
-		return originalLoad.apply(this, arguments);
A
Asher 已提交
3348
+		// NOTE@coder: Map node_module.asar requests to regular node_modules.
3349 3350 3351
+		return originalLoad.apply(this, [request.replace(/node_modules\.asar(\.unpacked)?/, 'node_modules'), parent, isMain]);
 	};
 })();
A
Asher 已提交
3352
 
A
Asher 已提交
3353
@@ -133,8 +134,11 @@ function _createExtHostProtocol(): Promise<IMessagePassingProtocol> {
A
Asher 已提交
3354
 
A
Asher 已提交
3355 3356 3357 3358 3359 3360 3361 3362 3363 3364
 						// Wait for rich client to reconnect
 						protocol.onSocketClose(() => {
-							// The socket has closed, let's give the renderer a certain amount of time to reconnect
-							disconnectRunner1.schedule();
+							// NOTE@coder: Inform the server so we can manage offline
+							// connections there instead. Our goal is to persist connections
+							// forever (to a reasonable point) to account for things like
+							// hibernating overnight.
+							process.send!({ type: 'VSCODE_EXTHOST_DISCONNECTED' });
 						});
A
Asher 已提交
3365
 					}
A
Asher 已提交
3366
 				}
A
Asher 已提交
3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380
@@ -307,11 +311,9 @@ export async function startExtensionHostProcess(): Promise<void> {
 
 	// Attempt to load uri transformer
 	let uriTransformer: IURITransformer | null = null;
-	if (initData.remote.authority && args.uriTransformerPath) {
+	if (initData.remote.authority) {
 		try {
-			const rawURITransformerFactory = <any>require.__$__nodeRequire(args.uriTransformerPath);
-			const rawURITransformer = <IRawURITransformer>rawURITransformerFactory(initData.remote.authority);
-			uriTransformer = new URITransformer(rawURITransformer);
+			uriTransformer = new URITransformer(initData.remote.authority);
 		} catch (e) {
 			console.error(e);
 		}
3381
diff --git a/src/vs/workbench/services/extensions/worker/extHost.services.ts b/src/vs/workbench/services/extensions/worker/extHost.services.ts
A
Asher 已提交
3382
index 100864519d..0785d3391d 100644
3383 3384
--- a/src/vs/workbench/services/extensions/worker/extHost.services.ts
+++ b/src/vs/workbench/services/extensions/worker/extHost.services.ts
A
Asher 已提交
3385
@@ -20,9 +20,10 @@ import { IExtHostStorage, ExtHostStorage } from 'vs/workbench/api/common/extHost
3386
 import { ExtHostExtensionService } from 'vs/workbench/api/worker/extHostExtensionService';
3387 3388
 import { ILogService } from 'vs/platform/log/common/log';
 import { ExtHostLogService } from 'vs/workbench/api/worker/extHostLogService';
A
Asher 已提交
3389
+import { ExtHostNodeProxy, IExtHostNodeProxy } from 'vs/server/browser/extHostNodeProxy';
3390
+import { ExtensionStoragePaths } from 'vs/workbench/api/node/extHostStoragePaths';
A
Asher 已提交
3391 3392
 import { IExtHostTunnelService, ExtHostTunnelService } from 'vs/workbench/api/common/extHostTunnelService';
 import { IExtHostApiDeprecationService, ExtHostApiDeprecationService, } from 'vs/workbench/api/common/extHostApiDeprecationService';
A
Asher 已提交
3393
-import { NotImplementedProxy } from 'vs/base/common/types';
A
Asher 已提交
3394
 
A
Asher 已提交
3395 3396 3397
 // register singleton services
 registerSingleton(ILogService, ExtHostLogService);
@@ -36,9 +37,10 @@ registerSingleton(IExtHostDocumentsAndEditors, ExtHostDocumentsAndEditors);
3398 3399
 registerSingleton(IExtHostStorage, ExtHostStorage);
 registerSingleton(IExtHostExtensionService, ExtHostExtensionService);
A
Asher 已提交
3400
 registerSingleton(IExtHostSearch, ExtHostSearch);
3401
+registerSingleton(IExtHostNodeProxy, ExtHostNodeProxy);
A
Asher 已提交
3402
 registerSingleton(IExtHostTunnelService, ExtHostTunnelService);
A
Asher 已提交
3403
 
3404 3405 3406
 registerSingleton(IExtHostTerminalService, WorkerExtHostTerminalService);
 registerSingleton(IExtHostTask, WorkerExtHostTask);
 registerSingleton(IExtHostDebugService, WorkerExtHostDebugService);
A
Asher 已提交
3407
-registerSingleton(IExtensionStoragePaths, class extends NotImplementedProxy<IExtensionStoragePaths>(String(IExtensionStoragePaths)) { whenReady = Promise.resolve(); });
3408
+registerSingleton(IExtensionStoragePaths, ExtensionStoragePaths);
A
Asher 已提交
3409
diff --git a/src/vs/workbench/services/extensions/worker/extensionHostWorkerMain.ts b/src/vs/workbench/services/extensions/worker/extensionHostWorkerMain.ts
3410
index 79455414c0..a407593b4d 100644
A
Asher 已提交
3411 3412 3413
--- a/src/vs/workbench/services/extensions/worker/extensionHostWorkerMain.ts
+++ b/src/vs/workbench/services/extensions/worker/extensionHostWorkerMain.ts
@@ -14,7 +14,11 @@
A
Asher 已提交
3414
 
A
Asher 已提交
3415 3416 3417 3418 3419
 	require.config({
 		baseUrl: monacoBaseUrl,
-		catchError: true
+		catchError: true,
+		paths: {
3420 3421
+			'@coder/node-browser': `../node_modules/@coder/node-browser/out/client/client.js`,
+			'@coder/requirefs': `../node_modules/@coder/requirefs/out/requirefs.js`,
A
Asher 已提交
3422 3423
+		}
 	});
A
Asher 已提交
3424
 
A
Asher 已提交
3425
 	require(['vs/workbench/services/extensions/worker/extensionHostWorker'], () => { }, err => console.error(err));
A
Asher 已提交
3426
diff --git a/src/vs/workbench/services/localizations/electron-browser/localizationsService.ts b/src/vs/workbench/services/localizations/electron-browser/localizationsService.ts
A
Asher 已提交
3427
index d8cae2cf01..c700697bb6 100644
A
Asher 已提交
3428 3429
--- a/src/vs/workbench/services/localizations/electron-browser/localizationsService.ts
+++ b/src/vs/workbench/services/localizations/electron-browser/localizationsService.ts
A
Asher 已提交
3430
@@ -5,17 +5,17 @@
A
Asher 已提交
3431
 
A
Asher 已提交
3432
 import { createChannelSender } from 'vs/base/parts/ipc/common/ipc';
A
Asher 已提交
3433 3434 3435 3436
 import { ILocalizationsService } from 'vs/platform/localizations/common/localizations';
-import { ISharedProcessService } from 'vs/platform/ipc/electron-browser/sharedProcessService';
 import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
+import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
A
Asher 已提交
3437
 
A
Asher 已提交
3438
 export class LocalizationsService {
A
Asher 已提交
3439
 
A
Asher 已提交
3440
 	_serviceBrand: undefined;
A
Asher 已提交
3441
 
A
Asher 已提交
3442 3443 3444 3445 3446 3447 3448 3449
 	constructor(
-		@ISharedProcessService sharedProcessService: ISharedProcessService,
+		@IRemoteAgentService remoteAgentService: IRemoteAgentService,
 	) {
-		return createChannelSender<ILocalizationsService>(sharedProcessService.getChannel('localizations'));
+		return createChannelSender<ILocalizationsService>(remoteAgentService.getConnection()!.getChannel('localizations'));
 	}
 }
A
Asher 已提交
3450
 
A
Asher 已提交
3451
diff --git a/src/vs/workbench/workbench.web.main.ts b/src/vs/workbench/workbench.web.main.ts
A
Asher 已提交
3452
index 742e618d01..5a73f7dfd9 100644
A
Asher 已提交
3453 3454
--- a/src/vs/workbench/workbench.web.main.ts
+++ b/src/vs/workbench/workbench.web.main.ts
A
Asher 已提交
3455
@@ -35,7 +35,8 @@ import 'vs/workbench/services/textfile/browser/browserTextFileService';
A
Asher 已提交
3456 3457 3458
 import 'vs/workbench/services/keybinding/browser/keymapService';
 import 'vs/workbench/services/extensions/browser/extensionService';
 import 'vs/workbench/services/extensionManagement/common/extensionManagementServerService';
A
Asher 已提交
3459
-import 'vs/workbench/services/telemetry/browser/telemetryService';
A
Asher 已提交
3460
+// NOTE@coder: We send it all to the server side to be processed there instead.
A
Asher 已提交
3461
+// import 'vs/workbench/services/telemetry/browser/telemetryService';
A
Asher 已提交
3462
 import 'vs/workbench/services/configurationResolver/browser/configurationResolverService';
A
Asher 已提交
3463 3464
 import 'vs/workbench/services/credentials/browser/credentialsService';
 import 'vs/workbench/services/url/browser/urlService';
A
Asher 已提交
3465
diff --git a/yarn.lock b/yarn.lock
A
Asher 已提交
3466
index dd88c0485c..fd12a49740 100644
A
Asher 已提交
3467 3468
--- a/yarn.lock
+++ b/yarn.lock
A
Asher 已提交
3469 3470
@@ -140,6 +140,23 @@
     lodash "^4.17.13"
A
Asher 已提交
3471
     to-fast-properties "^2.0.0"
A
Asher 已提交
3472
 
A
Asher 已提交
3473 3474 3475 3476
+"@coder/logger@^1.1.12":
+  version "1.1.12"
+  resolved "https://registry.yarnpkg.com/@coder/logger/-/logger-1.1.12.tgz#def113b7183abc35a8da2b57f0929f7e9626f4e0"
+  integrity sha512-oM0j3lTVPqApUm3e0bKKcXpfAiJEys31fgEfQlHmvEA13ujsC4zDuXnt0uzDtph48eMoNRLOF/EE4mNShVJKVw==
A
Asher 已提交
3477 3478 3479 3480 3481 3482
+
+"@coder/node-browser@^1.0.8":
+  version "1.0.8"
+  resolved "https://registry.yarnpkg.com/@coder/node-browser/-/node-browser-1.0.8.tgz#c22f581b089ad7d95ad1362fd351c57b7fbc6e70"
+  integrity sha512-NLF9sYMRCN9WK1C224pHax1Cay3qKypg25BhVg7VfNbo3Cpa3daata8RF/rT8JK3lPsu8PmFgDRQjzGC9X1Lrw==
+
3483 3484 3485 3486
+"@coder/requirefs@^1.1.5":
+  version "1.1.5"
+  resolved "https://registry.yarnpkg.com/@coder/requirefs/-/requirefs-1.1.5.tgz#259db370d563a79a96fb150bc9d69c7db6edc9fb"
+  integrity sha512-3jB47OFCql9+9FI6Vc4YX0cfFnG5rxBfrZUH45S4XYtYGOz+/Xl4h4d2iMk50b7veHkeSWGlB4VHC3UZ16zuYQ==
A
Asher 已提交
3487 3488 3489
+  optionalDependencies:
+    jszip "2.6.0"
+
A
Asher 已提交
3490 3491 3492
 "@electron/get@^1.0.1":
   version "1.7.2"
   resolved "https://registry.yarnpkg.com/@electron/get/-/get-1.7.2.tgz#286436a9fb56ff1a1fcdf0e80131fd65f4d1e0fd"
A
Asher 已提交
3493
@@ -5410,6 +5427,13 @@ jsprim@^1.2.2:
A
Asher 已提交
3494 3495
     json-schema "0.2.3"
     verror "1.10.0"
A
Asher 已提交
3496
 
A
Asher 已提交
3497 3498 3499 3500 3501 3502 3503 3504 3505 3506
+jszip@2.6.0:
+  version "2.6.0"
+  resolved "https://registry.yarnpkg.com/jszip/-/jszip-2.6.0.tgz#7fb3e9c2f11c8a9840612db5dabbc8cf3a7534b7"
+  integrity sha1-f7PpwvEciphAYS212rvIzzp1NLc=
+  dependencies:
+    pako "~1.0.0"
+
 just-debounce@^1.0.0:
   version "1.0.0"
   resolved "https://registry.yarnpkg.com/just-debounce/-/just-debounce-1.0.0.tgz#87fccfaeffc0b68cd19d55f6722943f929ea35ea"
A
Asher 已提交
3507
@@ -6776,6 +6800,11 @@ p-try@^2.0.0:
A
Asher 已提交
3508 3509
   resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.0.0.tgz#85080bb87c64688fa47996fe8f7dfbe8211760b1"
   integrity sha512-hMp0onDKIajHfIkdRk3P4CdCmErkYAxxDtP3Wx/4nZ3aGlau2VKh3mZpcuFkH27WQkL/3WBCPOktzA9ZOAnMQQ==
A
Asher 已提交
3510
 
A
Asher 已提交
3511
+pako@~1.0.0:
A
Asher 已提交
3512 3513 3514
+  version "1.0.11"
+  resolved "https://registry.yarnpkg.com/pako/-/pako-1.0.11.tgz#6c9599d340d54dfd3946380252a35705a6b992bf"
+  integrity sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==
A
Asher 已提交
3515 3516 3517 3518
+
 pako@~1.0.5:
   version "1.0.6"
   resolved "https://registry.yarnpkg.com/pako/-/pako-1.0.6.tgz#0101211baa70c4bca4a0f63f2206e97b7dfaf258"