initial commit

This commit is contained in:
Zoe
2023-01-03 09:29:04 -06:00
commit 7851137d88
12889 changed files with 2557443 additions and 0 deletions

11
node_modules/vscode-languageclient/License.txt generated vendored Normal file
View File

@@ -0,0 +1,11 @@
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

17
node_modules/vscode-languageclient/README.md generated vendored Normal file
View File

@@ -0,0 +1,17 @@
# VSCode Language Server - Client Module
[![NPM Version](https://img.shields.io/npm/v/vscode-languageclient.svg)](https://npmjs.org/package/vscode-languageclient)
[![NPM Downloads](https://img.shields.io/npm/dm/vscode-languageclient.svg)](https://npmjs.org/package/vscode-languageclient)
[![Build Status](https://travis-ci.org/Microsoft/vscode-languageserver-node.svg?branch=master)](https://travis-ci.org/Microsoft/vscode-languageserver-node)
This npm module allows VSCode extensions to easily integrate language servers adhering to the [language server protocol](https://github.com/Microsoft/vscode-languageserver-protocol)
See [here](https://code.visualstudio.com/docs/extensions/example-language-server) for a detailed documentation on how to
implement language servers for [VSCode](https://code.visualstudio.com/).
## History
For the history please see the [main repository](https://github.com/Microsoft/vscode-languageserver-node/blob/master/README.md)
## License
[MIT](https://github.com/Microsoft/vscode-languageserver-node/blob/master/License.txt)

6
node_modules/vscode-languageclient/browser.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ----------------------------------------------------------------------------------------- */
export * from './lib/browser/main';

7
node_modules/vscode-languageclient/browser.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ----------------------------------------------------------------------------------------- */
'use strict';
module.exports = require('./lib/browser/main');

View File

@@ -0,0 +1,9 @@
import { CommonLanguageClient, LanguageClientOptions, MessageTransports } from '../common/api';
export * from 'vscode-languageserver-protocol/browser';
export * from '../common/api';
export declare class LanguageClient extends CommonLanguageClient {
private worker;
constructor(id: string, name: string, clientOptions: LanguageClientOptions, worker: Worker);
protected createMessageTransports(_encoding: string): Promise<MessageTransports>;
protected getLocale(): string;
}

39
node_modules/vscode-languageclient/lib/browser/main.js generated vendored Normal file
View File

@@ -0,0 +1,39 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LanguageClient = void 0;
const api_1 = require("../common/api");
const browser_1 = require("vscode-languageserver-protocol/browser");
__exportStar(require("vscode-languageserver-protocol/browser"), exports);
__exportStar(require("../common/api"), exports);
class LanguageClient extends api_1.CommonLanguageClient {
constructor(id, name, clientOptions, worker) {
super(id, name, clientOptions);
this.worker = worker;
}
createMessageTransports(_encoding) {
const reader = new browser_1.BrowserMessageReader(this.worker);
const writer = new browser_1.BrowserMessageWriter(this.worker);
return Promise.resolve({ reader, writer });
}
getLocale() {
// ToDo: need to find a way to let the locale
// travel to the worker extension host.
return 'en';
}
}
exports.LanguageClient = LanguageClient;
//# sourceMappingURL=main.js.map

View File

@@ -0,0 +1,5 @@
export * from 'vscode-languageserver-protocol';
export { Converter as Code2ProtocolConverter } from './codeConverter';
export { Converter as Protocol2CodeConverter } from './protocolConverter';
export * from './client';
export * from './commonClient';

20
node_modules/vscode-languageclient/lib/common/api.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("vscode-languageserver-protocol"), exports);
__exportStar(require("./client"), exports);
__exportStar(require("./commonClient"), exports);
//# sourceMappingURL=api.js.map

View File

@@ -0,0 +1,37 @@
import { Disposable, TextDocument, ProviderResult, Position as VPosition, CallHierarchyItem as VCallHierarchyItem, CallHierarchyIncomingCall as VCallHierarchyIncomingCall, CallHierarchyOutgoingCall as VCallHierarchyOutgoingCall, CancellationToken, CallHierarchyProvider as VCallHierarchyProvider } from 'vscode';
import { ClientCapabilities, ServerCapabilities, DocumentSelector, CallHierarchyOptions, CallHierarchyRegistrationOptions } from 'vscode-languageserver-protocol';
import { TextDocumentFeature, BaseLanguageClient } from './client';
export interface PrepareCallHierarchySignature {
(this: void, document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VCallHierarchyItem | VCallHierarchyItem[]>;
}
export interface CallHierarchyIncomingCallsSignature {
(this: void, item: VCallHierarchyItem, token: CancellationToken): ProviderResult<VCallHierarchyIncomingCall[]>;
}
export interface CallHierarchyOutgoingCallsSignature {
(this: void, item: VCallHierarchyItem, token: CancellationToken): ProviderResult<VCallHierarchyOutgoingCall[]>;
}
/**
* Call hierarchy middleware
*
* @since 3.16.0
*/
export interface CallHierarchyMiddleware {
prepareCallHierarchy?: (this: void, document: TextDocument, positions: VPosition, token: CancellationToken, next: PrepareCallHierarchySignature) => ProviderResult<VCallHierarchyItem | VCallHierarchyItem[]>;
provideCallHierarchyIncomingCalls?: (this: void, item: VCallHierarchyItem, token: CancellationToken, next: CallHierarchyIncomingCallsSignature) => ProviderResult<VCallHierarchyIncomingCall[]>;
provideCallHierarchyOutgoingCalls?: (this: void, item: VCallHierarchyItem, token: CancellationToken, next: CallHierarchyOutgoingCallsSignature) => ProviderResult<VCallHierarchyOutgoingCall[]>;
}
declare class CallHierarchyProvider implements VCallHierarchyProvider {
private client;
private middleware;
constructor(client: BaseLanguageClient);
prepareCallHierarchy(document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VCallHierarchyItem | VCallHierarchyItem[]>;
provideCallHierarchyIncomingCalls(item: VCallHierarchyItem, token: CancellationToken): ProviderResult<VCallHierarchyIncomingCall[]>;
provideCallHierarchyOutgoingCalls(item: VCallHierarchyItem, token: CancellationToken): ProviderResult<VCallHierarchyOutgoingCall[]>;
}
export declare class CallHierarchyFeature extends TextDocumentFeature<boolean | CallHierarchyOptions, CallHierarchyRegistrationOptions, CallHierarchyProvider> {
constructor(client: BaseLanguageClient);
fillClientCapabilities(cap: ClientCapabilities): void;
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void;
protected registerLanguageProvider(options: CallHierarchyRegistrationOptions): [Disposable, CallHierarchyProvider];
}
export {};

View File

@@ -0,0 +1,95 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.CallHierarchyFeature = void 0;
const vscode_1 = require("vscode");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const client_1 = require("./client");
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = {};
}
return target[key];
}
class CallHierarchyProvider {
constructor(client) {
this.client = client;
this.middleware = client.clientOptions.middleware;
}
prepareCallHierarchy(document, position, token) {
const client = this.client;
const middleware = this.middleware;
const prepareCallHierarchy = (document, position, token) => {
const params = client.code2ProtocolConverter.asTextDocumentPositionParams(document, position);
return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, params, token).then((result) => {
return client.protocol2CodeConverter.asCallHierarchyItems(result);
}, (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, error, null);
});
};
return middleware.prepareCallHierarchy
? middleware.prepareCallHierarchy(document, position, token, prepareCallHierarchy)
: prepareCallHierarchy(document, position, token);
}
provideCallHierarchyIncomingCalls(item, token) {
const client = this.client;
const middleware = this.middleware;
const provideCallHierarchyIncomingCalls = (item, token) => {
const params = {
item: client.code2ProtocolConverter.asCallHierarchyItem(item)
};
return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type, params, token).then((result) => {
return client.protocol2CodeConverter.asCallHierarchyIncomingCalls(result);
}, (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type, error, null);
});
};
return middleware.provideCallHierarchyIncomingCalls
? middleware.provideCallHierarchyIncomingCalls(item, token, provideCallHierarchyIncomingCalls)
: provideCallHierarchyIncomingCalls(item, token);
}
provideCallHierarchyOutgoingCalls(item, token) {
const client = this.client;
const middleware = this.middleware;
const provideCallHierarchyOutgoingCalls = (item, token) => {
const params = {
item: client.code2ProtocolConverter.asCallHierarchyItem(item)
};
return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type, params, token).then((result) => {
return client.protocol2CodeConverter.asCallHierarchyOutgoingCalls(result);
}, (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type, error, null);
});
};
return middleware.provideCallHierarchyOutgoingCalls
? middleware.provideCallHierarchyOutgoingCalls(item, token, provideCallHierarchyOutgoingCalls)
: provideCallHierarchyOutgoingCalls(item, token);
}
}
class CallHierarchyFeature extends client_1.TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type);
}
fillClientCapabilities(cap) {
const capabilities = cap;
const capability = ensure(ensure(capabilities, 'textDocument'), 'callHierarchy');
capability.dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
const [id, options] = this.getRegistration(documentSelector, capabilities.callHierarchyProvider);
if (!id || !options) {
return;
}
this.register({ id: id, registerOptions: options });
}
registerLanguageProvider(options) {
const client = this._client;
const provider = new CallHierarchyProvider(client);
return [vscode_1.languages.registerCallHierarchyProvider(options.documentSelector, provider), provider];
}
}
exports.CallHierarchyFeature = CallHierarchyFeature;
//# sourceMappingURL=callHierarchy.js.map

View File

@@ -0,0 +1,575 @@
import { TextDocumentChangeEvent, TextDocument, Disposable, OutputChannel, FileSystemWatcher as VFileSystemWatcher, DiagnosticCollection, Diagnostic as VDiagnostic, Uri, ProviderResult, CancellationToken, Position as VPosition, Location as VLocation, Range as VRange, CompletionItem as VCompletionItem, CompletionList as VCompletionList, SignatureHelp as VSignatureHelp, SignatureHelpContext as VSignatureHelpContext, Definition as VDefinition, DefinitionLink as VDefinitionLink, DocumentHighlight as VDocumentHighlight, SymbolInformation as VSymbolInformation, CodeActionContext as VCodeActionContext, Command as VCommand, CodeLens as VCodeLens, FormattingOptions as VFormattingOptions, TextEdit as VTextEdit, WorkspaceEdit as VWorkspaceEdit, Hover as VHover, CodeAction as VCodeAction, DocumentSymbol as VDocumentSymbol, DocumentLink as VDocumentLink, TextDocumentWillSaveEvent, WorkspaceFolder as VWorkspaceFolder, CompletionContext as VCompletionContext, CompletionItemProvider, HoverProvider, SignatureHelpProvider, DefinitionProvider, ReferenceProvider, DocumentHighlightProvider, CodeActionProvider, DocumentSymbolProvider, DocumentFormattingEditProvider, DocumentRangeFormattingEditProvider, OnTypeFormattingEditProvider, RenameProvider, DocumentLinkProvider, DocumentColorProvider, DeclarationProvider, FoldingRangeProvider, ImplementationProvider, SelectionRangeProvider, TypeDefinitionProvider, WorkspaceSymbolProvider, CallHierarchyProvider, FileWillCreateEvent, FileWillRenameEvent, FileWillDeleteEvent, FileCreateEvent, FileDeleteEvent, FileRenameEvent, LinkedEditingRangeProvider } from 'vscode';
import { Message, MessageSignature, ResponseError, RequestType0, RequestType, NotificationType0, NotificationType, ProtocolRequestType, ProtocolRequestType0, RequestHandler, RequestHandler0, GenericRequestHandler, ProtocolNotificationType, ProtocolNotificationType0, NotificationHandler, NotificationHandler0, GenericNotificationHandler, MessageReader, MessageWriter, Trace, Event, ClientCapabilities, TextDocumentRegistrationOptions, InitializeParams, InitializeResult, InitializeError, ServerCapabilities, DocumentSelector, DidOpenTextDocumentNotification, DidChangeTextDocumentNotification, DidCloseTextDocumentNotification, DidSaveTextDocumentNotification, WillSaveTextDocumentNotification, WillSaveTextDocumentWaitUntilRequest, FileEvent, CompletionRequest, HoverRequest, SignatureHelpRequest, DefinitionRequest, ReferencesRequest, DocumentHighlightRequest, DocumentSymbolRequest, WorkspaceSymbolRequest, CodeActionRequest, DocumentFormattingRequest, DocumentRangeFormattingRequest, DocumentOnTypeFormattingRequest, RenameRequest, DocumentLinkRequest, ProgressType, ProgressToken, StaticRegistrationOptions, DocumentColorRequest, DeclarationRequest, FoldingRangeRequest, ImplementationRequest, SelectionRangeRequest, TypeDefinitionRequest, CallHierarchyPrepareRequest, CancellationStrategy, RegistrationType, SemanticTokensRegistrationType, ShowDocumentRequest, FileOperationRegistrationOptions, WillCreateFilesRequest, WillRenameFilesRequest, WillDeleteFilesRequest, DidCreateFilesNotification, DidDeleteFilesNotification, DidRenameFilesNotification, ShowDocumentParams, ShowDocumentResult, LinkedEditingRangeRequest, WorkDoneProgressBegin, WorkDoneProgressEnd, WorkDoneProgressReport } from 'vscode-languageserver-protocol';
import type { ColorProviderMiddleware } from './colorProvider';
import type { ImplementationMiddleware } from './implementation';
import type { TypeDefinitionMiddleware } from './typeDefinition';
import { ConfigurationWorkspaceMiddleware } from './configuration';
import type { WorkspaceFolderWorkspaceMiddleware } from './workspaceFolders';
import type { FoldingRangeProviderMiddleware } from './foldingRange';
import type { DeclarationMiddleware } from './declaration';
import type { SelectionRangeProviderMiddleware } from './selectionRange';
import type { CallHierarchyMiddleware } from './callHierarchy';
import type { SemanticTokensMiddleware, SemanticTokensProviders } from './semanticTokens';
import type { FileOperationsMiddleware } from './fileOperations';
import { LinkedEditingRangeMiddleware } from './linkedEditingRange';
import * as c2p from './codeConverter';
import * as p2c from './protocolConverter';
interface ConnectionOptions {
cancellationStrategy: CancellationStrategy;
maxRestartCount?: number;
}
/**
* An action to be performed when the connection is producing errors.
*/
export declare enum ErrorAction {
/**
* Continue running the server.
*/
Continue = 1,
/**
* Shutdown the server.
*/
Shutdown = 2
}
/**
* An action to be performed when the connection to a server got closed.
*/
export declare enum CloseAction {
/**
* Don't restart the server. The connection stays closed.
*/
DoNotRestart = 1,
/**
* Restart the server.
*/
Restart = 2
}
/**
* A plugable error handler that is invoked when the connection is either
* producing errors or got closed.
*/
export interface ErrorHandler {
/**
* An error has occurred while writing or reading from the connection.
*
* @param error - the error received
* @param message - the message to be delivered to the server if know.
* @param count - a count indicating how often an error is received. Will
* be reset if a message got successfully send or received.
*/
error(error: Error, message: Message | undefined, count: number | undefined): ErrorAction;
/**
* The connection to the server got closed.
*/
closed(): CloseAction;
}
/**
* A handler that is invoked when the initialization of the server failed.
*/
export interface InitializationFailedHandler {
/**
* @param error The error returned from the server
* @returns if true is returned the client tries to reinitialize the server.
* Implementors of a handler are responsible to not initialize the server
* infinitely. Return false if initialization should stop and an error
* should be reported.
*/
(error: ResponseError<InitializeError> | Error | any): boolean;
}
export interface SynchronizeOptions {
/**
* The configuration sections to synchronize. Pushing settings from the
* client to the server is deprecated in favour of the new pull model
* that allows servers to query settings scoped on resources. In this
* model the client can only deliver an empty change event since the
* actually setting value can vary on the provided resource scope.
*
* @deprecated Use the new pull model (`workspace/configuration` request)
*/
configurationSection?: string | string[];
/**
* Asks the client to send file change events to the server. Watchers
* operate on workspace folders. The LSP client doesn't support watching
* files outside a workspace folder.
*/
fileEvents?: VFileSystemWatcher | VFileSystemWatcher[];
}
export declare enum RevealOutputChannelOn {
Info = 1,
Warn = 2,
Error = 3,
Never = 4
}
export interface HandleDiagnosticsSignature {
(this: void, uri: Uri, diagnostics: VDiagnostic[]): void;
}
export interface HandleWorkDoneProgressSignature {
(this: void, token: ProgressToken, params: WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd): void;
}
export interface ProvideCompletionItemsSignature {
(this: void, document: TextDocument, position: VPosition, context: VCompletionContext, token: CancellationToken): ProviderResult<VCompletionItem[] | VCompletionList>;
}
export interface ResolveCompletionItemSignature {
(this: void, item: VCompletionItem, token: CancellationToken): ProviderResult<VCompletionItem>;
}
export interface ProvideHoverSignature {
(this: void, document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VHover>;
}
export interface ProvideSignatureHelpSignature {
(this: void, document: TextDocument, position: VPosition, context: VSignatureHelpContext, token: CancellationToken): ProviderResult<VSignatureHelp>;
}
export interface ProvideDefinitionSignature {
(this: void, document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VDefinition | VDefinitionLink[]>;
}
export interface ProvideReferencesSignature {
(this: void, document: TextDocument, position: VPosition, options: {
includeDeclaration: boolean;
}, token: CancellationToken): ProviderResult<VLocation[]>;
}
export interface ProvideDocumentHighlightsSignature {
(this: void, document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VDocumentHighlight[]>;
}
export interface ProvideDocumentSymbolsSignature {
(this: void, document: TextDocument, token: CancellationToken): ProviderResult<VSymbolInformation[] | VDocumentSymbol[]>;
}
export interface ProvideWorkspaceSymbolsSignature {
(this: void, query: string, token: CancellationToken): ProviderResult<VSymbolInformation[]>;
}
export interface ProvideCodeActionsSignature {
(this: void, document: TextDocument, range: VRange, context: VCodeActionContext, token: CancellationToken): ProviderResult<(VCommand | VCodeAction)[]>;
}
export interface ResolveCodeActionSignature {
(this: void, item: VCodeAction, token: CancellationToken): ProviderResult<VCodeAction>;
}
export interface ProvideCodeLensesSignature {
(this: void, document: TextDocument, token: CancellationToken): ProviderResult<VCodeLens[]>;
}
export interface ResolveCodeLensSignature {
(this: void, codeLens: VCodeLens, token: CancellationToken): ProviderResult<VCodeLens>;
}
export interface ProvideDocumentFormattingEditsSignature {
(this: void, document: TextDocument, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface ProvideDocumentRangeFormattingEditsSignature {
(this: void, document: TextDocument, range: VRange, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface ProvideOnTypeFormattingEditsSignature {
(this: void, document: TextDocument, position: VPosition, ch: string, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface ProvideRenameEditsSignature {
(this: void, document: TextDocument, position: VPosition, newName: string, token: CancellationToken): ProviderResult<VWorkspaceEdit>;
}
export interface PrepareRenameSignature {
(this: void, document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VRange | {
range: VRange;
placeholder: string;
}>;
}
export interface ProvideDocumentLinksSignature {
(this: void, document: TextDocument, token: CancellationToken): ProviderResult<VDocumentLink[]>;
}
export interface ResolveDocumentLinkSignature {
(this: void, link: VDocumentLink, token: CancellationToken): ProviderResult<VDocumentLink>;
}
export interface ExecuteCommandSignature {
(this: void, command: string, args: any[]): ProviderResult<any>;
}
export interface NextSignature<P, R> {
(this: void, data: P, next: (data: P) => R): R;
}
export interface DidChangeConfigurationSignature {
(this: void, sections: string[] | undefined): void;
}
export interface DidChangeWatchedFileSignature {
(this: void, event: FileEvent): void;
}
export interface _WorkspaceMiddleware {
didChangeConfiguration?: (this: void, sections: string[] | undefined, next: DidChangeConfigurationSignature) => void;
didChangeWatchedFile?: (this: void, event: FileEvent, next: DidChangeWatchedFileSignature) => void;
}
export declare type WorkspaceMiddleware = _WorkspaceMiddleware & ConfigurationWorkspaceMiddleware & WorkspaceFolderWorkspaceMiddleware & FileOperationsMiddleware;
export interface _WindowMiddleware {
showDocument?: (this: void, params: ShowDocumentParams, next: ShowDocumentRequest.HandlerSignature) => Promise<ShowDocumentResult>;
}
export declare type WindowMiddleware = _WindowMiddleware;
/**
* The Middleware lets extensions intercept the request and notifications send and received
* from the server
*/
export interface _Middleware {
didOpen?: NextSignature<TextDocument, void>;
didChange?: NextSignature<TextDocumentChangeEvent, void>;
willSave?: NextSignature<TextDocumentWillSaveEvent, void>;
willSaveWaitUntil?: NextSignature<TextDocumentWillSaveEvent, Thenable<VTextEdit[]>>;
didSave?: NextSignature<TextDocument, void>;
didClose?: NextSignature<TextDocument, void>;
handleDiagnostics?: (this: void, uri: Uri, diagnostics: VDiagnostic[], next: HandleDiagnosticsSignature) => void;
handleWorkDoneProgress?: (this: void, token: ProgressToken, params: WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd, next: HandleWorkDoneProgressSignature) => void;
provideCompletionItem?: (this: void, document: TextDocument, position: VPosition, context: VCompletionContext, token: CancellationToken, next: ProvideCompletionItemsSignature) => ProviderResult<VCompletionItem[] | VCompletionList>;
resolveCompletionItem?: (this: void, item: VCompletionItem, token: CancellationToken, next: ResolveCompletionItemSignature) => ProviderResult<VCompletionItem>;
provideHover?: (this: void, document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideHoverSignature) => ProviderResult<VHover>;
provideSignatureHelp?: (this: void, document: TextDocument, position: VPosition, context: VSignatureHelpContext, token: CancellationToken, next: ProvideSignatureHelpSignature) => ProviderResult<VSignatureHelp>;
provideDefinition?: (this: void, document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideDefinitionSignature) => ProviderResult<VDefinition | VDefinitionLink[]>;
provideReferences?: (this: void, document: TextDocument, position: VPosition, options: {
includeDeclaration: boolean;
}, token: CancellationToken, next: ProvideReferencesSignature) => ProviderResult<VLocation[]>;
provideDocumentHighlights?: (this: void, document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideDocumentHighlightsSignature) => ProviderResult<VDocumentHighlight[]>;
provideDocumentSymbols?: (this: void, document: TextDocument, token: CancellationToken, next: ProvideDocumentSymbolsSignature) => ProviderResult<VSymbolInformation[] | VDocumentSymbol[]>;
provideWorkspaceSymbols?: (this: void, query: string, token: CancellationToken, next: ProvideWorkspaceSymbolsSignature) => ProviderResult<VSymbolInformation[]>;
provideCodeActions?: (this: void, document: TextDocument, range: VRange, context: VCodeActionContext, token: CancellationToken, next: ProvideCodeActionsSignature) => ProviderResult<(VCommand | VCodeAction)[]>;
resolveCodeAction?: (this: void, item: VCodeAction, token: CancellationToken, next: ResolveCodeActionSignature) => ProviderResult<VCodeAction>;
provideCodeLenses?: (this: void, document: TextDocument, token: CancellationToken, next: ProvideCodeLensesSignature) => ProviderResult<VCodeLens[]>;
resolveCodeLens?: (this: void, codeLens: VCodeLens, token: CancellationToken, next: ResolveCodeLensSignature) => ProviderResult<VCodeLens>;
provideDocumentFormattingEdits?: (this: void, document: TextDocument, options: VFormattingOptions, token: CancellationToken, next: ProvideDocumentFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
provideDocumentRangeFormattingEdits?: (this: void, document: TextDocument, range: VRange, options: VFormattingOptions, token: CancellationToken, next: ProvideDocumentRangeFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
provideOnTypeFormattingEdits?: (this: void, document: TextDocument, position: VPosition, ch: string, options: VFormattingOptions, token: CancellationToken, next: ProvideOnTypeFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
provideRenameEdits?: (this: void, document: TextDocument, position: VPosition, newName: string, token: CancellationToken, next: ProvideRenameEditsSignature) => ProviderResult<VWorkspaceEdit>;
prepareRename?: (this: void, document: TextDocument, position: VPosition, token: CancellationToken, next: PrepareRenameSignature) => ProviderResult<VRange | {
range: VRange;
placeholder: string;
}>;
provideDocumentLinks?: (this: void, document: TextDocument, token: CancellationToken, next: ProvideDocumentLinksSignature) => ProviderResult<VDocumentLink[]>;
resolveDocumentLink?: (this: void, link: VDocumentLink, token: CancellationToken, next: ResolveDocumentLinkSignature) => ProviderResult<VDocumentLink>;
executeCommand?: (this: void, command: string, args: any[], next: ExecuteCommandSignature) => ProviderResult<any>;
workspace?: WorkspaceMiddleware;
window?: WindowMiddleware;
}
export declare type Middleware = _Middleware & TypeDefinitionMiddleware & ImplementationMiddleware & ColorProviderMiddleware & FoldingRangeProviderMiddleware & DeclarationMiddleware & SelectionRangeProviderMiddleware & CallHierarchyMiddleware & SemanticTokensMiddleware & LinkedEditingRangeMiddleware;
export interface LanguageClientOptions {
documentSelector?: DocumentSelector | string[];
synchronize?: SynchronizeOptions;
diagnosticCollectionName?: string;
outputChannel?: OutputChannel;
outputChannelName?: string;
traceOutputChannel?: OutputChannel;
revealOutputChannelOn?: RevealOutputChannelOn;
/**
* The encoding use to read stdout and stderr. Defaults
* to 'utf8' if omitted.
*/
stdioEncoding?: string;
initializationOptions?: any | (() => any);
initializationFailedHandler?: InitializationFailedHandler;
progressOnInitialization?: boolean;
errorHandler?: ErrorHandler;
middleware?: Middleware;
uriConverters?: {
code2Protocol: c2p.URIConverter;
protocol2Code: p2c.URIConverter;
};
workspaceFolder?: VWorkspaceFolder;
connectionOptions?: ConnectionOptions;
markdown?: {
isTrusted?: boolean;
};
}
export declare enum State {
Stopped = 1,
Starting = 3,
Running = 2
}
export interface StateChangeEvent {
oldState: State;
newState: State;
}
export interface RegistrationData<T> {
id: string;
registerOptions: T;
}
/**
* A static feature. A static feature can't be dynamically activate via the
* server. It is wired during the initialize sequence.
*/
export interface StaticFeature {
/**
* Called to fill the initialize params.
*
* @params the initialize params.
*/
fillInitializeParams?: (params: InitializeParams) => void;
/**
* Called to fill in the client capabilities this feature implements.
*
* @param capabilities The client capabilities to fill.
*/
fillClientCapabilities(capabilities: ClientCapabilities): void;
/**
* Initialize the feature. This method is called on a feature instance
* when the client has successfully received the initialize request from
* the server and before the client sends the initialized notification
* to the server.
*
* @param capabilities the server capabilities
* @param documentSelector the document selector pass to the client's constructor.
* May be `undefined` if the client was created without a selector.
*/
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector | undefined): void;
/**
* Called when the client is stopped to dispose this feature. Usually a feature
* un-registers listeners registered hooked up with the VS Code extension host.
*/
dispose(): void;
}
export interface DynamicFeature<RO> {
/**
* Called to fill the initialize params.
*
* @params the initialize params.
*/
fillInitializeParams?: (params: InitializeParams) => void;
/**
* Called to fill in the client capabilities this feature implements.
*
* @param capabilities The client capabilities to fill.
*/
fillClientCapabilities(capabilities: ClientCapabilities): void;
/**
* Initialize the feature. This method is called on a feature instance
* when the client has successfully received the initialize request from
* the server and before the client sends the initialized notification
* to the server.
*
* @param capabilities the server capabilities.
* @param documentSelector the document selector pass to the client's constructor.
* May be `undefined` if the client was created without a selector.
*/
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector | undefined): void;
/**
* The signature (e.g. method) for which this features support dynamic activation / registration.
*/
registrationType: RegistrationType<RO>;
/**
* Is called when the server send a register request for the given message.
*
* @param data additional registration data as defined in the protocol.
*/
register(data: RegistrationData<RO>): void;
/**
* Is called when the server wants to unregister a feature.
*
* @param id the id used when registering the feature.
*/
unregister(id: string): void;
/**
* Called when the client is stopped to dispose this feature. Usually a feature
* un-registers listeners registered hooked up with the VS Code extension host.
*/
dispose(): void;
}
export interface NotificationFeature<T extends Function> {
/**
* Triggers the corresponding RPC method.
*/
getProvider(document: TextDocument): {
send: T;
} | undefined;
}
export interface TextDocumentProviderFeature<T> {
/**
* Triggers the corresponding RPC method.
*/
getProvider(textDocument: TextDocument): T | undefined;
}
export declare abstract class TextDocumentFeature<PO, RO extends TextDocumentRegistrationOptions & PO, PR> implements DynamicFeature<RO> {
protected _client: BaseLanguageClient;
private _registrationType;
private _registrations;
constructor(_client: BaseLanguageClient, _registrationType: RegistrationType<RO>);
get registrationType(): RegistrationType<RO>;
abstract fillClientCapabilities(capabilities: ClientCapabilities): void;
abstract initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void;
register(data: RegistrationData<RO>): void;
protected abstract registerLanguageProvider(options: RO): [Disposable, PR];
unregister(id: string): void;
dispose(): void;
protected getRegistration(documentSelector: DocumentSelector | undefined, capability: undefined | PO | (RO & StaticRegistrationOptions)): [string | undefined, (RO & {
documentSelector: DocumentSelector;
}) | undefined];
protected getRegistrationOptions(documentSelector: DocumentSelector | undefined, capability: undefined | PO): (RO & {
documentSelector: DocumentSelector;
}) | undefined;
getProvider(textDocument: TextDocument): PR | undefined;
protected getAllProviders(): Iterable<PR>;
}
export interface WorkspaceProviderFeature<PR> {
getProviders(): PR[] | undefined;
}
export interface ProvideResolveFeature<T1 extends Function, T2 extends Function> {
provide: T1;
resolve: T2;
}
declare module 'vscode' {
interface CodeActionProvider<T extends CodeAction = CodeAction> {
resolveCodeAction?(codeAction: T, token: CancellationToken): ProviderResult<T>;
}
}
export interface MessageTransports {
reader: MessageReader;
writer: MessageWriter;
detached?: boolean;
}
export declare namespace MessageTransports {
function is(value: any): value is MessageTransports;
}
export declare abstract class BaseLanguageClient {
private _id;
private _name;
private _clientOptions;
private _state;
private _onReady;
private _onReadyCallbacks;
private _onStop;
private _connectionPromise;
private _resolvedConnection;
private _initializeResult;
private _outputChannel;
private _disposeOutputChannel;
private _traceOutputChannel;
private _capabilities;
private _listeners;
private _providers;
private _diagnostics;
private _syncedDocuments;
private _fileEvents;
private _fileEventDelayer;
private _telemetryEmitter;
private _stateChangeEmitter;
private _trace;
private _traceFormat;
private _tracer;
private _c2p;
private _p2c;
constructor(id: string, name: string, clientOptions: LanguageClientOptions);
private get state();
private set state(value);
private getPublicState;
get initializeResult(): InitializeResult | undefined;
sendRequest<R, PR, E, RO>(type: ProtocolRequestType0<R, PR, E, RO>, token?: CancellationToken): Promise<R>;
sendRequest<P, R, PR, E, RO>(type: ProtocolRequestType<P, R, PR, E, RO>, params: P, token?: CancellationToken): Promise<R>;
sendRequest<R, E>(type: RequestType0<R, E>, token?: CancellationToken): Promise<R>;
sendRequest<P, R, E>(type: RequestType<P, R, E>, params: P, token?: CancellationToken): Promise<R>;
sendRequest<R>(method: string, token?: CancellationToken): Promise<R>;
sendRequest<R>(method: string, param: any, token?: CancellationToken): Promise<R>;
onRequest<R, PR, E, RO>(type: ProtocolRequestType0<R, PR, E, RO>, handler: RequestHandler0<R, E>): Disposable;
onRequest<P, R, PR, E, RO>(type: ProtocolRequestType<P, R, PR, E, RO>, handler: RequestHandler<P, R, E>): Disposable;
onRequest<R, E>(type: RequestType0<R, E>, handler: RequestHandler0<R, E>): Disposable;
onRequest<P, R, E>(type: RequestType<P, R, E>, handler: RequestHandler<P, R, E>): Disposable;
onRequest<R, E>(method: string, handler: GenericRequestHandler<R, E>): Disposable;
sendNotification<RO>(type: ProtocolNotificationType0<RO>): void;
sendNotification<P, RO>(type: ProtocolNotificationType<P, RO>, params?: P): void;
sendNotification(type: NotificationType0): void;
sendNotification<P>(type: NotificationType<P>, params?: P): void;
sendNotification(method: string): void;
sendNotification(method: string, params: any): void;
onNotification<RO>(type: ProtocolNotificationType0<RO>, handler: NotificationHandler0): Disposable;
onNotification<P, RO>(type: ProtocolNotificationType<P, RO>, handler: NotificationHandler<P>): Disposable;
onNotification(type: NotificationType0, handler: NotificationHandler0): Disposable;
onNotification<P>(type: NotificationType<P>, handler: NotificationHandler<P>): Disposable;
onNotification(method: string, handler: GenericNotificationHandler): Disposable;
onProgress<P>(type: ProgressType<P>, token: string | number, handler: NotificationHandler<P>): Disposable;
sendProgress<P>(type: ProgressType<P>, token: string | number, value: P): void;
get clientOptions(): LanguageClientOptions;
get protocol2CodeConverter(): p2c.Converter;
get code2ProtocolConverter(): c2p.Converter;
get onTelemetry(): Event<any>;
get onDidChangeState(): Event<StateChangeEvent>;
get outputChannel(): OutputChannel;
get traceOutputChannel(): OutputChannel;
get diagnostics(): DiagnosticCollection | undefined;
createDefaultErrorHandler(maxRestartCount?: number): ErrorHandler;
set trace(value: Trace);
private data2String;
info(message: string, data?: any, showNotification?: boolean): void;
warn(message: string, data?: any, showNotification?: boolean): void;
error(message: string, data?: any, showNotification?: boolean): void;
private showNotificationMessage;
private logTrace;
private logObjectTrace;
needsStart(): boolean;
needsStop(): boolean;
onReady(): Promise<void>;
private isConnectionActive;
start(): Disposable;
private resolveConnection;
private initialize;
private doInitialize;
private _clientGetRootPath;
stop(): Promise<void>;
private cleanUp;
private cleanUpChannel;
private notifyFileEvent;
private _didChangeTextDocumentFeature;
private forceDocumentSync;
private handleDiagnostics;
private setDiagnostics;
protected abstract getLocale(): string;
protected abstract createMessageTransports(encoding: string): Promise<MessageTransports>;
private createConnection;
protected handleConnectionClosed(): void;
private handleConnectionError;
private hookConfigurationChanged;
private refreshTrace;
private hookFileEvents;
private readonly _features;
private readonly _dynamicFeatures;
registerFeatures(features: (StaticFeature | DynamicFeature<any>)[]): void;
registerFeature(feature: StaticFeature | DynamicFeature<any>): void;
getFeature(request: typeof DidOpenTextDocumentNotification.method): DynamicFeature<TextDocumentRegistrationOptions> & NotificationFeature<(textDocument: TextDocument) => void>;
getFeature(request: typeof DidChangeTextDocumentNotification.method): DynamicFeature<TextDocumentRegistrationOptions> & NotificationFeature<(textDocument: TextDocument) => void>;
getFeature(request: typeof WillSaveTextDocumentNotification.method): DynamicFeature<TextDocumentRegistrationOptions> & NotificationFeature<(textDocument: TextDocument) => void>;
getFeature(request: typeof WillSaveTextDocumentWaitUntilRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & NotificationFeature<(textDocument: TextDocument) => ProviderResult<VTextEdit[]>>;
getFeature(request: typeof DidSaveTextDocumentNotification.method): DynamicFeature<TextDocumentRegistrationOptions> & NotificationFeature<(textDocument: TextDocument) => void>;
getFeature(request: typeof DidCloseTextDocumentNotification.method): DynamicFeature<TextDocumentRegistrationOptions> & NotificationFeature<(textDocument: TextDocument) => void>;
getFeature(request: typeof DidCreateFilesNotification.method): DynamicFeature<FileOperationRegistrationOptions> & {
send: (event: FileCreateEvent) => Promise<void>;
};
getFeature(request: typeof DidRenameFilesNotification.method): DynamicFeature<FileOperationRegistrationOptions> & {
send: (event: FileRenameEvent) => Promise<void>;
};
getFeature(request: typeof DidDeleteFilesNotification.method): DynamicFeature<FileOperationRegistrationOptions> & {
send: (event: FileDeleteEvent) => Promise<void>;
};
getFeature(request: typeof WillCreateFilesRequest.method): DynamicFeature<FileOperationRegistrationOptions> & {
send: (event: FileWillCreateEvent) => Promise<void>;
};
getFeature(request: typeof WillRenameFilesRequest.method): DynamicFeature<FileOperationRegistrationOptions> & {
send: (event: FileWillRenameEvent) => Promise<void>;
};
getFeature(request: typeof WillDeleteFilesRequest.method): DynamicFeature<FileOperationRegistrationOptions> & {
send: (event: FileWillDeleteEvent) => Promise<void>;
};
getFeature(request: typeof CompletionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<CompletionItemProvider>;
getFeature(request: typeof HoverRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<HoverProvider>;
getFeature(request: typeof SignatureHelpRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<SignatureHelpProvider>;
getFeature(request: typeof DefinitionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DefinitionProvider>;
getFeature(request: typeof ReferencesRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<ReferenceProvider>;
getFeature(request: typeof DocumentHighlightRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentHighlightProvider>;
getFeature(request: typeof CodeActionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<CodeActionProvider>;
getFeature(request: typeof DocumentFormattingRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentFormattingEditProvider>;
getFeature(request: typeof DocumentRangeFormattingRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentRangeFormattingEditProvider>;
getFeature(request: typeof DocumentOnTypeFormattingRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<OnTypeFormattingEditProvider>;
getFeature(request: typeof RenameRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<RenameProvider>;
getFeature(request: typeof DocumentSymbolRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentSymbolProvider>;
getFeature(request: typeof DocumentLinkRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentLinkProvider>;
getFeature(request: typeof DocumentColorRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentColorProvider>;
getFeature(request: typeof DeclarationRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DeclarationProvider>;
getFeature(request: typeof FoldingRangeRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<FoldingRangeProvider>;
getFeature(request: typeof ImplementationRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<ImplementationProvider>;
getFeature(request: typeof SelectionRangeRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<SelectionRangeProvider>;
getFeature(request: typeof TypeDefinitionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<TypeDefinitionProvider>;
getFeature(request: typeof CallHierarchyPrepareRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<CallHierarchyProvider>;
getFeature(request: typeof SemanticTokensRegistrationType.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<SemanticTokensProviders>;
getFeature(request: typeof LinkedEditingRangeRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<LinkedEditingRangeProvider>;
getFeature(request: typeof WorkspaceSymbolRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & WorkspaceProviderFeature<WorkspaceSymbolProvider>;
protected registerBuiltinFeatures(): void;
protected fillInitializeParams(params: InitializeParams): void;
private computeClientCapabilities;
private initializeFeatures;
private handleRegistrationRequest;
private handleUnregistrationRequest;
private handleApplyWorkspaceEdit;
handleFailedRequest<T>(type: MessageSignature, error: any, defaultValue: T): T;
private static Canceled;
private makeCancelError;
}
export {};

2673
node_modules/vscode-languageclient/lib/common/client.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,68 @@
import * as code from 'vscode';
import * as proto from 'vscode-languageserver-protocol';
import { CreateFilesParams, DeleteFilesParams, RenameFilesParams } from 'vscode-languageserver-protocol/lib/common/protocol.fileOperations';
export interface FileFormattingOptions {
trimTrailingWhitespace?: boolean;
trimFinalNewlines?: boolean;
insertFinalNewline?: boolean;
}
export interface Converter {
asUri(uri: code.Uri): string;
asTextDocumentIdentifier(textDocument: code.TextDocument): proto.TextDocumentIdentifier;
asVersionedTextDocumentIdentifier(textDocument: code.TextDocument): proto.VersionedTextDocumentIdentifier;
asOpenTextDocumentParams(textDocument: code.TextDocument): proto.DidOpenTextDocumentParams;
asChangeTextDocumentParams(textDocument: code.TextDocument): proto.DidChangeTextDocumentParams;
asChangeTextDocumentParams(event: code.TextDocumentChangeEvent): proto.DidChangeTextDocumentParams;
asCloseTextDocumentParams(textDocument: code.TextDocument): proto.DidCloseTextDocumentParams;
asSaveTextDocumentParams(textDocument: code.TextDocument, includeContent?: boolean): proto.DidSaveTextDocumentParams;
asWillSaveTextDocumentParams(event: code.TextDocumentWillSaveEvent): proto.WillSaveTextDocumentParams;
asDidCreateFilesParams(event: code.FileCreateEvent): CreateFilesParams;
asDidRenameFilesParams(event: code.FileRenameEvent): RenameFilesParams;
asDidDeleteFilesParams(event: code.FileDeleteEvent): DeleteFilesParams;
asWillCreateFilesParams(event: code.FileCreateEvent): CreateFilesParams;
asWillRenameFilesParams(event: code.FileRenameEvent): RenameFilesParams;
asWillDeleteFilesParams(event: code.FileDeleteEvent): DeleteFilesParams;
asTextDocumentPositionParams(textDocument: code.TextDocument, position: code.Position): proto.TextDocumentPositionParams;
asCompletionParams(textDocument: code.TextDocument, position: code.Position, context: code.CompletionContext): proto.CompletionParams;
asSignatureHelpParams(textDocument: code.TextDocument, position: code.Position, context: code.SignatureHelpContext): proto.SignatureHelpParams;
asWorkerPosition(position: code.Position): proto.Position;
asPosition(value: code.Position): proto.Position;
asPosition(value: undefined): undefined;
asPosition(value: null): null;
asPosition(value: code.Position | undefined | null): proto.Position | undefined | null;
asPositions(value: code.Position[]): proto.Position[];
asRange(value: code.Range): proto.Range;
asRange(value: undefined): undefined;
asRange(value: null): null;
asRange(value: code.Range | undefined | null): proto.Range | undefined | null;
asLocation(value: code.Location): proto.Location;
asLocation(value: undefined): undefined;
asLocation(value: null): null;
asLocation(value: code.Location | undefined | null): proto.Location | undefined | null;
asDiagnosticSeverity(value: code.DiagnosticSeverity): number;
asDiagnosticTag(value: code.DiagnosticTag): number | undefined;
asDiagnostic(item: code.Diagnostic): proto.Diagnostic;
asDiagnostics(items: code.Diagnostic[]): proto.Diagnostic[];
asCompletionItem(item: code.CompletionItem): proto.CompletionItem;
asSymbolKind(item: code.SymbolKind): proto.SymbolKind;
asSymbolTag(item: code.SymbolTag): proto.SymbolTag;
asSymbolTags(items: ReadonlyArray<code.SymbolTag>): proto.SymbolTag[];
asTextEdit(edit: code.TextEdit): proto.TextEdit;
asReferenceParams(textDocument: code.TextDocument, position: code.Position, options: {
includeDeclaration: boolean;
}): proto.ReferenceParams;
asCodeAction(item: code.CodeAction): proto.CodeAction;
asCodeActionContext(context: code.CodeActionContext): proto.CodeActionContext;
asCommand(item: code.Command): proto.Command;
asCodeLens(item: code.CodeLens): proto.CodeLens;
asFormattingOptions(options: code.FormattingOptions, fileOptions: FileFormattingOptions): proto.FormattingOptions;
asDocumentSymbolParams(textDocument: code.TextDocument): proto.DocumentSymbolParams;
asCodeLensParams(textDocument: code.TextDocument): proto.CodeLensParams;
asDocumentLink(item: code.DocumentLink): proto.DocumentLink;
asDocumentLinkParams(textDocument: code.TextDocument): proto.DocumentLinkParams;
asCallHierarchyItem(value: code.CallHierarchyItem): proto.CallHierarchyItem;
}
export interface URIConverter {
(value: code.Uri): string;
}
export declare function createConverter(uriConverter?: URIConverter): Converter;

View File

@@ -0,0 +1,703 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createConverter = void 0;
const code = require("vscode");
const proto = require("vscode-languageserver-protocol");
const Is = require("./utils/is");
const protocolCompletionItem_1 = require("./protocolCompletionItem");
const protocolCodeLens_1 = require("./protocolCodeLens");
const protocolDocumentLink_1 = require("./protocolDocumentLink");
const protocolCodeAction_1 = require("./protocolCodeAction");
const protocolDiagnostic_1 = require("./protocolDiagnostic");
const protocolCallHierarchyItem_1 = require("./protocolCallHierarchyItem");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
var InsertReplaceRange;
(function (InsertReplaceRange) {
function is(value) {
const candidate = value;
return candidate && !!candidate.inserting && !!candidate.replacing;
}
InsertReplaceRange.is = is;
})(InsertReplaceRange || (InsertReplaceRange = {}));
function createConverter(uriConverter) {
const nullConverter = (value) => value.toString();
const _uriConverter = uriConverter || nullConverter;
function asUri(value) {
return _uriConverter(value);
}
function asTextDocumentIdentifier(textDocument) {
return {
uri: _uriConverter(textDocument.uri)
};
}
function asVersionedTextDocumentIdentifier(textDocument) {
return {
uri: _uriConverter(textDocument.uri),
version: textDocument.version
};
}
function asOpenTextDocumentParams(textDocument) {
return {
textDocument: {
uri: _uriConverter(textDocument.uri),
languageId: textDocument.languageId,
version: textDocument.version,
text: textDocument.getText()
}
};
}
function isTextDocumentChangeEvent(value) {
let candidate = value;
return !!candidate.document && !!candidate.contentChanges;
}
function isTextDocument(value) {
let candidate = value;
return !!candidate.uri && !!candidate.version;
}
function asChangeTextDocumentParams(arg) {
if (isTextDocument(arg)) {
let result = {
textDocument: {
uri: _uriConverter(arg.uri),
version: arg.version
},
contentChanges: [{ text: arg.getText() }]
};
return result;
}
else if (isTextDocumentChangeEvent(arg)) {
let document = arg.document;
let result = {
textDocument: {
uri: _uriConverter(document.uri),
version: document.version
},
contentChanges: arg.contentChanges.map((change) => {
let range = change.range;
return {
range: {
start: { line: range.start.line, character: range.start.character },
end: { line: range.end.line, character: range.end.character }
},
rangeLength: change.rangeLength,
text: change.text
};
})
};
return result;
}
else {
throw Error('Unsupported text document change parameter');
}
}
function asCloseTextDocumentParams(textDocument) {
return {
textDocument: asTextDocumentIdentifier(textDocument)
};
}
function asSaveTextDocumentParams(textDocument, includeContent = false) {
let result = {
textDocument: asTextDocumentIdentifier(textDocument)
};
if (includeContent) {
result.text = textDocument.getText();
}
return result;
}
function asTextDocumentSaveReason(reason) {
switch (reason) {
case code.TextDocumentSaveReason.Manual:
return proto.TextDocumentSaveReason.Manual;
case code.TextDocumentSaveReason.AfterDelay:
return proto.TextDocumentSaveReason.AfterDelay;
case code.TextDocumentSaveReason.FocusOut:
return proto.TextDocumentSaveReason.FocusOut;
}
return proto.TextDocumentSaveReason.Manual;
}
function asWillSaveTextDocumentParams(event) {
return {
textDocument: asTextDocumentIdentifier(event.document),
reason: asTextDocumentSaveReason(event.reason)
};
}
function asDidCreateFilesParams(event) {
return {
files: event.files.map((fileUri) => ({
uri: _uriConverter(fileUri),
})),
};
}
function asDidRenameFilesParams(event) {
return {
files: event.files.map((file) => ({
oldUri: _uriConverter(file.oldUri),
newUri: _uriConverter(file.newUri),
})),
};
}
function asDidDeleteFilesParams(event) {
return {
files: event.files.map((fileUri) => ({
uri: _uriConverter(fileUri),
})),
};
}
function asWillCreateFilesParams(event) {
return {
files: event.files.map((fileUri) => ({
uri: _uriConverter(fileUri),
})),
};
}
function asWillRenameFilesParams(event) {
return {
files: event.files.map((file) => ({
oldUri: _uriConverter(file.oldUri),
newUri: _uriConverter(file.newUri),
})),
};
}
function asWillDeleteFilesParams(event) {
return {
files: event.files.map((fileUri) => ({
uri: _uriConverter(fileUri),
})),
};
}
function asTextDocumentPositionParams(textDocument, position) {
return {
textDocument: asTextDocumentIdentifier(textDocument),
position: asWorkerPosition(position)
};
}
function asCompletionTriggerKind(triggerKind) {
switch (triggerKind) {
case code.CompletionTriggerKind.TriggerCharacter:
return proto.CompletionTriggerKind.TriggerCharacter;
case code.CompletionTriggerKind.TriggerForIncompleteCompletions:
return proto.CompletionTriggerKind.TriggerForIncompleteCompletions;
default:
return proto.CompletionTriggerKind.Invoked;
}
}
function asCompletionParams(textDocument, position, context) {
return {
textDocument: asTextDocumentIdentifier(textDocument),
position: asWorkerPosition(position),
context: {
triggerKind: asCompletionTriggerKind(context.triggerKind),
triggerCharacter: context.triggerCharacter
}
};
}
function asSignatureHelpTriggerKind(triggerKind) {
switch (triggerKind) {
case code.SignatureHelpTriggerKind.Invoke:
return proto.SignatureHelpTriggerKind.Invoked;
case code.SignatureHelpTriggerKind.TriggerCharacter:
return proto.SignatureHelpTriggerKind.TriggerCharacter;
case code.SignatureHelpTriggerKind.ContentChange:
return proto.SignatureHelpTriggerKind.ContentChange;
}
}
function asParameterInformation(value) {
// We leave the documentation out on purpose since it usually adds no
// value for the server.
return {
label: value.label
};
}
function asParameterInformations(values) {
return values.map(asParameterInformation);
}
function asSignatureInformation(value) {
// We leave the documentation out on purpose since it usually adds no
// value for the server.
return {
label: value.label,
parameters: asParameterInformations(value.parameters)
};
}
function asSignatureInformations(values) {
return values.map(asSignatureInformation);
}
function asSignatureHelp(value) {
if (value === undefined) {
return value;
}
return {
signatures: asSignatureInformations(value.signatures),
activeSignature: value.activeSignature,
activeParameter: value.activeParameter
};
}
function asSignatureHelpParams(textDocument, position, context) {
return {
textDocument: asTextDocumentIdentifier(textDocument),
position: asWorkerPosition(position),
context: {
isRetrigger: context.isRetrigger,
triggerCharacter: context.triggerCharacter,
triggerKind: asSignatureHelpTriggerKind(context.triggerKind),
activeSignatureHelp: asSignatureHelp(context.activeSignatureHelp)
}
};
}
function asWorkerPosition(position) {
return { line: position.line, character: position.character };
}
function asPosition(value) {
if (value === undefined || value === null) {
return value;
}
return { line: value.line, character: value.character };
}
function asPositions(value) {
let result = [];
for (let elem of value) {
result.push(asPosition(elem));
}
return result;
}
function asRange(value) {
if (value === undefined || value === null) {
return value;
}
return { start: asPosition(value.start), end: asPosition(value.end) };
}
function asLocation(value) {
if (value === undefined || value === null) {
return value;
}
return proto.Location.create(asUri(value.uri), asRange(value.range));
}
function asDiagnosticSeverity(value) {
switch (value) {
case code.DiagnosticSeverity.Error:
return proto.DiagnosticSeverity.Error;
case code.DiagnosticSeverity.Warning:
return proto.DiagnosticSeverity.Warning;
case code.DiagnosticSeverity.Information:
return proto.DiagnosticSeverity.Information;
case code.DiagnosticSeverity.Hint:
return proto.DiagnosticSeverity.Hint;
}
}
function asDiagnosticTags(tags) {
if (!tags) {
return undefined;
}
let result = [];
for (let tag of tags) {
let converted = asDiagnosticTag(tag);
if (converted !== undefined) {
result.push(converted);
}
}
return result.length > 0 ? result : undefined;
}
function asDiagnosticTag(tag) {
switch (tag) {
case code.DiagnosticTag.Unnecessary:
return proto.DiagnosticTag.Unnecessary;
case code.DiagnosticTag.Deprecated:
return proto.DiagnosticTag.Deprecated;
default:
return undefined;
}
}
function asRelatedInformation(item) {
return {
message: item.message,
location: asLocation(item.location)
};
}
function asRelatedInformations(items) {
return items.map(asRelatedInformation);
}
function asDiagnosticCode(value) {
if (value === undefined || value === null) {
return undefined;
}
if (Is.number(value) || Is.string(value)) {
return value;
}
return { value: value.value, target: asUri(value.target) };
}
function asDiagnostic(item) {
const result = proto.Diagnostic.create(asRange(item.range), item.message);
const protocolDiagnostic = item instanceof protocolDiagnostic_1.ProtocolDiagnostic ? item : undefined;
if (protocolDiagnostic !== undefined && protocolDiagnostic.data !== undefined) {
result.data = protocolDiagnostic.data;
}
const code = asDiagnosticCode(item.code);
if (protocolDiagnostic_1.DiagnosticCode.is(code)) {
if (protocolDiagnostic !== undefined && protocolDiagnostic.hasDiagnosticCode) {
result.code = code;
}
else {
result.code = code.value;
result.codeDescription = { href: code.target };
}
}
else {
result.code = code;
}
if (Is.number(item.severity)) {
result.severity = asDiagnosticSeverity(item.severity);
}
if (Array.isArray(item.tags)) {
result.tags = asDiagnosticTags(item.tags);
}
if (item.relatedInformation) {
result.relatedInformation = asRelatedInformations(item.relatedInformation);
}
if (item.source) {
result.source = item.source;
}
return result;
}
function asDiagnostics(items) {
if (items === undefined || items === null) {
return items;
}
return items.map(asDiagnostic);
}
function asDocumentation(format, documentation) {
switch (format) {
case '$string':
return documentation;
case proto.MarkupKind.PlainText:
return { kind: format, value: documentation };
case proto.MarkupKind.Markdown:
return { kind: format, value: documentation.value };
default:
return `Unsupported Markup content received. Kind is: ${format}`;
}
}
function asCompletionItemTag(tag) {
switch (tag) {
case code.CompletionItemTag.Deprecated:
return proto.CompletionItemTag.Deprecated;
}
return undefined;
}
function asCompletionItemTags(tags) {
if (tags === undefined) {
return tags;
}
const result = [];
for (let tag of tags) {
const converted = asCompletionItemTag(tag);
if (converted !== undefined) {
result.push(converted);
}
}
return result;
}
function asCompletionItemKind(value, original) {
if (original !== undefined) {
return original;
}
return value + 1;
}
function asCompletionItem(item) {
let result = { label: item.label };
let protocolItem = item instanceof protocolCompletionItem_1.default ? item : undefined;
if (item.detail) {
result.detail = item.detail;
}
// We only send items back we created. So this can't be something else than
// a string right now.
if (item.documentation) {
if (!protocolItem || protocolItem.documentationFormat === '$string') {
result.documentation = item.documentation;
}
else {
result.documentation = asDocumentation(protocolItem.documentationFormat, item.documentation);
}
}
if (item.filterText) {
result.filterText = item.filterText;
}
fillPrimaryInsertText(result, item);
if (Is.number(item.kind)) {
result.kind = asCompletionItemKind(item.kind, protocolItem && protocolItem.originalItemKind);
}
if (item.sortText) {
result.sortText = item.sortText;
}
if (item.additionalTextEdits) {
result.additionalTextEdits = asTextEdits(item.additionalTextEdits);
}
if (item.commitCharacters) {
result.commitCharacters = item.commitCharacters.slice();
}
if (item.command) {
result.command = asCommand(item.command);
}
if (item.preselect === true || item.preselect === false) {
result.preselect = item.preselect;
}
const tags = asCompletionItemTags(item.tags);
if (protocolItem) {
if (protocolItem.data !== undefined) {
result.data = protocolItem.data;
}
if (protocolItem.deprecated === true || protocolItem.deprecated === false) {
if (protocolItem.deprecated === true && tags !== undefined && tags.length > 0) {
const index = tags.indexOf(code.CompletionItemTag.Deprecated);
if (index !== -1) {
tags.splice(index, 1);
}
}
result.deprecated = protocolItem.deprecated;
}
if (protocolItem.insertTextMode !== undefined) {
result.insertTextMode = protocolItem.insertTextMode;
}
}
if (tags !== undefined && tags.length > 0) {
result.tags = tags;
}
if (result.insertTextMode === undefined && item.keepWhitespace === true) {
result.insertTextMode = vscode_languageserver_protocol_1.InsertTextMode.adjustIndentation;
}
return result;
}
function fillPrimaryInsertText(target, source) {
let format = proto.InsertTextFormat.PlainText;
let text = undefined;
let range = undefined;
if (source.textEdit) {
text = source.textEdit.newText;
range = source.textEdit.range;
}
else if (source.insertText instanceof code.SnippetString) {
format = proto.InsertTextFormat.Snippet;
text = source.insertText.value;
}
else {
text = source.insertText;
}
if (source.range) {
range = source.range;
}
target.insertTextFormat = format;
if (source.fromEdit && text !== undefined && range !== undefined) {
target.textEdit = asCompletionTextEdit(text, range);
}
else {
target.insertText = text;
}
}
function asCompletionTextEdit(newText, range) {
if (InsertReplaceRange.is(range)) {
return proto.InsertReplaceEdit.create(newText, asRange(range.inserting), asRange(range.replacing));
}
else {
return { newText, range: asRange(range) };
}
}
function asTextEdit(edit) {
return { range: asRange(edit.range), newText: edit.newText };
}
function asTextEdits(edits) {
if (edits === undefined || edits === null) {
return edits;
}
return edits.map(asTextEdit);
}
function asSymbolKind(item) {
if (item <= code.SymbolKind.TypeParameter) {
// Symbol kind is one based in the protocol and zero based in code.
return (item + 1);
}
return proto.SymbolKind.Property;
}
function asSymbolTag(item) {
return item;
}
function asSymbolTags(items) {
return items.map(asSymbolTag);
}
function asReferenceParams(textDocument, position, options) {
return {
textDocument: asTextDocumentIdentifier(textDocument),
position: asWorkerPosition(position),
context: { includeDeclaration: options.includeDeclaration }
};
}
function asCodeAction(item) {
let result = proto.CodeAction.create(item.title);
if (item instanceof protocolCodeAction_1.default && item.data !== undefined) {
result.data = item.data;
}
if (item.kind !== undefined) {
result.kind = asCodeActionKind(item.kind);
}
if (item.diagnostics !== undefined) {
result.diagnostics = asDiagnostics(item.diagnostics);
}
if (item.edit !== undefined) {
throw new Error(`VS Code code actions can only be converted to a protocol code action without an edit.`);
}
if (item.command !== undefined) {
result.command = asCommand(item.command);
}
if (item.isPreferred !== undefined) {
result.isPreferred = item.isPreferred;
}
if (item.disabled !== undefined) {
result.disabled = { reason: item.disabled.reason };
}
return result;
}
function asCodeActionContext(context) {
if (context === undefined || context === null) {
return context;
}
let only;
if (context.only && Is.string(context.only.value)) {
only = [context.only.value];
}
return proto.CodeActionContext.create(asDiagnostics(context.diagnostics), only);
}
function asCodeActionKind(item) {
if (item === undefined || item === null) {
return undefined;
}
return item.value;
}
function asCommand(item) {
let result = proto.Command.create(item.title, item.command);
if (item.arguments) {
result.arguments = item.arguments;
}
return result;
}
function asCodeLens(item) {
let result = proto.CodeLens.create(asRange(item.range));
if (item.command) {
result.command = asCommand(item.command);
}
if (item instanceof protocolCodeLens_1.default) {
if (item.data) {
result.data = item.data;
}
}
return result;
}
function asFormattingOptions(options, fileOptions) {
const result = { tabSize: options.tabSize, insertSpaces: options.insertSpaces };
if (fileOptions.trimTrailingWhitespace) {
result.trimTrailingWhitespace = true;
}
if (fileOptions.trimFinalNewlines) {
result.trimFinalNewlines = true;
}
if (fileOptions.insertFinalNewline) {
result.insertFinalNewline = true;
}
return result;
}
function asDocumentSymbolParams(textDocument) {
return {
textDocument: asTextDocumentIdentifier(textDocument)
};
}
function asCodeLensParams(textDocument) {
return {
textDocument: asTextDocumentIdentifier(textDocument)
};
}
function asDocumentLink(item) {
let result = proto.DocumentLink.create(asRange(item.range));
if (item.target) {
result.target = asUri(item.target);
}
if (item.tooltip !== undefined) {
result.tooltip = item.tooltip;
}
let protocolItem = item instanceof protocolDocumentLink_1.default ? item : undefined;
if (protocolItem && protocolItem.data) {
result.data = protocolItem.data;
}
return result;
}
function asDocumentLinkParams(textDocument) {
return {
textDocument: asTextDocumentIdentifier(textDocument)
};
}
function asCallHierarchyItem(value) {
const result = {
name: value.name,
kind: asSymbolKind(value.kind),
uri: asUri(value.uri),
range: asRange(value.range),
selectionRange: asRange(value.selectionRange)
};
if (value.detail !== undefined && value.detail.length > 0) {
result.detail = value.detail;
}
if (value.tags !== undefined) {
result.tags = asSymbolTags(value.tags);
}
if (value instanceof protocolCallHierarchyItem_1.default && value.data !== undefined) {
result.data = value.data;
}
return result;
}
return {
asUri,
asTextDocumentIdentifier,
asVersionedTextDocumentIdentifier,
asOpenTextDocumentParams,
asChangeTextDocumentParams,
asCloseTextDocumentParams,
asSaveTextDocumentParams,
asWillSaveTextDocumentParams,
asDidCreateFilesParams,
asDidRenameFilesParams,
asDidDeleteFilesParams,
asWillCreateFilesParams,
asWillRenameFilesParams,
asWillDeleteFilesParams,
asTextDocumentPositionParams,
asCompletionParams,
asSignatureHelpParams,
asWorkerPosition,
asRange,
asPosition,
asPositions,
asLocation,
asDiagnosticSeverity,
asDiagnosticTag,
asDiagnostic,
asDiagnostics,
asCompletionItem,
asTextEdit,
asSymbolKind,
asSymbolTag,
asSymbolTags,
asReferenceParams,
asCodeAction,
asCodeActionContext,
asCommand,
asCodeLens,
asFormattingOptions,
asDocumentSymbolParams,
asCodeLensParams,
asDocumentLink,
asDocumentLinkParams,
asCallHierarchyItem
};
}
exports.createConverter = createConverter;
//# sourceMappingURL=codeConverter.js.map

View File

@@ -0,0 +1,28 @@
import { Disposable, TextDocument, ProviderResult, Range as VRange, Color as VColor, ColorPresentation as VColorPresentation, ColorInformation as VColorInformation, DocumentColorProvider } from 'vscode';
import { ClientCapabilities, CancellationToken, ServerCapabilities, DocumentSelector, DocumentColorRegistrationOptions, DocumentColorOptions } from 'vscode-languageserver-protocol';
import { TextDocumentFeature, BaseLanguageClient } from './client';
export interface ProvideDocumentColorsSignature {
(document: TextDocument, token: CancellationToken): ProviderResult<VColorInformation[]>;
}
export interface ProvideColorPresentationSignature {
(color: VColor, context: {
document: TextDocument;
range: VRange;
}, token: CancellationToken): ProviderResult<VColorPresentation[]>;
}
export interface ColorProviderMiddleware {
provideDocumentColors?: (this: void, document: TextDocument, token: CancellationToken, next: ProvideDocumentColorsSignature) => ProviderResult<VColorInformation[]>;
provideColorPresentations?: (this: void, color: VColor, context: {
document: TextDocument;
range: VRange;
}, token: CancellationToken, next: ProvideColorPresentationSignature) => ProviderResult<VColorPresentation[]>;
}
export declare class ColorProviderFeature extends TextDocumentFeature<boolean | DocumentColorOptions, DocumentColorRegistrationOptions, DocumentColorProvider> {
constructor(client: BaseLanguageClient);
fillClientCapabilities(capabilities: ClientCapabilities): void;
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void;
protected registerLanguageProvider(options: DocumentColorRegistrationOptions): [Disposable, DocumentColorProvider];
private asColor;
private asColorInformations;
private asColorPresentations;
}

View File

@@ -0,0 +1,92 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ColorProviderFeature = void 0;
const vscode_1 = require("vscode");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const client_1 = require("./client");
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = {};
}
return target[key];
}
class ColorProviderFeature extends client_1.TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.DocumentColorRequest.type);
}
fillClientCapabilities(capabilities) {
ensure(ensure(capabilities, 'textDocument'), 'colorProvider').dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
let [id, options] = this.getRegistration(documentSelector, capabilities.colorProvider);
if (!id || !options) {
return;
}
this.register({ id: id, registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideColorPresentations: (color, context, token) => {
const client = this._client;
const provideColorPresentations = (color, context, token) => {
const requestParams = {
color,
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(context.document),
range: client.code2ProtocolConverter.asRange(context.range)
};
return client.sendRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, requestParams, token).then(this.asColorPresentations.bind(this), (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, error, null);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideColorPresentations
? middleware.provideColorPresentations(color, context, token, provideColorPresentations)
: provideColorPresentations(color, context, token);
},
provideDocumentColors: (document, token) => {
const client = this._client;
const provideDocumentColors = (document, token) => {
const requestParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)
};
return client.sendRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, requestParams, token).then(this.asColorInformations.bind(this), (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, error, null);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideDocumentColors
? middleware.provideDocumentColors(document, token, provideDocumentColors)
: provideDocumentColors(document, token);
}
};
return [vscode_1.languages.registerColorProvider(options.documentSelector, provider), provider];
}
asColor(color) {
return new vscode_1.Color(color.red, color.green, color.blue, color.alpha);
}
asColorInformations(colorInformation) {
if (Array.isArray(colorInformation)) {
return colorInformation.map(ci => {
return new vscode_1.ColorInformation(this._client.protocol2CodeConverter.asRange(ci.range), this.asColor(ci.color));
});
}
return [];
}
asColorPresentations(colorPresentations) {
if (Array.isArray(colorPresentations)) {
return colorPresentations.map(cp => {
let presentation = new vscode_1.ColorPresentation(cp.label);
presentation.additionalTextEdits = this._client.protocol2CodeConverter.asTextEdits(cp.additionalTextEdits);
presentation.textEdit = this._client.protocol2CodeConverter.asTextEdit(cp.textEdit);
return presentation;
});
}
return [];
}
}
exports.ColorProviderFeature = ColorProviderFeature;
//# sourceMappingURL=colorProvider.js.map

View File

@@ -0,0 +1,9 @@
import { BaseLanguageClient, LanguageClientOptions, StaticFeature, DynamicFeature } from './client';
export declare abstract class CommonLanguageClient extends BaseLanguageClient {
constructor(id: string, name: string, clientOptions: LanguageClientOptions);
registerProposedFeatures(): void;
protected registerBuiltinFeatures(): void;
}
export declare namespace ProposedFeatures {
function createAll(_client: BaseLanguageClient): (StaticFeature | DynamicFeature<any>)[];
}

View File

@@ -0,0 +1,61 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProposedFeatures = exports.CommonLanguageClient = void 0;
const client_1 = require("./client");
const colorProvider_1 = require("./colorProvider");
const configuration_1 = require("./configuration");
const implementation_1 = require("./implementation");
const typeDefinition_1 = require("./typeDefinition");
const workspaceFolders_1 = require("./workspaceFolders");
const foldingRange_1 = require("./foldingRange");
const declaration_1 = require("./declaration");
const selectionRange_1 = require("./selectionRange");
const progress_1 = require("./progress");
const callHierarchy_1 = require("./callHierarchy");
const semanticTokens_1 = require("./semanticTokens");
const fileOperations_1 = require("./fileOperations");
const linkedEditingRange_1 = require("./linkedEditingRange");
class CommonLanguageClient extends client_1.BaseLanguageClient {
constructor(id, name, clientOptions) {
super(id, name, clientOptions);
}
registerProposedFeatures() {
this.registerFeatures(ProposedFeatures.createAll(this));
}
registerBuiltinFeatures() {
super.registerBuiltinFeatures();
this.registerFeature(new configuration_1.ConfigurationFeature(this));
this.registerFeature(new typeDefinition_1.TypeDefinitionFeature(this));
this.registerFeature(new implementation_1.ImplementationFeature(this));
this.registerFeature(new colorProvider_1.ColorProviderFeature(this));
this.registerFeature(new workspaceFolders_1.WorkspaceFoldersFeature(this));
this.registerFeature(new foldingRange_1.FoldingRangeFeature(this));
this.registerFeature(new declaration_1.DeclarationFeature(this));
this.registerFeature(new selectionRange_1.SelectionRangeFeature(this));
this.registerFeature(new progress_1.ProgressFeature(this));
this.registerFeature(new callHierarchy_1.CallHierarchyFeature(this));
this.registerFeature(new semanticTokens_1.SemanticTokensFeature(this));
this.registerFeature(new linkedEditingRange_1.LinkedEditingFeature(this));
this.registerFeature(new fileOperations_1.DidCreateFilesFeature(this));
this.registerFeature(new fileOperations_1.DidRenameFilesFeature(this));
this.registerFeature(new fileOperations_1.DidDeleteFilesFeature(this));
this.registerFeature(new fileOperations_1.WillCreateFilesFeature(this));
this.registerFeature(new fileOperations_1.WillRenameFilesFeature(this));
this.registerFeature(new fileOperations_1.WillDeleteFilesFeature(this));
}
}
exports.CommonLanguageClient = CommonLanguageClient;
// Exporting proposed protocol.
var ProposedFeatures;
(function (ProposedFeatures) {
function createAll(_client) {
let result = [];
return result;
}
ProposedFeatures.createAll = createAll;
})(ProposedFeatures = exports.ProposedFeatures || (exports.ProposedFeatures = {}));
//# sourceMappingURL=commonClient.js.map

View File

@@ -0,0 +1,14 @@
import { StaticFeature, BaseLanguageClient } from './client';
import { ClientCapabilities, ConfigurationRequest } from 'vscode-languageserver-protocol';
export interface ConfigurationWorkspaceMiddleware {
configuration?: ConfigurationRequest.MiddlewareSignature;
}
export declare class ConfigurationFeature implements StaticFeature {
private _client;
constructor(_client: BaseLanguageClient);
fillClientCapabilities(capabilities: ClientCapabilities): void;
initialize(): void;
private getConfiguration;
dispose(): void;
}
export declare function toJSONObject(obj: any): any;

View File

@@ -0,0 +1,85 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.toJSONObject = exports.ConfigurationFeature = void 0;
const vscode_1 = require("vscode");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
class ConfigurationFeature {
constructor(_client) {
this._client = _client;
}
fillClientCapabilities(capabilities) {
capabilities.workspace = capabilities.workspace || {};
capabilities.workspace.configuration = true;
}
initialize() {
let client = this._client;
client.onRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, (params, token) => {
let configuration = (params) => {
let result = [];
for (let item of params.items) {
let resource = item.scopeUri !== void 0 && item.scopeUri !== null ? this._client.protocol2CodeConverter.asUri(item.scopeUri) : undefined;
result.push(this.getConfiguration(resource, item.section !== null ? item.section : undefined));
}
return result;
};
let middleware = client.clientOptions.middleware.workspace;
return middleware && middleware.configuration
? middleware.configuration(params, token, configuration)
: configuration(params, token);
});
}
getConfiguration(resource, section) {
let result = null;
if (section) {
let index = section.lastIndexOf('.');
if (index === -1) {
result = toJSONObject(vscode_1.workspace.getConfiguration(undefined, resource).get(section));
}
else {
let config = vscode_1.workspace.getConfiguration(section.substr(0, index), resource);
if (config) {
result = toJSONObject(config.get(section.substr(index + 1)));
}
}
}
else {
let config = vscode_1.workspace.getConfiguration(undefined, resource);
result = {};
for (let key of Object.keys(config)) {
if (config.has(key)) {
result[key] = toJSONObject(config.get(key));
}
}
}
if (result === undefined) {
result = null;
}
return result;
}
dispose() {
}
}
exports.ConfigurationFeature = ConfigurationFeature;
function toJSONObject(obj) {
if (obj) {
if (Array.isArray(obj)) {
return obj.map(toJSONObject);
}
else if (typeof obj === 'object') {
const res = Object.create(null);
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
res[key] = toJSONObject(obj[key]);
}
}
return res;
}
}
return obj;
}
exports.toJSONObject = toJSONObject;
//# sourceMappingURL=configuration.js.map

View File

@@ -0,0 +1,15 @@
import { Disposable, TextDocument, ProviderResult, Position as VPosition, Declaration as VDeclaration, DeclarationProvider } from 'vscode';
import { ClientCapabilities, CancellationToken, ServerCapabilities, DocumentSelector, DeclarationRegistrationOptions, DeclarationOptions } from 'vscode-languageserver-protocol';
import { TextDocumentFeature, BaseLanguageClient } from './client';
export interface ProvideDeclarationSignature {
(this: void, document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VDeclaration>;
}
export interface DeclarationMiddleware {
provideDeclaration?: (this: void, document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideDeclarationSignature) => ProviderResult<VDeclaration>;
}
export declare class DeclarationFeature extends TextDocumentFeature<boolean | DeclarationOptions, DeclarationRegistrationOptions, DeclarationProvider> {
constructor(client: BaseLanguageClient);
fillClientCapabilities(capabilities: ClientCapabilities): void;
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void;
protected registerLanguageProvider(options: DeclarationRegistrationOptions): [Disposable, DeclarationProvider];
}

View File

@@ -0,0 +1,52 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeclarationFeature = void 0;
const vscode_1 = require("vscode");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const client_1 = require("./client");
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = {};
}
return target[key];
}
class DeclarationFeature extends client_1.TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.DeclarationRequest.type);
}
fillClientCapabilities(capabilities) {
const declarationSupport = ensure(ensure(capabilities, 'textDocument'), 'declaration');
declarationSupport.dynamicRegistration = true;
declarationSupport.linkSupport = true;
}
initialize(capabilities, documentSelector) {
const [id, options] = this.getRegistration(documentSelector, capabilities.declarationProvider);
if (!id || !options) {
return;
}
this.register({ id: id, registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideDeclaration: (document, position, token) => {
const client = this._client;
const provideDeclaration = (document, position, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDeclarationResult, (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, error, null);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideDeclaration
? middleware.provideDeclaration(document, position, token, provideDeclaration)
: provideDeclaration(document, position, token);
}
};
return [vscode_1.languages.registerDeclarationProvider(options.documentSelector, provider), provider];
}
}
exports.DeclarationFeature = DeclarationFeature;
//# sourceMappingURL=declaration.js.map

View File

@@ -0,0 +1,94 @@
import * as code from 'vscode';
import * as proto from 'vscode-languageserver-protocol';
import { DynamicFeature, BaseLanguageClient, RegistrationData, NextSignature } from './client';
/**
* File operation middleware
*
* @since 3.16.0
*/
export interface FileOperationsMiddleware {
didCreateFiles?: NextSignature<code.FileCreateEvent, void>;
willCreateFiles?: NextSignature<code.FileCreateEvent, Thenable<code.WorkspaceEdit | null | undefined>>;
didRenameFiles?: NextSignature<code.FileRenameEvent, void>;
willRenameFiles?: NextSignature<code.FileRenameEvent, Thenable<code.WorkspaceEdit | null | undefined>>;
didDeleteFiles?: NextSignature<code.FileDeleteEvent, void>;
willDeleteFiles?: NextSignature<code.FileDeleteEvent, Thenable<code.WorkspaceEdit | null | undefined>>;
}
interface Event<I> {
readonly files: ReadonlyArray<I>;
}
declare abstract class FileOperationFeature<I, E extends Event<I>> implements DynamicFeature<proto.FileOperationRegistrationOptions> {
protected _client: BaseLanguageClient;
private _event;
private _registrationType;
private _clientCapability;
private _serverCapability;
private _listener;
private _filters;
constructor(client: BaseLanguageClient, event: code.Event<E>, registrationType: proto.RegistrationType<proto.FileOperationRegistrationOptions>, clientCapability: keyof proto.FileOperationClientCapabilities, serverCapability: keyof proto.FileOperationOptions);
get registrationType(): proto.RegistrationType<proto.FileOperationRegistrationOptions>;
fillClientCapabilities(capabilities: proto.ClientCapabilities): void;
initialize(capabilities: proto.ServerCapabilities): void;
register(data: RegistrationData<proto.FileOperationRegistrationOptions>): void;
abstract send(data: E): Promise<void>;
unregister(id: string): void;
dispose(): void;
protected filter(event: E, prop: (i: I) => code.Uri): Promise<E>;
private static getFileType;
private static asMinimatchOptions;
}
declare abstract class NotificationFileOperationFeature<I, E extends {
readonly files: ReadonlyArray<I>;
}, P> extends FileOperationFeature<I, E> {
private _notificationType;
private _accessUri;
private _createParams;
constructor(client: BaseLanguageClient, event: code.Event<E>, notificationType: proto.ProtocolNotificationType<P, proto.FileOperationRegistrationOptions>, clientCapability: keyof proto.FileOperationClientCapabilities, serverCapability: keyof proto.FileOperationOptions, accessUri: (i: I) => code.Uri, createParams: (e: E) => P);
send(originalEvent: E): Promise<void>;
protected abstract doSend(event: E, next: (event: E) => void): void;
}
export declare class DidCreateFilesFeature extends NotificationFileOperationFeature<code.Uri, code.FileCreateEvent, proto.CreateFilesParams> {
constructor(client: BaseLanguageClient);
protected doSend(event: code.FileCreateEvent, next: (event: code.FileCreateEvent) => void): void;
}
export declare class DidRenameFilesFeature extends NotificationFileOperationFeature<{
oldUri: code.Uri;
newUri: code.Uri;
}, code.FileRenameEvent, proto.RenameFilesParams> {
constructor(client: BaseLanguageClient);
protected doSend(event: code.FileRenameEvent, next: (event: code.FileRenameEvent) => void): void;
}
export declare class DidDeleteFilesFeature extends NotificationFileOperationFeature<code.Uri, code.FileDeleteEvent, proto.DeleteFilesParams> {
constructor(client: BaseLanguageClient);
protected doSend(event: code.FileCreateEvent, next: (event: code.FileCreateEvent) => void): void;
}
interface RequestEvent<I> {
readonly files: ReadonlyArray<I>;
waitUntil(thenable: Thenable<code.WorkspaceEdit>): void;
waitUntil(thenable: Thenable<any>): void;
}
declare abstract class RequestFileOperationFeature<I, E extends RequestEvent<I>, P> extends FileOperationFeature<I, E> {
private _requestType;
private _accessUri;
private _createParams;
constructor(client: BaseLanguageClient, event: code.Event<E>, requestType: proto.ProtocolRequestType<P, proto.WorkspaceEdit | null, never, void, proto.FileOperationRegistrationOptions>, clientCapability: keyof proto.FileOperationClientCapabilities, serverCapability: keyof proto.FileOperationOptions, accessUri: (i: I) => code.Uri, createParams: (e: Event<I>) => P);
send(originalEvent: E & RequestEvent<I>): Promise<void>;
private waitUntil;
protected abstract doSend(event: E, next: (event: Event<I>) => Thenable<code.WorkspaceEdit> | Thenable<any>): Thenable<code.WorkspaceEdit> | Thenable<any>;
}
export declare class WillCreateFilesFeature extends RequestFileOperationFeature<code.Uri, code.FileWillCreateEvent, proto.CreateFilesParams> {
constructor(client: BaseLanguageClient);
protected doSend(event: code.FileWillCreateEvent, next: (event: code.FileCreateEvent) => Thenable<code.WorkspaceEdit> | Thenable<any>): Thenable<code.WorkspaceEdit> | Thenable<any>;
}
export declare class WillRenameFilesFeature extends RequestFileOperationFeature<{
oldUri: code.Uri;
newUri: code.Uri;
}, code.FileWillRenameEvent, proto.RenameFilesParams> {
constructor(client: BaseLanguageClient);
protected doSend(event: code.FileWillRenameEvent, next: (event: code.FileRenameEvent) => Thenable<code.WorkspaceEdit> | Thenable<any>): Thenable<code.WorkspaceEdit> | Thenable<any>;
}
export declare class WillDeleteFilesFeature extends RequestFileOperationFeature<code.Uri, code.FileWillDeleteEvent, proto.DeleteFilesParams> {
constructor(client: BaseLanguageClient);
protected doSend(event: code.FileWillDeleteEvent, next: (event: code.FileDeleteEvent) => Thenable<code.WorkspaceEdit> | Thenable<any>): Thenable<code.WorkspaceEdit> | Thenable<any>;
}
export {};

View File

@@ -0,0 +1,264 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.WillDeleteFilesFeature = exports.WillRenameFilesFeature = exports.WillCreateFilesFeature = exports.DidDeleteFilesFeature = exports.DidRenameFilesFeature = exports.DidCreateFilesFeature = void 0;
const code = require("vscode");
const minimatch = require("minimatch");
const proto = require("vscode-languageserver-protocol");
const UUID = require("./utils/uuid");
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = {};
}
return target[key];
}
function access(target, key) {
return target[key];
}
function assign(target, key, value) {
target[key] = value;
}
class FileOperationFeature {
constructor(client, event, registrationType, clientCapability, serverCapability) {
this._filters = new Map();
this._client = client;
this._event = event;
this._registrationType = registrationType;
this._clientCapability = clientCapability;
this._serverCapability = serverCapability;
}
get registrationType() {
return this._registrationType;
}
fillClientCapabilities(capabilities) {
const value = ensure(ensure(capabilities, 'workspace'), 'fileOperations');
// this happens n times but it is the same value so we tolerate this.
assign(value, 'dynamicRegistration', true);
assign(value, this._clientCapability, true);
}
initialize(capabilities) {
var _a;
const options = (_a = capabilities.workspace) === null || _a === void 0 ? void 0 : _a.fileOperations;
const capability = options !== undefined ? access(options, this._serverCapability) : undefined;
if ((capability === null || capability === void 0 ? void 0 : capability.filters) !== undefined) {
try {
this.register({
id: UUID.generateUuid(),
registerOptions: { filters: capability.filters }
});
}
catch (e) {
this._client.warn(`Ignoring invalid glob pattern for ${this._serverCapability} registration: ${e}`);
}
}
}
register(data) {
if (!this._listener) {
this._listener = this._event(this.send, this);
}
const minimatchFilter = data.registerOptions.filters.map((filter) => {
const matcher = new minimatch.Minimatch(filter.pattern.glob, FileOperationFeature.asMinimatchOptions(filter.pattern.options));
if (!matcher.makeRe()) {
throw new Error(`Invalid pattern ${filter.pattern.glob}!`);
}
return { scheme: filter.scheme, matcher, kind: filter.pattern.matches };
});
this._filters.set(data.id, minimatchFilter);
}
unregister(id) {
this._filters.delete(id);
if (this._filters.size === 0 && this._listener) {
this._listener.dispose();
this._listener = undefined;
}
}
dispose() {
this._filters.clear();
if (this._listener) {
this._listener.dispose();
this._listener = undefined;
}
}
async filter(event, prop) {
// (Asynchronously) map each file onto a boolean of whether it matches
// any of the globs.
const fileMatches = await Promise.all(event.files.map(async (item) => {
const uri = prop(item);
// Use fsPath to make this consistent with file system watchers but help
// minimatch to use '/' instead of `\\` if present.
const path = uri.fsPath.replace(/\\/g, '/');
for (const filters of this._filters.values()) {
for (const filter of filters) {
if (filter.scheme !== undefined && filter.scheme !== uri.scheme) {
continue;
}
if (filter.matcher.match(path)) {
// The pattern matches. If kind is undefined then everything is ok
if (filter.kind === undefined) {
return true;
}
const fileType = await FileOperationFeature.getFileType(uri);
// If we can't determine the file type than we treat it as a match.
// Dropping it would be another alternative.
if (fileType === undefined) {
this._client.error(`Failed to determine file type for ${uri.toString()}.`);
return true;
}
if ((fileType === code.FileType.File && filter.kind === proto.FileOperationPatternKind.file) || (fileType === code.FileType.Directory && filter.kind === proto.FileOperationPatternKind.folder)) {
return true;
}
}
else if (filter.kind === proto.FileOperationPatternKind.folder) {
const fileType = await FileOperationFeature.getFileType(uri);
if (fileType === code.FileType.Directory && filter.matcher.match(`${path}/`)) {
return true;
}
}
}
}
return false;
}));
// Filter the files to those that matched.
const files = event.files.filter((_, index) => fileMatches[index]);
return Object.assign(Object.assign({}, event), { files });
}
static async getFileType(uri) {
try {
return (await code.workspace.fs.stat(uri)).type;
}
catch (e) {
return undefined;
}
}
static asMinimatchOptions(options) {
if (options === undefined) {
return undefined;
}
if (options.ignoreCase === true) {
return { nocase: true };
}
return undefined;
}
}
class NotificationFileOperationFeature extends FileOperationFeature {
constructor(client, event, notificationType, clientCapability, serverCapability, accessUri, createParams) {
super(client, event, notificationType, clientCapability, serverCapability);
this._notificationType = notificationType;
this._accessUri = accessUri;
this._createParams = createParams;
}
async send(originalEvent) {
// Create a copy of the event that has the files filtered to match what the
// server wants.
const filteredEvent = await this.filter(originalEvent, this._accessUri);
if (filteredEvent.files.length) {
const next = async (event) => {
this._client.sendNotification(this._notificationType, this._createParams(event));
};
this.doSend(filteredEvent, next);
}
}
}
class DidCreateFilesFeature extends NotificationFileOperationFeature {
constructor(client) {
super(client, code.workspace.onDidCreateFiles, proto.DidCreateFilesNotification.type, 'didCreate', 'didCreate', (i) => i, client.code2ProtocolConverter.asDidCreateFilesParams);
}
doSend(event, next) {
var _a;
const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace;
return (middleware === null || middleware === void 0 ? void 0 : middleware.didCreateFiles) ? middleware.didCreateFiles(event, next)
: next(event);
}
}
exports.DidCreateFilesFeature = DidCreateFilesFeature;
class DidRenameFilesFeature extends NotificationFileOperationFeature {
constructor(client) {
super(client, code.workspace.onDidRenameFiles, proto.DidRenameFilesNotification.type, 'didRename', 'didRename', (i) => i.oldUri, client.code2ProtocolConverter.asDidRenameFilesParams);
}
doSend(event, next) {
var _a;
const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace;
return (middleware === null || middleware === void 0 ? void 0 : middleware.didRenameFiles) ? middleware.didRenameFiles(event, next)
: next(event);
}
}
exports.DidRenameFilesFeature = DidRenameFilesFeature;
class DidDeleteFilesFeature extends NotificationFileOperationFeature {
constructor(client) {
super(client, code.workspace.onDidDeleteFiles, proto.DidDeleteFilesNotification.type, 'didDelete', 'didDelete', (i) => i, client.code2ProtocolConverter.asDidDeleteFilesParams);
}
doSend(event, next) {
var _a;
const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace;
return (middleware === null || middleware === void 0 ? void 0 : middleware.didDeleteFiles) ? middleware.didDeleteFiles(event, next)
: next(event);
}
}
exports.DidDeleteFilesFeature = DidDeleteFilesFeature;
class RequestFileOperationFeature extends FileOperationFeature {
constructor(client, event, requestType, clientCapability, serverCapability, accessUri, createParams) {
super(client, event, requestType, clientCapability, serverCapability);
this._requestType = requestType;
this._accessUri = accessUri;
this._createParams = createParams;
}
async send(originalEvent) {
const waitUntil = this.waitUntil(originalEvent);
originalEvent.waitUntil(waitUntil);
}
async waitUntil(originalEvent) {
// Create a copy of the event that has the files filtered to match what the
// server wants.
const filteredEvent = await this.filter(originalEvent, this._accessUri);
if (filteredEvent.files.length) {
const next = (event) => {
return this._client.sendRequest(this._requestType, this._createParams(event))
.then(this._client.protocol2CodeConverter.asWorkspaceEdit);
};
return this.doSend(filteredEvent, next);
}
else {
return undefined;
}
}
}
class WillCreateFilesFeature extends RequestFileOperationFeature {
constructor(client) {
super(client, code.workspace.onWillCreateFiles, proto.WillCreateFilesRequest.type, 'willCreate', 'willCreate', (i) => i, client.code2ProtocolConverter.asWillCreateFilesParams);
}
doSend(event, next) {
var _a;
const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace;
return (middleware === null || middleware === void 0 ? void 0 : middleware.willCreateFiles) ? middleware.willCreateFiles(event, next)
: next(event);
}
}
exports.WillCreateFilesFeature = WillCreateFilesFeature;
class WillRenameFilesFeature extends RequestFileOperationFeature {
constructor(client) {
super(client, code.workspace.onWillRenameFiles, proto.WillRenameFilesRequest.type, 'willRename', 'willRename', (i) => i.oldUri, client.code2ProtocolConverter.asWillRenameFilesParams);
}
doSend(event, next) {
var _a;
const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace;
return (middleware === null || middleware === void 0 ? void 0 : middleware.willRenameFiles) ? middleware.willRenameFiles(event, next)
: next(event);
}
}
exports.WillRenameFilesFeature = WillRenameFilesFeature;
class WillDeleteFilesFeature extends RequestFileOperationFeature {
constructor(client) {
super(client, code.workspace.onWillDeleteFiles, proto.WillDeleteFilesRequest.type, 'willDelete', 'willDelete', (i) => i, client.code2ProtocolConverter.asWillDeleteFilesParams);
}
doSend(event, next) {
var _a;
const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace;
return (middleware === null || middleware === void 0 ? void 0 : middleware.willDeleteFiles) ? middleware.willDeleteFiles(event, next)
: next(event);
}
}
exports.WillDeleteFilesFeature = WillDeleteFilesFeature;
//# sourceMappingURL=fileOperations.js.map

View File

@@ -0,0 +1,17 @@
import { Disposable, TextDocument, ProviderResult, FoldingRange as VFoldingRange, FoldingContext, FoldingRangeProvider } from 'vscode';
import { ClientCapabilities, CancellationToken, ServerCapabilities, DocumentSelector, FoldingRangeRegistrationOptions, FoldingRangeOptions } from 'vscode-languageserver-protocol';
import { TextDocumentFeature, BaseLanguageClient } from './client';
export interface ProvideFoldingRangeSignature {
(this: void, document: TextDocument, context: FoldingContext, token: CancellationToken): ProviderResult<VFoldingRange[]>;
}
export interface FoldingRangeProviderMiddleware {
provideFoldingRanges?: (this: void, document: TextDocument, context: FoldingContext, token: CancellationToken, next: ProvideFoldingRangeSignature) => ProviderResult<VFoldingRange[]>;
}
export declare class FoldingRangeFeature extends TextDocumentFeature<boolean | FoldingRangeOptions, FoldingRangeRegistrationOptions, FoldingRangeProvider> {
constructor(client: BaseLanguageClient);
fillClientCapabilities(capabilities: ClientCapabilities): void;
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void;
protected registerLanguageProvider(options: FoldingRangeRegistrationOptions): [Disposable, FoldingRangeProvider];
private static asFoldingRangeKind;
private static asFoldingRanges;
}

View File

@@ -0,0 +1,77 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.FoldingRangeFeature = void 0;
const vscode_1 = require("vscode");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const client_1 = require("./client");
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = {};
}
return target[key];
}
class FoldingRangeFeature extends client_1.TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.FoldingRangeRequest.type);
}
fillClientCapabilities(capabilities) {
let capability = ensure(ensure(capabilities, 'textDocument'), 'foldingRange');
capability.dynamicRegistration = true;
capability.rangeLimit = 5000;
capability.lineFoldingOnly = true;
}
initialize(capabilities, documentSelector) {
let [id, options] = this.getRegistration(documentSelector, capabilities.foldingRangeProvider);
if (!id || !options) {
return;
}
this.register({ id: id, registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideFoldingRanges: (document, context, token) => {
const client = this._client;
const provideFoldingRanges = (document, _, token) => {
const requestParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)
};
return client.sendRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, requestParams, token).then(FoldingRangeFeature.asFoldingRanges, (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, error, null);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideFoldingRanges
? middleware.provideFoldingRanges(document, context, token, provideFoldingRanges)
: provideFoldingRanges(document, context, token);
}
};
return [vscode_1.languages.registerFoldingRangeProvider(options.documentSelector, provider), provider];
}
static asFoldingRangeKind(kind) {
if (kind) {
switch (kind) {
case vscode_languageserver_protocol_1.FoldingRangeKind.Comment:
return vscode_1.FoldingRangeKind.Comment;
case vscode_languageserver_protocol_1.FoldingRangeKind.Imports:
return vscode_1.FoldingRangeKind.Imports;
case vscode_languageserver_protocol_1.FoldingRangeKind.Region:
return vscode_1.FoldingRangeKind.Region;
}
}
return void 0;
}
static asFoldingRanges(foldingRanges) {
if (Array.isArray(foldingRanges)) {
return foldingRanges.map(r => {
return new vscode_1.FoldingRange(r.startLine, r.endLine, FoldingRangeFeature.asFoldingRangeKind(r.kind));
});
}
return [];
}
}
exports.FoldingRangeFeature = FoldingRangeFeature;
//# sourceMappingURL=foldingRange.js.map

View File

@@ -0,0 +1,15 @@
import { Disposable, TextDocument, ProviderResult, Position as VPosition, Definition as VDefinition, DefinitionLink as VDefinitionLink, ImplementationProvider } from 'vscode';
import { ClientCapabilities, CancellationToken, ServerCapabilities, DocumentSelector, ImplementationRegistrationOptions, ImplementationOptions } from 'vscode-languageserver-protocol';
import { TextDocumentFeature, BaseLanguageClient } from './client';
export interface ProvideImplementationSignature {
(this: void, document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VDefinition | VDefinitionLink[]>;
}
export interface ImplementationMiddleware {
provideImplementation?: (this: void, document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideImplementationSignature) => ProviderResult<VDefinition | VDefinitionLink[]>;
}
export declare class ImplementationFeature extends TextDocumentFeature<boolean | ImplementationOptions, ImplementationRegistrationOptions, ImplementationProvider> {
constructor(client: BaseLanguageClient);
fillClientCapabilities(capabilities: ClientCapabilities): void;
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void;
protected registerLanguageProvider(options: ImplementationRegistrationOptions): [Disposable, ImplementationProvider];
}

View File

@@ -0,0 +1,52 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImplementationFeature = void 0;
const vscode_1 = require("vscode");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const client_1 = require("./client");
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = {};
}
return target[key];
}
class ImplementationFeature extends client_1.TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.ImplementationRequest.type);
}
fillClientCapabilities(capabilities) {
let implementationSupport = ensure(ensure(capabilities, 'textDocument'), 'implementation');
implementationSupport.dynamicRegistration = true;
implementationSupport.linkSupport = true;
}
initialize(capabilities, documentSelector) {
let [id, options] = this.getRegistration(documentSelector, capabilities.implementationProvider);
if (!id || !options) {
return;
}
this.register({ id: id, registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideImplementation: (document, position, token) => {
const client = this._client;
const provideImplementation = (document, position, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDefinitionResult, (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, error, null);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideImplementation
? middleware.provideImplementation(document, position, token, provideImplementation)
: provideImplementation(document, position, token);
}
};
return [vscode_1.languages.registerImplementationProvider(options.documentSelector, provider), provider];
}
}
exports.ImplementationFeature = ImplementationFeature;
//# sourceMappingURL=implementation.js.map

View File

@@ -0,0 +1,21 @@
/// <reference path="../../typings/vscode-proposed.d.ts" />
import * as code from 'vscode';
import * as proto from 'vscode-languageserver-protocol';
import { TextDocumentFeature, BaseLanguageClient } from './client';
export interface ProvideLinkedEditingRangeSignature {
(this: void, document: code.TextDocument, position: code.Position, token: code.CancellationToken): code.ProviderResult<code.LinkedEditingRanges>;
}
/**
* Linked editing middleware
*
* @since 3.16.0
*/
export interface LinkedEditingRangeMiddleware {
provideLinkedEditingRange?: (this: void, document: code.TextDocument, position: code.Position, token: code.CancellationToken, next: ProvideLinkedEditingRangeSignature) => code.ProviderResult<code.LinkedEditingRanges>;
}
export declare class LinkedEditingFeature extends TextDocumentFeature<boolean | proto.LinkedEditingRangeOptions, proto.LinkedEditingRangeRegistrationOptions, code.LinkedEditingRangeProvider> {
constructor(client: BaseLanguageClient);
fillClientCapabilities(capabilities: proto.ClientCapabilities): void;
initialize(capabilities: proto.ServerCapabilities, documentSelector: proto.DocumentSelector): void;
protected registerLanguageProvider(options: proto.LinkedEditingRangeRegistrationOptions): [code.Disposable, code.LinkedEditingRangeProvider];
}

View File

@@ -0,0 +1,52 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
/// <reference path="../../typings/vscode-proposed.d.ts" />
Object.defineProperty(exports, "__esModule", { value: true });
exports.LinkedEditingFeature = void 0;
const code = require("vscode");
const proto = require("vscode-languageserver-protocol");
const client_1 = require("./client");
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = {};
}
return target[key];
}
class LinkedEditingFeature extends client_1.TextDocumentFeature {
constructor(client) {
super(client, proto.LinkedEditingRangeRequest.type);
}
fillClientCapabilities(capabilities) {
const linkedEditingSupport = ensure(ensure(capabilities, 'textDocument'), 'linkedEditingRange');
linkedEditingSupport.dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
let [id, options] = this.getRegistration(documentSelector, capabilities.linkedEditingRangeProvider);
if (!id || !options) {
return;
}
this.register({ id: id, registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideLinkedEditingRanges: (document, position, token) => {
const client = this._client;
const provideLinkedEditing = (document, position, token) => {
return client.sendRequest(proto.LinkedEditingRangeRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asLinkedEditingRanges, (error) => {
return client.handleFailedRequest(proto.LinkedEditingRangeRequest.type, error, null);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideLinkedEditingRange
? middleware.provideLinkedEditingRange(document, position, token, provideLinkedEditing)
: provideLinkedEditing(document, position, token);
}
};
return [code.languages.registerLinkedEditingRangeProvider(options.documentSelector, provider), provider];
}
}
exports.LinkedEditingFeature = LinkedEditingFeature;
//# sourceMappingURL=linkedEditingRange.js.map

View File

@@ -0,0 +1,10 @@
import { ClientCapabilities } from 'vscode-languageserver-protocol';
import { BaseLanguageClient, StaticFeature } from './client';
export declare class ProgressFeature implements StaticFeature {
private _client;
private activeParts;
constructor(_client: BaseLanguageClient);
fillClientCapabilities(capabilities: ClientCapabilities): void;
initialize(): void;
dispose(): void;
}

View File

@@ -0,0 +1,42 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProgressFeature = void 0;
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const progressPart_1 = require("./progressPart");
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = Object.create(null);
}
return target[key];
}
class ProgressFeature {
constructor(_client) {
this._client = _client;
this.activeParts = new Set();
}
fillClientCapabilities(capabilities) {
ensure(capabilities, 'window').workDoneProgress = true;
}
initialize() {
const client = this._client;
const deleteHandler = (part) => {
this.activeParts.delete(part);
};
const createHandler = (params) => {
this.activeParts.add(new progressPart_1.ProgressPart(this._client, params.token, deleteHandler));
};
client.onRequest(vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.type, createHandler);
}
dispose() {
for (const part of this.activeParts) {
part.done();
}
this.activeParts.clear();
}
}
exports.ProgressFeature = ProgressFeature;
//# sourceMappingURL=progress.js.map

View File

@@ -0,0 +1,22 @@
import { Disposable } from 'vscode';
import { ProgressToken, ProgressType, NotificationHandler, ProtocolNotificationType } from 'vscode-languageserver-protocol';
export interface ProgressContext {
onProgress<P>(type: ProgressType<P>, token: string | number, handler: NotificationHandler<P>): Disposable;
sendNotification<P, RO>(type: ProtocolNotificationType<P, RO>, params?: P): void;
}
export declare class ProgressPart {
private _client;
private _token;
private _infinite;
private _reported;
private _progress;
private _cancellationToken;
private _disposable;
private _resolve;
private _reject;
constructor(_client: ProgressContext, _token: ProgressToken, done?: (part: ProgressPart) => void);
private begin;
private report;
cancel(): void;
done(): void;
}

View File

@@ -0,0 +1,82 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProgressPart = void 0;
const vscode_1 = require("vscode");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const Is = require("./utils/is");
class ProgressPart {
constructor(_client, _token, done) {
this._client = _client;
this._token = _token;
this._reported = 0;
this._disposable = this._client.onProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, (value) => {
switch (value.kind) {
case 'begin':
this.begin(value);
break;
case 'report':
this.report(value);
break;
case 'end':
this.done();
done && done(this);
break;
}
});
}
begin(params) {
// Since we don't use commands this will be a silent window progress with a hidden notification.
vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Window, cancellable: params.cancellable, title: params.title }, async (progress, cancellationToken) => {
this._progress = progress;
this._infinite = params.percentage === undefined;
this._cancellationToken = cancellationToken;
this._cancellationToken.onCancellationRequested(() => {
this._client.sendNotification(vscode_languageserver_protocol_1.WorkDoneProgressCancelNotification.type, { token: this._token });
});
this.report(params);
return new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
});
}
report(params) {
if (this._infinite && Is.string(params.message)) {
this._progress.report({ message: params.message });
}
else if (Is.number(params.percentage)) {
let percentage = Math.max(0, Math.min(params.percentage, 100));
let delta = Math.max(0, percentage - this._reported);
this._progress.report({ message: params.message, increment: delta });
this._reported += delta;
}
}
cancel() {
if (this._disposable) {
this._disposable.dispose();
this._disposable = undefined;
}
if (this._reject) {
this._reject();
this._resolve = undefined;
this._reject = undefined;
}
}
done() {
if (this._disposable) {
this._disposable.dispose();
this._disposable = undefined;
}
if (this._resolve) {
this._resolve();
this._resolve = undefined;
this._reject = undefined;
}
}
}
exports.ProgressPart = ProgressPart;
//# sourceMappingURL=progressPart.js.map

View File

@@ -0,0 +1,5 @@
import * as code from 'vscode';
export default class ProtocolCallHierarchyItem extends code.CallHierarchyItem {
data?: unknown;
constructor(kind: code.SymbolKind, name: string, detail: string, uri: code.Uri, range: code.Range, selectionRange: code.Range, data?: unknown);
}

View File

@@ -0,0 +1,17 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
const code = require("vscode");
class ProtocolCallHierarchyItem extends code.CallHierarchyItem {
constructor(kind, name, detail, uri, range, selectionRange, data) {
super(kind, name, detail, uri, range, selectionRange);
if (data !== undefined) {
this.data = data;
}
}
}
exports.default = ProtocolCallHierarchyItem;
//# sourceMappingURL=protocolCallHierarchyItem.js.map

View File

@@ -0,0 +1,5 @@
import * as vscode from 'vscode';
export default class ProtocolCodeAction extends vscode.CodeAction {
readonly data: unknown | undefined;
constructor(title: string, data: unknown | undefined);
}

View File

@@ -0,0 +1,15 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
const vscode = require("vscode");
class ProtocolCodeAction extends vscode.CodeAction {
constructor(title, data) {
super(title);
this.data = data;
}
}
exports.default = ProtocolCodeAction;
//# sourceMappingURL=protocolCodeAction.js.map

View File

@@ -0,0 +1,5 @@
import * as code from 'vscode';
export default class ProtocolCodeLens extends code.CodeLens {
data: any;
constructor(range: code.Range);
}

View File

@@ -0,0 +1,14 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
const code = require("vscode");
class ProtocolCodeLens extends code.CodeLens {
constructor(range) {
super(range);
}
}
exports.default = ProtocolCodeLens;
//# sourceMappingURL=protocolCodeLens.js.map

View File

@@ -0,0 +1,11 @@
import * as code from 'vscode';
import * as proto from 'vscode-languageserver-protocol';
export default class ProtocolCompletionItem extends code.CompletionItem {
data: any;
fromEdit: boolean | undefined;
documentationFormat: string | undefined;
originalItemKind: proto.CompletionItemKind | undefined;
deprecated: boolean | undefined;
insertTextMode: proto.InsertTextMode | undefined;
constructor(label: string);
}

View File

@@ -0,0 +1,14 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
const code = require("vscode");
class ProtocolCompletionItem extends code.CompletionItem {
constructor(label) {
super(label);
}
}
exports.default = ProtocolCompletionItem;
//# sourceMappingURL=protocolCompletionItem.js.map

View File

@@ -0,0 +1,152 @@
/// <reference path="../../typings/vscode-proposed.d.ts" />
import * as code from 'vscode';
import * as ls from 'vscode-languageserver-protocol';
import ProtocolCompletionItem from './protocolCompletionItem';
export interface Converter {
asUri(value: string): code.Uri;
asDiagnostic(diagnostic: ls.Diagnostic): code.Diagnostic;
asDiagnostics(diagnostics: ls.Diagnostic[]): code.Diagnostic[];
asPosition(value: undefined | null): undefined;
asPosition(value: ls.Position): code.Position;
asPosition(value: ls.Position | undefined | null): code.Position | undefined;
asRange(value: undefined | null): undefined;
asRange(value: ls.Range): code.Range;
asRange(value: ls.Range | undefined | null): code.Range | undefined;
asRanges(values: ls.Range[]): code.Range[];
asDiagnosticSeverity(value: number | undefined | null): code.DiagnosticSeverity;
asDiagnosticTag(tag: ls.DiagnosticTag): code.DiagnosticTag | undefined;
asHover(hover: ls.Hover): code.Hover;
asHover(hover: undefined | null): undefined;
asHover(hover: ls.Hover | undefined | null): code.Hover | undefined;
asCompletionResult(result: ls.CompletionList): code.CompletionList;
asCompletionResult(result: ls.CompletionItem[]): code.CompletionItem[];
asCompletionResult(result: undefined | null): undefined;
asCompletionResult(result: ls.CompletionItem[] | ls.CompletionList | undefined | null): code.CompletionItem[] | code.CompletionList | undefined;
asCompletionItem(item: ls.CompletionItem): ProtocolCompletionItem;
asTextEdit(edit: undefined | null): undefined;
asTextEdit(edit: ls.TextEdit): code.TextEdit;
asTextEdit(edit: ls.TextEdit | undefined | null): code.TextEdit | undefined;
asTextEdits(items: ls.TextEdit[]): code.TextEdit[];
asTextEdits(items: undefined | null): undefined;
asTextEdits(items: ls.TextEdit[] | undefined | null): code.TextEdit[] | undefined;
asSignatureHelp(item: undefined | null): undefined;
asSignatureHelp(item: ls.SignatureHelp): code.SignatureHelp;
asSignatureHelp(item: ls.SignatureHelp | undefined | null): code.SignatureHelp | undefined;
asSignatureInformation(item: ls.SignatureInformation): code.SignatureInformation;
asSignatureInformations(items: ls.SignatureInformation[]): code.SignatureInformation[];
asParameterInformation(item: ls.ParameterInformation): code.ParameterInformation;
asParameterInformations(item: ls.ParameterInformation[]): code.ParameterInformation[];
asLocation(item: ls.Location): code.Location;
asLocation(item: undefined | null): undefined;
asLocation(item: ls.Location | undefined | null): code.Location | undefined;
asDeclarationResult(item: ls.Declaration): code.Location | code.Location[];
asDeclarationResult(item: ls.DeclarationLink[]): code.LocationLink[];
asDeclarationResult(item: undefined | null): undefined;
asDeclarationResult(item: ls.Declaration | ls.DeclarationLink[] | undefined | null): code.Declaration | undefined;
asDefinitionResult(item: ls.Definition): code.Definition;
asDefinitionResult(item: ls.DefinitionLink[]): code.DefinitionLink[];
asDefinitionResult(item: undefined | null): undefined;
asDefinitionResult(item: ls.Definition | ls.DefinitionLink[] | undefined | null): code.Definition | code.DefinitionLink[] | undefined;
asReferences(values: ls.Location[]): code.Location[];
asReferences(values: undefined | null): code.Location[] | undefined;
asReferences(values: ls.Location[] | undefined | null): code.Location[] | undefined;
asDocumentHighlightKind(item: number): code.DocumentHighlightKind;
asDocumentHighlight(item: ls.DocumentHighlight): code.DocumentHighlight;
asDocumentHighlights(values: ls.DocumentHighlight[]): code.DocumentHighlight[];
asDocumentHighlights(values: undefined | null): undefined;
asDocumentHighlights(values: ls.DocumentHighlight[] | undefined | null): code.DocumentHighlight[] | undefined;
asSymbolKind(item: ls.SymbolKind): code.SymbolKind;
asSymbolTag(item: ls.SymbolTag): code.SymbolTag | undefined;
asSymbolTags(items: undefined | null): undefined;
asSymbolTags(items: ReadonlyArray<ls.SymbolTag>): code.SymbolTag[];
asSymbolTags(items: ReadonlyArray<ls.SymbolTag> | undefined | null): code.SymbolTag[] | undefined;
asSymbolInformation(item: ls.SymbolInformation, uri?: code.Uri): code.SymbolInformation;
asSymbolInformations(values: ls.SymbolInformation[], uri?: code.Uri): code.SymbolInformation[];
asSymbolInformations(values: undefined | null, uri?: code.Uri): undefined;
asSymbolInformations(values: ls.SymbolInformation[] | undefined | null, uri?: code.Uri): code.SymbolInformation[] | undefined;
asDocumentSymbol(value: ls.DocumentSymbol): code.DocumentSymbol;
asDocumentSymbols(value: undefined | null): undefined;
asDocumentSymbols(value: ls.DocumentSymbol[]): code.DocumentSymbol[];
asDocumentSymbols(value: ls.DocumentSymbol[] | undefined | null): code.DocumentSymbol[] | undefined;
asCommand(item: ls.Command): code.Command;
asCommands(items: ls.Command[]): code.Command[];
asCommands(items: undefined | null): undefined;
asCommands(items: ls.Command[] | undefined | null): code.Command[] | undefined;
asCodeAction(item: ls.CodeAction): code.CodeAction;
asCodeAction(item: undefined | null): undefined;
asCodeAction(item: ls.CodeAction | undefined | null): code.CodeAction | undefined;
asCodeActionKind(item: null | undefined): undefined;
asCodeActionKind(item: ls.CodeActionKind): code.CodeActionKind;
asCodeActionKind(item: ls.CodeActionKind | null | undefined): code.CodeActionKind | undefined;
asCodeActionKinds(item: null | undefined): undefined;
asCodeActionKinds(items: ls.CodeActionKind[]): code.CodeActionKind[];
asCodeActionKinds(item: ls.CodeActionKind[] | null | undefined): code.CodeActionKind[] | undefined;
asCodeLens(item: ls.CodeLens): code.CodeLens;
asCodeLens(item: undefined | null): undefined;
asCodeLens(item: ls.CodeLens | undefined | null): code.CodeLens | undefined;
asCodeLenses(items: ls.CodeLens[]): code.CodeLens[];
asCodeLenses(items: undefined | null): undefined;
asCodeLenses(items: ls.CodeLens[] | undefined | null): code.CodeLens[] | undefined;
asWorkspaceEdit(item: ls.WorkspaceEdit): code.WorkspaceEdit;
asWorkspaceEdit(item: undefined | null): undefined;
asWorkspaceEdit(item: ls.WorkspaceEdit | undefined | null): code.WorkspaceEdit | undefined;
asDocumentLink(item: ls.DocumentLink): code.DocumentLink;
asDocumentLinks(items: ls.DocumentLink[]): code.DocumentLink[];
asDocumentLinks(items: undefined | null): undefined;
asDocumentLinks(items: ls.DocumentLink[] | undefined | null): code.DocumentLink[] | undefined;
asColor(color: ls.Color): code.Color;
asColorInformation(ci: ls.ColorInformation): code.ColorInformation;
asColorInformations(colorPresentations: ls.ColorInformation[]): code.ColorInformation[];
asColorInformations(colorPresentations: undefined | null): undefined;
asColorInformations(colorInformation: ls.ColorInformation[] | undefined | null): code.ColorInformation[];
asColorPresentation(cp: ls.ColorPresentation): code.ColorPresentation;
asColorPresentations(colorPresentations: ls.ColorPresentation[]): code.ColorPresentation[];
asColorPresentations(colorPresentations: undefined | null): undefined;
asColorPresentations(colorPresentations: ls.ColorPresentation[] | undefined | null): undefined;
asFoldingRangeKind(kind: string | undefined): code.FoldingRangeKind | undefined;
asFoldingRange(r: ls.FoldingRange): code.FoldingRange;
asFoldingRanges(foldingRanges: ls.FoldingRange[]): code.FoldingRange[];
asFoldingRanges(foldingRanges: undefined | null): undefined;
asFoldingRanges(foldingRanges: ls.FoldingRange[] | undefined | null): code.FoldingRange[] | undefined;
asFoldingRanges(foldingRanges: ls.FoldingRange[] | undefined | null): code.FoldingRange[] | undefined;
asSelectionRange(selectionRange: ls.SelectionRange): code.SelectionRange;
asSelectionRanges(selectionRanges: ls.SelectionRange[]): code.SelectionRange[];
asSelectionRanges(selectionRanges: undefined | null): undefined;
asSelectionRanges(selectionRanges: ls.SelectionRange[] | undefined | null): code.SelectionRange[] | undefined;
asSelectionRanges(selectionRanges: ls.SelectionRange[] | undefined | null): code.SelectionRange[] | undefined;
asSemanticTokensLegend(value: ls.SemanticTokensLegend): code.SemanticTokensLegend;
asSemanticTokens(value: ls.SemanticTokens): code.SemanticTokens;
asSemanticTokens(value: undefined | null): undefined;
asSemanticTokens(value: ls.SemanticTokens | undefined | null): code.SemanticTokens | undefined;
asSemanticTokens(value: ls.SemanticTokens | undefined | null): code.SemanticTokens | undefined;
asSemanticTokensEdit(value: ls.SemanticTokensEdit): code.SemanticTokensEdit;
asSemanticTokensEdits(value: ls.SemanticTokensDelta): code.SemanticTokensEdits;
asSemanticTokensEdits(value: undefined | null): undefined;
asSemanticTokensEdits(value: ls.SemanticTokensDelta | undefined | null): code.SemanticTokensEdits | undefined;
asSemanticTokensEdits(value: ls.SemanticTokensDelta | undefined | null): code.SemanticTokensEdits | undefined;
asCallHierarchyItem(item: null): undefined;
asCallHierarchyItem(item: ls.CallHierarchyItem): code.CallHierarchyItem;
asCallHierarchyItem(item: ls.CallHierarchyItem | null): code.CallHierarchyItem | undefined;
asCallHierarchyItem(item: ls.CallHierarchyItem | null): code.CallHierarchyItem | undefined;
asCallHierarchyItems(items: null): undefined;
asCallHierarchyItems(items: ls.CallHierarchyItem[]): code.CallHierarchyItem[];
asCallHierarchyItems(items: ls.CallHierarchyItem[] | null): code.CallHierarchyItem[] | undefined;
asCallHierarchyItems(items: ls.CallHierarchyItem[] | null): code.CallHierarchyItem[] | undefined;
asCallHierarchyIncomingCall(item: ls.CallHierarchyIncomingCall): code.CallHierarchyIncomingCall;
asCallHierarchyIncomingCalls(items: null): undefined;
asCallHierarchyIncomingCalls(items: ReadonlyArray<ls.CallHierarchyIncomingCall>): code.CallHierarchyIncomingCall[];
asCallHierarchyIncomingCalls(items: ReadonlyArray<ls.CallHierarchyIncomingCall> | null): code.CallHierarchyIncomingCall[] | undefined;
asCallHierarchyIncomingCalls(items: ReadonlyArray<ls.CallHierarchyIncomingCall> | null): code.CallHierarchyIncomingCall[] | undefined;
asCallHierarchyOutgoingCall(item: ls.CallHierarchyOutgoingCall): code.CallHierarchyOutgoingCall;
asCallHierarchyOutgoingCalls(items: null): undefined;
asCallHierarchyOutgoingCalls(items: ReadonlyArray<ls.CallHierarchyOutgoingCall>): code.CallHierarchyOutgoingCall[];
asCallHierarchyOutgoingCalls(items: ReadonlyArray<ls.CallHierarchyOutgoingCall> | null): code.CallHierarchyOutgoingCall[] | undefined;
asCallHierarchyOutgoingCalls(items: ReadonlyArray<ls.CallHierarchyOutgoingCall> | null): code.CallHierarchyOutgoingCall[] | undefined;
asLinkedEditingRanges(value: null | undefined): undefined;
asLinkedEditingRanges(value: ls.LinkedEditingRanges): code.LinkedEditingRanges;
asLinkedEditingRanges(value: ls.LinkedEditingRanges | null | undefined): code.LinkedEditingRanges | undefined;
}
export interface URIConverter {
(value: string): code.Uri;
}
export declare function createConverter(uriConverter: URIConverter | undefined, trustMarkdown: boolean | undefined): Converter;

View File

@@ -0,0 +1,904 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
/// <reference path="../../typings/vscode-proposed.d.ts" />
Object.defineProperty(exports, "__esModule", { value: true });
exports.createConverter = void 0;
const code = require("vscode");
const ls = require("vscode-languageserver-protocol");
const Is = require("./utils/is");
const protocolCompletionItem_1 = require("./protocolCompletionItem");
const protocolCodeLens_1 = require("./protocolCodeLens");
const protocolDocumentLink_1 = require("./protocolDocumentLink");
const protocolCodeAction_1 = require("./protocolCodeAction");
const protocolDiagnostic_1 = require("./protocolDiagnostic");
const protocolCallHierarchyItem_1 = require("./protocolCallHierarchyItem");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
var CodeBlock;
(function (CodeBlock) {
function is(value) {
let candidate = value;
return candidate && Is.string(candidate.language) && Is.string(candidate.value);
}
CodeBlock.is = is;
})(CodeBlock || (CodeBlock = {}));
function createConverter(uriConverter, trustMarkdown) {
const nullConverter = (value) => code.Uri.parse(value);
const _uriConverter = uriConverter || nullConverter;
function asUri(value) {
return _uriConverter(value);
}
function asDiagnostics(diagnostics) {
return diagnostics.map(asDiagnostic);
}
function asDiagnostic(diagnostic) {
let result = new protocolDiagnostic_1.ProtocolDiagnostic(asRange(diagnostic.range), diagnostic.message, asDiagnosticSeverity(diagnostic.severity), diagnostic.data);
if (diagnostic.code !== undefined) {
if (ls.CodeDescription.is(diagnostic.codeDescription)) {
result.code = {
value: diagnostic.code,
target: asUri(diagnostic.codeDescription.href)
};
}
else if (protocolDiagnostic_1.DiagnosticCode.is(diagnostic.code)) {
result.hasDiagnosticCode = true;
result.code = {
value: diagnostic.code.value,
target: asUri(diagnostic.code.target)
};
}
else {
result.code = diagnostic.code;
}
}
if (diagnostic.source) {
result.source = diagnostic.source;
}
if (diagnostic.relatedInformation) {
result.relatedInformation = asRelatedInformation(diagnostic.relatedInformation);
}
if (Array.isArray(diagnostic.tags)) {
result.tags = asDiagnosticTags(diagnostic.tags);
}
return result;
}
function asRelatedInformation(relatedInformation) {
return relatedInformation.map(asDiagnosticRelatedInformation);
}
function asDiagnosticRelatedInformation(information) {
return new code.DiagnosticRelatedInformation(asLocation(information.location), information.message);
}
function asDiagnosticTags(tags) {
if (!tags) {
return undefined;
}
let result = [];
for (let tag of tags) {
let converted = asDiagnosticTag(tag);
if (converted !== undefined) {
result.push(converted);
}
}
return result.length > 0 ? result : undefined;
}
function asDiagnosticTag(tag) {
switch (tag) {
case ls.DiagnosticTag.Unnecessary:
return code.DiagnosticTag.Unnecessary;
case ls.DiagnosticTag.Deprecated:
return code.DiagnosticTag.Deprecated;
default:
return undefined;
}
}
function asPosition(value) {
if (!value) {
return undefined;
}
return new code.Position(value.line, value.character);
}
function asRange(value) {
if (!value) {
return undefined;
}
return new code.Range(asPosition(value.start), asPosition(value.end));
}
function asRanges(value) {
return value.map(value => asRange(value));
}
function asDiagnosticSeverity(value) {
if (value === undefined || value === null) {
return code.DiagnosticSeverity.Error;
}
switch (value) {
case ls.DiagnosticSeverity.Error:
return code.DiagnosticSeverity.Error;
case ls.DiagnosticSeverity.Warning:
return code.DiagnosticSeverity.Warning;
case ls.DiagnosticSeverity.Information:
return code.DiagnosticSeverity.Information;
case ls.DiagnosticSeverity.Hint:
return code.DiagnosticSeverity.Hint;
}
return code.DiagnosticSeverity.Error;
}
function asHoverContent(value) {
if (Is.string(value)) {
return asMarkdownString(value);
}
else if (CodeBlock.is(value)) {
let result = asMarkdownString();
return result.appendCodeblock(value.value, value.language);
}
else if (Array.isArray(value)) {
let result = [];
for (let element of value) {
let item = asMarkdownString();
if (CodeBlock.is(element)) {
item.appendCodeblock(element.value, element.language);
}
else {
item.appendMarkdown(element);
}
result.push(item);
}
return result;
}
else {
let result;
switch (value.kind) {
case ls.MarkupKind.Markdown:
return asMarkdownString(value.value);
case ls.MarkupKind.PlainText:
result = asMarkdownString();
result.appendText(value.value);
return result;
default:
result = asMarkdownString();
result.appendText(`Unsupported Markup content received. Kind is: ${value.kind}`);
return result;
}
}
}
function asDocumentation(value) {
if (Is.string(value)) {
return value;
}
else {
switch (value.kind) {
case ls.MarkupKind.Markdown:
return asMarkdownString(value.value);
case ls.MarkupKind.PlainText:
return value.value;
default:
return `Unsupported Markup content received. Kind is: ${value.kind}`;
}
}
}
function asMarkdownString(value) {
const result = new code.MarkdownString(value);
if (trustMarkdown === true) {
result.isTrusted = trustMarkdown;
}
return result;
}
function asHover(hover) {
if (!hover) {
return undefined;
}
return new code.Hover(asHoverContent(hover.contents), asRange(hover.range));
}
function asCompletionResult(result) {
if (!result) {
return undefined;
}
if (Array.isArray(result)) {
let items = result;
return items.map(asCompletionItem);
}
let list = result;
return new code.CompletionList(list.items.map(asCompletionItem), list.isIncomplete);
}
function asCompletionItemKind(value) {
// Protocol item kind is 1 based, codes item kind is zero based.
if (ls.CompletionItemKind.Text <= value && value <= ls.CompletionItemKind.TypeParameter) {
return [value - 1, undefined];
}
return [code.CompletionItemKind.Text, value];
}
function asCompletionItemTag(tag) {
switch (tag) {
case ls.CompletionItemTag.Deprecated:
return code.CompletionItemTag.Deprecated;
}
return undefined;
}
function asCompletionItemTags(tags) {
if (tags === undefined || tags === null) {
return [];
}
const result = [];
for (let tag of tags) {
const converted = asCompletionItemTag(tag);
if (converted !== undefined) {
result.push(converted);
}
}
return result;
}
function asCompletionItem(item) {
let tags = asCompletionItemTags(item.tags);
let result = new protocolCompletionItem_1.default(item.label);
if (item.detail) {
result.detail = item.detail;
}
if (item.documentation) {
result.documentation = asDocumentation(item.documentation);
result.documentationFormat = Is.string(item.documentation) ? '$string' : item.documentation.kind;
}
if (item.filterText) {
result.filterText = item.filterText;
}
let insertText = asCompletionInsertText(item);
if (insertText) {
result.insertText = insertText.text;
result.range = insertText.range;
result.fromEdit = insertText.fromEdit;
}
if (Is.number(item.kind)) {
let [itemKind, original] = asCompletionItemKind(item.kind);
result.kind = itemKind;
if (original) {
result.originalItemKind = original;
}
}
if (item.sortText) {
result.sortText = item.sortText;
}
if (item.additionalTextEdits) {
result.additionalTextEdits = asTextEdits(item.additionalTextEdits);
}
if (Is.stringArray(item.commitCharacters)) {
result.commitCharacters = item.commitCharacters.slice();
}
if (item.command) {
result.command = asCommand(item.command);
}
if (item.deprecated === true || item.deprecated === false) {
result.deprecated = item.deprecated;
if (item.deprecated === true) {
tags.push(code.CompletionItemTag.Deprecated);
}
}
if (item.preselect === true || item.preselect === false) {
result.preselect = item.preselect;
}
if (item.data !== undefined) {
result.data = item.data;
}
if (tags.length > 0) {
result.tags = tags;
}
if (item.insertTextMode !== undefined) {
result.insertTextMode = item.insertTextMode;
if (item.insertTextMode === vscode_languageserver_protocol_1.InsertTextMode.asIs) {
result.keepWhitespace = true;
}
}
return result;
}
function asCompletionInsertText(item) {
if (item.textEdit) {
if (item.insertTextFormat === ls.InsertTextFormat.Snippet) {
return { text: new code.SnippetString(item.textEdit.newText), range: asCompletionRange(item.textEdit), fromEdit: true };
}
else {
return { text: item.textEdit.newText, range: asCompletionRange(item.textEdit), fromEdit: true };
}
}
else if (item.insertText) {
if (item.insertTextFormat === ls.InsertTextFormat.Snippet) {
return { text: new code.SnippetString(item.insertText), fromEdit: false };
}
else {
return { text: item.insertText, fromEdit: false };
}
}
else {
return undefined;
}
}
function asCompletionRange(value) {
if (ls.InsertReplaceEdit.is(value)) {
return { inserting: asRange(value.insert), replacing: asRange(value.replace) };
}
else {
return asRange(value.range);
}
}
function asTextEdit(edit) {
if (!edit) {
return undefined;
}
return new code.TextEdit(asRange(edit.range), edit.newText);
}
function asTextEdits(items) {
if (!items) {
return undefined;
}
return items.map(asTextEdit);
}
function asSignatureHelp(item) {
if (!item) {
return undefined;
}
let result = new code.SignatureHelp();
if (Is.number(item.activeSignature)) {
result.activeSignature = item.activeSignature;
}
else {
// activeSignature was optional in the past
result.activeSignature = 0;
}
if (Is.number(item.activeParameter)) {
result.activeParameter = item.activeParameter;
}
else {
// activeParameter was optional in the past
result.activeParameter = 0;
}
if (item.signatures) {
result.signatures = asSignatureInformations(item.signatures);
}
return result;
}
function asSignatureInformations(items) {
return items.map(asSignatureInformation);
}
function asSignatureInformation(item) {
let result = new code.SignatureInformation(item.label);
if (item.documentation !== undefined) {
result.documentation = asDocumentation(item.documentation);
}
if (item.parameters !== undefined) {
result.parameters = asParameterInformations(item.parameters);
}
if (item.activeParameter !== undefined) {
result.activeParameter = item.activeParameter;
}
{
return result;
}
}
function asParameterInformations(item) {
return item.map(asParameterInformation);
}
function asParameterInformation(item) {
let result = new code.ParameterInformation(item.label);
if (item.documentation) {
result.documentation = asDocumentation(item.documentation);
}
return result;
}
function asLocation(item) {
if (!item) {
return undefined;
}
return new code.Location(_uriConverter(item.uri), asRange(item.range));
}
function asDeclarationResult(item) {
if (!item) {
return undefined;
}
return asLocationResult(item);
}
function asDefinitionResult(item) {
if (!item) {
return undefined;
}
return asLocationResult(item);
}
function asLocationLink(item) {
if (!item) {
return undefined;
}
let result = {
targetUri: _uriConverter(item.targetUri),
targetRange: asRange(item.targetRange),
originSelectionRange: asRange(item.originSelectionRange),
targetSelectionRange: asRange(item.targetSelectionRange)
};
if (!result.targetSelectionRange) {
throw new Error(`targetSelectionRange must not be undefined or null`);
}
return result;
}
function asLocationResult(item) {
if (!item) {
return undefined;
}
if (Is.array(item)) {
if (item.length === 0) {
return [];
}
else if (ls.LocationLink.is(item[0])) {
let links = item;
return links.map((link) => asLocationLink(link));
}
else {
let locations = item;
return locations.map((location) => asLocation(location));
}
}
else if (ls.LocationLink.is(item)) {
return [asLocationLink(item)];
}
else {
return asLocation(item);
}
}
function asReferences(values) {
if (!values) {
return undefined;
}
return values.map(location => asLocation(location));
}
function asDocumentHighlights(values) {
if (!values) {
return undefined;
}
return values.map(asDocumentHighlight);
}
function asDocumentHighlight(item) {
let result = new code.DocumentHighlight(asRange(item.range));
if (Is.number(item.kind)) {
result.kind = asDocumentHighlightKind(item.kind);
}
return result;
}
function asDocumentHighlightKind(item) {
switch (item) {
case ls.DocumentHighlightKind.Text:
return code.DocumentHighlightKind.Text;
case ls.DocumentHighlightKind.Read:
return code.DocumentHighlightKind.Read;
case ls.DocumentHighlightKind.Write:
return code.DocumentHighlightKind.Write;
}
return code.DocumentHighlightKind.Text;
}
function asSymbolInformations(values, uri) {
if (!values) {
return undefined;
}
return values.map(information => asSymbolInformation(information, uri));
}
function asSymbolKind(item) {
if (item <= ls.SymbolKind.TypeParameter) {
// Symbol kind is one based in the protocol and zero based in code.
return item - 1;
}
return code.SymbolKind.Property;
}
function asSymbolTag(value) {
switch (value) {
case ls.SymbolTag.Deprecated:
return code.SymbolTag.Deprecated;
default:
return undefined;
}
}
function asSymbolTags(items) {
if (items === undefined || items === null) {
return undefined;
}
const result = [];
for (const item of items) {
const converted = asSymbolTag(item);
if (converted !== undefined) {
result.push(converted);
}
}
return result.length === 0 ? undefined : result;
}
function asSymbolInformation(item, uri) {
// Symbol kind is one based in the protocol and zero based in code.
let result = new code.SymbolInformation(item.name, asSymbolKind(item.kind), asRange(item.location.range), item.location.uri ? _uriConverter(item.location.uri) : uri);
fillTags(result, item);
if (item.containerName) {
result.containerName = item.containerName;
}
return result;
}
function asDocumentSymbols(values) {
if (values === undefined || values === null) {
return undefined;
}
return values.map(asDocumentSymbol);
}
function asDocumentSymbol(value) {
let result = new code.DocumentSymbol(value.name, value.detail || '', asSymbolKind(value.kind), asRange(value.range), asRange(value.selectionRange));
fillTags(result, value);
if (value.children !== undefined && value.children.length > 0) {
let children = [];
for (let child of value.children) {
children.push(asDocumentSymbol(child));
}
result.children = children;
}
return result;
}
function fillTags(result, value) {
result.tags = asSymbolTags(value.tags);
if (value.deprecated) {
if (!result.tags) {
result.tags = [code.SymbolTag.Deprecated];
}
else {
if (!result.tags.includes(code.SymbolTag.Deprecated)) {
result.tags = result.tags.concat(code.SymbolTag.Deprecated);
}
}
}
}
function asCommand(item) {
let result = { title: item.title, command: item.command };
if (item.arguments) {
result.arguments = item.arguments;
}
return result;
}
function asCommands(items) {
if (!items) {
return undefined;
}
return items.map(asCommand);
}
const kindMapping = new Map();
kindMapping.set(ls.CodeActionKind.Empty, code.CodeActionKind.Empty);
kindMapping.set(ls.CodeActionKind.QuickFix, code.CodeActionKind.QuickFix);
kindMapping.set(ls.CodeActionKind.Refactor, code.CodeActionKind.Refactor);
kindMapping.set(ls.CodeActionKind.RefactorExtract, code.CodeActionKind.RefactorExtract);
kindMapping.set(ls.CodeActionKind.RefactorInline, code.CodeActionKind.RefactorInline);
kindMapping.set(ls.CodeActionKind.RefactorRewrite, code.CodeActionKind.RefactorRewrite);
kindMapping.set(ls.CodeActionKind.Source, code.CodeActionKind.Source);
kindMapping.set(ls.CodeActionKind.SourceOrganizeImports, code.CodeActionKind.SourceOrganizeImports);
function asCodeActionKind(item) {
if (item === undefined || item === null) {
return undefined;
}
let result = kindMapping.get(item);
if (result) {
return result;
}
let parts = item.split('.');
result = code.CodeActionKind.Empty;
for (let part of parts) {
result = result.append(part);
}
return result;
}
function asCodeActionKinds(items) {
if (items === undefined || items === null) {
return undefined;
}
return items.map(kind => asCodeActionKind(kind));
}
function asCodeAction(item) {
if (item === undefined || item === null) {
return undefined;
}
let result = new protocolCodeAction_1.default(item.title, item.data);
if (item.kind !== undefined) {
result.kind = asCodeActionKind(item.kind);
}
if (item.diagnostics !== undefined) {
result.diagnostics = asDiagnostics(item.diagnostics);
}
if (item.edit !== undefined) {
result.edit = asWorkspaceEdit(item.edit);
}
if (item.command !== undefined) {
result.command = asCommand(item.command);
}
if (item.isPreferred !== undefined) {
result.isPreferred = item.isPreferred;
}
if (item.disabled !== undefined) {
result.disabled = { reason: item.disabled.reason };
}
return result;
}
function asCodeLens(item) {
if (!item) {
return undefined;
}
let result = new protocolCodeLens_1.default(asRange(item.range));
if (item.command) {
result.command = asCommand(item.command);
}
if (item.data !== undefined && item.data !== null) {
result.data = item.data;
}
return result;
}
function asCodeLenses(items) {
if (!items) {
return undefined;
}
return items.map((codeLens) => asCodeLens(codeLens));
}
function asWorkspaceEdit(item) {
if (!item) {
return undefined;
}
const sharedMetadata = new Map();
if (item.changeAnnotations !== undefined) {
for (const key of Object.keys(item.changeAnnotations)) {
const metaData = asWorkspaceEditEntryMetadata(item.changeAnnotations[key]);
sharedMetadata.set(key, metaData);
}
}
const asMetadata = (annotation) => {
if (annotation === undefined) {
return undefined;
}
else {
return sharedMetadata.get(annotation);
}
};
const result = new code.WorkspaceEdit();
if (item.documentChanges) {
for (const change of item.documentChanges) {
if (ls.CreateFile.is(change)) {
result.createFile(_uriConverter(change.uri), change.options, asMetadata(change.annotationId));
}
else if (ls.RenameFile.is(change)) {
result.renameFile(_uriConverter(change.oldUri), _uriConverter(change.newUri), change.options, asMetadata(change.annotationId));
}
else if (ls.DeleteFile.is(change)) {
result.deleteFile(_uriConverter(change.uri), change.options, asMetadata(change.annotationId));
}
else if (ls.TextDocumentEdit.is(change)) {
const uri = _uriConverter(change.textDocument.uri);
for (const edit of change.edits) {
if (vscode_languageserver_protocol_1.AnnotatedTextEdit.is(edit)) {
result.replace(uri, asRange(edit.range), edit.newText, asMetadata(edit.annotationId));
}
else {
result.replace(uri, asRange(edit.range), edit.newText);
}
}
}
else {
throw new Error(`Unknown workspace edit change received:\n${JSON.stringify(change, undefined, 4)}`);
}
}
}
else if (item.changes) {
Object.keys(item.changes).forEach(key => {
result.set(_uriConverter(key), asTextEdits(item.changes[key]));
});
}
return result;
}
function asWorkspaceEditEntryMetadata(annotation) {
if (annotation === undefined) {
return undefined;
}
return { label: annotation.label, needsConfirmation: !!annotation.needsConfirmation, description: annotation.description };
}
function asDocumentLink(item) {
let range = asRange(item.range);
let target = item.target ? asUri(item.target) : undefined;
// target must be optional in DocumentLink
let link = new protocolDocumentLink_1.default(range, target);
if (item.tooltip !== undefined) {
link.tooltip = item.tooltip;
}
if (item.data !== undefined && item.data !== null) {
link.data = item.data;
}
return link;
}
function asDocumentLinks(items) {
if (!items) {
return undefined;
}
return items.map(asDocumentLink);
}
function asColor(color) {
return new code.Color(color.red, color.green, color.blue, color.alpha);
}
function asColorInformation(ci) {
return new code.ColorInformation(asRange(ci.range), asColor(ci.color));
}
function asColorInformations(colorInformation) {
if (Array.isArray(colorInformation)) {
return colorInformation.map(asColorInformation);
}
return undefined;
}
function asColorPresentation(cp) {
let presentation = new code.ColorPresentation(cp.label);
presentation.additionalTextEdits = asTextEdits(cp.additionalTextEdits);
if (cp.textEdit) {
presentation.textEdit = asTextEdit(cp.textEdit);
}
return presentation;
}
function asColorPresentations(colorPresentations) {
if (Array.isArray(colorPresentations)) {
return colorPresentations.map(asColorPresentation);
}
return undefined;
}
function asFoldingRangeKind(kind) {
if (kind) {
switch (kind) {
case ls.FoldingRangeKind.Comment:
return code.FoldingRangeKind.Comment;
case ls.FoldingRangeKind.Imports:
return code.FoldingRangeKind.Imports;
case ls.FoldingRangeKind.Region:
return code.FoldingRangeKind.Region;
}
}
return undefined;
}
function asFoldingRange(r) {
return new code.FoldingRange(r.startLine, r.endLine, asFoldingRangeKind(r.kind));
}
function asFoldingRanges(foldingRanges) {
if (Array.isArray(foldingRanges)) {
return foldingRanges.map(asFoldingRange);
}
return undefined;
}
function asSelectionRange(selectionRange) {
return new code.SelectionRange(asRange(selectionRange.range), selectionRange.parent ? asSelectionRange(selectionRange.parent) : undefined);
}
function asSelectionRanges(selectionRanges) {
if (!Array.isArray(selectionRanges)) {
return [];
}
let result = [];
for (let range of selectionRanges) {
result.push(asSelectionRange(range));
}
return result;
}
function asCallHierarchyItem(item) {
if (item === null) {
return undefined;
}
let result = new protocolCallHierarchyItem_1.default(asSymbolKind(item.kind), item.name, item.detail || '', asUri(item.uri), asRange(item.range), asRange(item.selectionRange), item.data);
if (item.tags !== undefined) {
result.tags = asSymbolTags(item.tags);
}
return result;
}
function asCallHierarchyItems(items) {
if (items === null) {
return undefined;
}
return items.map(item => asCallHierarchyItem(item));
}
function asCallHierarchyIncomingCall(item) {
return new code.CallHierarchyIncomingCall(asCallHierarchyItem(item.from), asRanges(item.fromRanges));
}
function asCallHierarchyIncomingCalls(items) {
if (items === null) {
return undefined;
}
return items.map(item => asCallHierarchyIncomingCall(item));
}
function asCallHierarchyOutgoingCall(item) {
return new code.CallHierarchyOutgoingCall(asCallHierarchyItem(item.to), asRanges(item.fromRanges));
}
function asCallHierarchyOutgoingCalls(items) {
if (items === null) {
return undefined;
}
return items.map(item => asCallHierarchyOutgoingCall(item));
}
function asSemanticTokens(value) {
if (value === undefined || value === null) {
return undefined;
}
return new code.SemanticTokens(new Uint32Array(value.data), value.resultId);
}
function asSemanticTokensEdit(value) {
return new code.SemanticTokensEdit(value.start, value.deleteCount, value.data !== undefined ? new Uint32Array(value.data) : undefined);
}
function asSemanticTokensEdits(value) {
if (value === undefined || value === null) {
return undefined;
}
return new code.SemanticTokensEdits(value.edits.map(asSemanticTokensEdit), value.resultId);
}
function asSemanticTokensLegend(value) {
return value;
}
function asLinkedEditingRanges(value) {
if (value === null || value === undefined) {
return undefined;
}
return new code.LinkedEditingRanges(asRanges(value.ranges), asRegularExpression(value.wordPattern));
}
function asRegularExpression(value) {
if (value === null || value === undefined) {
return undefined;
}
return new RegExp(value);
}
return {
asUri,
asDiagnostics,
asDiagnostic,
asRange,
asRanges,
asPosition,
asDiagnosticSeverity,
asDiagnosticTag,
asHover,
asCompletionResult,
asCompletionItem,
asTextEdit,
asTextEdits,
asSignatureHelp,
asSignatureInformations,
asSignatureInformation,
asParameterInformations,
asParameterInformation,
asDeclarationResult,
asDefinitionResult,
asLocation,
asReferences,
asDocumentHighlights,
asDocumentHighlight,
asDocumentHighlightKind,
asSymbolKind,
asSymbolTag,
asSymbolTags,
asSymbolInformations,
asSymbolInformation,
asDocumentSymbols,
asDocumentSymbol,
asCommand,
asCommands,
asCodeAction,
asCodeActionKind,
asCodeActionKinds,
asCodeLens,
asCodeLenses,
asWorkspaceEdit,
asDocumentLink,
asDocumentLinks,
asFoldingRangeKind,
asFoldingRange,
asFoldingRanges,
asColor,
asColorInformation,
asColorInformations,
asColorPresentation,
asColorPresentations,
asSelectionRange,
asSelectionRanges,
asSemanticTokensLegend,
asSemanticTokens,
asSemanticTokensEdit,
asSemanticTokensEdits,
asCallHierarchyItem,
asCallHierarchyItems,
asCallHierarchyIncomingCall,
asCallHierarchyIncomingCalls,
asCallHierarchyOutgoingCall,
asCallHierarchyOutgoingCalls,
asLinkedEditingRanges: asLinkedEditingRanges
};
}
exports.createConverter = createConverter;
//# sourceMappingURL=protocolConverter.js.map

View File

@@ -0,0 +1,17 @@
import * as vscode from 'vscode';
/**
* We keep this for a while to not break servers which adopted
* proposed API.
*/
export interface DiagnosticCode {
value: string | number;
target: string;
}
export declare namespace DiagnosticCode {
function is(value: string | number | DiagnosticCode | undefined | null): value is DiagnosticCode;
}
export declare class ProtocolDiagnostic extends vscode.Diagnostic {
readonly data: unknown | undefined;
hasDiagnosticCode: boolean;
constructor(range: vscode.Range, message: string, severity: vscode.DiagnosticSeverity, data: unknown | undefined);
}

View File

@@ -0,0 +1,26 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProtocolDiagnostic = exports.DiagnosticCode = void 0;
const vscode = require("vscode");
const Is = require("./utils/is");
var DiagnosticCode;
(function (DiagnosticCode) {
function is(value) {
const candidate = value;
return candidate !== undefined && candidate !== null && (Is.number(candidate.value) || Is.string(candidate.value)) && Is.string(candidate.target);
}
DiagnosticCode.is = is;
})(DiagnosticCode = exports.DiagnosticCode || (exports.DiagnosticCode = {}));
class ProtocolDiagnostic extends vscode.Diagnostic {
constructor(range, message, severity, data) {
super(range, message, severity);
this.data = data;
this.hasDiagnosticCode = false;
}
}
exports.ProtocolDiagnostic = ProtocolDiagnostic;
//# sourceMappingURL=protocolDiagnostic.js.map

View File

@@ -0,0 +1,5 @@
import * as code from 'vscode';
export default class ProtocolDocumentLink extends code.DocumentLink {
data: any;
constructor(range: code.Range, target?: code.Uri | undefined);
}

View File

@@ -0,0 +1,14 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
const code = require("vscode");
class ProtocolDocumentLink extends code.DocumentLink {
constructor(range, target) {
super(range, target);
}
}
exports.default = ProtocolDocumentLink;
//# sourceMappingURL=protocolDocumentLink.js.map

View File

@@ -0,0 +1,15 @@
import { Disposable, TextDocument, ProviderResult, Position as VPosition, SelectionRange as VSelectionRange, SelectionRangeProvider } from 'vscode';
import { ClientCapabilities, CancellationToken, ServerCapabilities, DocumentSelector, SelectionRangeOptions, SelectionRangeRegistrationOptions } from 'vscode-languageserver-protocol';
import { TextDocumentFeature, BaseLanguageClient } from './client';
export interface ProvideSelectionRangeSignature {
(this: void, document: TextDocument, positions: VPosition[], token: CancellationToken): ProviderResult<VSelectionRange[]>;
}
export interface SelectionRangeProviderMiddleware {
provideSelectionRanges?: (this: void, document: TextDocument, positions: VPosition[], token: CancellationToken, next: ProvideSelectionRangeSignature) => ProviderResult<VSelectionRange[]>;
}
export declare class SelectionRangeFeature extends TextDocumentFeature<boolean | SelectionRangeOptions, SelectionRangeRegistrationOptions, SelectionRangeProvider> {
constructor(client: BaseLanguageClient);
fillClientCapabilities(capabilities: ClientCapabilities): void;
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void;
protected registerLanguageProvider(options: SelectionRangeRegistrationOptions): [Disposable, SelectionRangeProvider];
}

View File

@@ -0,0 +1,55 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.SelectionRangeFeature = void 0;
const vscode_1 = require("vscode");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const client_1 = require("./client");
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = Object.create(null);
}
return target[key];
}
class SelectionRangeFeature extends client_1.TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.SelectionRangeRequest.type);
}
fillClientCapabilities(capabilities) {
let capability = ensure(ensure(capabilities, 'textDocument'), 'selectionRange');
capability.dynamicRegistration = true;
}
initialize(capabilities, documentSelector) {
let [id, options] = this.getRegistration(documentSelector, capabilities.selectionRangeProvider);
if (!id || !options) {
return;
}
this.register({ id: id, registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideSelectionRanges: (document, positions, token) => {
const client = this._client;
const provideSelectionRanges = (document, positions, token) => {
const requestParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
positions: client.code2ProtocolConverter.asPositions(positions)
};
return client.sendRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, requestParams, token).then((ranges) => client.protocol2CodeConverter.asSelectionRanges(ranges), (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, error, null);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideSelectionRanges
? middleware.provideSelectionRanges(document, positions, token, provideSelectionRanges)
: provideSelectionRanges(document, positions, token);
}
};
return [vscode_1.languages.registerSelectionRangeProvider(options.documentSelector, provider), provider];
}
}
exports.SelectionRangeFeature = SelectionRangeFeature;
//# sourceMappingURL=selectionRange.js.map

View File

@@ -0,0 +1,33 @@
import * as vscode from 'vscode';
import { BaseLanguageClient, TextDocumentFeature } from './client';
import { ClientCapabilities, ServerCapabilities, DocumentSelector, SemanticTokensOptions, SemanticTokensRegistrationOptions } from 'vscode-languageserver-protocol';
export interface DocumentSemanticsTokensSignature {
(this: void, document: vscode.TextDocument, token: vscode.CancellationToken): vscode.ProviderResult<vscode.SemanticTokens>;
}
export interface DocumentSemanticsTokensEditsSignature {
(this: void, document: vscode.TextDocument, previousResultId: string, token: vscode.CancellationToken): vscode.ProviderResult<vscode.SemanticTokensEdits | vscode.SemanticTokens>;
}
export interface DocumentRangeSemanticTokensSignature {
(this: void, document: vscode.TextDocument, range: vscode.Range, token: vscode.CancellationToken): vscode.ProviderResult<vscode.SemanticTokens>;
}
/**
* The semantic token middleware
*
* @since 3.16.0
*/
export interface SemanticTokensMiddleware {
provideDocumentSemanticTokens?: (this: void, document: vscode.TextDocument, token: vscode.CancellationToken, next: DocumentSemanticsTokensSignature) => vscode.ProviderResult<vscode.SemanticTokens>;
provideDocumentSemanticTokensEdits?: (this: void, document: vscode.TextDocument, previousResultId: string, token: vscode.CancellationToken, next: DocumentSemanticsTokensEditsSignature) => vscode.ProviderResult<vscode.SemanticTokensEdits | vscode.SemanticTokens>;
provideDocumentRangeSemanticTokens?: (this: void, document: vscode.TextDocument, range: vscode.Range, token: vscode.CancellationToken, next: DocumentRangeSemanticTokensSignature) => vscode.ProviderResult<vscode.SemanticTokens>;
}
export interface SemanticTokensProviders {
range?: vscode.DocumentRangeSemanticTokensProvider;
full?: vscode.DocumentSemanticTokensProvider;
onDidChangeSemanticTokensEmitter: vscode.EventEmitter<void>;
}
export declare class SemanticTokensFeature extends TextDocumentFeature<boolean | SemanticTokensOptions, SemanticTokensRegistrationOptions, SemanticTokensProviders> {
constructor(client: BaseLanguageClient);
fillClientCapabilities(capabilities: ClientCapabilities): void;
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void;
protected registerLanguageProvider(options: SemanticTokensRegistrationOptions): [vscode.Disposable, SemanticTokensProviders];
}

View File

@@ -0,0 +1,172 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.SemanticTokensFeature = void 0;
const vscode = require("vscode");
const client_1 = require("./client");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const Is = require("./utils/is");
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = {};
}
return target[key];
}
class SemanticTokensFeature extends client_1.TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.SemanticTokensRegistrationType.type);
}
fillClientCapabilities(capabilities) {
const capability = ensure(ensure(capabilities, 'textDocument'), 'semanticTokens');
capability.dynamicRegistration = true;
capability.tokenTypes = [
vscode_languageserver_protocol_1.SemanticTokenTypes.namespace,
vscode_languageserver_protocol_1.SemanticTokenTypes.type,
vscode_languageserver_protocol_1.SemanticTokenTypes.class,
vscode_languageserver_protocol_1.SemanticTokenTypes.enum,
vscode_languageserver_protocol_1.SemanticTokenTypes.interface,
vscode_languageserver_protocol_1.SemanticTokenTypes.struct,
vscode_languageserver_protocol_1.SemanticTokenTypes.typeParameter,
vscode_languageserver_protocol_1.SemanticTokenTypes.parameter,
vscode_languageserver_protocol_1.SemanticTokenTypes.variable,
vscode_languageserver_protocol_1.SemanticTokenTypes.property,
vscode_languageserver_protocol_1.SemanticTokenTypes.enumMember,
vscode_languageserver_protocol_1.SemanticTokenTypes.event,
vscode_languageserver_protocol_1.SemanticTokenTypes.function,
vscode_languageserver_protocol_1.SemanticTokenTypes.method,
vscode_languageserver_protocol_1.SemanticTokenTypes.macro,
vscode_languageserver_protocol_1.SemanticTokenTypes.keyword,
vscode_languageserver_protocol_1.SemanticTokenTypes.modifier,
vscode_languageserver_protocol_1.SemanticTokenTypes.comment,
vscode_languageserver_protocol_1.SemanticTokenTypes.string,
vscode_languageserver_protocol_1.SemanticTokenTypes.number,
vscode_languageserver_protocol_1.SemanticTokenTypes.regexp,
vscode_languageserver_protocol_1.SemanticTokenTypes.operator
];
capability.tokenModifiers = [
vscode_languageserver_protocol_1.SemanticTokenModifiers.declaration,
vscode_languageserver_protocol_1.SemanticTokenModifiers.definition,
vscode_languageserver_protocol_1.SemanticTokenModifiers.readonly,
vscode_languageserver_protocol_1.SemanticTokenModifiers.static,
vscode_languageserver_protocol_1.SemanticTokenModifiers.deprecated,
vscode_languageserver_protocol_1.SemanticTokenModifiers.abstract,
vscode_languageserver_protocol_1.SemanticTokenModifiers.async,
vscode_languageserver_protocol_1.SemanticTokenModifiers.modification,
vscode_languageserver_protocol_1.SemanticTokenModifiers.documentation,
vscode_languageserver_protocol_1.SemanticTokenModifiers.defaultLibrary
];
capability.formats = [vscode_languageserver_protocol_1.TokenFormat.Relative];
capability.requests = {
range: true,
full: {
delta: true
}
};
capability.multilineTokenSupport = false;
capability.overlappingTokenSupport = false;
ensure(ensure(capabilities, 'workspace'), 'semanticTokens').refreshSupport = true;
}
initialize(capabilities, documentSelector) {
const client = this._client;
client.onRequest(vscode_languageserver_protocol_1.SemanticTokensRefreshRequest.type, async () => {
for (const provider of this.getAllProviders()) {
provider.onDidChangeSemanticTokensEmitter.fire();
}
});
const [id, options] = this.getRegistration(documentSelector, capabilities.semanticTokensProvider);
if (!id || !options) {
return;
}
this.register({ id: id, registerOptions: options });
}
registerLanguageProvider(options) {
const fullProvider = Is.boolean(options.full) ? options.full : options.full !== undefined;
const hasEditProvider = options.full !== undefined && typeof options.full !== 'boolean' && options.full.delta === true;
const eventEmitter = new vscode.EventEmitter();
const documentProvider = fullProvider
? {
onDidChangeSemanticTokens: eventEmitter.event,
provideDocumentSemanticTokens: (document, token) => {
const client = this._client;
const middleware = client.clientOptions.middleware;
const provideDocumentSemanticTokens = (document, token) => {
const params = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)
};
return client.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRequest.type, params, token).then((result) => {
return client.protocol2CodeConverter.asSemanticTokens(result);
}, (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensRequest.type, error, null);
});
};
return middleware.provideDocumentSemanticTokens
? middleware.provideDocumentSemanticTokens(document, token, provideDocumentSemanticTokens)
: provideDocumentSemanticTokens(document, token);
},
provideDocumentSemanticTokensEdits: hasEditProvider
? (document, previousResultId, token) => {
const client = this._client;
const middleware = client.clientOptions.middleware;
const provideDocumentSemanticTokensEdits = (document, previousResultId, token) => {
const params = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
previousResultId
};
return client.sendRequest(vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type, params, token).then((result) => {
if (vscode_languageserver_protocol_1.SemanticTokens.is(result)) {
return client.protocol2CodeConverter.asSemanticTokens(result);
}
else {
return client.protocol2CodeConverter.asSemanticTokensEdits(result);
}
}, (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type, error, null);
});
};
return middleware.provideDocumentSemanticTokensEdits
? middleware.provideDocumentSemanticTokensEdits(document, previousResultId, token, provideDocumentSemanticTokensEdits)
: provideDocumentSemanticTokensEdits(document, previousResultId, token);
}
: undefined
}
: undefined;
const hasRangeProvider = options.range === true;
const rangeProvider = hasRangeProvider
? {
provideDocumentRangeSemanticTokens: (document, range, token) => {
const client = this._client;
const middleware = client.clientOptions.middleware;
const provideDocumentRangeSemanticTokens = (document, range, token) => {
const params = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
range: client.code2ProtocolConverter.asRange(range)
};
return client.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type, params, token).then((result) => {
return client.protocol2CodeConverter.asSemanticTokens(result);
}, (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type, error, null);
});
};
return middleware.provideDocumentRangeSemanticTokens
? middleware.provideDocumentRangeSemanticTokens(document, range, token, provideDocumentRangeSemanticTokens)
: provideDocumentRangeSemanticTokens(document, range, token);
}
}
: undefined;
const disposables = [];
const client = this._client;
const legend = client.protocol2CodeConverter.asSemanticTokensLegend(options.legend);
if (documentProvider !== undefined) {
disposables.push(vscode.languages.registerDocumentSemanticTokensProvider(options.documentSelector, documentProvider, legend));
}
if (rangeProvider !== undefined) {
disposables.push(vscode.languages.registerDocumentRangeSemanticTokensProvider(options.documentSelector, rangeProvider, legend));
}
return [new vscode.Disposable(() => disposables.forEach(item => item.dispose())), { range: rangeProvider, full: documentProvider, onDidChangeSemanticTokensEmitter: eventEmitter }];
}
}
exports.SemanticTokensFeature = SemanticTokensFeature;
//# sourceMappingURL=semanticTokens.js.map

