extHost.api.impl.ts 39.5 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

7
import { Emitter } from 'vs/base/common/event';
8
import { TernarySearchTree } from 'vs/base/common/map';
J
Johannes Rieken 已提交
9
import { score } from 'vs/editor/common/modes/languageSelector';
10
import * as Platform from 'vs/base/common/platform';
E
Erich Gamma 已提交
11
import * as errors from 'vs/base/common/errors';
12 13
import product from 'vs/platform/node/product';
import pkg from 'vs/platform/node/package';
J
Johannes Rieken 已提交
14
import { ExtHostFileSystemEventService } from 'vs/workbench/api/node/extHostFileSystemEventService';
J
Johannes Rieken 已提交
15
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/node/extHostDocumentsAndEditors';
J
Johannes Rieken 已提交
16
import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments';
17
import { ExtHostDocumentContentProvider } from 'vs/workbench/api/node/extHostDocumentContentProviders';
J
Johannes Rieken 已提交
18 19 20
import { ExtHostDocumentSaveParticipant } from 'vs/workbench/api/node/extHostDocumentSaveParticipant';
import { ExtHostConfiguration } from 'vs/workbench/api/node/extHostConfiguration';
import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics';
S
Sandeep Somavarapu 已提交
21
import { ExtHostTreeViews } from 'vs/workbench/api/node/extHostTreeViews';
J
Johannes Rieken 已提交
22 23
import { ExtHostWorkspace } from 'vs/workbench/api/node/extHostWorkspace';
import { ExtHostQuickOpen } from 'vs/workbench/api/node/extHostQuickOpen';
24
import { ExtHostProgress } from 'vs/workbench/api/node/extHostProgress';
J
Joao Moreno 已提交
25
import { ExtHostSCM } from 'vs/workbench/api/node/extHostSCM';
J
Johannes Rieken 已提交
26 27 28 29 30 31
import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService';
import { ExtHostStatusBar } from 'vs/workbench/api/node/extHostStatusBar';
import { ExtHostCommands } from 'vs/workbench/api/node/extHostCommands';
import { ExtHostOutputService } from 'vs/workbench/api/node/extHostOutputService';
import { ExtHostTerminalService } from 'vs/workbench/api/node/extHostTerminalService';
import { ExtHostMessageService } from 'vs/workbench/api/node/extHostMessageService';
J
Johannes Rieken 已提交
32
import { ExtHostEditors } from 'vs/workbench/api/node/extHostTextEditors';
J
Johannes Rieken 已提交
33 34
import { ExtHostLanguages } from 'vs/workbench/api/node/extHostLanguages';
import { ExtHostLanguageFeatures } from 'vs/workbench/api/node/extHostLanguageFeatures';
35
import { ExtHostApiCommands } from 'vs/workbench/api/node/extHostApiCommands';
36
import { ExtHostTask } from 'vs/workbench/api/node/extHostTask';
37
import { ExtHostDebugService } from 'vs/workbench/api/node/extHostDebugService';
38
import { ExtHostWindow } from 'vs/workbench/api/node/extHostWindow';
J
Johannes Rieken 已提交
39
import * as extHostTypes from 'vs/workbench/api/node/extHostTypes';
E
Erich Gamma 已提交
40 41
import URI from 'vs/base/common/uri';
import Severity from 'vs/base/common/severity';
42
import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions';
J
Johannes Rieken 已提交
43 44 45
import { ExtHostExtensionService } from 'vs/workbench/api/node/extHostExtensionService';
import { TPromise } from 'vs/base/common/winjs.base';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
46
import * as vscode from 'vscode';
E
Erich Gamma 已提交
47
import * as paths from 'vs/base/common/paths';
48
import { MainContext, ExtHostContext, IInitData, IExtHostContext } from './extHost.protocol';
49
import * as languageConfiguration from 'vs/editor/common/modes/languageConfiguration';
50
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
A
Alex Dima 已提交
51
import { ProxyIdentifier } from 'vs/workbench/services/extensions/node/proxyIdentifier';
B
Benjamin Pasero 已提交
52
import { ExtHostDialogs } from 'vs/workbench/api/node/extHostDialogs';
53
import { ExtHostFileSystem } from 'vs/workbench/api/node/extHostFileSystem';
54
import { ExtHostDecorations } from 'vs/workbench/api/node/extHostDecorations';
55
import { toGlobPattern, toLanguageSelector } from 'vs/workbench/api/node/extHostTypeConverters';
A
Alex Dima 已提交
56
import { ExtensionActivatedByAPI } from 'vs/workbench/api/node/extHostExtensionActivator';
A
Alex Dima 已提交
57
import { OverviewRulerLane } from 'vs/editor/common/model';
58
import { ExtHostLogService } from 'vs/workbench/api/node/extHostLogService';
M
Matt Bierner 已提交
59
import { ExtHostWebviews } from 'vs/workbench/api/node/extHostWebview';
60
import { ExtHostSearch } from './extHostSearch';
J
Joao Moreno 已提交
61
import { ExtHostUrls } from './extHostUrls';
E
Erich Gamma 已提交
62

63
export interface IExtensionApiFactory {
64
	(extension: IExtensionDescription): typeof vscode;
65 66
}

67 68 69 70 71 72 73 74 75 76
export function checkProposedApiEnabled(extension: IExtensionDescription): void {
	if (!extension.enableProposedApi) {
		throwProposedApiError(extension);
	}
}

function throwProposedApiError(extension: IExtensionDescription): never {
	throw new Error(`[${extension.id}]: Proposed API is only available when running out of dev or with the following command line switch: --enable-proposed-api ${extension.id}`);
}

77
function proposedApiFunction<T>(extension: IExtensionDescription, fn: T): T {
78
	if (extension.enableProposedApi) {
79 80
		return fn;
	} else {
81
		return <any>throwProposedApiError;
82 83 84
	}
}

E
Erich Gamma 已提交
85
/**
86
 * This method instantiates and returns the extension API surface
E
Erich Gamma 已提交
87
 */