View File

@@ -0,0 +1,15 @@
import { Disposable, TextDocument, ProviderResult, Position as VPosition, Definition as VDefinition, DefinitionLink as VDefinitionLink, TypeDefinitionProvider } from 'vscode';
import { ClientCapabilities, CancellationToken, ServerCapabilities, DocumentSelector, TypeDefinitionRegistrationOptions, TypeDefinitionOptions } from 'vscode-languageserver-protocol';
import { TextDocumentFeature, BaseLanguageClient } from './client';
export interface ProvideTypeDefinitionSignature {
(this: void, document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VDefinition | VDefinitionLink[]>;
}
export interface TypeDefinitionMiddleware {
provideTypeDefinition?: (this: void, document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideTypeDefinitionSignature) => ProviderResult<VDefinition | VDefinitionLink[]>;
}
export declare class TypeDefinitionFeature extends TextDocumentFeature<boolean | TypeDefinitionOptions, TypeDefinitionRegistrationOptions, TypeDefinitionProvider> {
constructor(client: BaseLanguageClient);
fillClientCapabilities(capabilities: ClientCapabilities): void;
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void;
protected registerLanguageProvider(options: TypeDefinitionRegistrationOptions): [Disposable, TypeDefinitionProvider];
}

View File

@@ -0,0 +1,53 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeDefinitionFeature = void 0;
const vscode_1 = require("vscode");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const client_1 = require("./client");
function ensure(target, key) {
if (target[key] === void 0) {
target[key] = {};
}
return target[key];
}
class TypeDefinitionFeature extends client_1.TextDocumentFeature {
constructor(client) {
super(client, vscode_languageserver_protocol_1.TypeDefinitionRequest.type);
}
fillClientCapabilities(capabilities) {
ensure(ensure(capabilities, 'textDocument'), 'typeDefinition').dynamicRegistration = true;
let typeDefinitionSupport = ensure(ensure(capabilities, 'textDocument'), 'typeDefinition');
typeDefinitionSupport.dynamicRegistration = true;
typeDefinitionSupport.linkSupport = true;
}
initialize(capabilities, documentSelector) {
let [id, options] = this.getRegistration(documentSelector, capabilities.typeDefinitionProvider);
if (!id || !options) {
return;
}
this.register({ id: id, registerOptions: options });
}
registerLanguageProvider(options) {
const provider = {
provideTypeDefinition: (document, position, token) => {
const client = this._client;
const provideTypeDefinition = (document, position, token) => {
return client.sendRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDefinitionResult, (error) => {
return client.handleFailedRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, error, null);
});
};
const middleware = client.clientOptions.middleware;
return middleware.provideTypeDefinition
? middleware.provideTypeDefinition(document, position, token, provideTypeDefinition)
: provideTypeDefinition(document, position, token);
}
};
return [vscode_1.languages.registerTypeDefinitionProvider(options.documentSelector, provider), provider];
}
}
exports.TypeDefinitionFeature = TypeDefinitionFeature;
//# sourceMappingURL=typeDefinition.js.map

View File

@@ -0,0 +1,16 @@
export interface ITask<T> {
(): T;
}
export declare class Delayer<T> {
defaultDelay: number;
private timeout;
private completionPromise;
private onSuccess;
private task;
constructor(defaultDelay: number);
trigger(task: ITask<T>, delay?: number): Promise<T>;
forceDelivery(): T | undefined;
isTriggered(): boolean;
cancel(): void;
private cancelTimeout;
}

View File

@@ -0,0 +1,67 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.Delayer = void 0;
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
class Delayer {
constructor(defaultDelay) {
this.defaultDelay = defaultDelay;
this.timeout = undefined;
this.completionPromise = undefined;
this.onSuccess = undefined;
this.task = undefined;
}
trigger(task, delay = this.defaultDelay) {
this.task = task;
if (delay >= 0) {
this.cancelTimeout();
}
if (!this.completionPromise) {
this.completionPromise = new Promise((resolve) => {
this.onSuccess = resolve;
}).then(() => {
this.completionPromise = undefined;
this.onSuccess = undefined;
var result = this.task();
this.task = undefined;
return result;
});
}
if (delay >= 0 || this.timeout === void 0) {
this.timeout = vscode_languageserver_protocol_1.RAL().timer.setTimeout(() => {
this.timeout = undefined;
this.onSuccess(undefined);
}, delay >= 0 ? delay : this.defaultDelay);
}
return this.completionPromise;
}
forceDelivery() {
if (!this.completionPromise) {
return undefined;
}
this.cancelTimeout();
let result = this.task();
this.completionPromise = undefined;
this.onSuccess = undefined;
this.task = undefined;
return result;
}
isTriggered() {
return this.timeout !== void 0;
}
cancel() {
this.cancelTimeout();
this.completionPromise = undefined;
}
cancelTimeout() {
if (this.timeout !== void 0) {
vscode_languageserver_protocol_1.RAL().timer.clearTimeout(this.timeout);
this.timeout = undefined;
}
}
}
exports.Delayer = Delayer;
//# sourceMappingURL=async.js.map