88 89
export function createApiFactory(
	initData: IInitData,
A
Alex Dima 已提交
90
	rpcProtocol: IExtHostContext,
91 92
	extHostWorkspace: ExtHostWorkspace,
	extHostConfiguration: ExtHostConfiguration,
J
Joao Moreno 已提交
93
	extensionService: ExtHostExtensionService,
94
	extHostLogService: ExtHostLogService
95
): IExtensionApiFactory {
96

97
	// Addressable instances
98
	rpcProtocol.set(ExtHostContext.ExtHostLogService, extHostLogService);
A
Alex Dima 已提交
99 100
	const extHostHeapService = rpcProtocol.set(ExtHostContext.ExtHostHeapService, new ExtHostHeapService());
	const extHostDecorations = rpcProtocol.set(ExtHostContext.ExtHostDecorations, new ExtHostDecorations(rpcProtocol));
M
Matt Bierner 已提交
101
	const extHostWebviews = rpcProtocol.set(ExtHostContext.ExtHostWebviews, new ExtHostWebviews(rpcProtocol));
J
Joao Moreno 已提交
102
	const extHostUrls = rpcProtocol.set(ExtHostContext.ExtHostUrls, new ExtHostUrls(rpcProtocol));
103
	const extHostDocumentsAndEditors = rpcProtocol.set(ExtHostContext.ExtHostDocumentsAndEditors, new ExtHostDocumentsAndEditors(rpcProtocol));
A
Alex Dima 已提交
104
	const extHostDocuments = rpcProtocol.set(ExtHostContext.ExtHostDocuments, new ExtHostDocuments(rpcProtocol, extHostDocumentsAndEditors));
105
	const extHostDocumentContentProviders = rpcProtocol.set(ExtHostContext.ExtHostDocumentContentProviders, new ExtHostDocumentContentProvider(rpcProtocol, extHostDocumentsAndEditors, extHostLogService));
106
	const extHostDocumentSaveParticipant = rpcProtocol.set(ExtHostContext.ExtHostDocumentSaveParticipant, new ExtHostDocumentSaveParticipant(extHostLogService, extHostDocuments, rpcProtocol.getProxy(MainContext.MainThreadTextEditors)));
A
Alex Dima 已提交
107
	const extHostEditors = rpcProtocol.set(ExtHostContext.ExtHostEditors, new ExtHostEditors(rpcProtocol, extHostDocumentsAndEditors));
108
	const extHostCommands = rpcProtocol.set(ExtHostContext.ExtHostCommands, new ExtHostCommands(rpcProtocol, extHostHeapService, extHostLogService));
A
Alex Dima 已提交
109 110
	const extHostTreeViews = rpcProtocol.set(ExtHostContext.ExtHostTreeViews, new ExtHostTreeViews(rpcProtocol.getProxy(MainContext.MainThreadTreeViews), extHostCommands));
	rpcProtocol.set(ExtHostContext.ExtHostWorkspace, extHostWorkspace);
A
Andre Weinand 已提交
111
	const extHostDebugService = rpcProtocol.set(ExtHostContext.ExtHostDebugService, new ExtHostDebugService(rpcProtocol, extHostWorkspace, extensionService, extHostDocumentsAndEditors, extHostConfiguration));
A
Alex Dima 已提交
112 113
	rpcProtocol.set(ExtHostContext.ExtHostConfiguration, extHostConfiguration);
	const extHostDiagnostics = rpcProtocol.set(ExtHostContext.ExtHostDiagnostics, new ExtHostDiagnostics(rpcProtocol));
A
Alex Dima 已提交
114
	const extHostLanguageFeatures = rpcProtocol.set(ExtHostContext.ExtHostLanguageFeatures, new ExtHostLanguageFeatures(rpcProtocol, null, extHostDocuments, extHostCommands, extHostHeapService, extHostDiagnostics));
115
	const extHostFileSystem = rpcProtocol.set(ExtHostContext.ExtHostFileSystem, new ExtHostFileSystem(rpcProtocol, extHostLanguageFeatures));
A
Alex Dima 已提交
116 117
	const extHostFileSystemEvent = rpcProtocol.set(ExtHostContext.ExtHostFileSystemEventService, new ExtHostFileSystemEventService());
	const extHostQuickOpen = rpcProtocol.set(ExtHostContext.ExtHostQuickOpen, new ExtHostQuickOpen(rpcProtocol, extHostWorkspace, extHostCommands));
118
	const extHostTerminalService = rpcProtocol.set(ExtHostContext.ExtHostTerminalService, new ExtHostTerminalService(rpcProtocol, extHostConfiguration, extHostLogService));
119
	const extHostSCM = rpcProtocol.set(ExtHostContext.ExtHostSCM, new ExtHostSCM(rpcProtocol, extHostCommands, extHostLogService));
120
	const extHostSearch = rpcProtocol.set(ExtHostContext.ExtHostSearch, new ExtHostSearch(rpcProtocol));
A
Alex Dima 已提交
121 122 123
	const extHostTask = rpcProtocol.set(ExtHostContext.ExtHostTask, new ExtHostTask(rpcProtocol, extHostWorkspace));
	const extHostWindow = rpcProtocol.set(ExtHostContext.ExtHostWindow, new ExtHostWindow(rpcProtocol));
	rpcProtocol.set(ExtHostContext.ExtHostExtensionService, extensionService);
124
	const extHostProgress = rpcProtocol.set(ExtHostContext.ExtHostProgress, new ExtHostProgress(rpcProtocol.getProxy(MainContext.MainThreadProgress)));
125 126 127

	// Check that no named customers are missing
	const expected: ProxyIdentifier<any>[] = Object.keys(ExtHostContext).map((key) => ExtHostContext[key]);
A
Alex Dima 已提交
128
	rpcProtocol.assertRegistered(expected);
129

130
	// Other instances
A
Alex Dima 已提交
131 132 133 134 135
	const extHostMessageService = new ExtHostMessageService(rpcProtocol);
	const extHostDialogs = new ExtHostDialogs(rpcProtocol);
	const extHostStatusBar = new ExtHostStatusBar(rpcProtocol);
	const extHostOutputService = new ExtHostOutputService(rpcProtocol);
	const extHostLanguages = new ExtHostLanguages(rpcProtocol);
136

137
	// Register API-ish commands
138
	ExtHostApiCommands.register(extHostCommands, extHostTask);
139

140
	return function (extension: IExtensionDescription): typeof vscode {
141

142 143 144 145 146 147 148 149
		// Check document selectors for being overly generic. Technically this isn't a problem but
		// in practice many extensions say they support `fooLang` but need fs-access to do so. Those
		// extension should specify then the `file`-scheme, e.g `{ scheme: 'fooLang', language: 'fooLang' }`
		// We only inform once, it is not a warning because we just want to raise awareness and because
		// we cannot say if the extension is doing it right or wrong...
		let checkSelector = (function () {
			let done = initData.environment.extensionDevelopmentPath !== extension.extensionFolderPath;
			function inform(selector: vscode.DocumentSelector) {
150
				console.info(`Extension '${extension.id}' uses a document selector without scheme. Learn more about this: https://go.microsoft.com/fwlink/?linkid=872305`);
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
				done = true;
			}
			return function perform(selector: vscode.DocumentSelector): vscode.DocumentSelector {
				if (!done) {
					if (Array.isArray(selector)) {
						selector.forEach(perform);
					} else if (typeof selector === 'string') {
						inform(selector);
					} else if (typeof selector.scheme === 'undefined') {
						inform(selector);
					}
				}
				return selector;
			};
		})();

167 168
		// namespace: commands
		const commands: typeof vscode.commands = {
M
Matt Bierner 已提交
169
			registerCommand(id: string, command: <T>(...args: any[]) => T | Thenable<T>, thisArgs?: any): vscode.Disposable {
170
				return extHostCommands.registerCommand(true, id, command, thisArgs);
171
			},
172
			registerTextEditorCommand(id: string, callback: (textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, ...args: any[]) => void, thisArg?: any): vscode.Disposable {
173
				return extHostCommands.registerCommand(true, id, (...args: any[]): any => {
174 175 176
					let activeTextEditor = extHostEditors.getActiveTextEditor();
					if (!activeTextEditor) {
						console.warn('Cannot execute ' + id + ' because there is no active text editor.');
177
						return undefined;
178
					}
179 180 181 182 183 184 185 186 187 188

					return activeTextEditor.edit((edit: vscode.TextEditorEdit) => {
						args.unshift(activeTextEditor, edit);
						callback.apply(thisArg, args);

					}).then((result) => {
						if (!result) {
							console.warn('Edits from command ' + id + ' were not applied.');
						}
					}, (err) => {
189
						console.warn('An error occurred while running command ' + id, err);
190
					});
191
				});
192 193
			},
			registerDiffInformationCommand: proposedApiFunction(extension, (id: string, callback: (diff: vscode.LineChange[], ...args: any[]) => any, thisArg?: any): vscode.Disposable => {
194
				return extHostCommands.registerCommand(true, id, async (...args: any[]) => {
195 196 197 198 199 200 201 202 203
					let activeTextEditor = extHostEditors.getActiveTextEditor();
					if (!activeTextEditor) {
						console.warn('Cannot execute ' + id + ' because there is no active text editor.');
						return undefined;
					}

					const diff = await extHostEditors.getDiffInformation(activeTextEditor.id);
					callback.apply(thisArg, [diff, ...args]);
				});
204
			}),
205
			executeCommand<T>(id: string, ...args: any[]): Thenable<T> {
206
				return extHostCommands.executeCommand<T>(id, ...args);
207
			},
208 209 210
			getCommands(filterInternal: boolean = false): Thenable<string[]> {
				return extHostCommands.getCommands(filterInternal);
			}
211
		};
212

213 214
		// namespace: env
		const env: typeof vscode.env = Object.freeze({
215 216
			get machineId() { return initData.telemetryInfo.machineId; },
			get sessionId() { return initData.telemetryInfo.sessionId; },
217
			get language() { return Platform.language; },
J
Johannes Rieken 已提交
218 219
			get appName() { return product.nameLong; },
			get appRoot() { return initData.environment.appRoot; },
M
Matt Bierner 已提交
220
			get logLevel() { return extHostLogService.getLevel(); }
221
		});
E
Erich Gamma 已提交
222

223 224 225
		// namespace: extensions
		const extensions: typeof vscode.extensions = {
			getExtension(extensionId: string): Extension<any> {
226
				let desc = extensionService.getExtensionDescription(extensionId);
227 228 229
				if (desc) {
					return new Extension(extensionService, desc);
				}
230
				return undefined;
231 232
			},
			get all(): Extension<any>[] {
233
				return extensionService.getAllExtensionDescriptions().map((desc) => new Extension(extensionService, desc));
E
Erich Gamma 已提交
234
			}
235
		};
E
Erich Gamma 已提交
236

237 238 239 240 241
		// namespace: languages
		const languages: typeof vscode.languages = {
			createDiagnosticCollection(name?: string): vscode.DiagnosticCollection {
				return extHostDiagnostics.createDiagnosticCollection(name);
			},
242 243 244 245
			get onDidChangeDiagnostics() {
				checkProposedApiEnabled(extension);
				return extHostDiagnostics.onDidChangeDiagnostics;
			},
246 247 248
			getDiagnostics: (resource?) => {
				return <any>extHostDiagnostics.getDiagnostics(resource);
			},
249 250 251 252
			getLanguages(): TPromise<string[]> {
				return extHostLanguages.getLanguages();
			},
			match(selector: vscode.DocumentSelector, document: vscode.TextDocument): number {
253
				return score(toLanguageSelector(selector), document.uri, document.languageId, true);
254
			},
255 256
			registerCodeActionsProvider(selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable {
				return extHostLanguageFeatures.registerCodeActionProvider(checkSelector(selector), provider, metadata);
257 258
			},
			registerCodeLensProvider(selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable {
259
				return extHostLanguageFeatures.registerCodeLensProvider(checkSelector(selector), provider);
260 261
			},
			registerDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable {
262
				return extHostLanguageFeatures.registerDefinitionProvider(checkSelector(selector), provider);
263
			},
M
Matt Bierner 已提交
264
			registerImplementationProvider(selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable {
265
				return extHostLanguageFeatures.registerImplementationProvider(checkSelector(selector), provider);
266
			},
267
			registerTypeDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable {
268
				return extHostLanguageFeatures.registerTypeDefinitionProvider(checkSelector(selector), provider);
269
			},
270
			registerHoverProvider(selector: vscode.DocumentSelector, provider: vscode.HoverProvider): vscode.Disposable {
271
				return extHostLanguageFeatures.registerHoverProvider(checkSelector(selector), provider, extension.id);
272 273
			},
			registerDocumentHighlightProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable {
274
				return extHostLanguageFeatures.registerDocumentHighlightProvider(checkSelector(selector), provider);
275 276
			},
			registerReferenceProvider(selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable {
277
				return extHostLanguageFeatures.registerReferenceProvider(checkSelector(selector), provider);
278 279
			},
			registerRenameProvider(selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable {
280
				return extHostLanguageFeatures.registerRenameProvider(checkSelector(selector), provider, extension.enableProposedApi);
281 282
			},
			registerDocumentSymbolProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider): vscode.Disposable {
283
				return extHostLanguageFeatures.registerDocumentSymbolProvider(checkSelector(selector), provider);
284 285
			},
			registerWorkspaceSymbolProvider(provider: vscode.WorkspaceSymbolProvider): vscode.Disposable {
286
				return extHostLanguageFeatures.registerWorkspaceSymbolProvider(provider);
287 288
			},
			registerDocumentFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable {
289
				return extHostLanguageFeatures.registerDocumentFormattingEditProvider(checkSelector(selector), provider);
290 291
			},
			registerDocumentRangeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable {
292
				return extHostLanguageFeatures.registerDocumentRangeFormattingEditProvider(checkSelector(selector), provider);
293 294
			},
			registerOnTypeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, firstTriggerCharacter: string, ...moreTriggerCharacters: string[]): vscode.Disposable {
295
				return extHostLanguageFeatures.registerOnTypeFormattingEditProvider(checkSelector(selector), provider, [firstTriggerCharacter].concat(moreTriggerCharacters));
296 297
			},
			registerSignatureHelpProvider(selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, ...triggerCharacters: string[]): vscode.Disposable {
298
				return extHostLanguageFeatures.registerSignatureHelpProvider(checkSelector(selector), provider, triggerCharacters);
299 300
			},
			registerCompletionItemProvider(selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, ...triggerCharacters: string[]): vscode.Disposable {
301
				return extHostLanguageFeatures.registerCompletionItemProvider(checkSelector(selector), provider, triggerCharacters);
302 303
			},
			registerDocumentLinkProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable {
304
				return extHostLanguageFeatures.registerDocumentLinkProvider(checkSelector(selector), provider);
305
			},
306
			registerColorProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable {
307
				return extHostLanguageFeatures.registerColorProvider(checkSelector(selector), provider);
308
			},
309
			registerFoldingRangeProvider(selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable {
310
				return extHostLanguageFeatures.registerFoldingRangeProvider(checkSelector(selector), provider);
311
			},
312
			setLanguageConfiguration: (language: string, configuration: vscode.LanguageConfiguration): vscode.Disposable => {
313
				return extHostLanguageFeatures.setLanguageConfiguration(language, configuration);
314
			}
315
		};
E
Erich Gamma 已提交
316

317 318 319 320 321 322 323 324
		// namespace: window
		const window: typeof vscode.window = {
			get activeTextEditor() {
				return extHostEditors.getActiveTextEditor();
			},
			get visibleTextEditors() {
				return extHostEditors.getVisibleTextEditors();
			},
D
Daniel Imms 已提交
325
			get terminals() {
326
				return proposedApiFunction(extension, extHostTerminalService.terminals);
D
Daniel Imms 已提交
327
			},
J
Johannes Rieken 已提交
328
			showTextDocument(documentOrUri: vscode.TextDocument | vscode.Uri, columnOrOptions?: vscode.ViewColumn | vscode.TextDocumentShowOptions, preserveFocus?: boolean): TPromise<vscode.TextEditor> {
B
Benjamin Pasero 已提交
329
				let documentPromise: TPromise<vscode.TextDocument>;
J
Johannes Rieken 已提交
330 331
				if (URI.isUri(documentOrUri)) {
					documentPromise = TPromise.wrap(workspace.openTextDocument(documentOrUri));
B
Benjamin Pasero 已提交
332
				} else {
J
Johannes Rieken 已提交
333
					documentPromise = TPromise.wrap(<vscode.TextDocument>documentOrUri);
B
Benjamin Pasero 已提交
334 335 336 337
				}
				return documentPromise.then(document => {
					return extHostEditors.showTextDocument(document, columnOrOptions, preserveFocus);
				});
338 339 340 341
			},
			createTextEditorDecorationType(options: vscode.DecorationRenderOptions): vscode.TextEditorDecorationType {
				return extHostEditors.createTextEditorDecorationType(options);
			},
342 343 344
			onDidChangeActiveTextEditor(listener, thisArg?, disposables?) {
				return extHostEditors.onDidChangeActiveTextEditor(listener, thisArg, disposables);
			},
345 346 347
			onDidChangeVisibleTextEditors(listener, thisArg, disposables) {
				return extHostEditors.onDidChangeVisibleTextEditors(listener, thisArg, disposables);
			},
348
			onDidChangeTextEditorSelection(listener: (e: vscode.TextEditorSelectionChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
349 350
				return extHostEditors.onDidChangeTextEditorSelection(listener, thisArgs, disposables);
			},
351
			onDidChangeTextEditorOptions(listener: (e: vscode.TextEditorOptionsChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
352 353
				return extHostEditors.onDidChangeTextEditorOptions(listener, thisArgs, disposables);
			},
354
			onDidChangeTextEditorVisibleRanges(listener: (e: vscode.TextEditorVisibleRangesChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
355
				return extHostEditors.onDidChangeTextEditorVisibleRanges(listener, thisArgs, disposables);
356
			},
357 358 359
			onDidChangeTextEditorViewColumn(listener, thisArg?, disposables?) {
				return extHostEditors.onDidChangeTextEditorViewColumn(listener, thisArg, disposables);
			},
360 361 362
			onDidCloseTerminal(listener, thisArg?, disposables?) {
				return extHostTerminalService.onDidCloseTerminal(listener, thisArg, disposables);
			},
363
			onDidOpenTerminal: proposedApiFunction(extension, (listener, thisArg?, disposables?) => {
364
				return extHostTerminalService.onDidOpenTerminal(listener, thisArg, disposables);
365
			}),
J
Joao Moreno 已提交
366 367
			get state() {
				return extHostWindow.state;
368
			},
J
Joao Moreno 已提交
369
			onDidChangeWindowState(listener, thisArg?, disposables?) {
J
Joao Moreno 已提交
370
				return extHostWindow.onDidChangeWindowState(listener, thisArg, disposables);
J
Joao Moreno 已提交
371
			},
J
Joao Moreno 已提交
372
			showInformationMessage(message, first, ...rest) {
373
				return extHostMessageService.showMessage(extension, Severity.Info, message, first, rest);
374
			},
J
Joao Moreno 已提交
375
			showWarningMessage(message, first, ...rest) {
376
				return extHostMessageService.showMessage(extension, Severity.Warning, message, first, rest);
377
			},
J
Joao Moreno 已提交
378
			showErrorMessage(message, first, ...rest) {
379
				return extHostMessageService.showMessage(extension, Severity.Error, message, first, rest);
380
			},
C
Christof Marti 已提交
381
			showQuickPick(items: any, options: vscode.QuickPickOptions, token?: vscode.CancellationToken): any {
382 383
				return extHostQuickOpen.showQuickPick(items, options, token);
			},
384
			showWorkspaceFolderPick(options: vscode.WorkspaceFolderPickOptions) {
385
				return extHostQuickOpen.showWorkspaceFolderPick(options);
386
			},
387 388 389
			showInputBox(options?: vscode.InputBoxOptions, token?: vscode.CancellationToken) {
				return extHostQuickOpen.showInput(options, token);
			},
390 391 392 393 394 395
			showOpenDialog(options) {
				return extHostDialogs.showOpenDialog(options);
			},
			showSaveDialog(options) {
				return extHostDialogs.showSaveDialog(options);
			},
396
			createStatusBarItem(position?: vscode.StatusBarAlignment, priority?: number): vscode.StatusBarItem {
397
				return extHostStatusBar.createStatusBarEntry(extension.id, <number>position, priority);
398 399 400 401
			},
			setStatusBarMessage(text: string, timeoutOrThenable?: number | Thenable<any>): vscode.Disposable {
				return extHostStatusBar.setStatusBarMessage(text, timeoutOrThenable);
			},
402
			withScmProgress<R>(task: (progress: vscode.Progress<number>) => Thenable<R>) {
403
				console.warn(`[Deprecation Warning] function 'withScmProgress' is deprecated and should no longer be used. Use 'withProgress' instead.`);
404
				return extHostProgress.withProgress(extension, { location: extHostTypes.ProgressLocation.SourceControl }, (progress, token) => task({ report(n: number) { /*noop*/ } }));
J
Johannes Rieken 已提交
405
			},
406
			withProgress<R>(options: vscode.ProgressOptions, task: (progress: vscode.Progress<{ message?: string; worked?: number }>, token: vscode.CancellationToken) => Thenable<R>) {
J
Johannes Rieken 已提交
407
				return extHostProgress.withProgress(extension, options, task);
408
			},
409 410 411
			createOutputChannel(name: string): vscode.OutputChannel {
				return extHostOutputService.createOutputChannel(name);
			},
412 413 414
			createWebviewPanel(viewType: string, title: string, column: vscode.ViewColumn, options: vscode.WebviewPanelOptions & vscode.WebviewOptions): vscode.WebviewPanel {
				return extHostWebviews.createWebview(viewType, title, column, options, extension.extensionFolderPath);
			},
415 416 417 418
			createTerminal(nameOrOptions: vscode.TerminalOptions | string, shellPath?: string, shellArgs?: string[]): vscode.Terminal {
				if (typeof nameOrOptions === 'object') {
					return extHostTerminalService.createTerminalFromOptions(<vscode.TerminalOptions>nameOrOptions);
				}
D
Daniel Imms 已提交
419
				return extHostTerminalService.createTerminal(<string>nameOrOptions, shellPath, shellArgs);
420
			},
421 422 423 424 425
			registerTreeDataProvider(viewId: string, treeDataProvider: vscode.TreeDataProvider<any>): vscode.Disposable {
				return extHostTreeViews.registerTreeDataProvider(viewId, treeDataProvider);
			},
			createTreeView(viewId: string, options: { treeDataProvider: vscode.TreeDataProvider<any> }): vscode.TreeView<any> {
				return extHostTreeViews.createTreeView(viewId, options);
S
Sandeep Somavarapu 已提交
426
			},
427 428
			// proposed API
			sampleFunction: proposedApiFunction(extension, () => {
429
				return extHostMessageService.showMessage(extension, Severity.Info, 'Hello Proposed Api!', {}, []);
430
			}),
431 432
			registerDecorationProvider: proposedApiFunction(extension, (provider: vscode.DecorationProvider) => {
				return extHostDecorations.registerDecorationProvider(provider, extension.id);
M
Matt Bierner 已提交
433
			}),
434 435
			registerWebviewPanelSerializer: proposedApiFunction(extension, (viewType: string, serializer: vscode.WebviewPanelSerializer) => {
				return extHostWebviews.registerWebviewPanelSerializer(viewType, serializer);
J
Joao Moreno 已提交
436
			}),
J
Joao Moreno 已提交
437 438
			registerProtocolHandler: proposedApiFunction(extension, (handler: vscode.ProtocolHandler) => {
				return extHostUrls.registerProtocolHandler(extension.id, handler);
439
			})
440
		};
E
Erich Gamma 已提交
441

442 443 444 445 446 447 448 449
		// namespace: workspace
		const workspace: typeof vscode.workspace = {
			get rootPath() {
				return extHostWorkspace.getPath();
			},
			set rootPath(value) {
				throw errors.readonly();
			},
450 451
			getWorkspaceFolder(resource) {
				return extHostWorkspace.getWorkspaceFolder(resource);
452
			},
453
			get workspaceFolders() {
454
				return extHostWorkspace.getWorkspaceFolders();
455
			},
456 457 458 459 460 461
			get name() {
				return extHostWorkspace.workspace ? extHostWorkspace.workspace.name : undefined;
			},
			set name(value) {
				throw errors.readonly();
			},
462 463 464
			updateWorkspaceFolders: (index, deleteCount, ...workspaceFoldersToAdd) => {
				return extHostWorkspace.updateWorkspaceFolders(extension, index, deleteCount || 0, ...workspaceFoldersToAdd);
			},
465
			onDidChangeWorkspaceFolders: function (listener, thisArgs?, disposables?) {
466
				return extHostWorkspace.onDidChangeWorkspace(listener, thisArgs, disposables);
467
			},
J
Johannes Rieken 已提交
468 469
			asRelativePath: (pathOrUri, includeWorkspace) => {
				return extHostWorkspace.getRelativePath(pathOrUri, includeWorkspace);
470 471
			},
			findFiles: (include, exclude, maxResults?, token?) => {
472
				return extHostWorkspace.findFiles(toGlobPattern(include), toGlobPattern(exclude), maxResults, extension.id, token);
473 474 475 476 477
			},
			saveAll: (includeUntitled?) => {
				return extHostWorkspace.saveAll(includeUntitled);
			},
			applyEdit(edit: vscode.WorkspaceEdit): TPromise<boolean> {
478
				return extHostEditors.applyWorkspaceEdit(edit);
479 480
			},
			createFileSystemWatcher: (pattern, ignoreCreate, ignoreChange, ignoreDelete): vscode.FileSystemWatcher => {
481
				return extHostFileSystemEvent.createFileSystemWatcher(toGlobPattern(pattern), ignoreCreate, ignoreChange, ignoreDelete);
482 483 484 485 486 487 488
			},
			get textDocuments() {
				return extHostDocuments.getAllDocumentData().map(data => data.document);
			},
			set textDocuments(value) {
				throw errors.readonly();
			},
489
			openTextDocument(uriOrFileNameOrOptions?: vscode.Uri | string | { language?: string; content?: string; }) {
B
Benjamin Pasero 已提交
490 491
				let uriPromise: TPromise<URI>;

492
				let options = uriOrFileNameOrOptions as { language?: string; content?: string; };
B
Benjamin Pasero 已提交
493
				if (typeof uriOrFileNameOrOptions === 'string') {
B
Benjamin Pasero 已提交
494 495
					uriPromise = TPromise.as(URI.file(uriOrFileNameOrOptions));
				} else if (uriOrFileNameOrOptions instanceof URI) {
J
Johannes Rieken 已提交
496
					uriPromise = TPromise.as(uriOrFileNameOrOptions);
B
Benjamin Pasero 已提交
497 498
				} else if (!options || typeof options === 'object') {
					uriPromise = extHostDocuments.createDocumentData(options);
499
				} else {
B
Benjamin Pasero 已提交
500
					throw new Error('illegal argument - uriOrFileNameOrOptions');
501
				}
B
Benjamin Pasero 已提交
502 503 504 505 506 507

				return uriPromise.then(uri => {
					return extHostDocuments.ensureDocumentData(uri).then(() => {
						const data = extHostDocuments.getDocumentData(uri);
						return data && data.document;
					});
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
				});
			},
			onDidOpenTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidAddDocument(listener, thisArgs, disposables);
			},
			onDidCloseTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidRemoveDocument(listener, thisArgs, disposables);
			},
			onDidChangeTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidChangeDocument(listener, thisArgs, disposables);
			},
			onDidSaveTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidSaveDocument(listener, thisArgs, disposables);
			},
			onWillSaveTextDocument: (listener, thisArgs?, disposables?) => {
523
				return extHostDocumentSaveParticipant.getOnWillSaveTextDocumentEvent(extension)(listener, thisArgs, disposables);
524
			},
525
			onDidChangeConfiguration: (listener: (_: any) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) => {
526 527
				return extHostConfiguration.onDidChangeConfiguration(listener, thisArgs, disposables);
			},
528 529
			getConfiguration(section?: string, resource?: vscode.Uri): vscode.WorkspaceConfiguration {
				resource = arguments.length === 1 ? void 0 : resource;
S
Sandeep Somavarapu 已提交
530
				return extHostConfiguration.getConfiguration(section, resource, extension.id);
531
			},
532 533
			registerTextDocumentContentProvider(scheme: string, provider: vscode.TextDocumentContentProvider) {
				return extHostDocumentContentProviders.registerTextDocumentContentProvider(scheme, provider);
534
			},
535
			registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
536
				return extHostTask.registerTaskProvider(extension, provider);
J
Johannes Rieken 已提交
537
			},
538 539
			fetchTasks: proposedApiFunction(extension, (filter?: vscode.TaskFilter): Thenable<vscode.Task[]> => {
				return extHostTask.fetchTasks(filter);
540 541
			}),
			executeTask: proposedApiFunction(extension, (task: vscode.Task): Thenable<vscode.TaskExecution> => {
542
				return extHostTask.executeTask(extension, task);
543
			}),
544 545 546
			get taskExecutions(): vscode.TaskExecution[] {
				return extHostTask.taskExecutions;
			},
547 548 549 550 551 552
			onDidStartTask: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidStartTask(listeners, thisArgs, disposables);
			},
			onDidEndTask: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidEndTask(listeners, thisArgs, disposables);
			},
553 554
			registerFileSystemProvider: proposedApiFunction(extension, (scheme, provider, options) => {
				return extHostFileSystem.registerFileSystemProvider(scheme, provider, options);
555
			}),
556 557 558
			registerDeprecatedFileSystemProvider: proposedApiFunction(extension, (scheme, provider) => {
				return extHostFileSystem.registerDeprecatedFileSystemProvider(scheme, provider);
			}),
559
			registerSearchProvider: proposedApiFunction(extension, (scheme, provider) => {
560
				return extHostSearch.registerSearchProvider(scheme, provider);
J
Johannes Rieken 已提交
561
			})
562
		};
563

564 565
		// namespace: scm
		const scm: typeof vscode.scm = {
566
			get inputBox() {
J
Joao Moreno 已提交
567
				return extHostSCM.getLastInputBox(extension);
568
			},
J
Joao Moreno 已提交
569 570
			createSourceControl(id: string, label: string, rootUri?: vscode.Uri) {
				return extHostSCM.createSourceControl(extension, id, label, rootUri);
J
Joao Moreno 已提交
571
			}
572
		};
J
Joao Moreno 已提交
573

574 575
		// namespace: debug
		const debug: typeof vscode.debug = {
576 577 578
			get activeDebugSession() {
				return extHostDebugService.activeDebugSession;
			},
579 580
			get activeDebugConsole() {
				return extHostDebugService.activeDebugConsole;
581
			},
582 583
			get breakpoints() {
				return extHostDebugService.breakpoints;
584
			},
585 586 587
			onDidStartDebugSession(listener, thisArg?, disposables?) {
				return extHostDebugService.onDidStartDebugSession(listener, thisArg, disposables);
			},
588
			onDidTerminateDebugSession(listener, thisArg?, disposables?) {
589
				return extHostDebugService.onDidTerminateDebugSession(listener, thisArg, disposables);
590
			},
A
Andre Weinand 已提交
591
			onDidChangeActiveDebugSession(listener, thisArg?, disposables?) {
592
				return extHostDebugService.onDidChangeActiveDebugSession(listener, thisArg, disposables);
A
Andre Weinand 已提交
593 594
			},
			onDidReceiveDebugSessionCustomEvent(listener, thisArg?, disposables?) {
A
Andre Weinand 已提交
595
				return extHostDebugService.onDidReceiveDebugSessionCustomEvent(listener, thisArg, disposables);
596
			},
597
			onDidChangeBreakpoints(listener, thisArgs?, disposables?) {
598 599
				return extHostDebugService.onDidChangeBreakpoints(listener, thisArgs, disposables);
			},
A
Andre Weinand 已提交
600
			registerDebugConfigurationProvider(debugType: string, provider: vscode.DebugConfigurationProvider) {
601
				return extHostDebugService.registerDebugConfigurationProvider(debugType, provider);
602
			},
603 604 605 606
			startDebugging(folder: vscode.WorkspaceFolder | undefined, nameOrConfig: string | vscode.DebugConfiguration) {
				return extHostDebugService.startDebugging(folder, nameOrConfig);
			},
			addBreakpoints(breakpoints: vscode.Breakpoint[]) {
607
				return extHostDebugService.addBreakpoints(breakpoints);
608 609
			},
			removeBreakpoints(breakpoints: vscode.Breakpoint[]) {
610
				return extHostDebugService.removeBreakpoints(breakpoints);
611
			}
612 613 614
		};


615
		return <typeof vscode>{
616 617 618 619 620 621 622 623
			version: pkg.version,
			// namespaces
			commands,
			env,
			extensions,
			languages,
			window,
			workspace,
J
Joao Moreno 已提交
624
			scm,
625
			debug,
626
			// types
627
			Breakpoint: extHostTypes.Breakpoint,
628
			CancellationTokenSource: CancellationTokenSource,
629
			CodeAction: extHostTypes.CodeAction,
M
Matt Bierner 已提交
630
			CodeActionKind: extHostTypes.CodeActionKind,
631
			CodeLens: extHostTypes.CodeLens,
632
			Color: extHostTypes.Color,
633 634
			ColorPresentation: extHostTypes.ColorPresentation,
			ColorInformation: extHostTypes.ColorInformation,
635
			EndOfLine: extHostTypes.EndOfLine,
636 637 638
			CompletionItem: extHostTypes.CompletionItem,
			CompletionItemKind: extHostTypes.CompletionItemKind,
			CompletionList: extHostTypes.CompletionList,
M
Matt Bierner 已提交
639
			CompletionTriggerKind: extHostTypes.CompletionTriggerKind,
640
			DebugAdapterExecutable: extHostTypes.DebugAdapterExecutable,
641
			Diagnostic: extHostTypes.Diagnostic,
642
			DiagnosticRelatedInformation: extHostTypes.DiagnosticRelatedInformation,
643 644 645 646
			DiagnosticSeverity: extHostTypes.DiagnosticSeverity,
			Disposable: extHostTypes.Disposable,
			DocumentHighlight: extHostTypes.DocumentHighlight,
			DocumentHighlightKind: extHostTypes.DocumentHighlightKind,
647
			DocumentLink: extHostTypes.DocumentLink,
648
			EventEmitter: Emitter,
649
			FunctionBreakpoint: extHostTypes.FunctionBreakpoint,
650
			Hover: extHostTypes.Hover,
651
			IndentAction: languageConfiguration.IndentAction,
652
			Location: extHostTypes.Location,
653
			LogLevel: extHostTypes.LogLevel,
654
			MarkdownString: extHostTypes.MarkdownString,
655
			OverviewRulerLane: OverviewRulerLane,
656 657 658 659 660 661 662
			ParameterInformation: extHostTypes.ParameterInformation,
			Position: extHostTypes.Position,
			Range: extHostTypes.Range,
			Selection: extHostTypes.Selection,
			SignatureHelp: extHostTypes.SignatureHelp,
			SignatureInformation: extHostTypes.SignatureInformation,
			SnippetString: extHostTypes.SnippetString,
663
			SourceBreakpoint: extHostTypes.SourceBreakpoint,
664 665
			StatusBarAlignment: extHostTypes.StatusBarAlignment,
			SymbolInformation: extHostTypes.SymbolInformation,
666 667 668 669 670 671
			HierarchicalSymbolInformation: class extends extHostTypes.HierarchicalSymbolInformation {
				constructor(name, kind, keyof, range) {
					checkProposedApiEnabled(extension);
					super(name, kind, keyof, range);
				}
			},
672
			SymbolKind: extHostTypes.SymbolKind,
673
			SourceControlInputBoxValidationType: extHostTypes.SourceControlInputBoxValidationType,
674 675
			TextDocumentSaveReason: extHostTypes.TextDocumentSaveReason,
			TextEdit: extHostTypes.TextEdit,
676
			TextEditorCursorStyle: TextEditorCursorStyle,
677
			TextEditorLineNumbersStyle: extHostTypes.TextEditorLineNumbersStyle,
678
			TextEditorRevealType: extHostTypes.TextEditorRevealType,
679
			TextEditorSelectionChangeKind: extHostTypes.TextEditorSelectionChangeKind,
680
			DecorationRangeBehavior: extHostTypes.DecorationRangeBehavior,
681
			Uri: URI,
682 683
			ViewColumn: extHostTypes.ViewColumn,
			WorkspaceEdit: extHostTypes.WorkspaceEdit,
J
Johannes Rieken 已提交
684
			ProgressLocation: extHostTypes.ProgressLocation,
S
Sandeep Somavarapu 已提交
685
			TreeItemCollapsibleState: extHostTypes.TreeItemCollapsibleState,
686
			ThemeIcon: extHostTypes.ThemeIcon,
S
Sandeep Somavarapu 已提交
687
			TreeItem: extHostTypes.TreeItem,
688
			ThemeColor: extHostTypes.ThemeColor,
J
Joao Moreno 已提交
689
			// functions
690
			TaskRevealKind: extHostTypes.TaskRevealKind,
691
			TaskPanelKind: extHostTypes.TaskPanelKind,
692
			TaskGroup: extHostTypes.TaskGroup,
D
Dirk Baeumer 已提交
693 694
			ProcessExecution: extHostTypes.ProcessExecution,
			ShellExecution: extHostTypes.ShellExecution,
695
			ShellQuoting: extHostTypes.ShellQuoting,
D
Dirk Baeumer 已提交
696
			TaskScope: extHostTypes.TaskScope,
S
Sandeep Somavarapu 已提交
697
			Task: extHostTypes.Task,
698
			ConfigurationTarget: extHostTypes.ConfigurationTarget,
699
			RelativePattern: extHostTypes.RelativePattern,
700

701 702
			DeprecatedFileChangeType: extHostTypes.DeprecatedFileChangeType,
			DeprecatedFileType: extHostTypes.DeprecatedFileType,
J
Johannes Rieken 已提交
703
			FileChangeType: extHostTypes.FileChangeType,
704
			FileSystemError: extHostTypes.FileSystemError,
705
			FoldingRange: extHostTypes.FoldingRange,
706
			FoldingRangeKind: extHostTypes.FoldingRangeKind
707
		};
708
	};
E
Erich Gamma 已提交
709 710 711 712
}