View File

@@ -0,0 +1,12 @@
export declare function boolean(value: any): value is boolean;
export declare function string(value: any): value is string;
export declare function number(value: any): value is number;
export declare function error(value: any): value is Error;
export declare function func(value: any): value is Function;
export declare function array<T>(value: any): value is T[];
export declare function stringArray(value: any): value is string[];
export declare function typedArray<T>(value: any, check: (value: any) => boolean): value is T[];
export declare function thenable<T>(value: any): value is Thenable<T>;
export declare function asPromise<T>(value: Promise<T>): Promise<T>;
export declare function asPromise<T>(value: Thenable<T>): Promise<T>;
export declare function asPromise<T>(value: T): Promise<T>;

View File

@@ -0,0 +1,58 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.asPromise = exports.thenable = exports.typedArray = exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;
function boolean(value) {
return value === true || value === false;
}
exports.boolean = boolean;
function string(value) {
return typeof value === 'string' || value instanceof String;
}
exports.string = string;
function number(value) {
return typeof value === 'number' || value instanceof Number;
}
exports.number = number;
function error(value) {
return value instanceof Error;
}
exports.error = error;
function func(value) {
return typeof value === 'function';
}
exports.func = func;
function array(value) {
return Array.isArray(value);
}
exports.array = array;
function stringArray(value) {
return array(value) && value.every(elem => string(elem));
}
exports.stringArray = stringArray;
function typedArray(value, check) {
return Array.isArray(value) && value.every(check);
}
exports.typedArray = typedArray;
function thenable(value) {
return value && func(value.then);
}
exports.thenable = thenable;
function asPromise(value) {
if (value instanceof Promise) {
return value;
}
else if (thenable(value)) {
return new Promise((resolve, reject) => {
value.then((resolved) => resolve(resolved), (error) => reject(error));
});
}
else {
return Promise.resolve(value);
}
}
exports.asPromise = asPromise;
//# sourceMappingURL=is.js.map