class Extension<T> implements vscode.Extension<T> {

A
Alex Dima 已提交
713
	private _extensionService: ExtHostExtensionService;
E
Erich Gamma 已提交
714 715 716 717 718

	public id: string;
	public extensionPath: string;
	public packageJSON: any;

J
Johannes Rieken 已提交
719
	constructor(extensionService: ExtHostExtensionService, description: IExtensionDescription) {
A
Alex Dima 已提交
720
		this._extensionService = extensionService;
E
Erich Gamma 已提交
721 722 723 724 725 726
		this.id = description.id;
		this.extensionPath = paths.normalize(description.extensionFolderPath, true);
		this.packageJSON = description;
	}

	get isActive(): boolean {
A
Alex Dima 已提交
727
		return this._extensionService.isActivated(this.id);
E
Erich Gamma 已提交
728 729 730
	}

	get exports(): T {
A
Alex Dima 已提交
731
		return <T>this._extensionService.getExtensionExports(this.id);
E
Erich Gamma 已提交
732 733 734
	}

	activate(): Thenable<T> {
735
		return this._extensionService.activateByIdWithErrors(this.id, new ExtensionActivatedByAPI(false)).then(() => this.exports);
E
Erich Gamma 已提交
736 737 738
	}
}

J
Johannes Rieken 已提交
739
export function initializeExtensionApi(extensionService: ExtHostExtensionService, apiFactory: IExtensionApiFactory): TPromise<void> {
740
	return extensionService.getExtensionPathIndex().then(trie => defineAPI(apiFactory, trie));
J
Johannes Rieken 已提交
741 742
}