View File

@@ -0,0 +1,22 @@
/**
* Represents a UUID as defined by rfc4122.
*/
export interface UUID {
/**
* @returns the canonical representation in sets of hexadecimal numbers separated by dashes.
*/
asHex(): string;
equals(other: UUID): boolean;
}
/**
* An empty UUID that contains only zeros.
*/
export declare const empty: UUID;
export declare function v4(): UUID;
export declare function isUUID(value: string): boolean;
/**
* Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
* @param value A uuid string.
*/
export declare function parse(value: string): UUID;
export declare function generateUuid(): string;

View File

@@ -0,0 +1,98 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateUuid = exports.parse = exports.isUUID = exports.v4 = exports.empty = void 0;
class ValueUUID {
constructor(_value) {
this._value = _value;
// empty
}
asHex() {
return this._value;
}
equals(other) {
return this.asHex() === other.asHex();
}
}
class V4UUID extends ValueUUID {
constructor() {
super([
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
'-',
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
'-',
'4',
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
'-',
V4UUID._oneOf(V4UUID._timeHighBits),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
'-',
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
].join(''));
}
static _oneOf(array) {
return array[Math.floor(array.length * Math.random())];
}
static _randomHex() {
return V4UUID._oneOf(V4UUID._chars);
}
}
V4UUID._chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
V4UUID._timeHighBits = ['8', '9', 'a', 'b'];
/**
* An empty UUID that contains only zeros.
*/
exports.empty = new ValueUUID('00000000-0000-0000-0000-000000000000');
function v4() {
return new V4UUID();
}
exports.v4 = v4;
const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function isUUID(value) {
return _UUIDPattern.test(value);
}
exports.isUUID = isUUID;
/**
* Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
* @param value A uuid string.
*/
function parse(value) {
if (!isUUID(value)) {
throw new Error('invalid uuid');
}
return new ValueUUID(value);
}
exports.parse = parse;
function generateUuid() {
return v4().asHex();
}
exports.generateUuid = generateUuid;
//# sourceMappingURL=uuid.js.map

View File

@@ -0,0 +1,25 @@
import { WorkspaceFolder as VWorkspaceFolder, WorkspaceFoldersChangeEvent as VWorkspaceFoldersChangeEvent } from 'vscode';
import { DynamicFeature, RegistrationData, BaseLanguageClient, NextSignature } from './client';
import { ClientCapabilities, InitializeParams, ServerCapabilities, WorkspaceFoldersRequest, RegistrationType } from 'vscode-languageserver-protocol';
export declare function arrayDiff<T>(left: ReadonlyArray<T>, right: ReadonlyArray<T>): T[];
export interface WorkspaceFolderWorkspaceMiddleware {
workspaceFolders?: WorkspaceFoldersRequest.MiddlewareSignature;
didChangeWorkspaceFolders?: NextSignature<VWorkspaceFoldersChangeEvent, void>;
}
export declare class WorkspaceFoldersFeature implements DynamicFeature<void> {
private _client;
private _listeners;
private _initialFolders;
constructor(_client: BaseLanguageClient);
get registrationType(): RegistrationType<void>;
fillInitializeParams(params: InitializeParams): void;
protected initializeWithFolders(currentWorkspaceFolders: ReadonlyArray<VWorkspaceFolder> | undefined): void;
fillClientCapabilities(capabilities: ClientCapabilities): void;
initialize(capabilities: ServerCapabilities): void;
protected sendInitialEvent(currentWorkspaceFolders: ReadonlyArray<VWorkspaceFolder> | undefined): void;
private doSendEvent;
register(data: RegistrationData<undefined>): void;
unregister(id: string): void;
dispose(): void;
private asProtocol;
}

View File

@@ -0,0 +1,137 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkspaceFoldersFeature = exports.arrayDiff = void 0;
const UUID = require("./utils/uuid");
const vscode_1 = require("vscode");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
function access(target, key) {
if (target === void 0) {
return undefined;
}
return target[key];
}
function arrayDiff(left, right) {
return left.filter(element => right.indexOf(element) < 0);
}
exports.arrayDiff = arrayDiff;
class WorkspaceFoldersFeature {
constructor(_client) {
this._client = _client;
this._listeners = new Map();
}
get registrationType() {
return vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type;
}
fillInitializeParams(params) {
const folders = vscode_1.workspace.workspaceFolders;
this.initializeWithFolders(folders);
if (folders === void 0) {
params.workspaceFolders = null;
}
else {
params.workspaceFolders = folders.map(folder => this.asProtocol(folder));
}
}
initializeWithFolders(currentWorkspaceFolders) {
this._initialFolders = currentWorkspaceFolders;
}
fillClientCapabilities(capabilities) {
capabilities.workspace = capabilities.workspace || {};
capabilities.workspace.workspaceFolders = true;
}
initialize(capabilities) {
const client = this._client;
client.onRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type, (token) => {
const workspaceFolders = () => {
const folders = vscode_1.workspace.workspaceFolders;
if (folders === undefined) {
return null;
}
const result = folders.map((folder) => {
return this.asProtocol(folder);
});
return result;
};
const middleware = client.clientOptions.middleware.workspace;
return middleware && middleware.workspaceFolders
? middleware.workspaceFolders(token, workspaceFolders)
: workspaceFolders(token);
});
const value = access(access(access(capabilities, 'workspace'), 'workspaceFolders'), 'changeNotifications');
let id;
if (typeof value === 'string') {
id = value;
}
else if (value === true) {
id = UUID.generateUuid();
}
if (id) {
this.register({ id: id, registerOptions: undefined });
}
}
sendInitialEvent(currentWorkspaceFolders) {
if (this._initialFolders && currentWorkspaceFolders) {
const removed = arrayDiff(this._initialFolders, currentWorkspaceFolders);
const added = arrayDiff(currentWorkspaceFolders, this._initialFolders);
if (added.length > 0 || removed.length > 0) {
this.doSendEvent(added, removed);
}
}
else if (this._initialFolders) {
this.doSendEvent([], this._initialFolders);
}
else if (currentWorkspaceFolders) {
this.doSendEvent(currentWorkspaceFolders, []);
}
}
doSendEvent(addedFolders, removedFolders) {
let params = {
event: {
added: addedFolders.map(folder => this.asProtocol(folder)),
removed: removedFolders.map(folder => this.asProtocol(folder))
}
};
this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, params);
}
register(data) {
let id = data.id;
let client = this._client;
let disposable = vscode_1.workspace.onDidChangeWorkspaceFolders((event) => {
let didChangeWorkspaceFolders = (event) => {
this.doSendEvent(event.added, event.removed);
};
let middleware = client.clientOptions.middleware.workspace;
middleware && middleware.didChangeWorkspaceFolders
? middleware.didChangeWorkspaceFolders(event, didChangeWorkspaceFolders)
: didChangeWorkspaceFolders(event);
});
this._listeners.set(id, disposable);
this.sendInitialEvent(vscode_1.workspace.workspaceFolders);
}
unregister(id) {
let disposable = this._listeners.get(id);
if (disposable === void 0) {
return;
}
this._listeners.delete(id);
disposable.dispose();
}
dispose() {
for (let disposable of this._listeners.values()) {
disposable.dispose();
}
this._listeners.clear();
}
asProtocol(workspaceFolder) {
if (workspaceFolder === void 0) {
return null;
}
return { uri: this._client.code2ProtocolConverter.asUri(workspaceFolder.uri), name: workspaceFolder.name };
}
}
exports.WorkspaceFoldersFeature = WorkspaceFoldersFeature;
//# sourceMappingURL=workspaceFolders.js.map