743
function defineAPI(factory: IExtensionApiFactory, extensionPaths: TernarySearchTree<IExtensionDescription>): void {
J
Johannes Rieken 已提交
744 745

	// each extension is meant to get its own api implementation
J
Johannes Rieken 已提交
746
	const extApiImpl = new Map<string, typeof vscode>();
J
Johannes Rieken 已提交
747
	let defaultApiImpl: typeof vscode;
748 749 750

	const node_module = <any>require.__$__nodeRequire('module');
	const original = node_module._load;
E
Erich Gamma 已提交
751
	node_module._load = function load(request, parent, isMain) {
752 753 754 755 756
		if (request !== 'vscode') {
			return original.apply(this, arguments);
		}

		// get extension id from filename and api for extension
J
Johannes Rieken 已提交
757
		const ext = extensionPaths.findSubstr(parent.filename);
758
		if (ext) {
J
Johannes Rieken 已提交
759
			let apiImpl = extApiImpl.get(ext.id);
760
			if (!apiImpl) {
J
Johannes Rieken 已提交
761 762
				apiImpl = factory(ext);
				extApiImpl.set(ext.id, apiImpl);
763 764 765 766 767 768
			}
			return apiImpl;
		}

		// fall back to a default implementation
		if (!defaultApiImpl) {
769
			defaultApiImpl = factory(nullExtensionDescription);
E
Erich Gamma 已提交
770
		}
771
		return defaultApiImpl;
E
Erich Gamma 已提交
772 773
	};
}
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788

const nullExtensionDescription: IExtensionDescription = {
	id: 'nullExtensionDescription',
	name: 'Null Extension Description',
	publisher: 'vscode',
	activationEvents: undefined,
	contributes: undefined,
	enableProposedApi: false,
	engines: undefined,
	extensionDependencies: undefined,
	extensionFolderPath: undefined,
	isBuiltin: false,
	main: undefined,
	version: undefined
};