97
node_modules/vscode-languageclient/lib/node/main.d.ts generated vendored Normal file
View File

@@ -0,0 +1,97 @@
/// <reference types="node" />
import * as cp from 'child_process';
import ChildProcess = cp.ChildProcess;
import { Disposable } from 'vscode';
import { CommonLanguageClient } from '../common/commonClient';
import { LanguageClientOptions, MessageTransports } from '../common/client';
import { InitializeParams } from 'vscode-languageserver-protocol/node';
export * from 'vscode-languageserver-protocol/node';
export * from '../common/api';
export interface ExecutableOptions {
cwd?: string;
env?: any;
detached?: boolean;
shell?: boolean;
}
export interface Executable {
command: string;
args?: string[];
options?: ExecutableOptions;
}
export interface ForkOptions {
cwd?: string;
env?: any;
encoding?: string;
execArgv?: string[];
}
export declare enum TransportKind {
stdio = 0,
ipc = 1,
pipe = 2,
socket = 3
}
export interface SocketTransport {
kind: TransportKind.socket;
port: number;
}
/**
* To avoid any timing, pipe name or port number issues the pipe (TransportKind.pipe)
* and the sockets (TransportKind.socket and SocketTransport) are owned by the
* VS Code processes. The server process simply connects to the pipe / socket.
* In node term the VS Code process calls `createServer`, then starts the server
* process, waits until the server process has connected to the pipe / socket
* and then signals that the connection has been established and messages can
* be send back and forth. If the language server is implemented in a different
* program language the server simply needs to create a connection to the
* passed pipe name or port number.
*/
export declare type Transport = TransportKind | SocketTransport;
export interface NodeModule {
module: string;
transport?: Transport;
args?: string[];
runtime?: string;
options?: ForkOptions;
}
export interface StreamInfo {
writer: NodeJS.WritableStream;
reader: NodeJS.ReadableStream;
detached?: boolean;
}
export interface ChildProcessInfo {
process: ChildProcess;
detached: boolean;
}
export declare type ServerOptions = Executable | {
run: Executable;
debug: Executable;
} | {
run: NodeModule;
debug: NodeModule;
} | NodeModule | (() => Promise<ChildProcess | StreamInfo | MessageTransports | ChildProcessInfo>);
export declare class LanguageClient extends CommonLanguageClient {
private _serverOptions;
private _forceDebug;
private _serverProcess;
private _isDetached;
constructor(name: string, serverOptions: ServerOptions, clientOptions: LanguageClientOptions, forceDebug?: boolean);
constructor(id: string, name: string, serverOptions: ServerOptions, clientOptions: LanguageClientOptions, forceDebug?: boolean);
private checkVersion;
stop(): Promise<void>;
private checkProcessDied;
protected handleConnectionClosed(): void;
protected fillInitializeParams(params: InitializeParams): void;
protected createMessageTransports(encoding: string): Promise<MessageTransports>;
private _getRuntimePath;
private _mainGetRootPath;
private _getServerWorkingDir;
getLocale(): string;
}
export declare class SettingMonitor {
private _client;
private _setting;
private _listeners;
constructor(_client: LanguageClient, _setting: string);
start(): Disposable;
private onDidChangeConfiguration;
}

489
node_modules/vscode-languageclient/lib/node/main.js generated vendored Normal file
View File

@@ -0,0 +1,489 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SettingMonitor = exports.LanguageClient = exports.TransportKind = void 0;
const cp = require("child_process");
const fs = require("fs");
const path = require("path");
const SemVer = require("semver");
const vscode_1 = require("vscode");
const Is = require("../common/utils/is");
const commonClient_1 = require("../common/commonClient");
const client_1 = require("../common/client");
const processes_1 = require("./processes");
const node_1 = require("vscode-languageserver-protocol/node");
__exportStar(require("vscode-languageserver-protocol/node"), exports);
__exportStar(require("../common/api"), exports);
const REQUIRED_VSCODE_VERSION = '^1.52.0'; // do not change format, updated by `updateVSCode` script
var Executable;
(function (Executable) {
function is(value) {
return Is.string(value.command);
}
Executable.is = is;
})(Executable || (Executable = {}));
var TransportKind;
(function (TransportKind) {
TransportKind[TransportKind["stdio"] = 0] = "stdio";
TransportKind[TransportKind["ipc"] = 1] = "ipc";
TransportKind[TransportKind["pipe"] = 2] = "pipe";
TransportKind[TransportKind["socket"] = 3] = "socket";
})(TransportKind = exports.TransportKind || (exports.TransportKind = {}));
var Transport;
(function (Transport) {
function isSocket(value) {
let candidate = value;
return candidate && candidate.kind === TransportKind.socket && Is.number(candidate.port);
}
Transport.isSocket = isSocket;
})(Transport || (Transport = {}));
var NodeModule;
(function (NodeModule) {
function is(value) {
return Is.string(value.module);
}
NodeModule.is = is;
})(NodeModule || (NodeModule = {}));
var StreamInfo;
(function (StreamInfo) {
function is(value) {
let candidate = value;
return candidate && candidate.writer !== void 0 && candidate.reader !== void 0;
}
StreamInfo.is = is;
})(StreamInfo || (StreamInfo = {}));
var ChildProcessInfo;
(function (ChildProcessInfo) {
function is(value) {
let candidate = value;
return candidate && candidate.process !== void 0 && typeof candidate.detached === 'boolean';
}
ChildProcessInfo.is = is;
})(ChildProcessInfo || (ChildProcessInfo = {}));
class LanguageClient extends commonClient_1.CommonLanguageClient {
constructor(arg1, arg2, arg3, arg4, arg5) {
let id;
let name;
let serverOptions;
let clientOptions;
let forceDebug;
if (Is.string(arg2)) {
id = arg1;
name = arg2;
serverOptions = arg3;
clientOptions = arg4;
forceDebug = !!arg5;
}
else {
id = arg1.toLowerCase();
name = arg1;
serverOptions = arg2;
clientOptions = arg3;
forceDebug = arg4;
}
if (forceDebug === void 0) {
forceDebug = false;
}
super(id, name, clientOptions);
this._serverOptions = serverOptions;
this._forceDebug = forceDebug;
try {
this.checkVersion();
}
catch (error) {
if (Is.string(error.message)) {
this.outputChannel.appendLine(error.message);
}
throw error;
}
}
checkVersion() {
let codeVersion = SemVer.parse(vscode_1.version);
if (!codeVersion) {
throw new Error(`No valid VS Code version detected. Version string is: ${vscode_1.version}`);
}
// Remove the insider pre-release since we stay API compatible.
if (codeVersion.prerelease && codeVersion.prerelease.length > 0) {
codeVersion.prerelease = [];
}
if (!SemVer.satisfies(codeVersion, REQUIRED_VSCODE_VERSION)) {
throw new Error(`The language client requires VS Code version ${REQUIRED_VSCODE_VERSION} but received version ${vscode_1.version}`);
}
}
stop() {
return super.stop().then(() => {
if (this._serverProcess) {
let toCheck = this._serverProcess;
this._serverProcess = undefined;
if (this._isDetached === void 0 || !this._isDetached) {
this.checkProcessDied(toCheck);
}
this._isDetached = undefined;
}
});
}
checkProcessDied(childProcess) {
if (!childProcess) {
return;
}
setTimeout(() => {
// Test if the process is still alive. Throws an exception if not
try {
process.kill(childProcess.pid, 0);
processes_1.terminate(childProcess);
}
catch (error) {
// All is fine.
}
}, 2000);
}
handleConnectionClosed() {
this._serverProcess = undefined;
super.handleConnectionClosed();
}
fillInitializeParams(params) {
super.fillInitializeParams(params);
if (params.processId === null) {
params.processId = process.pid;
}
}
createMessageTransports(encoding) {
function getEnvironment(env, fork) {
if (!env && !fork) {
return undefined;
}
let result = Object.create(null);
Object.keys(process.env).forEach(key => result[key] = process.env[key]);
if (fork) {
result['ELECTRON_RUN_AS_NODE'] = '1';
result['ELECTRON_NO_ASAR'] = '1';
}
if (env) {
Object.keys(env).forEach(key => result[key] = env[key]);
}
return result;
}
const debugStartWith = ['--debug=', '--debug-brk=', '--inspect=', '--inspect-brk='];
const debugEquals = ['--debug', '--debug-brk', '--inspect', '--inspect-brk'];
function startedInDebugMode() {
let args = process.execArgv;
if (args) {
return args.some((arg) => {
return debugStartWith.some(value => arg.startsWith(value)) ||
debugEquals.some(value => arg === value);
});
}
return false;
}
function assertStdio(process) {
if (process.stdin === null || process.stdout === null || process.stderr === null) {
throw new Error('Process created without stdio streams');
}
}
let server = this._serverOptions;
// We got a function.
if (Is.func(server)) {
return server().then((result) => {
if (client_1.MessageTransports.is(result)) {
this._isDetached = !!result.detached;
return result;
}
else if (StreamInfo.is(result)) {
this._isDetached = !!result.detached;
return { reader: new node_1.StreamMessageReader(result.reader), writer: new node_1.StreamMessageWriter(result.writer) };
}
else {
let cp;
if (ChildProcessInfo.is(result)) {
cp = result.process;
this._isDetached = result.detached;
}
else {
cp = result;
this._isDetached = false;
}
cp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
return { reader: new node_1.StreamMessageReader(cp.stdout), writer: new node_1.StreamMessageWriter(cp.stdin) };
}
});
}
let json;
let runDebug = server;
if (runDebug.run || runDebug.debug) {
if (this._forceDebug || startedInDebugMode()) {
json = runDebug.debug;
}
else {
json = runDebug.run;
}
}
else {
json = server;
}
return this._getServerWorkingDir(json.options).then(serverWorkingDir => {
if (NodeModule.is(json) && json.module) {
let node = json;
let transport = node.transport || TransportKind.stdio;
if (node.runtime) {
let args = [];
let options = node.options || Object.create(null);
if (options.execArgv) {
options.execArgv.forEach(element => args.push(element));
}
args.push(node.module);
if (node.args) {
node.args.forEach(element => args.push(element));
}
const execOptions = Object.create(null);
execOptions.cwd = serverWorkingDir;
execOptions.env = getEnvironment(options.env, false);
const runtime = this._getRuntimePath(node.runtime, serverWorkingDir);
let pipeName = undefined;
if (transport === TransportKind.ipc) {
// exec options not correctly typed in lib
execOptions.stdio = [null, null, null, 'ipc'];
args.push('--node-ipc');
}
else if (transport === TransportKind.stdio) {
args.push('--stdio');
}
else if (transport === TransportKind.pipe) {
pipeName = node_1.generateRandomPipeName();
args.push(`--pipe=${pipeName}`);
}
else if (Transport.isSocket(transport)) {
args.push(`--socket=${transport.port}`);
}
args.push(`--clientProcessId=${process.pid.toString()}`);
if (transport === TransportKind.ipc || transport === TransportKind.stdio) {
let serverProcess = cp.spawn(runtime, args, execOptions);
if (!serverProcess || !serverProcess.pid) {
return Promise.reject(`Launching server using runtime ${runtime} failed.`);
}
this._serverProcess = serverProcess;
serverProcess.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
if (transport === TransportKind.ipc) {
serverProcess.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
return Promise.resolve({ reader: new node_1.IPCMessageReader(serverProcess), writer: new node_1.IPCMessageWriter(serverProcess) });
}
else {
return Promise.resolve({ reader: new node_1.StreamMessageReader(serverProcess.stdout), writer: new node_1.StreamMessageWriter(serverProcess.stdin) });
}
}
else if (transport === TransportKind.pipe) {
return node_1.createClientPipeTransport(pipeName).then((transport) => {
let process = cp.spawn(runtime, args, execOptions);
if (!process || !process.pid) {
return Promise.reject(`Launching server using runtime ${runtime} failed.`);
}
this._serverProcess = process;
process.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
process.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
return transport.onConnected().then((protocol) => {
return { reader: protocol[0], writer: protocol[1] };
});
});
}
else if (Transport.isSocket(transport)) {
return node_1.createClientSocketTransport(transport.port).then((transport) => {
let process = cp.spawn(runtime, args, execOptions);
if (!process || !process.pid) {
return Promise.reject(`Launching server using runtime ${runtime} failed.`);
}
this._serverProcess = process;
process.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
process.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
return transport.onConnected().then((protocol) => {
return { reader: protocol[0], writer: protocol[1] };
});
});
}
}
else {
let pipeName = undefined;
return new Promise((resolve, _reject) => {
let args = node.args && node.args.slice() || [];
if (transport === TransportKind.ipc) {
args.push('--node-ipc');
}
else if (transport === TransportKind.stdio) {
args.push('--stdio');
}
else if (transport === TransportKind.pipe) {
pipeName = node_1.generateRandomPipeName();
args.push(`--pipe=${pipeName}`);
}
else if (Transport.isSocket(transport)) {
args.push(`--socket=${transport.port}`);
}
args.push(`--clientProcessId=${process.pid.toString()}`);
let options = node.options || Object.create(null);
options.env = getEnvironment(options.env, true);
options.execArgv = options.execArgv || [];
options.cwd = serverWorkingDir;
options.silent = true;
if (transport === TransportKind.ipc || transport === TransportKind.stdio) {
let sp = cp.fork(node.module, args || [], options);
assertStdio(sp);
this._serverProcess = sp;
sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
if (transport === TransportKind.ipc) {
sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
resolve({ reader: new node_1.IPCMessageReader(this._serverProcess), writer: new node_1.IPCMessageWriter(this._serverProcess) });
}
else {
resolve({ reader: new node_1.StreamMessageReader(sp.stdout), writer: new node_1.StreamMessageWriter(sp.stdin) });
}
}
else if (transport === TransportKind.pipe) {
node_1.createClientPipeTransport(pipeName).then((transport) => {
let sp = cp.fork(node.module, args || [], options);
assertStdio(sp);
this._serverProcess = sp;
sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
transport.onConnected().then((protocol) => {
resolve({ reader: protocol[0], writer: protocol[1] });
});
});
}
else if (Transport.isSocket(transport)) {
node_1.createClientSocketTransport(transport.port).then((transport) => {
let sp = cp.fork(node.module, args || [], options);
assertStdio(sp);
this._serverProcess = sp;
sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
transport.onConnected().then((protocol) => {
resolve({ reader: protocol[0], writer: protocol[1] });
});
});
}
});
}
}
else if (Executable.is(json) && json.command) {
let command = json;
let args = command.args || [];
let options = Object.assign({}, command.options);
options.cwd = options.cwd || serverWorkingDir;
let serverProcess = cp.spawn(command.command, args, options);
if (!serverProcess || !serverProcess.pid) {
return Promise.reject(`Launching server using command ${command.command} failed.`);
}
serverProcess.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));
this._serverProcess = serverProcess;
this._isDetached = !!options.detached;
return Promise.resolve({ reader: new node_1.StreamMessageReader(serverProcess.stdout), writer: new node_1.StreamMessageWriter(serverProcess.stdin) });
}
return Promise.reject(new Error(`Unsupported server configuration ` + JSON.stringify(server, null, 4)));
});
}
_getRuntimePath(runtime, serverWorkingDirectory) {
if (path.isAbsolute(runtime)) {
return runtime;
}
const mainRootPath = this._mainGetRootPath();
if (mainRootPath !== undefined) {
const result = path.join(mainRootPath, runtime);
if (fs.existsSync(result)) {
return result;
}
}
if (serverWorkingDirectory !== undefined) {
const result = path.join(serverWorkingDirectory, runtime);
if (fs.existsSync(result)) {
return result;
}
}
return runtime;
}
_mainGetRootPath() {
let folders = vscode_1.workspace.workspaceFolders;
if (!folders || folders.length === 0) {
return undefined;
}
let folder = folders[0];
if (folder.uri.scheme === 'file') {
return folder.uri.fsPath;
}
return undefined;
}
_getServerWorkingDir(options) {
let cwd = options && options.cwd;
if (!cwd) {
cwd = this.clientOptions.workspaceFolder
? this.clientOptions.workspaceFolder.uri.fsPath
: this._mainGetRootPath();
}
if (cwd) {
// make sure the folder exists otherwise creating the process will fail
return new Promise(s => {
fs.lstat(cwd, (err, stats) => {
s(!err && stats.isDirectory() ? cwd : undefined);
});
});
}
return Promise.resolve(undefined);
}
getLocale() {
const envValue = process.env['VSCODE_NLS_CONFIG'];
if (envValue === undefined) {
return 'en';
}
let config = undefined;
try {
config = JSON.parse(envValue);
}
catch (err) {
}
if (config === undefined || typeof config.locale !== 'string') {
return 'en';
}
return config.locale;
}
}
exports.LanguageClient = LanguageClient;
class SettingMonitor {
constructor(_client, _setting) {
this._client = _client;
this._setting = _setting;
this._listeners = [];
}
start() {
vscode_1.workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this, this._listeners);
this.onDidChangeConfiguration();
return new vscode_1.Disposable(() => {
if (this._client.needsStop()) {
this._client.stop();
}
});
}
onDidChangeConfiguration() {
let index = this._setting.indexOf('.');
let primary = index >= 0 ? this._setting.substr(0, index) : this._setting;
let rest = index >= 0 ? this._setting.substr(index + 1) : undefined;
let enabled = rest ? vscode_1.workspace.getConfiguration(primary).get(rest, false) : vscode_1.workspace.getConfiguration(primary);
if (enabled && this._client.needsStart()) {
this._client.start();
}
else if (!enabled && this._client.needsStop()) {
this._client.stop();
}
}
}
exports.SettingMonitor = SettingMonitor;
//# sourceMappingURL=main.js.map

View File

@@ -0,0 +1,4 @@
/// <reference types="node" />
import * as cp from 'child_process';
import ChildProcess = cp.ChildProcess;
export declare function terminate(process: ChildProcess, cwd?: string): boolean;

View File

@@ -0,0 +1,48 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.terminate = void 0;
const cp = require("child_process");
const path_1 = require("path");
const isWindows = (process.platform === 'win32');
const isMacintosh = (process.platform === 'darwin');
const isLinux = (process.platform === 'linux');
function terminate(process, cwd) {
if (isWindows) {
try {
// This we run in Atom execFileSync is available.
// Ignore stderr since this is otherwise piped to parent.stderr
// which might be already closed.
let options = {
stdio: ['pipe', 'pipe', 'ignore']
};
if (cwd) {
options.cwd = cwd;
}
cp.execFileSync('taskkill', ['/T', '/F', '/PID', process.pid.toString()], options);
return true;
}
catch (err) {
return false;
}
}
else if (isLinux || isMacintosh) {
try {
var cmd = path_1.join(__dirname, 'terminateProcess.sh');
var result = cp.spawnSync(cmd, [process.pid.toString()]);
return result.error ? false : true;
}
catch (err) {
return false;
}
}
else {
process.kill('SIGKILL');
return true;
}
}
exports.terminate = terminate;
//# sourceMappingURL=processes.js.map

View File

@@ -0,0 +1,16 @@
#!/bin/bash
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
terminateTree() {
for cpid in $(pgrep -P $1); do
terminateTree $cpid
done
kill -9 $1 > /dev/null 2>&1
}
for pid in $*; do
terminateTree $pid
done

5
node_modules/vscode-languageclient/node.cmd generated vendored Normal file
View File

@@ -0,0 +1,5 @@
@echo off
REM This file is necessary to ensure that under Windows we don't
REM run the node.js file in the Windows Script Host when using
REM node in packakge.json scripts. See also PATHEXT setting
node.exe %*

6
node_modules/vscode-languageclient/node.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ----------------------------------------------------------------------------------------- */
export * from './lib/node/main';

7
node_modules/vscode-languageclient/node.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ----------------------------------------------------------------------------------------- */
'use strict';
module.exports = require('./lib/node/main');

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,129 @@
# brace-expansion
[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
as known from sh/bash, in JavaScript.
[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)
[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)
## Example
```js
var expand = require('brace-expansion');
expand('file-{a,b,c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('-v{,,}')
// => ['-v', '-v', '-v']
expand('file{0..2}.jpg')
// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
expand('file-{a..c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('file{2..0}.jpg')
// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
expand('file{0..4..2}.jpg')
// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
expand('file-{a..e..2}.jpg')
// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
expand('file{00..10..5}.jpg')
// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
expand('{{A..C},{a..c}}')
// => ['A', 'B', 'C', 'a', 'b', 'c']
expand('ppp{,config,oe{,conf}}')
// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
```
## API
```js
var expand = require('brace-expansion');
```
### var expanded = expand(str)
Return an array of all possible and valid expansions of `str`. If none are
found, `[str]` is returned.
Valid expansions are:
```js
/^(.*,)+(.+)?$/
// {a,b,...}
```
A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
A numeric sequence from `x` to `y` inclusive, with optional increment.
If `x` or `y` start with a leading `0`, all the numbers will be padded
to have equal length. Negative numbers and backwards iteration work too.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
An alphabetic sequence from `x` to `y` inclusive, with optional increment.
`x` and `y` must be exactly one character, and if given, `incr` must be a
number.
For compatibility reasons, the string `${` is not eligible for brace expansion.
## Installation
With [npm](https://npmjs.org) do:
```bash
npm install brace-expansion
```
## Contributors
- [Julian Gruber](https://github.com/juliangruber)
- [Isaac Z. Schlueter](https://github.com/isaacs)
## Sponsors
This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!
Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,201 @@
var concatMap = require('concat-map');
var balanced = require('balanced-match');
module.exports = expandTop;
var escSlash = '\0SLASH'+Math.random()+'\0';
var escOpen = '\0OPEN'+Math.random()+'\0';
var escClose = '\0CLOSE'+Math.random()+'\0';
var escComma = '\0COMMA'+Math.random()+'\0';
var escPeriod = '\0PERIOD'+Math.random()+'\0';
function numeric(str) {
return parseInt(str, 10) == str
? parseInt(str, 10)
: str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split('\\\\').join(escSlash)
.split('\\{').join(escOpen)
.split('\\}').join(escClose)
.split('\\,').join(escComma)
.split('\\.').join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join('\\')
.split(escOpen).join('{')
.split(escClose).join('}')
.split(escComma).join(',')
.split(escPeriod).join('.');
}
// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
if (!str)
return [''];
var parts = [];
var m = balanced('{', '}', str);
if (!m)
return str.split(',');
var pre = m.pre;
var body = m.body;
var post = m.post;
var p = pre.split(',');
p[p.length-1] += '{' + body + '}';
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length-1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
// I don't know why Bash 4.3 does this, but it does.
// Anything starting with {} will have the first two bytes preserved
// but *only* at the top level, so {},a}b will not expand to anything,
// but a{},b}c will be expanded to [a}c,abc].
// One could argue that this is a bug in Bash, but since the goal of
// this module is to match Bash's rules, we escape a leading {}
if (str.substr(0, 2) === '{}') {
str = '\\{\\}' + str.substr(2);
}
return expand(escapeBraces(str), true).map(unescapeBraces);
}
function identity(e) {
return e;
}
function embrace(str) {
return '{' + str + '}';
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
function expand(str, isTop) {
var expansions = [];
var m = balanced('{', '}', str);
if (!m || /\$$/.test(m.pre)) return [str];
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m.body.indexOf(',') >= 0;
if (!isSequence && !isOptions) {
// {a},b}
if (m.post.match(/,.*\}/)) {
str = m.pre + '{' + m.body + escClose + m.post;
return expand(str);
}
return [str];
}
var n;
if (isSequence) {
n = m.body.split(/\.\./);
} else {
n = parseCommaParts(m.body);
if (n.length === 1) {
// x{{a,b}}y ==> x{a}y x{b}y
n = expand(n[0], false).map(embrace);
if (n.length === 1) {
var post = m.post.length
? expand(m.post, false)
: [''];
return post.map(function(p) {
return m.pre + n[0] + p;
});
}
}
}
// at this point, n is the parts, and we know it's not a comma set
// with a single entry.
// no need to expand pre, since it is guaranteed to be free of brace-sets
var pre = m.pre;
var post = m.post.length
? expand(m.post, false)
: [''];
var N;
if (isSequence) {
var x = numeric(n[0]);
var y = numeric(n[1]);
var width = Math.max(n[0].length, n[1].length)
var incr = n.length == 3
? Math.abs(numeric(n[2]))
: 1;
var test = lte;
var reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
var pad = n.some(isPadded);
N = [];
for (var i = x; test(i, y); i += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === '\\')
c = '';
} else {
c = String(i);
if (pad) {
var need = width - c.length;
if (need > 0) {
var z = new Array(need + 1).join('0');
if (i < 0)
c = '-' + z + c.slice(1);
else
c = z + c;
}
}
}
N.push(c);
}
} else {
N = concatMap(n, function(el) { return expand(el, false) });
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + N[j] + post[k];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
return expansions;
}

View File

@@ -0,0 +1,47 @@
{
"name": "brace-expansion",
"description": "Brace expansion as known from sh/bash",
"version": "1.1.11",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/brace-expansion.git"
},
"homepage": "https://github.com/juliangruber/brace-expansion",
"main": "index.js",
"scripts": {
"test": "tape test/*.js",
"gentest": "bash test/generate.sh",
"bench": "matcha test/perf/bench.js"
},
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
},
"devDependencies": {
"matcha": "^0.7.0",
"tape": "^4.6.0"
},
"keywords": [],
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"license": "MIT",
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"firefox/20..latest",
"firefox/nightly",
"chrome/25..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
}
}

View File

@@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,230 @@
# minimatch
A minimal matching utility.
[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch)
This is the matching library used internally by npm.
It works by converting glob expressions into JavaScript `RegExp`
objects.
## Usage
```javascript
var minimatch = require("minimatch")
minimatch("bar.foo", "*.foo") // true!
minimatch("bar.foo", "*.bar") // false!
minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy!
```
## Features
Supports these glob features:
* Brace Expansion
* Extended glob matching
* "Globstar" `**` matching
See:
* `man sh`
* `man bash`
* `man 3 fnmatch`
* `man 5 gitignore`
## Minimatch Class
Create a minimatch object by instantiating the `minimatch.Minimatch` class.
```javascript
var Minimatch = require("minimatch").Minimatch
var mm = new Minimatch(pattern, options)
```
### Properties
* `pattern` The original pattern the minimatch object represents.
* `options` The options supplied to the constructor.
* `set` A 2-dimensional array of regexp or string expressions.
Each row in the
array corresponds to a brace-expanded pattern. Each item in the row
corresponds to a single path-part. For example, the pattern
`{a,b/c}/d` would expand to a set of patterns like:
[ [ a, d ]
, [ b, c, d ] ]
If a portion of the pattern doesn't have any "magic" in it
(that is, it's something like `"foo"` rather than `fo*o?`), then it
will be left as a string rather than converted to a regular
expression.
* `regexp` Created by the `makeRe` method. A single regular expression
expressing the entire pattern. This is useful in cases where you wish
to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
* `negate` True if the pattern is negated.
* `comment` True if the pattern is a comment.
* `empty` True if the pattern is `""`.
### Methods
* `makeRe` Generate the `regexp` member if necessary, and return it.
Will return `false` if the pattern is invalid.
* `match(fname)` Return true if the filename matches the pattern, or
false otherwise.
* `matchOne(fileArray, patternArray, partial)` Take a `/`-split
filename, and match it against a single row in the `regExpSet`. This
method is mainly for internal use, but is exposed so that it can be
used by a glob-walker that needs to avoid excessive filesystem calls.
All other methods are internal, and will be called as necessary.
### minimatch(path, pattern, options)
Main export. Tests a path against the pattern using the options.
```javascript
var isJS = minimatch(file, "*.js", { matchBase: true })
```
### minimatch.filter(pattern, options)
Returns a function that tests its
supplied argument, suitable for use with `Array.filter`. Example:
```javascript
var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true}))
```
### minimatch.match(list, pattern, options)
Match against the list of
files, in the style of fnmatch or glob. If nothing is matched, and
options.nonull is set, then return a list containing the pattern itself.
```javascript
var javascripts = minimatch.match(fileList, "*.js", {matchBase: true}))
```
### minimatch.makeRe(pattern, options)
Make a regular expression object from the pattern.
## Options
All options are `false` by default.
### debug
Dump a ton of stuff to stderr.
### nobrace
Do not expand `{a,b}` and `{1..3}` brace sets.
### noglobstar
Disable `**` matching against multiple folder names.
### dot
Allow patterns to match filenames starting with a period, even if
the pattern does not explicitly have a period in that spot.
Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
is set.
### noext
Disable "extglob" style patterns like `+(a|b)`.
### nocase
Perform a case-insensitive match.
### nonull
When a match is not found by `minimatch.match`, return a list containing
the pattern itself if this option is set. When not set, an empty list
is returned if there are no matches.
### matchBase
If set, then patterns without slashes will be matched
against the basename of the path if it contains slashes. For example,
`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.
### nocomment
Suppress the behavior of treating `#` at the start of a pattern as a
comment.
### nonegate
Suppress the behavior of treating a leading `!` character as negation.
### flipNegate
Returns from negate expressions the same as if they were not negated.
(Ie, true on a hit, false on a miss.)
### partial
Compare a partial path to a pattern. As long as the parts of the path that
are present are not contradicted by the pattern, it will be treated as a
match. This is useful in applications where you're walking through a
folder structure, and don't yet have the full path, but want to ensure that
you do not walk down paths that can never be a match.
For example,
```js
minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d
minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d
minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a
```
### allowWindowsEscape
Windows path separator `\` is by default converted to `/`, which
prohibits the usage of `\` as a escape character. This flag skips that
behavior and allows using the escape character.
## Comparisons to other fnmatch/glob implementations
While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between minimatch and other
implementations, and are intentional.
If the pattern starts with a `!` character, then it is negated. Set the
`nonegate` flag to suppress this behavior, and treat leading `!`
characters normally. This is perhaps relevant if you wish to start the
pattern with a negative extglob pattern like `!(a|B)`. Multiple `!`
characters at the start of a pattern will negate the pattern multiple
times.
If a pattern starts with `#`, then it is treated as a comment, and
will not match anything. Use `\#` to match a literal `#` at the
start of a line, or set the `nocomment` flag to suppress this behavior.
The double-star character `**` is supported by default, unless the
`noglobstar` flag is set. This is supported in the manner of bsdglob
and bash 4.1, where `**` only has special significance if it is the only
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.
If an escaped pattern has no matches, and the `nonull` flag is set,
then minimatch.match returns the pattern as-provided, rather than
interpreting the character escapes. For example,
`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.
If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern. Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity. Since those two are valid, matching proceeds.

View File

@@ -0,0 +1,947 @@
module.exports = minimatch
minimatch.Minimatch = Minimatch
var path = (function () { try { return require('path') } catch (e) {}}()) || {
sep: '/'
}
minimatch.sep = path.sep
var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
var expand = require('brace-expansion')
var plTypes = {
'!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
'?': { open: '(?:', close: ')?' },
'+': { open: '(?:', close: ')+' },
'*': { open: '(?:', close: ')*' },
'@': { open: '(?:', close: ')' }
}
// any single thing other than /
// don't need to escape / when using new RegExp()
var qmark = '[^/]'
// * => any number of characters
var star = qmark + '*?'
// ** when dots are allowed. Anything goes, except .. and .
// not (^ or / followed by one or two dots followed by $ or /),
// followed by anything, any number of times.
var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
// not a ^ or / followed by a dot,
// followed by anything, any number of times.
var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
// characters that need to be escaped in RegExp.
var reSpecials = charSet('().*{}+?[]^$\\!')
// "abc" -> { a:true, b:true, c:true }
function charSet (s) {
return s.split('').reduce(function (set, c) {
set[c] = true
return set
}, {})
}
// normalizes slashes.
var slashSplit = /\/+/
minimatch.filter = filter
function filter (pattern, options) {
options = options || {}
return function (p, i, list) {
return minimatch(p, pattern, options)
}
}
function ext (a, b) {
b = b || {}
var t = {}
Object.keys(a).forEach(function (k) {
t[k] = a[k]
})
Object.keys(b).forEach(function (k) {
t[k] = b[k]
})
return t
}
minimatch.defaults = function (def) {
if (!def || typeof def !== 'object' || !Object.keys(def).length) {
return minimatch
}
var orig = minimatch
var m = function minimatch (p, pattern, options) {
return orig(p, pattern, ext(def, options))
}
m.Minimatch = function Minimatch (pattern, options) {
return new orig.Minimatch(pattern, ext(def, options))
}
m.Minimatch.defaults = function defaults (options) {
return orig.defaults(ext(def, options)).Minimatch
}
m.filter = function filter (pattern, options) {
return orig.filter(pattern, ext(def, options))
}
m.defaults = function defaults (options) {
return orig.defaults(ext(def, options))
}
m.makeRe = function makeRe (pattern, options) {
return orig.makeRe(pattern, ext(def, options))
}
m.braceExpand = function braceExpand (pattern, options) {
return orig.braceExpand(pattern, ext(def, options))
}
m.match = function (list, pattern, options) {
return orig.match(list, pattern, ext(def, options))
}
return m
}
Minimatch.defaults = function (def) {
return minimatch.defaults(def).Minimatch
}
function minimatch (p, pattern, options) {
assertValidPattern(pattern)
if (!options) options = {}
// shortcut: comments match nothing.
if (!options.nocomment && pattern.charAt(0) === '#') {
return false
}
return new Minimatch(pattern, options).match(p)
}
function Minimatch (pattern, options) {
if (!(this instanceof Minimatch)) {
return new Minimatch(pattern, options)
}
assertValidPattern(pattern)
if (!options) options = {}
pattern = pattern.trim()
// windows support: need to use /, not \
if (!options.allowWindowsEscape && path.sep !== '/') {
pattern = pattern.split(path.sep).join('/')
}
this.options = options
this.set = []
this.pattern = pattern
this.regexp = null
this.negate = false
this.comment = false
this.empty = false
this.partial = !!options.partial
// make the set of regexps etc.
this.make()
}
Minimatch.prototype.debug = function () {}
Minimatch.prototype.make = make
function make () {
var pattern = this.pattern
var options = this.options
// empty patterns and comments match nothing.
if (!options.nocomment && pattern.charAt(0) === '#') {
this.comment = true
return
}
if (!pattern) {
this.empty = true
return
}
// step 1: figure out negation, etc.
this.parseNegate()
// step 2: expand braces
var set = this.globSet = this.braceExpand()
if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) }
this.debug(this.pattern, set)
// step 3: now we have a set, so turn each one into a series of path-portion
// matching patterns.
// These will be regexps, except in the case of "**", which is
// set to the GLOBSTAR object for globstar behavior,
// and will not contain any / characters
set = this.globParts = set.map(function (s) {
return s.split(slashSplit)
})
this.debug(this.pattern, set)
// glob --> regexps
set = set.map(function (s, si, set) {
return s.map(this.parse, this)
}, this)
this.debug(this.pattern, set)
// filter out everything that didn't compile properly.
set = set.filter(function (s) {
return s.indexOf(false) === -1
})
this.debug(this.pattern, set)
this.set = set
}
Minimatch.prototype.parseNegate = parseNegate
function parseNegate () {
var pattern = this.pattern
var negate = false
var options = this.options
var negateOffset = 0
if (options.nonegate) return
for (var i = 0, l = pattern.length
; i < l && pattern.charAt(i) === '!'
; i++) {
negate = !negate
negateOffset++
}
if (negateOffset) this.pattern = pattern.substr(negateOffset)
this.negate = negate
}
// Brace expansion:
// a{b,c}d -> abd acd
// a{b,}c -> abc ac
// a{0..3}d -> a0d a1d a2d a3d
// a{b,c{d,e}f}g -> abg acdfg acefg
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
//
// Invalid sets are not expanded.
// a{2..}b -> a{2..}b
// a{b}c -> a{b}c
minimatch.braceExpand = function (pattern, options) {
return braceExpand(pattern, options)
}
Minimatch.prototype.braceExpand = braceExpand
function braceExpand (pattern, options) {
if (!options) {
if (this instanceof Minimatch) {
options = this.options
} else {
options = {}
}
}
pattern = typeof pattern === 'undefined'
? this.pattern : pattern
assertValidPattern(pattern)
// Thanks to Yeting Li <https://github.com/yetingli> for
// improving this regexp to avoid a ReDOS vulnerability.
if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
// shortcut. no need to expand.
return [pattern]
}
return expand(pattern)
}
var MAX_PATTERN_LENGTH = 1024 * 64
var assertValidPattern = function (pattern) {
if (typeof pattern !== 'string') {
throw new TypeError('invalid pattern')
}
if (pattern.length > MAX_PATTERN_LENGTH) {
throw new TypeError('pattern is too long')
}
}
// parse a component of the expanded set.
// At this point, no pattern may contain "/" in it
// so we're going to return a 2d array, where each entry is the full
// pattern, split on '/', and then turned into a regular expression.
// A regexp is made at the end which joins each array with an
// escaped /, and another full one which joins each regexp with |.
//
// Following the lead of Bash 4.1, note that "**" only has special meaning
// when it is the *only* thing in a path portion. Otherwise, any series
// of * is equivalent to a single *. Globstar behavior is enabled by
// default, and can be disabled by setting options.noglobstar.
Minimatch.prototype.parse = parse
var SUBPARSE = {}
function parse (pattern, isSub) {
assertValidPattern(pattern)
var options = this.options
// shortcuts
if (pattern === '**') {
if (!options.noglobstar)
return GLOBSTAR
else
pattern = '*'
}
if (pattern === '') return ''
var re = ''
var hasMagic = !!options.nocase
var escaping = false
// ? => one single character
var patternListStack = []
var negativeLists = []
var stateChar
var inClass = false
var reClassStart = -1
var classStart = -1
// . and .. never match anything that doesn't start with .,
// even when options.dot is set.
var patternStart = pattern.charAt(0) === '.' ? '' // anything
// not (start or / followed by . or .. followed by / or end)
: options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
: '(?!\\.)'
var self = this
function clearStateChar () {
if (stateChar) {
// we had some state-tracking character
// that wasn't consumed by this pass.
switch (stateChar) {
case '*':
re += star
hasMagic = true
break
case '?':
re += qmark
hasMagic = true
break
default:
re += '\\' + stateChar
break
}
self.debug('clearStateChar %j %j', stateChar, re)
stateChar = false
}
}
for (var i = 0, len = pattern.length, c
; (i < len) && (c = pattern.charAt(i))
; i++) {
this.debug('%s\t%s %s %j', pattern, i, re, c)
// skip over any that are escaped.
if (escaping && reSpecials[c]) {
re += '\\' + c
escaping = false
continue
}
switch (c) {
/* istanbul ignore next */
case '/': {
// completely not allowed, even escaped.
// Should already be path-split by now.
return false
}
case '\\':
clearStateChar()
escaping = true
continue
// the various stateChar values
// for the "extglob" stuff.
case '?':
case '*':
case '+':
case '@':
case '!':
this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
// all of those are literals inside a class, except that
// the glob [!a] means [^a] in regexp
if (inClass) {
this.debug(' in class')
if (c === '!' && i === classStart + 1) c = '^'
re += c
continue
}
// if we already have a stateChar, then it means
// that there was something like ** or +? in there.
// Handle the stateChar, then proceed with this one.
self.debug('call clearStateChar %j', stateChar)
clearStateChar()
stateChar = c
// if extglob is disabled, then +(asdf|foo) isn't a thing.
// just clear the statechar *now*, rather than even diving into
// the patternList stuff.
if (options.noext) clearStateChar()
continue
case '(':
if (inClass) {
re += '('
continue
}
if (!stateChar) {
re += '\\('
continue
}
patternListStack.push({
type: stateChar,
start: i - 1,
reStart: re.length,
open: plTypes[stateChar].open,
close: plTypes[stateChar].close
})
// negation is (?:(?!js)[^/]*)
re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
this.debug('plType %j %j', stateChar, re)
stateChar = false
continue
case ')':
if (inClass || !patternListStack.length) {
re += '\\)'
continue
}
clearStateChar()
hasMagic = true
var pl = patternListStack.pop()
// negation is (?:(?!js)[^/]*)
// The others are (?:<pattern>)<type>
re += pl.close
if (pl.type === '!') {
negativeLists.push(pl)
}
pl.reEnd = re.length
continue
case '|':
if (inClass || !patternListStack.length || escaping) {
re += '\\|'
escaping = false
continue
}
clearStateChar()
re += '|'
continue
// these are mostly the same in regexp and glob
case '[':
// swallow any state-tracking char before the [
clearStateChar()
if (inClass) {
re += '\\' + c
continue
}
inClass = true
classStart = i
reClassStart = re.length
re += c
continue
case ']':
// a right bracket shall lose its special
// meaning and represent itself in
// a bracket expression if it occurs
// first in the list. -- POSIX.2 2.8.3.2
if (i === classStart + 1 || !inClass) {
re += '\\' + c
escaping = false
continue
}
// handle the case where we left a class open.
// "[z-a]" is valid, equivalent to "\[z-a\]"
// split where the last [ was, make sure we don't have
// an invalid re. if so, re-walk the contents of the
// would-be class to re-translate any characters that
// were passed through as-is
// TODO: It would probably be faster to determine this
// without a try/catch and a new RegExp, but it's tricky
// to do safely. For now, this is safe and works.
var cs = pattern.substring(classStart + 1, i)
try {
RegExp('[' + cs + ']')
} catch (er) {
// not a valid class!
var sp = this.parse(cs, SUBPARSE)
re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
hasMagic = hasMagic || sp[1]
inClass = false
continue
}
// finish up the class.
hasMagic = true
inClass = false
re += c
continue
default:
// swallow any state char that wasn't consumed
clearStateChar()
if (escaping) {
// no need
escaping = false
} else if (reSpecials[c]
&& !(c === '^' && inClass)) {
re += '\\'
}
re += c
} // switch
} // for
// handle the case where we left a class open.
// "[abc" is valid, equivalent to "\[abc"
if (inClass) {
// split where the last [ was, and escape it
// this is a huge pita. We now have to re-walk
// the contents of the would-be class to re-translate
// any characters that were passed through as-is
cs = pattern.substr(classStart + 1)
sp = this.parse(cs, SUBPARSE)
re = re.substr(0, reClassStart) + '\\[' + sp[0]
hasMagic = hasMagic || sp[1]
}
// handle the case where we had a +( thing at the *end*
// of the pattern.
// each pattern list stack adds 3 chars, and we need to go through
// and escape any | chars that were passed through as-is for the regexp.
// Go through and escape them, taking care not to double-escape any
// | chars that were already escaped.
for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
var tail = re.slice(pl.reStart + pl.open.length)
this.debug('setting tail', re, pl)
// maybe some even number of \, then maybe 1 \, followed by a |
tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
if (!$2) {
// the | isn't already escaped, so escape it.
$2 = '\\'
}
// need to escape all those slashes *again*, without escaping the
// one that we need for escaping the | character. As it works out,
// escaping an even number of slashes can be done by simply repeating
// it exactly after itself. That's why this trick works.
//
// I am sorry that you have to see this.
return $1 + $1 + $2 + '|'
})
this.debug('tail=%j\n %s', tail, tail, pl, re)
var t = pl.type === '*' ? star
: pl.type === '?' ? qmark
: '\\' + pl.type
hasMagic = true
re = re.slice(0, pl.reStart) + t + '\\(' + tail
}
// handle trailing things that only matter at the very end.
clearStateChar()
if (escaping) {
// trailing \\
re += '\\\\'
}
// only need to apply the nodot start if the re starts with
// something that could conceivably capture a dot
var addPatternStart = false
switch (re.charAt(0)) {
case '[': case '.': case '(': addPatternStart = true
}
// Hack to work around lack of negative lookbehind in JS
// A pattern like: *.!(x).!(y|z) needs to ensure that a name
// like 'a.xyz.yz' doesn't match. So, the first negative
// lookahead, has to look ALL the way ahead, to the end of
// the pattern.
for (var n = negativeLists.length - 1; n > -1; n--) {
var nl = negativeLists[n]
var nlBefore = re.slice(0, nl.reStart)
var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
var nlAfter = re.slice(nl.reEnd)
nlLast += nlAfter
// Handle nested stuff like *(*.js|!(*.json)), where open parens
// mean that we should *not* include the ) in the bit that is considered
// "after" the negated section.
var openParensBefore = nlBefore.split('(').length - 1
var cleanAfter = nlAfter
for (i = 0; i < openParensBefore; i++) {
cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
}
nlAfter = cleanAfter
var dollar = ''
if (nlAfter === '' && isSub !== SUBPARSE) {
dollar = '$'
}
var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
re = newRe
}
// if the re is not "" at this point, then we need to make sure
// it doesn't match against an empty path part.
// Otherwise a/* will match a/, which it should not.
if (re !== '' && hasMagic) {
re = '(?=.)' + re
}
if (addPatternStart) {
re = patternStart + re
}
// parsing just a piece of a larger pattern.
if (isSub === SUBPARSE) {
return [re, hasMagic]
}
// skip the regexp for non-magical patterns
// unescape anything in it, though, so that it'll be
// an exact match against a file etc.
if (!hasMagic) {
return globUnescape(pattern)
}
var flags = options.nocase ? 'i' : ''
try {
var regExp = new RegExp('^' + re + '$', flags)
} catch (er) /* istanbul ignore next - should be impossible */ {
// If it was an invalid regular expression, then it can't match
// anything. This trick looks for a character after the end of
// the string, which is of course impossible, except in multi-line
// mode, but it's not a /m regex.
return new RegExp('$.')
}
regExp._glob = pattern
regExp._src = re
return regExp
}
minimatch.makeRe = function (pattern, options) {
return new Minimatch(pattern, options || {}).makeRe()
}
Minimatch.prototype.makeRe = makeRe
function makeRe () {
if (this.regexp || this.regexp === false) return this.regexp
// at this point, this.set is a 2d array of partial
// pattern strings, or "**".
//
// It's better to use .match(). This function shouldn't
// be used, really, but it's pretty convenient sometimes,
// when you just want to work with a regex.
var set = this.set
if (!set.length) {
this.regexp = false
return this.regexp
}
var options = this.options
var twoStar = options.noglobstar ? star
: options.dot ? twoStarDot
: twoStarNoDot
var flags = options.nocase ? 'i' : ''
var re = set.map(function (pattern) {
return pattern.map(function (p) {
return (p === GLOBSTAR) ? twoStar
: (typeof p === 'string') ? regExpEscape(p)
: p._src
}).join('\\\/')
}).join('|')
// must match entire pattern
// ending in a * or ** will make it less strict.
re = '^(?:' + re + ')$'
// can match anything, as long as it's not this.
if (this.negate) re = '^(?!' + re + ').*$'
try {
this.regexp = new RegExp(re, flags)
} catch (ex) /* istanbul ignore next - should be impossible */ {
this.regexp = false
}
return this.regexp
}
minimatch.match = function (list, pattern, options) {
options = options || {}
var mm = new Minimatch(pattern, options)
list = list.filter(function (f) {
return mm.match(f)
})
if (mm.options.nonull && !list.length) {
list.push(pattern)
}
return list
}
Minimatch.prototype.match = function match (f, partial) {
if (typeof partial === 'undefined') partial = this.partial
this.debug('match', f, this.pattern)
// short-circuit in the case of busted things.
// comments, etc.
if (this.comment) return false
if (this.empty) return f === ''
if (f === '/' && partial) return true
var options = this.options
// windows: need to use /, not \
if (path.sep !== '/') {
f = f.split(path.sep).join('/')
}
// treat the test path as a set of pathparts.
f = f.split(slashSplit)
this.debug(this.pattern, 'split', f)
// just ONE of the pattern sets in this.set needs to match
// in order for it to be valid. If negating, then just one
// match means that we have failed.
// Either way, return on the first hit.
var set = this.set
this.debug(this.pattern, 'set', set)
// Find the basename of the path by looking for the last non-empty segment
var filename
var i
for (i = f.length - 1; i >= 0; i--) {
filename = f[i]
if (filename) break
}
for (i = 0; i < set.length; i++) {
var pattern = set[i]
var file = f
if (options.matchBase && pattern.length === 1) {
file = [filename]
}
var hit = this.matchOne(file, pattern, partial)
if (hit) {
if (options.flipNegate) return true
return !this.negate
}
}
// didn't get any hits. this is success if it's a negative
// pattern, failure otherwise.
if (options.flipNegate) return false
return this.negate
}
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
Minimatch.prototype.matchOne = function (file, pattern, partial) {
var options = this.options
this.debug('matchOne',
{ 'this': this, file: file, pattern: pattern })
this.debug('matchOne', file.length, pattern.length)
for (var fi = 0,
pi = 0,
fl = file.length,
pl = pattern.length
; (fi < fl) && (pi < pl)
; fi++, pi++) {
this.debug('matchOne loop')
var p = pattern[pi]
var f = file[fi]
this.debug(pattern, p, f)
// should be impossible.
// some invalid regexp stuff in the set.
/* istanbul ignore if */
if (p === false) return false
if (p === GLOBSTAR) {
this.debug('GLOBSTAR', [pattern, p, f])
// "**"
// a/**/b/**/c would match the following:
// a/b/x/y/z/c
// a/x/y/z/b/c
// a/b/x/b/x/c
// a/b/c
// To do this, take the rest of the pattern after
// the **, and see if it would match the file remainder.
// If so, return success.
// If not, the ** "swallows" a segment, and try again.
// This is recursively awful.
//
// a/**/b/**/c matching a/b/x/y/z/c
// - a matches a
// - doublestar
// - matchOne(b/x/y/z/c, b/**/c)
// - b matches b
// - doublestar
// - matchOne(x/y/z/c, c) -> no
// - matchOne(y/z/c, c) -> no
// - matchOne(z/c, c) -> no
// - matchOne(c, c) yes, hit
var fr = fi
var pr = pi + 1
if (pr === pl) {
this.debug('** at the end')
// a ** at the end will just swallow the rest.
// We have found a match.
// however, it will not swallow /.x, unless
// options.dot is set.
// . and .. are *never* matched by **, for explosively
// exponential reasons.
for (; fi < fl; fi++) {
if (file[fi] === '.' || file[fi] === '..' ||
(!options.dot && file[fi].charAt(0) === '.')) return false
}
return true
}
// ok, let's see if we can swallow whatever we can.
while (fr < fl) {
var swallowee = file[fr]
this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
// XXX remove this slice. Just pass the start index.
if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
this.debug('globstar found match!', fr, fl, swallowee)
// found a match.
return true
} else {
// can't swallow "." or ".." ever.
// can only swallow ".foo" when explicitly asked.
if (swallowee === '.' || swallowee === '..' ||
(!options.dot && swallowee.charAt(0) === '.')) {
this.debug('dot detected!', file, fr, pattern, pr)
break
}
// ** swallows a segment, and continue.
this.debug('globstar swallow a segment, and continue')
fr++
}
}
// no match was found.
// However, in partial mode, we can't say this is necessarily over.
// If there's more *pattern* left, then
/* istanbul ignore if */
if (partial) {
// ran out of file
this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
if (fr === fl) return true
}
return false
}
// something other than **
// non-magic patterns just have to match exactly
// patterns with magic have been turned into regexps.
var hit
if (typeof p === 'string') {
hit = f === p
this.debug('string match', p, f, hit)
} else {
hit = f.match(p)
this.debug('pattern match', p, f, hit)
}
if (!hit) return false
}
// Note: ending in / means that we'll get a final ""
// at the end of the pattern. This can only match a
// corresponding "" at the end of the file.
// If the file ends in /, then it can only match a
// a pattern that ends in /, unless the pattern just
// doesn't have any more for it. But, a/b/ should *not*
// match "a/b/*", even though "" matches against the
// [^/]*? pattern, except in partial mode, where it might
// simply not be reached yet.
// However, a/b/ should still satisfy a/*
// now either we fell off the end of the pattern, or we're done.
if (fi === fl && pi === pl) {
// ran out of pattern and filename at the same time.
// an exact hit!
return true
} else if (fi === fl) {
// ran out of file, but still had pattern left.
// this is ok if we're doing the match as part of
// a glob fs traversal.
return partial
} else /* istanbul ignore else */ if (pi === pl) {
// ran out of pattern, still have file left.
// this is only acceptable if we're on the very last
// empty segment of a file with a trailing slash.
// a/* should match a/b/
return (fi === fl - 1) && (file[fi] === '')
}
// should be unreachable.
/* istanbul ignore next */
throw new Error('wtf?')
}
// replace stuff like \* with *
function globUnescape (s) {
return s.replace(/\\(.)/g, '$1')
}
function regExpEscape (s) {
return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
}

View File

@@ -0,0 +1,33 @@
{
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me)",
"name": "minimatch",
"description": "a glob matcher in javascript",
"version": "3.1.2",
"publishConfig": {
"tag": "v3-legacy"
},
"repository": {
"type": "git",
"url": "git://github.com/isaacs/minimatch.git"
},
"main": "minimatch.js",
"scripts": {
"test": "tap",
"preversion": "npm test",
"postversion": "npm publish",
"postpublish": "git push origin --all; git push origin --tags"
},
"engines": {
"node": "*"
},
"dependencies": {
"brace-expansion": "^1.1.7"
},
"devDependencies": {
"tap": "^15.1.6"
},
"license": "ISC",
"files": [
"minimatch.js"
]
}

45
node_modules/vscode-languageclient/package.json generated vendored Normal file
View File

@@ -0,0 +1,45 @@
{
"name": "vscode-languageclient",
"description": "VSCode Language client implementation",
"version": "7.0.0",
"author": "Microsoft Corporation",
"license": "MIT",
"engines": {
"vscode": "^1.52.0"
},
"repository": {
"type": "git",
"url": "https://github.com/Microsoft/vscode-languageserver-node.git",
"directory": "client"
},
"bugs": {
"url": "https://github.com/Microsoft/vscode-languageserver-node/issues"
},
"main": "./lib/node/main.js",
"browser": {
"./lib/node/main.js": "./lib/browser/main.js"
},
"typings": "./lib/common/api.d.ts",
"devDependencies": {
"@types/minimatch": "^3.0.3",
"@types/semver": "^7.3.4",
"@types/vscode": "1.52.0",
"shx": "^0.3.2"
},
"dependencies": {
"minimatch": "^3.0.4",
"semver": "^7.3.4",
"vscode-languageserver-protocol": "3.16.0"
},
"scripts": {
"install:dev": "cd src/node && npm install",
"prepublishOnly": "git clean -xfd . && npm install && npm run clean && node ./bin/updateVSCode.js && npm run compile && npm test",
"postpublish": "node ../build/npm/post-publish.js",
"compile": "node ../build/bin/tsc -b ./tsconfig.json && shx cp src/node/terminateProcess.sh lib/node/terminateProcess.sh",
"compile:clean": "git clean -xfd . && npm install && npm run clean && npm run compile",
"watch": "node ../build/bin/tsc -b ./tsconfig-watch.json -w",
"test": "cd ../client-node-tests && npm test && cd ../client",
"clean": "node ../node_modules/rimraf/bin.js lib",
"preversion": "npm test"
}
}

View File

@@ -0,0 +1,77 @@
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
For Microsoft vscode-languageclient
This project incorporates material from the project(s) listed below (collectively, “Third Party Code”).
Microsoft is not the original author of the Third Party Code. The original copyright notice and license
under which Microsoft received such Third Party Code are set out below. This Third Party Code is licensed
to you under their original license terms set forth below. Microsoft reserves all other rights not expressly
granted, whether by implication, estoppel or otherwise.
1. DefinitelyTyped version 0.0.1 (https://github.com/borisyankov/DefinitelyTyped)
2. semver version 6.3.0 (https://github.com/npm/node-semver)
3. minimatch version 3.0.4 (https://github.com/isaacs/minimatch)
%% DefinitelyTyped NOTICES AND INFORMATION BEGIN HERE
=========================================
This project is licensed under the MIT license.
Copyrights are respective of each contributor listed at the beginning of each definition file.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=========================================
END OF DefinitelyTyped NOTICES AND INFORMATION
%% semver NOTICES AND INFORMATION BEGIN HERE
=========================================
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
=========================================
END OF semver NOTICES AND INFORMATION
%% minimatch NOTICES AND INFORMATION BEGIN HERE
=========================================
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
=========================================
END OF minimatch NOTICES AND INFORMATION

View File

@@ -0,0 +1,7 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
declare module 'vscode' {
}