-(function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
-/******/ // The module cache
-/******/ var installedModules = {};
-/******/
-/******/ // The require function
-/******/ function __webpack_require__(moduleId) {
-/******/
-/******/ // Check if module is in cache
-/******/ if(installedModules[moduleId]) {
-/******/ return installedModules[moduleId].exports;
-/******/ }
-/******/ // Create a new module (and put it into the cache)
-/******/ var module = installedModules[moduleId] = {
-/******/ i: moduleId,
-/******/ l: false,
-/******/ exports: {}
-/******/ };
-/******/
-/******/ // Execute the module function
-/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
-/******/
-/******/ // Flag the module as loaded
-/******/ module.l = true;
-/******/
-/******/ // Return the exports of the module
-/******/ return module.exports;
-/******/ }
-/******/
-/******/
-/******/ // expose the modules object (__webpack_modules__)
-/******/ __webpack_require__.m = modules;
-/******/
-/******/ // expose the module cache
-/******/ __webpack_require__.c = installedModules;
-/******/
-/******/ // define getter function for harmony exports
-/******/ __webpack_require__.d = function(exports, name, getter) {
-/******/ if(!__webpack_require__.o(exports, name)) {
-/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
-/******/ }
-/******/ };
-/******/
-/******/ // define __esModule on exports
-/******/ __webpack_require__.r = function(exports) {
-/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
-/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
-/******/ }
-/******/ Object.defineProperty(exports, '__esModule', { value: true });
-/******/ };
-/******/
-/******/ // create a fake namespace object
-/******/ // mode & 1: value is a module id, require it
-/******/ // mode & 2: merge all properties of value into the ns
-/******/ // mode & 4: return value when already ns object
-/******/ // mode & 8|1: behave like require
-/******/ __webpack_require__.t = function(value, mode) {
-/******/ if(mode & 1) value = __webpack_require__(value);
-/******/ if(mode & 8) return value;
-/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
-/******/ var ns = Object.create(null);
-/******/ __webpack_require__.r(ns);
-/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
-/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
-/******/ return ns;
-/******/ };
-/******/
-/******/ // getDefaultExport function for compatibility with non-harmony modules
-/******/ __webpack_require__.n = function(module) {
-/******/ var getter = module && module.__esModule ?
-/******/ function getDefault() { return module['default']; } :
-/******/ function getModuleExports() { return module; };
-/******/ __webpack_require__.d(getter, 'a', getter);
-/******/ return getter;
-/******/ };
-/******/
-/******/ // Object.prototype.hasOwnProperty.call
-/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
-/******/
-/******/ // __webpack_public_path__
-/******/ __webpack_require__.p = "";
-/******/
-/******/
-/******/ // Load entry module and return exports
-/******/ return __webpack_require__(__webpack_require__.s = 0);
-/******/ })
-/************************************************************************/
-/******/ ([
-/* 0 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
+var __create = Object.create;
+var __defProp = Object.defineProperty;
+var __getProtoOf = Object.getPrototypeOf;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
+var __commonJS = (callback, module2) => () => {
+ if (!module2) {
+ module2 = {exports: {}};
+ callback(module2.exports, module2);
+ }
+ return module2.exports;
};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
+var __export = (target, all) => {
+ __markAsModule(target);
+ for (var name in all)
+ __defProp(target, name, {get: all[name], enumerable: true});
};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.activate = void 0;
-const coc_nvim_1 = __webpack_require__(1);
-const server_1 = __importDefault(__webpack_require__(2));
-const commands_1 = __webpack_require__(140);
-const organizeImports_1 = __webpack_require__(114);
-const plugins_1 = __webpack_require__(141);
-function activate(context) {
- return __awaiter(this, void 0, void 0, function* () {
- let { subscriptions } = context;
- const config = coc_nvim_1.workspace.getConfiguration().get('tsserver', {});
- if (!config.enable)
- return;
- const pluginManager = new plugins_1.PluginManager();
- const service = new server_1.default(pluginManager);
- subscriptions.push(coc_nvim_1.services.regist(service));
- yield service.start();
- function registCommand(cmd) {
- let { id, execute } = cmd;
- subscriptions.push(coc_nvim_1.commands.registerCommand(id, execute, cmd));
- }
- registCommand(new commands_1.AutoFixCommand(service.clientHost));
- registCommand(new commands_1.ReloadProjectsCommand(service.clientHost));
- registCommand(new commands_1.OpenTsServerLogCommand(service.clientHost));
- registCommand(new commands_1.TypeScriptGoToProjectConfigCommand(service.clientHost));
- registCommand(new organizeImports_1.OrganizeImportsCommand(service.clientHost.serviceClient));
- registCommand(new commands_1.ConfigurePluginCommand(pluginManager));
- registCommand(coc_nvim_1.commands.register({
- id: 'tsserver.restart',
- execute: () => {
- // tslint:disable-next-line:no-floating-promises
- service.stop().then(() => {
- setTimeout(() => {
- service.restart();
- }, 100);
- });
- }
- }));
- return {
- configurePlugin: (pluginId, configuration) => {
- pluginManager.setConfiguration(pluginId, configuration);
- }
- };
- });
-}
-exports.activate = activate;
-
-
-/***/ }),
-/* 1 */
-/***/ (function(module, exports) {
-
-module.exports = require("coc.nvim");
-
-/***/ }),
-/* 2 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
+var __exportStar = (target, module2, desc) => {
+ __markAsModule(target);
+ if (module2 && typeof module2 === "object" || typeof module2 === "function") {
+ for (let key of __getOwnPropNames(module2))
+ if (!__hasOwnProp.call(target, key) && key !== "default")
+ __defProp(target, key, {get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable});
+ }
+ return target;
};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
+var __toModule = (module2) => {
+ if (module2 && module2.__esModule)
+ return module2;
+ return __exportStar(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", {value: module2, enumerable: true}), module2);
};
-Object.defineProperty(exports, "__esModule", { value: true });
-const coc_nvim_1 = __webpack_require__(1);
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const typescriptServiceClientHost_1 = __importDefault(__webpack_require__(33));
-const languageDescription_1 = __webpack_require__(115);
-class TsserverService {
- constructor(pluginManager) {
- this.pluginManager = pluginManager;
- this.id = 'tsserver';
- this.name = 'tsserver';
- this.state = coc_nvim_1.ServiceStat.Initial;
- this._onDidServiceReady = new vscode_languageserver_protocol_1.Emitter();
- this.onServiceReady = this._onDidServiceReady.event;
- this.disposables = [];
- this.descriptions = [];
- const config = coc_nvim_1.workspace.getConfiguration('tsserver');
- const enableJavascript = !!config.get('enableJavascript');
- this.enable = config.get('enable');
- this.descriptions = languageDescription_1.standardLanguageDescriptions.filter(o => {
- return enableJavascript ? true : o.id != 'javascript';
- });
- this.selector = this.descriptions.reduce((arr, c) => {
- return arr.concat(c.modeIds);
- }, []);
- coc_nvim_1.workspace.onDidOpenTextDocument(doc => {
- this.ensureConfigurationForDocument(doc);
- }, null, this.disposables);
- }
- get config() {
- return coc_nvim_1.workspace.getConfiguration('tsserver');
- }
- ensureConfigurationForDocument(document) {
- let uri = coc_nvim_1.Uri.parse(document.uri);
- let language = this.clientHost.findLanguage(uri);
- if (!language)
- return;
- language.fileConfigurationManager.ensureConfigurationForDocument(document).catch(_e => {
- // noop
- });
+
+// node_modules/vscode-jsonrpc/lib/common/ral.js
+var require_ral = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ var _ral;
+ function RAL() {
+ if (_ral === void 0) {
+ throw new Error(`No runtime abstraction layer installed`);
}
- start() {
- if (this.clientHost)
- return;
- this.state = coc_nvim_1.ServiceStat.Starting;
- this.clientHost = new typescriptServiceClientHost_1.default(this.descriptions, this.pluginManager);
- this.disposables.push(this.clientHost);
- let client = this.clientHost.serviceClient;
- return new Promise(resolve => {
- let started = false;
- client.onTsServerStarted(() => {
- Object.defineProperty(this, 'state', {
- get: () => {
- return this.clientHost.serviceClient.state;
- }
- });
- this._onDidServiceReady.fire(void 0);
- this.ensureConfiguration();
- if (!started) {
- started = true;
- resolve();
- }
- });
- });
+ return _ral;
+ }
+ (function(RAL2) {
+ function install(ral) {
+ if (ral === void 0) {
+ throw new Error(`No runtime abstraction layer provided`);
+ }
+ _ral = ral;
}
- ensureConfiguration() {
- if (!this.clientHost)
- return;
- for (let doc of coc_nvim_1.workspace.documents) {
- this.ensureConfigurationForDocument(doc.textDocument);
+ RAL2.install = install;
+ })(RAL || (RAL = {}));
+ exports2.default = RAL;
+});
+
+// node_modules/vscode-jsonrpc/lib/common/disposable.js
+var require_disposable = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.Disposable = void 0;
+ var Disposable13;
+ (function(Disposable14) {
+ function create(func) {
+ return {
+ dispose: func
+ };
+ }
+ Disposable14.create = create;
+ })(Disposable13 = exports2.Disposable || (exports2.Disposable = {}));
+});
+
+// node_modules/vscode-jsonrpc/lib/common/messageBuffer.js
+var require_messageBuffer = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.AbstractMessageBuffer = void 0;
+ var CR = 13;
+ var LF = 10;
+ var CRLF = "\r\n";
+ var AbstractMessageBuffer = class {
+ constructor(encoding = "utf-8") {
+ this._encoding = encoding;
+ this._chunks = [];
+ this._totalLength = 0;
+ }
+ get encoding() {
+ return this._encoding;
+ }
+ append(chunk) {
+ const toAppend = typeof chunk === "string" ? this.fromString(chunk, this._encoding) : chunk;
+ this._chunks.push(toAppend);
+ this._totalLength += toAppend.byteLength;
+ }
+ tryReadHeaders() {
+ if (this._chunks.length === 0) {
+ return void 0;
+ }
+ let state = 0;
+ let chunkIndex = 0;
+ let offset = 0;
+ let chunkBytesRead = 0;
+ row:
+ while (chunkIndex < this._chunks.length) {
+ const chunk = this._chunks[chunkIndex];
+ offset = 0;
+ column:
+ while (offset < chunk.length) {
+ const value = chunk[offset];
+ switch (value) {
+ case CR:
+ switch (state) {
+ case 0:
+ state = 1;
+ break;
+ case 2:
+ state = 3;
+ break;
+ default:
+ state = 0;
+ }
+ break;
+ case LF:
+ switch (state) {
+ case 1:
+ state = 2;
+ break;
+ case 3:
+ state = 4;
+ offset++;
+ break row;
+ default:
+ state = 0;
+ }
+ break;
+ default:
+ state = 0;
+ }
+ offset++;
+ }
+ chunkBytesRead += chunk.byteLength;
+ chunkIndex++;
}
+ if (state !== 4) {
+ return void 0;
+ }
+ const buffer = this._read(chunkBytesRead + offset);
+ const result = new Map();
+ const headers = this.toString(buffer, "ascii").split(CRLF);
+ if (headers.length < 2) {
+ return result;
+ }
+ for (let i = 0; i < headers.length - 2; i++) {
+ const header = headers[i];
+ const index = header.indexOf(":");
+ if (index === -1) {
+ throw new Error("Message header must separate key and value using :");
+ }
+ const key = header.substr(0, index);
+ const value = header.substr(index + 1).trim();
+ result.set(key, value);
+ }
+ return result;
}
- dispose() {
- coc_nvim_1.disposeAll(this.disposables);
+ tryReadBody(length) {
+ if (this._totalLength < length) {
+ return void 0;
+ }
+ return this._read(length);
}
- restart() {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.clientHost)
- return;
- let client = this.clientHost.serviceClient;
- yield client.restartTsServer();
- });
+ get numberOfBytes() {
+ return this._totalLength;
}
- stop() {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.clientHost)
- return;
- this.clientHost.reset();
- let client = this.clientHost.serviceClient;
- yield client.stop();
- return;
- });
+ _read(byteCount) {
+ if (byteCount === 0) {
+ return this.emptyBuffer();
+ }
+ if (byteCount > this._totalLength) {
+ throw new Error(`Cannot read so many bytes!`);
+ }
+ if (this._chunks[0].byteLength === byteCount) {
+ const chunk = this._chunks[0];
+ this._chunks.shift();
+ this._totalLength -= byteCount;
+ return this.asNative(chunk);
+ }
+ if (this._chunks[0].byteLength > byteCount) {
+ const chunk = this._chunks[0];
+ const result2 = this.asNative(chunk, byteCount);
+ this._chunks[0] = chunk.slice(byteCount);
+ this._totalLength -= byteCount;
+ return result2;
+ }
+ const result = this.allocNative(byteCount);
+ let resultOffset = 0;
+ let chunkIndex = 0;
+ while (byteCount > 0) {
+ const chunk = this._chunks[chunkIndex];
+ if (chunk.byteLength > byteCount) {
+ const chunkPart = chunk.slice(0, byteCount);
+ result.set(chunkPart, resultOffset);
+ resultOffset += byteCount;
+ this._chunks[chunkIndex] = chunk.slice(byteCount);
+ this._totalLength -= byteCount;
+ byteCount -= byteCount;
+ } else {
+ result.set(chunk, resultOffset);
+ resultOffset += chunk.byteLength;
+ this._chunks.shift();
+ this._totalLength -= chunk.byteLength;
+ byteCount -= chunk.byteLength;
+ }
+ }
+ return result;
}
-}
-exports.default = TsserverService;
-
-
-/***/ }),
-/* 3 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-function __export(m) {\r
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r
-}\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const vscode_jsonrpc_1 = __webpack_require__(4);\r
-exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;\r
-exports.ResponseError = vscode_jsonrpc_1.ResponseError;\r
-exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;\r
-exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;\r
-exports.Disposable = vscode_jsonrpc_1.Disposable;\r
-exports.Event = vscode_jsonrpc_1.Event;\r
-exports.Emitter = vscode_jsonrpc_1.Emitter;\r
-exports.Trace = vscode_jsonrpc_1.Trace;\r
-exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;\r
-exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;\r
-exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;\r
-exports.RequestType = vscode_jsonrpc_1.RequestType;\r
-exports.RequestType0 = vscode_jsonrpc_1.RequestType0;\r
-exports.NotificationType = vscode_jsonrpc_1.NotificationType;\r
-exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;\r
-exports.MessageReader = vscode_jsonrpc_1.MessageReader;\r
-exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;\r
-exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;\r
-exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;\r
-exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;\r
-exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;\r
-exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;\r
-exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;\r
-exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;\r
-exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;\r
-exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;\r
-exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;\r
-exports.ProgressType = vscode_jsonrpc_1.ProgressType;\r
-__export(__webpack_require__(18));\r
-__export(__webpack_require__(19));\r
-const callHierarchy = __webpack_require__(31);\r
-const st = __webpack_require__(32);\r
-var Proposed;\r
-(function (Proposed) {\r
- let CallHierarchyPrepareRequest;\r
- (function (CallHierarchyPrepareRequest) {\r
- CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;\r
- CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;\r
- })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));\r
- let CallHierarchyIncomingCallsRequest;\r
- (function (CallHierarchyIncomingCallsRequest) {\r
- CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;\r
- CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;\r
- })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));\r
- let CallHierarchyOutgoingCallsRequest;\r
- (function (CallHierarchyOutgoingCallsRequest) {\r
- CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;\r
- CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;\r
- })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));\r
- Proposed.SemanticTokenTypes = st.SemanticTokenTypes;\r
- Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;\r
- Proposed.SemanticTokens = st.SemanticTokens;\r
- let SemanticTokensRequest;\r
- (function (SemanticTokensRequest) {\r
- SemanticTokensRequest.method = st.SemanticTokensRequest.method;\r
- SemanticTokensRequest.type = st.SemanticTokensRequest.type;\r
- })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));\r
- let SemanticTokensEditsRequest;\r
- (function (SemanticTokensEditsRequest) {\r
- SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;\r
- SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;\r
- })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));\r
- let SemanticTokensRangeRequest;\r
- (function (SemanticTokensRangeRequest) {\r
- SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;\r
- SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;\r
- })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));\r
-})(Proposed = exports.Proposed || (exports.Proposed = {}));\r
-function createProtocolConnection(reader, writer, logger, strategy) {\r
- return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);\r
-}\r
-exports.createProtocolConnection = createProtocolConnection;\r
-
-
-/***/ }),
-/* 4 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-/// <reference path="../typings/thenable.d.ts" />\r
-\r
-function __export(m) {\r
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r
-}\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const Is = __webpack_require__(5);\r
-const messages_1 = __webpack_require__(6);\r
-exports.RequestType = messages_1.RequestType;\r
-exports.RequestType0 = messages_1.RequestType0;\r
-exports.RequestType1 = messages_1.RequestType1;\r
-exports.RequestType2 = messages_1.RequestType2;\r
-exports.RequestType3 = messages_1.RequestType3;\r
-exports.RequestType4 = messages_1.RequestType4;\r
-exports.RequestType5 = messages_1.RequestType5;\r
-exports.RequestType6 = messages_1.RequestType6;\r
-exports.RequestType7 = messages_1.RequestType7;\r
-exports.RequestType8 = messages_1.RequestType8;\r
-exports.RequestType9 = messages_1.RequestType9;\r
-exports.ResponseError = messages_1.ResponseError;\r
-exports.ErrorCodes = messages_1.ErrorCodes;\r
-exports.NotificationType = messages_1.NotificationType;\r
-exports.NotificationType0 = messages_1.NotificationType0;\r
-exports.NotificationType1 = messages_1.NotificationType1;\r
-exports.NotificationType2 = messages_1.NotificationType2;\r
-exports.NotificationType3 = messages_1.NotificationType3;\r
-exports.NotificationType4 = messages_1.NotificationType4;\r
-exports.NotificationType5 = messages_1.NotificationType5;\r
-exports.NotificationType6 = messages_1.NotificationType6;\r
-exports.NotificationType7 = messages_1.NotificationType7;\r
-exports.NotificationType8 = messages_1.NotificationType8;\r
-exports.NotificationType9 = messages_1.NotificationType9;\r
-const messageReader_1 = __webpack_require__(7);\r
-exports.MessageReader = messageReader_1.MessageReader;\r
-exports.StreamMessageReader = messageReader_1.StreamMessageReader;\r
-exports.IPCMessageReader = messageReader_1.IPCMessageReader;\r
-exports.SocketMessageReader = messageReader_1.SocketMessageReader;\r
-const messageWriter_1 = __webpack_require__(9);\r
-exports.MessageWriter = messageWriter_1.MessageWriter;\r
-exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;\r
-exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;\r
-exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;\r
-const events_1 = __webpack_require__(8);\r
-exports.Disposable = events_1.Disposable;\r
-exports.Event = events_1.Event;\r
-exports.Emitter = events_1.Emitter;\r
-const cancellation_1 = __webpack_require__(10);\r
-exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;\r
-exports.CancellationToken = cancellation_1.CancellationToken;\r
-const linkedMap_1 = __webpack_require__(11);\r
-__export(__webpack_require__(12));\r
-__export(__webpack_require__(17));\r
-var CancelNotification;\r
-(function (CancelNotification) {\r
- CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');\r
-})(CancelNotification || (CancelNotification = {}));\r
-var ProgressNotification;\r
-(function (ProgressNotification) {\r
- ProgressNotification.type = new messages_1.NotificationType('$/progress');\r
-})(ProgressNotification || (ProgressNotification = {}));\r
-class ProgressType {\r
- constructor() {\r
- }\r
-}\r
-exports.ProgressType = ProgressType;\r
-exports.NullLogger = Object.freeze({\r
- error: () => { },\r
- warn: () => { },\r
- info: () => { },\r
- log: () => { }\r
-});\r
-var Trace;\r
-(function (Trace) {\r
- Trace[Trace["Off"] = 0] = "Off";\r
- Trace[Trace["Messages"] = 1] = "Messages";\r
- Trace[Trace["Verbose"] = 2] = "Verbose";\r
-})(Trace = exports.Trace || (exports.Trace = {}));\r
-(function (Trace) {\r
- function fromString(value) {\r
- if (!Is.string(value)) {\r
- return Trace.Off;\r
- }\r
- value = value.toLowerCase();\r
- switch (value) {\r
- case 'off':\r
- return Trace.Off;\r
- case 'messages':\r
- return Trace.Messages;\r
- case 'verbose':\r
- return Trace.Verbose;\r
- default:\r
- return Trace.Off;\r
- }\r
- }\r
- Trace.fromString = fromString;\r
- function toString(value) {\r
- switch (value) {\r
- case Trace.Off:\r
- return 'off';\r
- case Trace.Messages:\r
- return 'messages';\r
- case Trace.Verbose:\r
- return 'verbose';\r
- default:\r
- return 'off';\r
- }\r
- }\r
- Trace.toString = toString;\r
-})(Trace = exports.Trace || (exports.Trace = {}));\r
-var TraceFormat;\r
-(function (TraceFormat) {\r
- TraceFormat["Text"] = "text";\r
- TraceFormat["JSON"] = "json";\r
-})(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));\r
-(function (TraceFormat) {\r
- function fromString(value) {\r
- value = value.toLowerCase();\r
- if (value === 'json') {\r
- return TraceFormat.JSON;\r
- }\r
- else {\r
- return TraceFormat.Text;\r
- }\r
- }\r
- TraceFormat.fromString = fromString;\r
-})(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));\r
-var SetTraceNotification;\r
-(function (SetTraceNotification) {\r
- SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');\r
-})(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));\r
-var LogTraceNotification;\r
-(function (LogTraceNotification) {\r
- LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');\r
-})(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));\r
-var ConnectionErrors;\r
-(function (ConnectionErrors) {\r
- /**\r
- * The connection is closed.\r
- */\r
- ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";\r
- /**\r
- * The connection got disposed.\r
- */\r
- ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";\r
- /**\r
- * The connection is already in listening mode.\r
- */\r
- ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";\r
-})(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));\r
-class ConnectionError extends Error {\r
- constructor(code, message) {\r
- super(message);\r
- this.code = code;\r
- Object.setPrototypeOf(this, ConnectionError.prototype);\r
- }\r
-}\r
-exports.ConnectionError = ConnectionError;\r
-var ConnectionStrategy;\r
-(function (ConnectionStrategy) {\r
- function is(value) {\r
- let candidate = value;\r
- return candidate && Is.func(candidate.cancelUndispatched);\r
- }\r
- ConnectionStrategy.is = is;\r
-})(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));\r
-var ConnectionState;\r
-(function (ConnectionState) {\r
- ConnectionState[ConnectionState["New"] = 1] = "New";\r
- ConnectionState[ConnectionState["Listening"] = 2] = "Listening";\r
- ConnectionState[ConnectionState["Closed"] = 3] = "Closed";\r
- ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";\r
-})(ConnectionState || (ConnectionState = {}));\r
-function _createMessageConnection(messageReader, messageWriter, logger, strategy) {\r
- let sequenceNumber = 0;\r
- let notificationSquenceNumber = 0;\r
- let unknownResponseSquenceNumber = 0;\r
- const version = '2.0';\r
- let starRequestHandler = undefined;\r
- let requestHandlers = Object.create(null);\r
- let starNotificationHandler = undefined;\r
- let notificationHandlers = Object.create(null);\r
- let progressHandlers = new Map();\r
- let timer;\r
- let messageQueue = new linkedMap_1.LinkedMap();\r
- let responsePromises = Object.create(null);\r
- let requestTokens = Object.create(null);\r
- let trace = Trace.Off;\r
- let traceFormat = TraceFormat.Text;\r
- let tracer;\r
- let state = ConnectionState.New;\r
- let errorEmitter = new events_1.Emitter();\r
- let closeEmitter = new events_1.Emitter();\r
- let unhandledNotificationEmitter = new events_1.Emitter();\r
- let unhandledProgressEmitter = new events_1.Emitter();\r
- let disposeEmitter = new events_1.Emitter();\r
- function createRequestQueueKey(id) {\r
- return 'req-' + id.toString();\r
- }\r
- function createResponseQueueKey(id) {\r
- if (id === null) {\r
- return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();\r
- }\r
- else {\r
- return 'res-' + id.toString();\r
- }\r
- }\r
- function createNotificationQueueKey() {\r
- return 'not-' + (++notificationSquenceNumber).toString();\r
- }\r
- function addMessageToQueue(queue, message) {\r
- if (messages_1.isRequestMessage(message)) {\r
- queue.set(createRequestQueueKey(message.id), message);\r
- }\r
- else if (messages_1.isResponseMessage(message)) {\r
- queue.set(createResponseQueueKey(message.id), message);\r
- }\r
- else {\r
- queue.set(createNotificationQueueKey(), message);\r
- }\r
- }\r
- function cancelUndispatched(_message) {\r
- return undefined;\r
- }\r
- function isListening() {\r
- return state === ConnectionState.Listening;\r
- }\r
- function isClosed() {\r
- return state === ConnectionState.Closed;\r
- }\r
- function isDisposed() {\r
- return state === ConnectionState.Disposed;\r
- }\r
- function closeHandler() {\r
- if (state === ConnectionState.New || state === ConnectionState.Listening) {\r
- state = ConnectionState.Closed;\r
- closeEmitter.fire(undefined);\r
- }\r
- // If the connection is disposed don't sent close events.\r
- }\r
- function readErrorHandler(error) {\r
- errorEmitter.fire([error, undefined, undefined]);\r
- }\r
- function writeErrorHandler(data) {\r
- errorEmitter.fire(data);\r
- }\r
- messageReader.onClose(closeHandler);\r
- messageReader.onError(readErrorHandler);\r
- messageWriter.onClose(closeHandler);\r
- messageWriter.onError(writeErrorHandler);\r
- function triggerMessageQueue() {\r
- if (timer || messageQueue.size === 0) {\r
- return;\r
- }\r
- timer = setImmediate(() => {\r
- timer = undefined;\r
- processMessageQueue();\r
- });\r
- }\r
- function processMessageQueue() {\r
- if (messageQueue.size === 0) {\r
- return;\r
- }\r
- let message = messageQueue.shift();\r
- try {\r
- if (messages_1.isRequestMessage(message)) {\r
- handleRequest(message);\r
- }\r
- else if (messages_1.isNotificationMessage(message)) {\r
- handleNotification(message);\r
- }\r
- else if (messages_1.isResponseMessage(message)) {\r
- handleResponse(message);\r
- }\r
- else {\r
- handleInvalidMessage(message);\r
- }\r
- }\r
- finally {\r
- triggerMessageQueue();\r
- }\r
- }\r
- let callback = (message) => {\r
- try {\r
- // We have received a cancellation message. Check if the message is still in the queue\r
- // and cancel it if allowed to do so.\r
- if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {\r
- let key = createRequestQueueKey(message.params.id);\r
- let toCancel = messageQueue.get(key);\r
- if (messages_1.isRequestMessage(toCancel)) {\r
- let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);\r
- if (response && (response.error !== void 0 || response.result !== void 0)) {\r
- messageQueue.delete(key);\r
- response.id = toCancel.id;\r
- traceSendingResponse(response, message.method, Date.now());\r
- messageWriter.write(response);\r
- return;\r
- }\r
- }\r
- }\r
- addMessageToQueue(messageQueue, message);\r
- }\r
- finally {\r
- triggerMessageQueue();\r
- }\r
- };\r
- function handleRequest(requestMessage) {\r
- if (isDisposed()) {\r
- // we return here silently since we fired an event when the\r
- // connection got disposed.\r
- return;\r
- }\r
- function reply(resultOrError, method, startTime) {\r
- let message = {\r
- jsonrpc: version,\r
- id: requestMessage.id\r
- };\r
- if (resultOrError instanceof messages_1.ResponseError) {\r
- message.error = resultOrError.toJson();\r
- }\r
- else {\r
- message.result = resultOrError === void 0 ? null : resultOrError;\r
- }\r
- traceSendingResponse(message, method, startTime);\r
- messageWriter.write(message);\r
- }\r
- function replyError(error, method, startTime) {\r
- let message = {\r
- jsonrpc: version,\r
- id: requestMessage.id,\r
- error: error.toJson()\r
- };\r
- traceSendingResponse(message, method, startTime);\r
- messageWriter.write(message);\r
- }\r
- function replySuccess(result, method, startTime) {\r
- // The JSON RPC defines that a response must either have a result or an error\r
- // So we can't treat undefined as a valid response result.\r
- if (result === void 0) {\r
- result = null;\r
- }\r
- let message = {\r
- jsonrpc: version,\r
- id: requestMessage.id,\r
- result: result\r
- };\r
- traceSendingResponse(message, method, startTime);\r
- messageWriter.write(message);\r
- }\r
- traceReceivedRequest(requestMessage);\r
- let element = requestHandlers[requestMessage.method];\r
- let type;\r
- let requestHandler;\r
- if (element) {\r
- type = element.type;\r
- requestHandler = element.handler;\r
- }\r
- let startTime = Date.now();\r
- if (requestHandler || starRequestHandler) {\r
- let cancellationSource = new cancellation_1.CancellationTokenSource();\r
- let tokenKey = String(requestMessage.id);\r
- requestTokens[tokenKey] = cancellationSource;\r
- try {\r
- let handlerResult;\r
- if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {\r
- handlerResult = requestHandler\r
- ? requestHandler(cancellationSource.token)\r
- : starRequestHandler(requestMessage.method, cancellationSource.token);\r
- }\r
- else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {\r
- handlerResult = requestHandler\r
- ? requestHandler(...requestMessage.params, cancellationSource.token)\r
- : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);\r
- }\r
- else {\r
- handlerResult = requestHandler\r
- ? requestHandler(requestMessage.params, cancellationSource.token)\r
- : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);\r
- }\r
- let promise = handlerResult;\r
- if (!handlerResult) {\r
- delete requestTokens[tokenKey];\r
- replySuccess(handlerResult, requestMessage.method, startTime);\r
- }\r
- else if (promise.then) {\r
- promise.then((resultOrError) => {\r
- delete requestTokens[tokenKey];\r
- reply(resultOrError, requestMessage.method, startTime);\r
- }, error => {\r
- delete requestTokens[tokenKey];\r
- if (error instanceof messages_1.ResponseError) {\r
- replyError(error, requestMessage.method, startTime);\r
- }\r
- else if (error && Is.string(error.message)) {\r
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);\r
- }\r
- else {\r
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);\r
- }\r
- });\r
- }\r
- else {\r
- delete requestTokens[tokenKey];\r
- reply(handlerResult, requestMessage.method, startTime);\r
- }\r
- }\r
- catch (error) {\r
- delete requestTokens[tokenKey];\r
- if (error instanceof messages_1.ResponseError) {\r
- reply(error, requestMessage.method, startTime);\r
- }\r
- else if (error && Is.string(error.message)) {\r
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);\r
- }\r
- else {\r
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);\r
- }\r
- }\r
- }\r
- else {\r
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);\r
- }\r
- }\r
- function handleResponse(responseMessage) {\r
- if (isDisposed()) {\r
- // See handle request.\r
- return;\r
- }\r
- if (responseMessage.id === null) {\r
- if (responseMessage.error) {\r
- logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);\r
- }\r
- else {\r
- logger.error(`Received response message without id. No further error information provided.`);\r
- }\r
- }\r
- else {\r
- let key = String(responseMessage.id);\r
- let responsePromise = responsePromises[key];\r
- traceReceivedResponse(responseMessage, responsePromise);\r
- if (responsePromise) {\r
- delete responsePromises[key];\r
- try {\r
- if (responseMessage.error) {\r
- let error = responseMessage.error;\r
- responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));\r
- }\r
- else if (responseMessage.result !== void 0) {\r
- responsePromise.resolve(responseMessage.result);\r
- }\r
- else {\r
- throw new Error('Should never happen.');\r
- }\r
- }\r
- catch (error) {\r
- if (error.message) {\r
- logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);\r
- }\r
- else {\r
- logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);\r
- }\r
- }\r
- }\r
- }\r
- }\r
- function handleNotification(message) {\r
- if (isDisposed()) {\r
- // See handle request.\r
- return;\r
- }\r
- let type = undefined;\r
- let notificationHandler;\r
- if (message.method === CancelNotification.type.method) {\r
- notificationHandler = (params) => {\r
- let id = params.id;\r
- let source = requestTokens[String(id)];\r
- if (source) {\r
- source.cancel();\r
- }\r
- };\r
- }\r
- else {\r
- let element = notificationHandlers[message.method];\r
- if (element) {\r
- notificationHandler = element.handler;\r
- type = element.type;\r
- }\r
- }\r
- if (notificationHandler || starNotificationHandler) {\r
- try {\r
- traceReceivedNotification(message);\r
- if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {\r
- notificationHandler ? notificationHandler() : starNotificationHandler(message.method);\r
- }\r
- else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {\r
- notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);\r
- }\r
- else {\r
- notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);\r
- }\r
- }\r
- catch (error) {\r
- if (error.message) {\r
- logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);\r
- }\r
- else {\r
- logger.error(`Notification handler '${message.method}' failed unexpectedly.`);\r
- }\r
- }\r
- }\r
- else {\r
- unhandledNotificationEmitter.fire(message);\r
- }\r
- }\r
- function handleInvalidMessage(message) {\r
- if (!message) {\r
- logger.error('Received empty message.');\r
- return;\r
- }\r
- logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);\r
- // Test whether we find an id to reject the promise\r
- let responseMessage = message;\r
- if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {\r
- let key = String(responseMessage.id);\r
- let responseHandler = responsePromises[key];\r
- if (responseHandler) {\r
- responseHandler.reject(new Error('The received response has neither a result nor an error property.'));\r
- }\r
- }\r
- }\r
- function traceSendingRequest(message) {\r
- if (trace === Trace.Off || !tracer) {\r
- return;\r
- }\r
- if (traceFormat === TraceFormat.Text) {\r
- let data = undefined;\r
- if (trace === Trace.Verbose && message.params) {\r
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
- }\r
- tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);\r
- }\r
- else {\r
- logLSPMessage('send-request', message);\r
- }\r
- }\r
- function traceSendingNotification(message) {\r
- if (trace === Trace.Off || !tracer) {\r
- return;\r
- }\r
- if (traceFormat === TraceFormat.Text) {\r
- let data = undefined;\r
- if (trace === Trace.Verbose) {\r
- if (message.params) {\r
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
- }\r
- else {\r
- data = 'No parameters provided.\n\n';\r
- }\r
- }\r
- tracer.log(`Sending notification '${message.method}'.`, data);\r
- }\r
- else {\r
- logLSPMessage('send-notification', message);\r
- }\r
- }\r
- function traceSendingResponse(message, method, startTime) {\r
- if (trace === Trace.Off || !tracer) {\r
- return;\r
- }\r
- if (traceFormat === TraceFormat.Text) {\r
- let data = undefined;\r
- if (trace === Trace.Verbose) {\r
- if (message.error && message.error.data) {\r
- data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;\r
- }\r
- else {\r
- if (message.result) {\r
- data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;\r
- }\r
- else if (message.error === void 0) {\r
- data = 'No result returned.\n\n';\r
- }\r
- }\r
- }\r
- tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);\r
- }\r
- else {\r
- logLSPMessage('send-response', message);\r
- }\r
- }\r
- function traceReceivedRequest(message) {\r
- if (trace === Trace.Off || !tracer) {\r
- return;\r
- }\r
- if (traceFormat === TraceFormat.Text) {\r
- let data = undefined;\r
- if (trace === Trace.Verbose && message.params) {\r
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
- }\r
- tracer.log(`Received request '${message.method} - (${message.id})'.`, data);\r
- }\r
- else {\r
- logLSPMessage('receive-request', message);\r
- }\r
- }\r
- function traceReceivedNotification(message) {\r
- if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {\r
- return;\r
- }\r
- if (traceFormat === TraceFormat.Text) {\r
- let data = undefined;\r
- if (trace === Trace.Verbose) {\r
- if (message.params) {\r
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
- }\r
- else {\r
- data = 'No parameters provided.\n\n';\r
- }\r
- }\r
- tracer.log(`Received notification '${message.method}'.`, data);\r
- }\r
- else {\r
- logLSPMessage('receive-notification', message);\r
- }\r
- }\r
- function traceReceivedResponse(message, responsePromise) {\r
- if (trace === Trace.Off || !tracer) {\r
- return;\r
- }\r
- if (traceFormat === TraceFormat.Text) {\r
- let data = undefined;\r
- if (trace === Trace.Verbose) {\r
- if (message.error && message.error.data) {\r
- data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;\r
- }\r
- else {\r
- if (message.result) {\r
- data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;\r
- }\r
- else if (message.error === void 0) {\r
- data = 'No result returned.\n\n';\r
- }\r
- }\r
- }\r
- if (responsePromise) {\r
- let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';\r
- tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);\r
- }\r
- else {\r
- tracer.log(`Received response ${message.id} without active response promise.`, data);\r
- }\r
- }\r
- else {\r
- logLSPMessage('receive-response', message);\r
- }\r
- }\r
- function logLSPMessage(type, message) {\r
- if (!tracer || trace === Trace.Off) {\r
- return;\r
- }\r
- const lspMessage = {\r
- isLSPMessage: true,\r
- type,\r
- message,\r
- timestamp: Date.now()\r
- };\r
- tracer.log(lspMessage);\r
- }\r
- function throwIfClosedOrDisposed() {\r
- if (isClosed()) {\r
- throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');\r
- }\r
- if (isDisposed()) {\r
- throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');\r
- }\r
- }\r
- function throwIfListening() {\r
- if (isListening()) {\r
- throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');\r
- }\r
- }\r
- function throwIfNotListening() {\r
- if (!isListening()) {\r
- throw new Error('Call listen() first.');\r
- }\r
- }\r
- function undefinedToNull(param) {\r
- if (param === void 0) {\r
- return null;\r
- }\r
- else {\r
- return param;\r
- }\r
- }\r
- function computeMessageParams(type, params) {\r
- let result;\r
- let numberOfParams = type.numberOfParams;\r
- switch (numberOfParams) {\r
- case 0:\r
- result = null;\r
- break;\r
- case 1:\r
- result = undefinedToNull(params[0]);\r
- break;\r
- default:\r
- result = [];\r
- for (let i = 0; i < params.length && i < numberOfParams; i++) {\r
- result.push(undefinedToNull(params[i]));\r
- }\r
- if (params.length < numberOfParams) {\r
- for (let i = params.length; i < numberOfParams; i++) {\r
- result.push(null);\r
- }\r
- }\r
- break;\r
- }\r
- return result;\r
- }\r
- let connection = {\r
- sendNotification: (type, ...params) => {\r
- throwIfClosedOrDisposed();\r
- let method;\r
- let messageParams;\r
- if (Is.string(type)) {\r
- method = type;\r
- switch (params.length) {\r
- case 0:\r
- messageParams = null;\r
- break;\r
- case 1:\r
- messageParams = params[0];\r
- break;\r
- default:\r
- messageParams = params;\r
- break;\r
- }\r
- }\r
- else {\r
- method = type.method;\r
- messageParams = computeMessageParams(type, params);\r
- }\r
- let notificationMessage = {\r
- jsonrpc: version,\r
- method: method,\r
- params: messageParams\r
- };\r
- traceSendingNotification(notificationMessage);\r
- messageWriter.write(notificationMessage);\r
- },\r
- onNotification: (type, handler) => {\r
- throwIfClosedOrDisposed();\r
- if (Is.func(type)) {\r
- starNotificationHandler = type;\r
- }\r
- else if (handler) {\r
- if (Is.string(type)) {\r
- notificationHandlers[type] = { type: undefined, handler };\r
- }\r
- else {\r
- notificationHandlers[type.method] = { type, handler };\r
- }\r
- }\r
- },\r
- onProgress: (_type, token, handler) => {\r
- if (progressHandlers.has(token)) {\r
- throw new Error(`Progress handler for token ${token} already registered`);\r
- }\r
- progressHandlers.set(token, handler);\r
- return {\r
- dispose: () => {\r
- progressHandlers.delete(token);\r
- }\r
- };\r
- },\r
- sendProgress: (_type, token, value) => {\r
- connection.sendNotification(ProgressNotification.type, { token, value });\r
- },\r
- onUnhandledProgress: unhandledProgressEmitter.event,\r
- sendRequest: (type, ...params) => {\r
- throwIfClosedOrDisposed();\r
- throwIfNotListening();\r
- let method;\r
- let messageParams;\r
- let token = undefined;\r
- if (Is.string(type)) {\r
- method = type;\r
- switch (params.length) {\r
- case 0:\r
- messageParams = null;\r
- break;\r
- case 1:\r
- // The cancellation token is optional so it can also be undefined.\r
- if (cancellation_1.CancellationToken.is(params[0])) {\r
- messageParams = null;\r
- token = params[0];\r
- }\r
- else {\r
- messageParams = undefinedToNull(params[0]);\r
- }\r
- break;\r
- default:\r
- const last = params.length - 1;\r
- if (cancellation_1.CancellationToken.is(params[last])) {\r
- token = params[last];\r
- if (params.length === 2) {\r
- messageParams = undefinedToNull(params[0]);\r
- }\r
- else {\r
- messageParams = params.slice(0, last).map(value => undefinedToNull(value));\r
- }\r
- }\r
- else {\r
- messageParams = params.map(value => undefinedToNull(value));\r
- }\r
- break;\r
- }\r
- }\r
- else {\r
- method = type.method;\r
- messageParams = computeMessageParams(type, params);\r
- let numberOfParams = type.numberOfParams;\r
- token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;\r
- }\r
- let id = sequenceNumber++;\r
- let result = new Promise((resolve, reject) => {\r
- let requestMessage = {\r
- jsonrpc: version,\r
- id: id,\r
- method: method,\r
- params: messageParams\r
- };\r
- let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };\r
- traceSendingRequest(requestMessage);\r
- try {\r
- messageWriter.write(requestMessage);\r
- }\r
- catch (e) {\r
- // Writing the message failed. So we need to reject the promise.\r
- responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));\r
- responsePromise = null;\r
- }\r
- if (responsePromise) {\r
- responsePromises[String(id)] = responsePromise;\r
- }\r
- });\r
- if (token) {\r
- token.onCancellationRequested(() => {\r
- connection.sendNotification(CancelNotification.type, { id });\r
- });\r
- }\r
- return result;\r
- },\r
- onRequest: (type, handler) => {\r
- throwIfClosedOrDisposed();\r
- if (Is.func(type)) {\r
- starRequestHandler = type;\r
- }\r
- else if (handler) {\r
- if (Is.string(type)) {\r
- requestHandlers[type] = { type: undefined, handler };\r
- }\r
- else {\r
- requestHandlers[type.method] = { type, handler };\r
- }\r
- }\r
- },\r
- trace: (_value, _tracer, sendNotificationOrTraceOptions) => {\r
- let _sendNotification = false;\r
- let _traceFormat = TraceFormat.Text;\r
- if (sendNotificationOrTraceOptions !== void 0) {\r
- if (Is.boolean(sendNotificationOrTraceOptions)) {\r
- _sendNotification = sendNotificationOrTraceOptions;\r
- }\r
- else {\r
- _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;\r
- _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;\r
- }\r
- }\r
- trace = _value;\r
- traceFormat = _traceFormat;\r
- if (trace === Trace.Off) {\r
- tracer = undefined;\r
- }\r
- else {\r
- tracer = _tracer;\r
- }\r
- if (_sendNotification && !isClosed() && !isDisposed()) {\r
- connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });\r
- }\r
- },\r
- onError: errorEmitter.event,\r
- onClose: closeEmitter.event,\r
- onUnhandledNotification: unhandledNotificationEmitter.event,\r
- onDispose: disposeEmitter.event,\r
- dispose: () => {\r
- if (isDisposed()) {\r
- return;\r
- }\r
- state = ConnectionState.Disposed;\r
- disposeEmitter.fire(undefined);\r
- let error = new Error('Connection got disposed.');\r
- Object.keys(responsePromises).forEach((key) => {\r
- responsePromises[key].reject(error);\r
- });\r
- responsePromises = Object.create(null);\r
- requestTokens = Object.create(null);\r
- messageQueue = new linkedMap_1.LinkedMap();\r
- // Test for backwards compatibility\r
- if (Is.func(messageWriter.dispose)) {\r
- messageWriter.dispose();\r
- }\r
- if (Is.func(messageReader.dispose)) {\r
- messageReader.dispose();\r
- }\r
- },\r
- listen: () => {\r
- throwIfClosedOrDisposed();\r
- throwIfListening();\r
- state = ConnectionState.Listening;\r
- messageReader.listen(callback);\r
- },\r
- inspect: () => {\r
- // eslint-disable-next-line no-console\r
- console.log('inspect');\r
- }\r
- };\r
- connection.onNotification(LogTraceNotification.type, (params) => {\r
- if (trace === Trace.Off || !tracer) {\r
- return;\r
- }\r
- tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);\r
- });\r
- connection.onNotification(ProgressNotification.type, (params) => {\r
- const handler = progressHandlers.get(params.token);\r
- if (handler) {\r
- handler(params.value);\r
- }\r
- else {\r
- unhandledProgressEmitter.fire(params);\r
- }\r
- });\r
- return connection;\r
-}\r
-function isMessageReader(value) {\r
- return value.listen !== void 0 && value.read === void 0;\r
-}\r
-function isMessageWriter(value) {\r
- return value.write !== void 0 && value.end === void 0;\r
-}\r
-function createMessageConnection(input, output, logger, strategy) {\r
- if (!logger) {\r
- logger = exports.NullLogger;\r
- }\r
- let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);\r
- let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);\r
- return _createMessageConnection(reader, writer, logger, strategy);\r
-}\r
-exports.createMessageConnection = createMessageConnection;\r
-
-
-/***/ }),
-/* 5 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-function boolean(value) {\r
- return value === true || value === false;\r
-}\r
-exports.boolean = boolean;\r
-function string(value) {\r
- return typeof value === 'string' || value instanceof String;\r
-}\r
-exports.string = string;\r
-function number(value) {\r
- return typeof value === 'number' || value instanceof Number;\r
-}\r
-exports.number = number;\r
-function error(value) {\r
- return value instanceof Error;\r
-}\r
-exports.error = error;\r
-function func(value) {\r
- return typeof value === 'function';\r
-}\r
-exports.func = func;\r
-function array(value) {\r
- return Array.isArray(value);\r
-}\r
-exports.array = array;\r
-function stringArray(value) {\r
- return array(value) && value.every(elem => string(elem));\r
-}\r
-exports.stringArray = stringArray;\r
-
-
-/***/ }),
-/* 6 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const is = __webpack_require__(5);\r
-/**\r
- * Predefined error codes.\r
- */\r
-var ErrorCodes;\r
-(function (ErrorCodes) {\r
- // Defined by JSON RPC\r
- ErrorCodes.ParseError = -32700;\r
- ErrorCodes.InvalidRequest = -32600;\r
- ErrorCodes.MethodNotFound = -32601;\r
- ErrorCodes.InvalidParams = -32602;\r
- ErrorCodes.InternalError = -32603;\r
- ErrorCodes.serverErrorStart = -32099;\r
- ErrorCodes.serverErrorEnd = -32000;\r
- ErrorCodes.ServerNotInitialized = -32002;\r
- ErrorCodes.UnknownErrorCode = -32001;\r
- // Defined by the protocol.\r
- ErrorCodes.RequestCancelled = -32800;\r
- ErrorCodes.ContentModified = -32801;\r
- // Defined by VSCode library.\r
- ErrorCodes.MessageWriteError = 1;\r
- ErrorCodes.MessageReadError = 2;\r
-})(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));\r
-/**\r
- * An error object return in a response in case a request\r
- * has failed.\r
- */\r
-class ResponseError extends Error {\r
- constructor(code, message, data) {\r
- super(message);\r
- this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;\r
- this.data = data;\r
- Object.setPrototypeOf(this, ResponseError.prototype);\r
- }\r
- toJson() {\r
- return {\r
- code: this.code,\r
- message: this.message,\r
- data: this.data,\r
- };\r
- }\r
-}\r
-exports.ResponseError = ResponseError;\r
-/**\r
- * An abstract implementation of a MessageType.\r
- */\r
-class AbstractMessageType {\r
- constructor(_method, _numberOfParams) {\r
- this._method = _method;\r
- this._numberOfParams = _numberOfParams;\r
- }\r
- get method() {\r
- return this._method;\r
- }\r
- get numberOfParams() {\r
- return this._numberOfParams;\r
- }\r
-}\r
-exports.AbstractMessageType = AbstractMessageType;\r
-/**\r
- * Classes to type request response pairs\r
- *\r
- * The type parameter RO will be removed in the next major version\r
- * of the JSON RPC library since it is a LSP concept and doesn't\r
- * belong here. For now it is tagged as default never.\r
- */\r
-class RequestType0 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 0);\r
- }\r
-}\r
-exports.RequestType0 = RequestType0;\r
-class RequestType extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 1);\r
- }\r
-}\r
-exports.RequestType = RequestType;\r
-class RequestType1 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 1);\r
- }\r
-}\r
-exports.RequestType1 = RequestType1;\r
-class RequestType2 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 2);\r
- }\r
-}\r
-exports.RequestType2 = RequestType2;\r
-class RequestType3 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 3);\r
- }\r
-}\r
-exports.RequestType3 = RequestType3;\r
-class RequestType4 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 4);\r
- }\r
-}\r
-exports.RequestType4 = RequestType4;\r
-class RequestType5 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 5);\r
- }\r
-}\r
-exports.RequestType5 = RequestType5;\r
-class RequestType6 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 6);\r
- }\r
-}\r
-exports.RequestType6 = RequestType6;\r
-class RequestType7 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 7);\r
- }\r
-}\r
-exports.RequestType7 = RequestType7;\r
-class RequestType8 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 8);\r
- }\r
-}\r
-exports.RequestType8 = RequestType8;\r
-class RequestType9 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 9);\r
- }\r
-}\r
-exports.RequestType9 = RequestType9;\r
-/**\r
- * The type parameter RO will be removed in the next major version\r
- * of the JSON RPC library since it is a LSP concept and doesn't\r
- * belong here. For now it is tagged as default never.\r
- */\r
-class NotificationType extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 1);\r
- this._ = undefined;\r
- }\r
-}\r
-exports.NotificationType = NotificationType;\r
-class NotificationType0 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 0);\r
- }\r
-}\r
-exports.NotificationType0 = NotificationType0;\r
-class NotificationType1 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 1);\r
- }\r
-}\r
-exports.NotificationType1 = NotificationType1;\r
-class NotificationType2 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 2);\r
- }\r
-}\r
-exports.NotificationType2 = NotificationType2;\r
-class NotificationType3 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 3);\r
- }\r
-}\r
-exports.NotificationType3 = NotificationType3;\r
-class NotificationType4 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 4);\r
- }\r
-}\r
-exports.NotificationType4 = NotificationType4;\r
-class NotificationType5 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 5);\r
- }\r
-}\r
-exports.NotificationType5 = NotificationType5;\r
-class NotificationType6 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 6);\r
- }\r
-}\r
-exports.NotificationType6 = NotificationType6;\r
-class NotificationType7 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 7);\r
- }\r
-}\r
-exports.NotificationType7 = NotificationType7;\r
-class NotificationType8 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 8);\r
- }\r
-}\r
-exports.NotificationType8 = NotificationType8;\r
-class NotificationType9 extends AbstractMessageType {\r
- constructor(method) {\r
- super(method, 9);\r
- }\r
-}\r
-exports.NotificationType9 = NotificationType9;\r
-/**\r
- * Tests if the given message is a request message\r
- */\r
-function isRequestMessage(message) {\r
- let candidate = message;\r
- return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));\r
-}\r
-exports.isRequestMessage = isRequestMessage;\r
-/**\r
- * Tests if the given message is a notification message\r
- */\r
-function isNotificationMessage(message) {\r
- let candidate = message;\r
- return candidate && is.string(candidate.method) && message.id === void 0;\r
-}\r
-exports.isNotificationMessage = isNotificationMessage;\r
-/**\r
- * Tests if the given message is a response message\r
- */\r
-function isResponseMessage(message) {\r
- let candidate = message;\r
- return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);\r
-}\r
-exports.isResponseMessage = isResponseMessage;\r
-
-
-/***/ }),
-/* 7 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const events_1 = __webpack_require__(8);\r
-const Is = __webpack_require__(5);\r
-let DefaultSize = 8192;\r
-let CR = Buffer.from('\r', 'ascii')[0];\r
-let LF = Buffer.from('\n', 'ascii')[0];\r
-let CRLF = '\r\n';\r
-class MessageBuffer {\r
- constructor(encoding = 'utf8') {\r
- this.encoding = encoding;\r
- this.index = 0;\r
- this.buffer = Buffer.allocUnsafe(DefaultSize);\r
- }\r
- append(chunk) {\r
- var toAppend = chunk;\r
- if (typeof (chunk) === 'string') {\r
- var str = chunk;\r
- var bufferLen = Buffer.byteLength(str, this.encoding);\r
- toAppend = Buffer.allocUnsafe(bufferLen);\r
- toAppend.write(str, 0, bufferLen, this.encoding);\r
- }\r
- if (this.buffer.length - this.index >= toAppend.length) {\r
- toAppend.copy(this.buffer, this.index, 0, toAppend.length);\r
- }\r
- else {\r
- var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;\r
- if (this.index === 0) {\r
- this.buffer = Buffer.allocUnsafe(newSize);\r
- toAppend.copy(this.buffer, 0, 0, toAppend.length);\r
- }\r
- else {\r
- this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);\r
- }\r
- }\r
- this.index += toAppend.length;\r
- }\r
- tryReadHeaders() {\r
- let result = undefined;\r
- let current = 0;\r
- while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {\r
- current++;\r
- }\r
- // No header / body separator found (e.g CRLFCRLF)\r
- if (current + 3 >= this.index) {\r
- return result;\r
- }\r
- result = Object.create(null);\r
- let headers = this.buffer.toString('ascii', 0, current).split(CRLF);\r
- headers.forEach((header) => {\r
- let index = header.indexOf(':');\r
- if (index === -1) {\r
- throw new Error('Message header must separate key and value using :');\r
- }\r
- let key = header.substr(0, index);\r
- let value = header.substr(index + 1).trim();\r
- result[key] = value;\r
- });\r
- let nextStart = current + 4;\r
- this.buffer = this.buffer.slice(nextStart);\r
- this.index = this.index - nextStart;\r
- return result;\r
- }\r
- tryReadContent(length) {\r
- if (this.index < length) {\r
- return null;\r
- }\r
- let result = this.buffer.toString(this.encoding, 0, length);\r
- let nextStart = length;\r
- this.buffer.copy(this.buffer, 0, nextStart);\r
- this.index = this.index - nextStart;\r
- return result;\r
- }\r
- get numberOfBytes() {\r
- return this.index;\r
- }\r
-}\r
-var MessageReader;\r
-(function (MessageReader) {\r
- function is(value) {\r
- let candidate = value;\r
- return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&\r
- Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);\r
- }\r
- MessageReader.is = is;\r
-})(MessageReader = exports.MessageReader || (exports.MessageReader = {}));\r
-class AbstractMessageReader {\r
- constructor() {\r
- this.errorEmitter = new events_1.Emitter();\r
- this.closeEmitter = new events_1.Emitter();\r
- this.partialMessageEmitter = new events_1.Emitter();\r
- }\r
- dispose() {\r
- this.errorEmitter.dispose();\r
- this.closeEmitter.dispose();\r
- }\r
- get onError() {\r
- return this.errorEmitter.event;\r
- }\r
- fireError(error) {\r
- this.errorEmitter.fire(this.asError(error));\r
- }\r
- get onClose() {\r
- return this.closeEmitter.event;\r
- }\r
- fireClose() {\r
- this.closeEmitter.fire(undefined);\r
- }\r
- get onPartialMessage() {\r
- return this.partialMessageEmitter.event;\r
- }\r
- firePartialMessage(info) {\r
- this.partialMessageEmitter.fire(info);\r
- }\r
- asError(error) {\r
- if (error instanceof Error) {\r
- return error;\r
- }\r
- else {\r
- return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);\r
- }\r
- }\r
-}\r
-exports.AbstractMessageReader = AbstractMessageReader;\r
-class StreamMessageReader extends AbstractMessageReader {\r
- constructor(readable, encoding = 'utf8') {\r
- super();\r
- this.readable = readable;\r
- this.buffer = new MessageBuffer(encoding);\r
- this._partialMessageTimeout = 10000;\r
- }\r
- set partialMessageTimeout(timeout) {\r
- this._partialMessageTimeout = timeout;\r
- }\r
- get partialMessageTimeout() {\r
- return this._partialMessageTimeout;\r
- }\r
- listen(callback) {\r
- this.nextMessageLength = -1;\r
- this.messageToken = 0;\r
- this.partialMessageTimer = undefined;\r
- this.callback = callback;\r
- this.readable.on('data', (data) => {\r
- this.onData(data);\r
- });\r
- this.readable.on('error', (error) => this.fireError(error));\r
- this.readable.on('close', () => this.fireClose());\r
- }\r
- onData(data) {\r
- this.buffer.append(data);\r
- while (true) {\r
- if (this.nextMessageLength === -1) {\r
- let headers = this.buffer.tryReadHeaders();\r
- if (!headers) {\r
- return;\r
- }\r
- let contentLength = headers['Content-Length'];\r
- if (!contentLength) {\r
- throw new Error('Header must provide a Content-Length property.');\r
- }\r
- let length = parseInt(contentLength);\r
- if (isNaN(length)) {\r
- throw new Error('Content-Length value must be a number.');\r
- }\r
- this.nextMessageLength = length;\r
- // Take the encoding form the header. For compatibility\r
- // treat both utf-8 and utf8 as node utf8\r
- }\r
- var msg = this.buffer.tryReadContent(this.nextMessageLength);\r
- if (msg === null) {\r
- /** We haven't received the full message yet. */\r
- this.setPartialMessageTimer();\r
- return;\r
- }\r
- this.clearPartialMessageTimer();\r
- this.nextMessageLength = -1;\r
- this.messageToken++;\r
- var json = JSON.parse(msg);\r
- this.callback(json);\r
- }\r
- }\r
- clearPartialMessageTimer() {\r
- if (this.partialMessageTimer) {\r
- clearTimeout(this.partialMessageTimer);\r
- this.partialMessageTimer = undefined;\r
- }\r
- }\r
- setPartialMessageTimer() {\r
- this.clearPartialMessageTimer();\r
- if (this._partialMessageTimeout <= 0) {\r
- return;\r
- }\r
- this.partialMessageTimer = setTimeout((token, timeout) => {\r
- this.partialMessageTimer = undefined;\r
- if (token === this.messageToken) {\r
- this.firePartialMessage({ messageToken: token, waitingTime: timeout });\r
- this.setPartialMessageTimer();\r
- }\r
- }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);\r
- }\r
-}\r
-exports.StreamMessageReader = StreamMessageReader;\r
-class IPCMessageReader extends AbstractMessageReader {\r
- constructor(process) {\r
- super();\r
- this.process = process;\r
- let eventEmitter = this.process;\r
- eventEmitter.on('error', (error) => this.fireError(error));\r
- eventEmitter.on('close', () => this.fireClose());\r
- }\r
- listen(callback) {\r
- this.process.on('message', callback);\r
- }\r
-}\r
-exports.IPCMessageReader = IPCMessageReader;\r
-class SocketMessageReader extends StreamMessageReader {\r
- constructor(socket, encoding = 'utf-8') {\r
- super(socket, encoding);\r
- }\r
-}\r
-exports.SocketMessageReader = SocketMessageReader;\r
-
-
-/***/ }),
-/* 8 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-var Disposable;\r
-(function (Disposable) {\r
- function create(func) {\r
- return {\r
- dispose: func\r
- };\r
- }\r
- Disposable.create = create;\r
-})(Disposable = exports.Disposable || (exports.Disposable = {}));\r
-var Event;\r
-(function (Event) {\r
- const _disposable = { dispose() { } };\r
- Event.None = function () { return _disposable; };\r
-})(Event = exports.Event || (exports.Event = {}));\r
-class CallbackList {\r
- add(callback, context = null, bucket) {\r
- if (!this._callbacks) {\r
- this._callbacks = [];\r
- this._contexts = [];\r
- }\r
- this._callbacks.push(callback);\r
- this._contexts.push(context);\r
- if (Array.isArray(bucket)) {\r
- bucket.push({ dispose: () => this.remove(callback, context) });\r
- }\r
- }\r
- remove(callback, context = null) {\r
- if (!this._callbacks) {\r
- return;\r
- }\r
- var foundCallbackWithDifferentContext = false;\r
- for (var i = 0, len = this._callbacks.length; i < len; i++) {\r
- if (this._callbacks[i] === callback) {\r
- if (this._contexts[i] === context) {\r
- // callback & context match => remove it\r
- this._callbacks.splice(i, 1);\r
- this._contexts.splice(i, 1);\r
- return;\r
- }\r
- else {\r
- foundCallbackWithDifferentContext = true;\r
- }\r
- }\r
- }\r
- if (foundCallbackWithDifferentContext) {\r
- throw new Error('When adding a listener with a context, you should remove it with the same context');\r
- }\r
- }\r
- invoke(...args) {\r
- if (!this._callbacks) {\r
- return [];\r
- }\r
- var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);\r
- for (var i = 0, len = callbacks.length; i < len; i++) {\r
- try {\r
- ret.push(callbacks[i].apply(contexts[i], args));\r
- }\r
- catch (e) {\r
- // eslint-disable-next-line no-console\r
- console.error(e);\r
- }\r
- }\r
- return ret;\r
- }\r
- isEmpty() {\r
- return !this._callbacks || this._callbacks.length === 0;\r
- }\r
- dispose() {\r
- this._callbacks = undefined;\r
- this._contexts = undefined;\r
- }\r
-}\r
-class Emitter {\r
- constructor(_options) {\r
- this._options = _options;\r
- }\r
- /**\r
- * For the public to allow to subscribe\r
- * to events from this Emitter\r
- */\r
- get event() {\r
- if (!this._event) {\r
- this._event = (listener, thisArgs, disposables) => {\r
- if (!this._callbacks) {\r
- this._callbacks = new CallbackList();\r
- }\r
- if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {\r
- this._options.onFirstListenerAdd(this);\r
- }\r
- this._callbacks.add(listener, thisArgs);\r
- let result;\r
- result = {\r
- dispose: () => {\r
- this._callbacks.remove(listener, thisArgs);\r
- result.dispose = Emitter._noop;\r
- if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {\r
- this._options.onLastListenerRemove(this);\r
- }\r
- }\r
- };\r
- if (Array.isArray(disposables)) {\r
- disposables.push(result);\r
- }\r
- return result;\r
- };\r
- }\r
- return this._event;\r
- }\r
- /**\r
- * To be kept private to fire an event to\r
- * subscribers\r
- */\r
- fire(event) {\r
- if (this._callbacks) {\r
- this._callbacks.invoke.call(this._callbacks, event);\r
- }\r
- }\r
- dispose() {\r
- if (this._callbacks) {\r
- this._callbacks.dispose();\r
- this._callbacks = undefined;\r
- }\r
- }\r
-}\r
-exports.Emitter = Emitter;\r
-Emitter._noop = function () { };\r
-
-
-/***/ }),
-/* 9 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const events_1 = __webpack_require__(8);\r
-const Is = __webpack_require__(5);\r
-let ContentLength = 'Content-Length: ';\r
-let CRLF = '\r\n';\r
-var MessageWriter;\r
-(function (MessageWriter) {\r
- function is(value) {\r
- let candidate = value;\r
- return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&\r
- Is.func(candidate.onError) && Is.func(candidate.write);\r
- }\r
- MessageWriter.is = is;\r
-})(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));\r
-class AbstractMessageWriter {\r
- constructor() {\r
- this.errorEmitter = new events_1.Emitter();\r
- this.closeEmitter = new events_1.Emitter();\r
- }\r
- dispose() {\r
- this.errorEmitter.dispose();\r
- this.closeEmitter.dispose();\r
- }\r
- get onError() {\r
- return this.errorEmitter.event;\r
- }\r
- fireError(error, message, count) {\r
- this.errorEmitter.fire([this.asError(error), message, count]);\r
- }\r
- get onClose() {\r
- return this.closeEmitter.event;\r
- }\r
- fireClose() {\r
- this.closeEmitter.fire(undefined);\r
- }\r
- asError(error) {\r
- if (error instanceof Error) {\r
- return error;\r
- }\r
- else {\r
- return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);\r
- }\r
- }\r
-}\r
-exports.AbstractMessageWriter = AbstractMessageWriter;\r
-class StreamMessageWriter extends AbstractMessageWriter {\r
- constructor(writable, encoding = 'utf8') {\r
- super();\r
- this.writable = writable;\r
- this.encoding = encoding;\r
- this.errorCount = 0;\r
- this.writable.on('error', (error) => this.fireError(error));\r
- this.writable.on('close', () => this.fireClose());\r
- }\r
- write(msg) {\r
- let json = JSON.stringify(msg);\r
- let contentLength = Buffer.byteLength(json, this.encoding);\r
- let headers = [\r
- ContentLength, contentLength.toString(), CRLF,\r
- CRLF\r
- ];\r
- try {\r
- // Header must be written in ASCII encoding\r
- this.writable.write(headers.join(''), 'ascii');\r
- // Now write the content. This can be written in any encoding\r
- this.writable.write(json, this.encoding);\r
- this.errorCount = 0;\r
- }\r
- catch (error) {\r
- this.errorCount++;\r
- this.fireError(error, msg, this.errorCount);\r
- }\r
- }\r
-}\r
-exports.StreamMessageWriter = StreamMessageWriter;\r
-class IPCMessageWriter extends AbstractMessageWriter {\r
- constructor(process) {\r
- super();\r
- this.process = process;\r
- this.errorCount = 0;\r
- this.queue = [];\r
- this.sending = false;\r
- let eventEmitter = this.process;\r
- eventEmitter.on('error', (error) => this.fireError(error));\r
- eventEmitter.on('close', () => this.fireClose);\r
- }\r
- write(msg) {\r
- if (!this.sending && this.queue.length === 0) {\r
- // See https://github.com/nodejs/node/issues/7657\r
- this.doWriteMessage(msg);\r
- }\r
- else {\r
- this.queue.push(msg);\r
- }\r
- }\r
- doWriteMessage(msg) {\r
- try {\r
- if (this.process.send) {\r
- this.sending = true;\r
- this.process.send(msg, undefined, undefined, (error) => {\r
- this.sending = false;\r
- if (error) {\r
- this.errorCount++;\r
- this.fireError(error, msg, this.errorCount);\r
- }\r
- else {\r
- this.errorCount = 0;\r
- }\r
- if (this.queue.length > 0) {\r
- this.doWriteMessage(this.queue.shift());\r
- }\r
- });\r
- }\r
- }\r
- catch (error) {\r
- this.errorCount++;\r
- this.fireError(error, msg, this.errorCount);\r
- }\r
- }\r
-}\r
-exports.IPCMessageWriter = IPCMessageWriter;\r
-class SocketMessageWriter extends AbstractMessageWriter {\r
- constructor(socket, encoding = 'utf8') {\r
- super();\r
- this.socket = socket;\r
- this.queue = [];\r
- this.sending = false;\r
- this.encoding = encoding;\r
- this.errorCount = 0;\r
- this.socket.on('error', (error) => this.fireError(error));\r
- this.socket.on('close', () => this.fireClose());\r
- }\r
- dispose() {\r
- super.dispose();\r
- this.socket.destroy();\r
- }\r
- write(msg) {\r
- if (!this.sending && this.queue.length === 0) {\r
- // See https://github.com/nodejs/node/issues/7657\r
- this.doWriteMessage(msg);\r
- }\r
- else {\r
- this.queue.push(msg);\r
- }\r
- }\r
- doWriteMessage(msg) {\r
- let json = JSON.stringify(msg);\r
- let contentLength = Buffer.byteLength(json, this.encoding);\r
- let headers = [\r
- ContentLength, contentLength.toString(), CRLF,\r
- CRLF\r
- ];\r
- try {\r
- // Header must be written in ASCII encoding\r
- this.sending = true;\r
- this.socket.write(headers.join(''), 'ascii', (error) => {\r
- if (error) {\r
- this.handleError(error, msg);\r
- }\r
- try {\r
- // Now write the content. This can be written in any encoding\r
- this.socket.write(json, this.encoding, (error) => {\r
- this.sending = false;\r
- if (error) {\r
- this.handleError(error, msg);\r
- }\r
- else {\r
- this.errorCount = 0;\r
- }\r
- if (this.queue.length > 0) {\r
- this.doWriteMessage(this.queue.shift());\r
- }\r
- });\r
- }\r
- catch (error) {\r
- this.handleError(error, msg);\r
- }\r
- });\r
- }\r
- catch (error) {\r
- this.handleError(error, msg);\r
- }\r
- }\r
- handleError(error, msg) {\r
- this.errorCount++;\r
- this.fireError(error, msg, this.errorCount);\r
- }\r
-}\r
-exports.SocketMessageWriter = SocketMessageWriter;\r
-
-
-/***/ }),
-/* 10 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/*---------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- *--------------------------------------------------------------------------------------------*/\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const events_1 = __webpack_require__(8);\r
-const Is = __webpack_require__(5);\r
-var CancellationToken;\r
-(function (CancellationToken) {\r
- CancellationToken.None = Object.freeze({\r
- isCancellationRequested: false,\r
- onCancellationRequested: events_1.Event.None\r
- });\r
- CancellationToken.Cancelled = Object.freeze({\r
- isCancellationRequested: true,\r
- onCancellationRequested: events_1.Event.None\r
- });\r
- function is(value) {\r
- let candidate = value;\r
- return candidate && (candidate === CancellationToken.None\r
- || candidate === CancellationToken.Cancelled\r
- || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));\r
- }\r
- CancellationToken.is = is;\r
-})(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));\r
-const shortcutEvent = Object.freeze(function (callback, context) {\r
- let handle = setTimeout(callback.bind(context), 0);\r
- return { dispose() { clearTimeout(handle); } };\r
-});\r
-class MutableToken {\r
- constructor() {\r
- this._isCancelled = false;\r
- }\r
- cancel() {\r
- if (!this._isCancelled) {\r
- this._isCancelled = true;\r
- if (this._emitter) {\r
- this._emitter.fire(undefined);\r
- this.dispose();\r
- }\r
- }\r
- }\r
- get isCancellationRequested() {\r
- return this._isCancelled;\r
- }\r
- get onCancellationRequested() {\r
- if (this._isCancelled) {\r
- return shortcutEvent;\r
- }\r
- if (!this._emitter) {\r
- this._emitter = new events_1.Emitter();\r
- }\r
- return this._emitter.event;\r
- }\r
- dispose() {\r
- if (this._emitter) {\r
- this._emitter.dispose();\r
- this._emitter = undefined;\r
- }\r
- }\r
-}\r
-class CancellationTokenSource {\r
- get token() {\r
- if (!this._token) {\r
- // be lazy and create the token only when\r
- // actually needed\r
- this._token = new MutableToken();\r
- }\r
- return this._token;\r
- }\r
- cancel() {\r
- if (!this._token) {\r
- // save an object by returning the default\r
- // cancelled token when cancellation happens\r
- // before someone asks for the token\r
- this._token = CancellationToken.Cancelled;\r
- }\r
- else {\r
- this._token.cancel();\r
- }\r
- }\r
- dispose() {\r
- if (!this._token) {\r
- // ensure to initialize with an empty token if we had none\r
- this._token = CancellationToken.None;\r
- }\r
- else if (this._token instanceof MutableToken) {\r
- // actually dispose\r
- this._token.dispose();\r
- }\r
- }\r
-}\r
-exports.CancellationTokenSource = CancellationTokenSource;\r
-
-
-/***/ }),
-/* 11 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-\r
-/*---------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- *--------------------------------------------------------------------------------------------*/\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-var Touch;\r
-(function (Touch) {\r
- Touch.None = 0;\r
- Touch.First = 1;\r
- Touch.Last = 2;\r
-})(Touch = exports.Touch || (exports.Touch = {}));\r
-class LinkedMap {\r
- constructor() {\r
- this._map = new Map();\r
- this._head = undefined;\r
- this._tail = undefined;\r
- this._size = 0;\r
- }\r
- clear() {\r
- this._map.clear();\r
- this._head = undefined;\r
- this._tail = undefined;\r
- this._size = 0;\r
- }\r
- isEmpty() {\r
- return !this._head && !this._tail;\r
- }\r
- get size() {\r
- return this._size;\r
- }\r
- has(key) {\r
- return this._map.has(key);\r
- }\r
- get(key) {\r
- const item = this._map.get(key);\r
- if (!item) {\r
- return undefined;\r
- }\r
- return item.value;\r
- }\r
- set(key, value, touch = Touch.None) {\r
- let item = this._map.get(key);\r
- if (item) {\r
- item.value = value;\r
- if (touch !== Touch.None) {\r
- this.touch(item, touch);\r
- }\r
- }\r
- else {\r
- item = { key, value, next: undefined, previous: undefined };\r
- switch (touch) {\r
- case Touch.None:\r
- this.addItemLast(item);\r
- break;\r
- case Touch.First:\r
- this.addItemFirst(item);\r
- break;\r
- case Touch.Last:\r
- this.addItemLast(item);\r
- break;\r
- default:\r
- this.addItemLast(item);\r
- break;\r
- }\r
- this._map.set(key, item);\r
- this._size++;\r
- }\r
- }\r
- delete(key) {\r
- const item = this._map.get(key);\r
- if (!item) {\r
- return false;\r
- }\r
- this._map.delete(key);\r
- this.removeItem(item);\r
- this._size--;\r
- return true;\r
- }\r
- shift() {\r
- if (!this._head && !this._tail) {\r
- return undefined;\r
- }\r
- if (!this._head || !this._tail) {\r
- throw new Error('Invalid list');\r
- }\r
- const item = this._head;\r
- this._map.delete(item.key);\r
- this.removeItem(item);\r
- this._size--;\r
- return item.value;\r
- }\r
- forEach(callbackfn, thisArg) {\r
- let current = this._head;\r
- while (current) {\r
- if (thisArg) {\r
- callbackfn.bind(thisArg)(current.value, current.key, this);\r
- }\r
- else {\r
- callbackfn(current.value, current.key, this);\r
- }\r
- current = current.next;\r
- }\r
- }\r
- forEachReverse(callbackfn, thisArg) {\r
- let current = this._tail;\r
- while (current) {\r
- if (thisArg) {\r
- callbackfn.bind(thisArg)(current.value, current.key, this);\r
- }\r
- else {\r
- callbackfn(current.value, current.key, this);\r
- }\r
- current = current.previous;\r
- }\r
- }\r
- values() {\r
- let result = [];\r
- let current = this._head;\r
- while (current) {\r
- result.push(current.value);\r
- current = current.next;\r
- }\r
- return result;\r
- }\r
- keys() {\r
- let result = [];\r
- let current = this._head;\r
- while (current) {\r
- result.push(current.key);\r
- current = current.next;\r
- }\r
- return result;\r
- }\r
- /* JSON RPC run on es5 which has no Symbol.iterator\r
- public keys(): IterableIterator<K> {\r
- let current = this._head;\r
- let iterator: IterableIterator<K> = {\r
- [Symbol.iterator]() {\r
- return iterator;\r
- },\r
- next():IteratorResult<K> {\r
- if (current) {\r
- let result = { value: current.key, done: false };\r
- current = current.next;\r
- return result;\r
- } else {\r
- return { value: undefined, done: true };\r
- }\r
- }\r
- };\r
- return iterator;\r
- }\r
-\r
- public values(): IterableIterator<V> {\r
- let current = this._head;\r
- let iterator: IterableIterator<V> = {\r
- [Symbol.iterator]() {\r
- return iterator;\r
- },\r
- next():IteratorResult<V> {\r
- if (current) {\r
- let result = { value: current.value, done: false };\r
- current = current.next;\r
- return result;\r
- } else {\r
- return { value: undefined, done: true };\r
- }\r
- }\r
- };\r
- return iterator;\r
- }\r
- */\r
- addItemFirst(item) {\r
- // First time Insert\r
- if (!this._head && !this._tail) {\r
- this._tail = item;\r
- }\r
- else if (!this._head) {\r
- throw new Error('Invalid list');\r
- }\r
- else {\r
- item.next = this._head;\r
- this._head.previous = item;\r
- }\r
- this._head = item;\r
- }\r
- addItemLast(item) {\r
- // First time Insert\r
- if (!this._head && !this._tail) {\r
- this._head = item;\r
- }\r
- else if (!this._tail) {\r
- throw new Error('Invalid list');\r
- }\r
- else {\r
- item.previous = this._tail;\r
- this._tail.next = item;\r
- }\r
- this._tail = item;\r
- }\r
- removeItem(item) {\r
- if (item === this._head && item === this._tail) {\r
- this._head = undefined;\r
- this._tail = undefined;\r
- }\r
- else if (item === this._head) {\r
- this._head = item.next;\r
- }\r
- else if (item === this._tail) {\r
- this._tail = item.previous;\r
- }\r
- else {\r
- const next = item.next;\r
- const previous = item.previous;\r
- if (!next || !previous) {\r
- throw new Error('Invalid list');\r
- }\r
- next.previous = previous;\r
- previous.next = next;\r
- }\r
- }\r
- touch(item, touch) {\r
- if (!this._head || !this._tail) {\r
- throw new Error('Invalid list');\r
- }\r
- if ((touch !== Touch.First && touch !== Touch.Last)) {\r
- return;\r
- }\r
- if (touch === Touch.First) {\r
- if (item === this._head) {\r
- return;\r
- }\r
- const next = item.next;\r
- const previous = item.previous;\r
- // Unlink the item\r
- if (item === this._tail) {\r
- // previous must be defined since item was not head but is tail\r
- // So there are more than on item in the map\r
- previous.next = undefined;\r
- this._tail = previous;\r
- }\r
- else {\r
- // Both next and previous are not undefined since item was neither head nor tail.\r
- next.previous = previous;\r
- previous.next = next;\r
- }\r
- // Insert the node at head\r
- item.previous = undefined;\r
- item.next = this._head;\r
- this._head.previous = item;\r
- this._head = item;\r
- }\r
- else if (touch === Touch.Last) {\r
- if (item === this._tail) {\r
- return;\r
- }\r
- const next = item.next;\r
- const previous = item.previous;\r
- // Unlink the item.\r
- if (item === this._head) {\r
- // next must be defined since item was not tail but is head\r
- // So there are more than on item in the map\r
- next.previous = undefined;\r
- this._head = next;\r
- }\r
- else {\r
- // Both next and previous are not undefined since item was neither head nor tail.\r
- next.previous = previous;\r
- previous.next = next;\r
- }\r
- item.next = undefined;\r
- item.previous = this._tail;\r
- this._tail.next = item;\r
- this._tail = item;\r
- }\r
- }\r
-}\r
-exports.LinkedMap = LinkedMap;\r
-
-
-/***/ }),
-/* 12 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const path_1 = __webpack_require__(13);\r
-const os_1 = __webpack_require__(14);\r
-const crypto_1 = __webpack_require__(15);\r
-const net_1 = __webpack_require__(16);\r
-const messageReader_1 = __webpack_require__(7);\r
-const messageWriter_1 = __webpack_require__(9);\r
-function generateRandomPipeName() {\r
- const randomSuffix = crypto_1.randomBytes(21).toString('hex');\r
- if (process.platform === 'win32') {\r
- return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;\r
- }\r
- else {\r
- // Mac/Unix: use socket file\r
- return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);\r
- }\r
-}\r
-exports.generateRandomPipeName = generateRandomPipeName;\r
-function createClientPipeTransport(pipeName, encoding = 'utf-8') {\r
- let connectResolve;\r
- let connected = new Promise((resolve, _reject) => {\r
- connectResolve = resolve;\r
- });\r
- return new Promise((resolve, reject) => {\r
- let server = net_1.createServer((socket) => {\r
- server.close();\r
- connectResolve([\r
- new messageReader_1.SocketMessageReader(socket, encoding),\r
- new messageWriter_1.SocketMessageWriter(socket, encoding)\r
- ]);\r
- });\r
- server.on('error', reject);\r
- server.listen(pipeName, () => {\r
- server.removeListener('error', reject);\r
- resolve({\r
- onConnected: () => { return connected; }\r
- });\r
- });\r
- });\r
-}\r
-exports.createClientPipeTransport = createClientPipeTransport;\r
-function createServerPipeTransport(pipeName, encoding = 'utf-8') {\r
- const socket = net_1.createConnection(pipeName);\r
- return [\r
- new messageReader_1.SocketMessageReader(socket, encoding),\r
- new messageWriter_1.SocketMessageWriter(socket, encoding)\r
- ];\r
-}\r
-exports.createServerPipeTransport = createServerPipeTransport;\r
-
-
-/***/ }),
-/* 13 */
-/***/ (function(module, exports) {
-
-module.exports = require("path");
-
-/***/ }),
-/* 14 */
-/***/ (function(module, exports) {
-
-module.exports = require("os");
-
-/***/ }),
-/* 15 */
-/***/ (function(module, exports) {
-
-module.exports = require("crypto");
-
-/***/ }),
-/* 16 */
-/***/ (function(module, exports) {
-
-module.exports = require("net");
-
-/***/ }),
-/* 17 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const net_1 = __webpack_require__(16);\r
-const messageReader_1 = __webpack_require__(7);\r
-const messageWriter_1 = __webpack_require__(9);\r
-function createClientSocketTransport(port, encoding = 'utf-8') {\r
- let connectResolve;\r
- let connected = new Promise((resolve, _reject) => {\r
- connectResolve = resolve;\r
- });\r
- return new Promise((resolve, reject) => {\r
- let server = net_1.createServer((socket) => {\r
- server.close();\r
- connectResolve([\r
- new messageReader_1.SocketMessageReader(socket, encoding),\r
- new messageWriter_1.SocketMessageWriter(socket, encoding)\r
- ]);\r
- });\r
- server.on('error', reject);\r
- server.listen(port, '127.0.0.1', () => {\r
- server.removeListener('error', reject);\r
- resolve({\r
- onConnected: () => { return connected; }\r
- });\r
- });\r
- });\r
-}\r
-exports.createClientSocketTransport = createClientSocketTransport;\r
-function createServerSocketTransport(port, encoding = 'utf-8') {\r
- const socket = net_1.createConnection(port, '127.0.0.1');\r
- return [\r
- new messageReader_1.SocketMessageReader(socket, encoding),\r
- new messageWriter_1.SocketMessageWriter(socket, encoding)\r
- ];\r
-}\r
-exports.createServerSocketTransport = createServerSocketTransport;\r
-
-
-/***/ }),
-/* 18 */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
-
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-/**\r
- * The Position namespace provides helper functions to work with\r
- * [Position](#Position) literals.\r
- */\r
-var Position;\r
-(function (Position) {\r
- /**\r
- * Creates a new Position literal from the given line and character.\r
- * @param line The position's line.\r
- * @param character The position's character.\r
- */\r
- function create(line, character) {\r
- return { line: line, character: character };\r
- }\r
- Position.create = create;\r
- /**\r
- * Checks whether the given liternal conforms to the [Position](#Position) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);\r
- }\r
- Position.is = is;\r
-})(Position || (Position = {}));\r
-/**\r
- * The Range namespace provides helper functions to work with\r
- * [Range](#Range) literals.\r
- */\r
-var Range;\r
-(function (Range) {\r
- function create(one, two, three, four) {\r
- if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {\r
- return { start: Position.create(one, two), end: Position.create(three, four) };\r
- }\r
- else if (Position.is(one) && Position.is(two)) {\r
- return { start: one, end: two };\r
- }\r
- else {\r
- throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");\r
- }\r
- }\r
- Range.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [Range](#Range) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);\r
- }\r
- Range.is = is;\r
-})(Range || (Range = {}));\r
-/**\r
- * The Location namespace provides helper functions to work with\r
- * [Location](#Location) literals.\r
- */\r
-var Location;\r
-(function (Location) {\r
- /**\r
- * Creates a Location literal.\r
- * @param uri The location's uri.\r
- * @param range The location's range.\r
- */\r
- function create(uri, range) {\r
- return { uri: uri, range: range };\r
- }\r
- Location.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [Location](#Location) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));\r
- }\r
- Location.is = is;\r
-})(Location || (Location = {}));\r
-/**\r
- * The LocationLink namespace provides helper functions to work with\r
- * [LocationLink](#LocationLink) literals.\r
- */\r
-var LocationLink;\r
-(function (LocationLink) {\r
- /**\r
- * Creates a LocationLink literal.\r
- * @param targetUri The definition's uri.\r
- * @param targetRange The full range of the definition.\r
- * @param targetSelectionRange The span of the symbol definition at the target.\r
- * @param originSelectionRange The span of the symbol being defined in the originating source file.\r
- */\r
- function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {\r
- return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };\r
- }\r
- LocationLink.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)\r
- && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))\r
- && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));\r
- }\r
- LocationLink.is = is;\r
-})(LocationLink || (LocationLink = {}));\r
-/**\r
- * The Color namespace provides helper functions to work with\r
- * [Color](#Color) literals.\r
- */\r
-var Color;\r
-(function (Color) {\r
- /**\r
- * Creates a new Color literal.\r
- */\r
- function create(red, green, blue, alpha) {\r
- return {\r
- red: red,\r
- green: green,\r
- blue: blue,\r
- alpha: alpha,\r
- };\r
- }\r
- Color.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [Color](#Color) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.number(candidate.red)\r
- && Is.number(candidate.green)\r
- && Is.number(candidate.blue)\r
- && Is.number(candidate.alpha);\r
- }\r
- Color.is = is;\r
-})(Color || (Color = {}));\r
-/**\r
- * The ColorInformation namespace provides helper functions to work with\r
- * [ColorInformation](#ColorInformation) literals.\r
- */\r
-var ColorInformation;\r
-(function (ColorInformation) {\r
- /**\r
- * Creates a new ColorInformation literal.\r
- */\r
- function create(range, color) {\r
- return {\r
- range: range,\r
- color: color,\r
- };\r
- }\r
- ColorInformation.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Range.is(candidate.range) && Color.is(candidate.color);\r
- }\r
- ColorInformation.is = is;\r
-})(ColorInformation || (ColorInformation = {}));\r
-/**\r
- * The Color namespace provides helper functions to work with\r
- * [ColorPresentation](#ColorPresentation) literals.\r
- */\r
-var ColorPresentation;\r
-(function (ColorPresentation) {\r
- /**\r
- * Creates a new ColorInformation literal.\r
- */\r
- function create(label, textEdit, additionalTextEdits) {\r
- return {\r
- label: label,\r
- textEdit: textEdit,\r
- additionalTextEdits: additionalTextEdits,\r
- };\r
- }\r
- ColorPresentation.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.string(candidate.label)\r
- && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))\r
- && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));\r
- }\r
- ColorPresentation.is = is;\r
-})(ColorPresentation || (ColorPresentation = {}));\r
-/**\r
- * Enum of known range kinds\r
- */\r
-var FoldingRangeKind;\r
-(function (FoldingRangeKind) {\r
- /**\r
- * Folding range for a comment\r
- */\r
- FoldingRangeKind["Comment"] = "comment";\r
- /**\r
- * Folding range for a imports or includes\r
- */\r
- FoldingRangeKind["Imports"] = "imports";\r
- /**\r
- * Folding range for a region (e.g. `#region`)\r
- */\r
- FoldingRangeKind["Region"] = "region";\r
-})(FoldingRangeKind || (FoldingRangeKind = {}));\r
-/**\r
- * The folding range namespace provides helper functions to work with\r
- * [FoldingRange](#FoldingRange) literals.\r
- */\r
-var FoldingRange;\r
-(function (FoldingRange) {\r
- /**\r
- * Creates a new FoldingRange literal.\r
- */\r
- function create(startLine, endLine, startCharacter, endCharacter, kind) {\r
- var result = {\r
- startLine: startLine,\r
- endLine: endLine\r
- };\r
- if (Is.defined(startCharacter)) {\r
- result.startCharacter = startCharacter;\r
- }\r
- if (Is.defined(endCharacter)) {\r
- result.endCharacter = endCharacter;\r
- }\r
- if (Is.defined(kind)) {\r
- result.kind = kind;\r
- }\r
- return result;\r
- }\r
- FoldingRange.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.number(candidate.startLine) && Is.number(candidate.startLine)\r
- && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))\r
- && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))\r
- && (Is.undefined(candidate.kind) || Is.string(candidate.kind));\r
- }\r
- FoldingRange.is = is;\r
-})(FoldingRange || (FoldingRange = {}));\r
-/**\r
- * The DiagnosticRelatedInformation namespace provides helper functions to work with\r
- * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.\r
- */\r
-var DiagnosticRelatedInformation;\r
-(function (DiagnosticRelatedInformation) {\r
- /**\r
- * Creates a new DiagnosticRelatedInformation literal.\r
- */\r
- function create(location, message) {\r
- return {\r
- location: location,\r
- message: message\r
- };\r
- }\r
- DiagnosticRelatedInformation.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);\r
- }\r
- DiagnosticRelatedInformation.is = is;\r
-})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));\r
-/**\r
- * The diagnostic's severity.\r
- */\r
-var DiagnosticSeverity;\r
-(function (DiagnosticSeverity) {\r
- /**\r
- * Reports an error.\r
- */\r
- DiagnosticSeverity.Error = 1;\r
- /**\r
- * Reports a warning.\r
- */\r
- DiagnosticSeverity.Warning = 2;\r
- /**\r
- * Reports an information.\r
- */\r
- DiagnosticSeverity.Information = 3;\r
- /**\r
- * Reports a hint.\r
- */\r
- DiagnosticSeverity.Hint = 4;\r
-})(DiagnosticSeverity || (DiagnosticSeverity = {}));\r
-/**\r
- * The diagnostic tags.\r
- *\r
- * @since 3.15.0\r
- */\r
-var DiagnosticTag;\r
-(function (DiagnosticTag) {\r
- /**\r
- * Unused or unnecessary code.\r
- *\r
- * Clients are allowed to render diagnostics with this tag faded out instead of having\r
- * an error squiggle.\r
- */\r
- DiagnosticTag.Unnecessary = 1;\r
- /**\r
- * Deprecated or obsolete code.\r
- *\r
- * Clients are allowed to rendered diagnostics with this tag strike through.\r
- */\r
- DiagnosticTag.Deprecated = 2;\r
-})(DiagnosticTag || (DiagnosticTag = {}));\r
-/**\r
- * The Diagnostic namespace provides helper functions to work with\r
- * [Diagnostic](#Diagnostic) literals.\r
- */\r
-var Diagnostic;\r
-(function (Diagnostic) {\r
- /**\r
- * Creates a new Diagnostic literal.\r
- */\r
- function create(range, message, severity, code, source, relatedInformation) {\r
- var result = { range: range, message: message };\r
- if (Is.defined(severity)) {\r
- result.severity = severity;\r
- }\r
- if (Is.defined(code)) {\r
- result.code = code;\r
- }\r
- if (Is.defined(source)) {\r
- result.source = source;\r
- }\r
- if (Is.defined(relatedInformation)) {\r
- result.relatedInformation = relatedInformation;\r
- }\r
- return result;\r
- }\r
- Diagnostic.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate)\r
- && Range.is(candidate.range)\r
- && Is.string(candidate.message)\r
- && (Is.number(candidate.severity) || Is.undefined(candidate.severity))\r
- && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))\r
- && (Is.string(candidate.source) || Is.undefined(candidate.source))\r
- && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));\r
- }\r
- Diagnostic.is = is;\r
-})(Diagnostic || (Diagnostic = {}));\r
-/**\r
- * The Command namespace provides helper functions to work with\r
- * [Command](#Command) literals.\r
- */\r
-var Command;\r
-(function (Command) {\r
- /**\r
- * Creates a new Command literal.\r
- */\r
- function create(title, command) {\r
- var args = [];\r
- for (var _i = 2; _i < arguments.length; _i++) {\r
- args[_i - 2] = arguments[_i];\r
- }\r
- var result = { title: title, command: command };\r
- if (Is.defined(args) && args.length > 0) {\r
- result.arguments = args;\r
- }\r
- return result;\r
- }\r
- Command.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [Command](#Command) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);\r
- }\r
- Command.is = is;\r
-})(Command || (Command = {}));\r
-/**\r
- * The TextEdit namespace provides helper function to create replace,\r
- * insert and delete edits more easily.\r
- */\r
-var TextEdit;\r
-(function (TextEdit) {\r
- /**\r
- * Creates a replace text edit.\r
- * @param range The range of text to be replaced.\r
- * @param newText The new text.\r
- */\r
- function replace(range, newText) {\r
- return { range: range, newText: newText };\r
- }\r
- TextEdit.replace = replace;\r
- /**\r
- * Creates a insert text edit.\r
- * @param position The position to insert the text at.\r
- * @param newText The text to be inserted.\r
- */\r
- function insert(position, newText) {\r
- return { range: { start: position, end: position }, newText: newText };\r
- }\r
- TextEdit.insert = insert;\r
- /**\r
- * Creates a delete text edit.\r
- * @param range The range of text to be deleted.\r
- */\r
- function del(range) {\r
- return { range: range, newText: '' };\r
- }\r
- TextEdit.del = del;\r
- function is(value) {\r
- var candidate = value;\r
- return Is.objectLiteral(candidate)\r
- && Is.string(candidate.newText)\r
- && Range.is(candidate.range);\r
- }\r
- TextEdit.is = is;\r
-})(TextEdit || (TextEdit = {}));\r
-/**\r
- * The TextDocumentEdit namespace provides helper function to create\r
- * an edit that manipulates a text document.\r
- */\r
-var TextDocumentEdit;\r
-(function (TextDocumentEdit) {\r
- /**\r
- * Creates a new `TextDocumentEdit`\r
- */\r
- function create(textDocument, edits) {\r
- return { textDocument: textDocument, edits: edits };\r
- }\r
- TextDocumentEdit.create = create;\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate)\r
- && VersionedTextDocumentIdentifier.is(candidate.textDocument)\r
- && Array.isArray(candidate.edits);\r
- }\r
- TextDocumentEdit.is = is;\r
-})(TextDocumentEdit || (TextDocumentEdit = {}));\r
-var CreateFile;\r
-(function (CreateFile) {\r
- function create(uri, options) {\r
- var result = {\r
- kind: 'create',\r
- uri: uri\r
- };\r
- if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {\r
- result.options = options;\r
- }\r
- return result;\r
- }\r
- CreateFile.create = create;\r
- function is(value) {\r
- var candidate = value;\r
- return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&\r
- (candidate.options === void 0 ||\r
- ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));\r
- }\r
- CreateFile.is = is;\r
-})(CreateFile || (CreateFile = {}));\r
-var RenameFile;\r
-(function (RenameFile) {\r
- function create(oldUri, newUri, options) {\r
- var result = {\r
- kind: 'rename',\r
- oldUri: oldUri,\r
- newUri: newUri\r
- };\r
- if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {\r
- result.options = options;\r
- }\r
- return result;\r
- }\r
- RenameFile.create = create;\r
- function is(value) {\r
- var candidate = value;\r
- return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&\r
- (candidate.options === void 0 ||\r
- ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));\r
- }\r
- RenameFile.is = is;\r
-})(RenameFile || (RenameFile = {}));\r
-var DeleteFile;\r
-(function (DeleteFile) {\r
- function create(uri, options) {\r
- var result = {\r
- kind: 'delete',\r
- uri: uri\r
- };\r
- if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {\r
- result.options = options;\r
- }\r
- return result;\r
- }\r
- DeleteFile.create = create;\r
- function is(value) {\r
- var candidate = value;\r
- return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&\r
- (candidate.options === void 0 ||\r
- ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));\r
- }\r
- DeleteFile.is = is;\r
-})(DeleteFile || (DeleteFile = {}));\r
-var WorkspaceEdit;\r
-(function (WorkspaceEdit) {\r
- function is(value) {\r
- var candidate = value;\r
- return candidate &&\r
- (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&\r
- (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {\r
- if (Is.string(change.kind)) {\r
- return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);\r
- }\r
- else {\r
- return TextDocumentEdit.is(change);\r
- }\r
- }));\r
- }\r
- WorkspaceEdit.is = is;\r
-})(WorkspaceEdit || (WorkspaceEdit = {}));\r
-var TextEditChangeImpl = /** @class */ (function () {\r
- function TextEditChangeImpl(edits) {\r
- this.edits = edits;\r
- }\r
- TextEditChangeImpl.prototype.insert = function (position, newText) {\r
- this.edits.push(TextEdit.insert(position, newText));\r
- };\r
- TextEditChangeImpl.prototype.replace = function (range, newText) {\r
- this.edits.push(TextEdit.replace(range, newText));\r
- };\r
- TextEditChangeImpl.prototype.delete = function (range) {\r
- this.edits.push(TextEdit.del(range));\r
- };\r
- TextEditChangeImpl.prototype.add = function (edit) {\r
- this.edits.push(edit);\r
- };\r
- TextEditChangeImpl.prototype.all = function () {\r
- return this.edits;\r
- };\r
- TextEditChangeImpl.prototype.clear = function () {\r
- this.edits.splice(0, this.edits.length);\r
- };\r
- return TextEditChangeImpl;\r
-}());\r
-/**\r
- * A workspace change helps constructing changes to a workspace.\r
- */\r
-var WorkspaceChange = /** @class */ (function () {\r
- function WorkspaceChange(workspaceEdit) {\r
- var _this = this;\r
- this._textEditChanges = Object.create(null);\r
- if (workspaceEdit) {\r
- this._workspaceEdit = workspaceEdit;\r
- if (workspaceEdit.documentChanges) {\r
- workspaceEdit.documentChanges.forEach(function (change) {\r
- if (TextDocumentEdit.is(change)) {\r
- var textEditChange = new TextEditChangeImpl(change.edits);\r
- _this._textEditChanges[change.textDocument.uri] = textEditChange;\r
- }\r
- });\r
- }\r
- else if (workspaceEdit.changes) {\r
- Object.keys(workspaceEdit.changes).forEach(function (key) {\r
- var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);\r
- _this._textEditChanges[key] = textEditChange;\r
- });\r
- }\r
- }\r
- }\r
- Object.defineProperty(WorkspaceChange.prototype, "edit", {\r
- /**\r
- * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal\r
- * use to be returned from a workspace edit operation like rename.\r
- */\r
- get: function () {\r
- return this._workspaceEdit;\r
- },\r
- enumerable: true,\r
- configurable: true\r
- });\r
- WorkspaceChange.prototype.getTextEditChange = function (key) {\r
- if (VersionedTextDocumentIdentifier.is(key)) {\r
- if (!this._workspaceEdit) {\r
- this._workspaceEdit = {\r
- documentChanges: []\r
- };\r
- }\r
- if (!this._workspaceEdit.documentChanges) {\r
- throw new Error('Workspace edit is not configured for document changes.');\r
- }\r
- var textDocument = key;\r
- var result = this._textEditChanges[textDocument.uri];\r
- if (!result) {\r
- var edits = [];\r
- var textDocumentEdit = {\r
- textDocument: textDocument,\r
- edits: edits\r
- };\r
- this._workspaceEdit.documentChanges.push(textDocumentEdit);\r
- result = new TextEditChangeImpl(edits);\r
- this._textEditChanges[textDocument.uri] = result;\r
- }\r
- return result;\r
- }\r
- else {\r
- if (!this._workspaceEdit) {\r
- this._workspaceEdit = {\r
- changes: Object.create(null)\r
- };\r
- }\r
- if (!this._workspaceEdit.changes) {\r
- throw new Error('Workspace edit is not configured for normal text edit changes.');\r
- }\r
- var result = this._textEditChanges[key];\r
- if (!result) {\r
- var edits = [];\r
- this._workspaceEdit.changes[key] = edits;\r
- result = new TextEditChangeImpl(edits);\r
- this._textEditChanges[key] = result;\r
- }\r
- return result;\r
- }\r
- };\r
- WorkspaceChange.prototype.createFile = function (uri, options) {\r
- this.checkDocumentChanges();\r
- this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));\r
- };\r
- WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {\r
- this.checkDocumentChanges();\r
- this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));\r
- };\r
- WorkspaceChange.prototype.deleteFile = function (uri, options) {\r
- this.checkDocumentChanges();\r
- this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));\r
- };\r
- WorkspaceChange.prototype.checkDocumentChanges = function () {\r
- if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {\r
- throw new Error('Workspace edit is not configured for document changes.');\r
- }\r
- };\r
- return WorkspaceChange;\r
-}());\r
-\r
-/**\r
- * The TextDocumentIdentifier namespace provides helper functions to work with\r
- * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.\r
- */\r
-var TextDocumentIdentifier;\r
-(function (TextDocumentIdentifier) {\r
- /**\r
- * Creates a new TextDocumentIdentifier literal.\r
- * @param uri The document's uri.\r
- */\r
- function create(uri) {\r
- return { uri: uri };\r
- }\r
- TextDocumentIdentifier.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Is.string(candidate.uri);\r
- }\r
- TextDocumentIdentifier.is = is;\r
-})(TextDocumentIdentifier || (TextDocumentIdentifier = {}));\r
-/**\r
- * The VersionedTextDocumentIdentifier namespace provides helper functions to work with\r
- * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.\r
- */\r
-var VersionedTextDocumentIdentifier;\r
-(function (VersionedTextDocumentIdentifier) {\r
- /**\r
- * Creates a new VersionedTextDocumentIdentifier literal.\r
- * @param uri The document's uri.\r
- * @param uri The document's text.\r
- */\r
- function create(uri, version) {\r
- return { uri: uri, version: version };\r
- }\r
- VersionedTextDocumentIdentifier.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));\r
- }\r
- VersionedTextDocumentIdentifier.is = is;\r
-})(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));\r
-/**\r
- * The TextDocumentItem namespace provides helper functions to work with\r
- * [TextDocumentItem](#TextDocumentItem) literals.\r
- */\r
-var TextDocumentItem;\r
-(function (TextDocumentItem) {\r
- /**\r
- * Creates a new TextDocumentItem literal.\r
- * @param uri The document's uri.\r
- * @param languageId The document's language identifier.\r
- * @param version The document's version number.\r
- * @param text The document's text.\r
- */\r
- function create(uri, languageId, version, text) {\r
- return { uri: uri, languageId: languageId, version: version, text: text };\r
- }\r
- TextDocumentItem.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);\r
- }\r
- TextDocumentItem.is = is;\r
-})(TextDocumentItem || (TextDocumentItem = {}));\r
-/**\r
- * Describes the content type that a client supports in various\r
- * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\r
- *\r
- * Please note that `MarkupKinds` must not start with a `$`. This kinds\r
- * are reserved for internal usage.\r
- */\r
-var MarkupKind;\r
-(function (MarkupKind) {\r
- /**\r
- * Plain text is supported as a content format\r
- */\r
- MarkupKind.PlainText = 'plaintext';\r
- /**\r
- * Markdown is supported as a content format\r
- */\r
- MarkupKind.Markdown = 'markdown';\r
-})(MarkupKind || (MarkupKind = {}));\r
-(function (MarkupKind) {\r
- /**\r
- * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;\r
- }\r
- MarkupKind.is = is;\r
-})(MarkupKind || (MarkupKind = {}));\r
-var MarkupContent;\r
-(function (MarkupContent) {\r
- /**\r
- * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);\r
- }\r
- MarkupContent.is = is;\r
-})(MarkupContent || (MarkupContent = {}));\r
-/**\r
- * The kind of a completion entry.\r
- */\r
-var CompletionItemKind;\r
-(function (CompletionItemKind) {\r
- CompletionItemKind.Text = 1;\r
- CompletionItemKind.Method = 2;\r
- CompletionItemKind.Function = 3;\r
- CompletionItemKind.Constructor = 4;\r
- CompletionItemKind.Field = 5;\r
- CompletionItemKind.Variable = 6;\r
- CompletionItemKind.Class = 7;\r
- CompletionItemKind.Interface = 8;\r
- CompletionItemKind.Module = 9;\r
- CompletionItemKind.Property = 10;\r
- CompletionItemKind.Unit = 11;\r
- CompletionItemKind.Value = 12;\r
- CompletionItemKind.Enum = 13;\r
- CompletionItemKind.Keyword = 14;\r
- CompletionItemKind.Snippet = 15;\r
- CompletionItemKind.Color = 16;\r
- CompletionItemKind.File = 17;\r
- CompletionItemKind.Reference = 18;\r
- CompletionItemKind.Folder = 19;\r
- CompletionItemKind.EnumMember = 20;\r
- CompletionItemKind.Constant = 21;\r
- CompletionItemKind.Struct = 22;\r
- CompletionItemKind.Event = 23;\r
- CompletionItemKind.Operator = 24;\r
- CompletionItemKind.TypeParameter = 25;\r
-})(CompletionItemKind || (CompletionItemKind = {}));\r
-/**\r
- * Defines whether the insert text in a completion item should be interpreted as\r
- * plain text or a snippet.\r
- */\r
-var InsertTextFormat;\r
-(function (InsertTextFormat) {\r
- /**\r
- * The primary text to be inserted is treated as a plain string.\r
- */\r
- InsertTextFormat.PlainText = 1;\r
- /**\r
- * The primary text to be inserted is treated as a snippet.\r
- *\r
- * A snippet can define tab stops and placeholders with `$1`, `$2`\r
- * and `${3:foo}`. `$0` defines the final tab stop, it defaults to\r
- * the end of the snippet. Placeholders with equal identifiers are linked,\r
- * that is typing in one will update others too.\r
- *\r
- * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md\r
- */\r
- InsertTextFormat.Snippet = 2;\r
-})(InsertTextFormat || (InsertTextFormat = {}));\r
-/**\r
- * Completion item tags are extra annotations that tweak the rendering of a completion\r
- * item.\r
- *\r
- * @since 3.15.0\r
- */\r
-var CompletionItemTag;\r
-(function (CompletionItemTag) {\r
- /**\r
- * Render a completion as obsolete, usually using a strike-out.\r
- */\r
- CompletionItemTag.Deprecated = 1;\r
-})(CompletionItemTag || (CompletionItemTag = {}));\r
-/**\r
- * The CompletionItem namespace provides functions to deal with\r
- * completion items.\r
- */\r
-var CompletionItem;\r
-(function (CompletionItem) {\r
- /**\r
- * Create a completion item and seed it with a label.\r
- * @param label The completion item's label\r
- */\r
- function create(label) {\r
- return { label: label };\r
- }\r
- CompletionItem.create = create;\r
-})(CompletionItem || (CompletionItem = {}));\r
-/**\r
- * The CompletionList namespace provides functions to deal with\r
- * completion lists.\r
- */\r
-var CompletionList;\r
-(function (CompletionList) {\r
- /**\r
- * Creates a new completion list.\r
- *\r
- * @param items The completion items.\r
- * @param isIncomplete The list is not complete.\r
- */\r
- function create(items, isIncomplete) {\r
- return { items: items ? items : [], isIncomplete: !!isIncomplete };\r
- }\r
- CompletionList.create = create;\r
-})(CompletionList || (CompletionList = {}));\r
-var MarkedString;\r
-(function (MarkedString) {\r
- /**\r
- * Creates a marked string from plain text.\r
- *\r
- * @param plainText The plain text.\r
- */\r
- function fromPlainText(plainText) {\r
- return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash\r
- }\r
- MarkedString.fromPlainText = fromPlainText;\r
- /**\r
- * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));\r
- }\r
- MarkedString.is = is;\r
-})(MarkedString || (MarkedString = {}));\r
-var Hover;\r
-(function (Hover) {\r
- /**\r
- * Checks whether the given value conforms to the [Hover](#Hover) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||\r
- MarkedString.is(candidate.contents) ||\r
- Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));\r
- }\r
- Hover.is = is;\r
-})(Hover || (Hover = {}));\r
-/**\r
- * The ParameterInformation namespace provides helper functions to work with\r
- * [ParameterInformation](#ParameterInformation) literals.\r
- */\r
-var ParameterInformation;\r
-(function (ParameterInformation) {\r
- /**\r
- * Creates a new parameter information literal.\r
- *\r
- * @param label A label string.\r
- * @param documentation A doc string.\r
- */\r
- function create(label, documentation) {\r
- return documentation ? { label: label, documentation: documentation } : { label: label };\r
- }\r
- ParameterInformation.create = create;\r
-})(ParameterInformation || (ParameterInformation = {}));\r
-/**\r
- * The SignatureInformation namespace provides helper functions to work with\r
- * [SignatureInformation](#SignatureInformation) literals.\r
- */\r
-var SignatureInformation;\r
-(function (SignatureInformation) {\r
- function create(label, documentation) {\r
- var parameters = [];\r
- for (var _i = 2; _i < arguments.length; _i++) {\r
- parameters[_i - 2] = arguments[_i];\r
- }\r
- var result = { label: label };\r
- if (Is.defined(documentation)) {\r
- result.documentation = documentation;\r
- }\r
- if (Is.defined(parameters)) {\r
- result.parameters = parameters;\r
- }\r
- else {\r
- result.parameters = [];\r
- }\r
- return result;\r
- }\r
- SignatureInformation.create = create;\r
-})(SignatureInformation || (SignatureInformation = {}));\r
-/**\r
- * A document highlight kind.\r
- */\r
-var DocumentHighlightKind;\r
-(function (DocumentHighlightKind) {\r
- /**\r
- * A textual occurrence.\r
- */\r
- DocumentHighlightKind.Text = 1;\r
- /**\r
- * Read-access of a symbol, like reading a variable.\r
- */\r
- DocumentHighlightKind.Read = 2;\r
- /**\r
- * Write-access of a symbol, like writing to a variable.\r
- */\r
- DocumentHighlightKind.Write = 3;\r
-})(DocumentHighlightKind || (DocumentHighlightKind = {}));\r
-/**\r
- * DocumentHighlight namespace to provide helper functions to work with\r
- * [DocumentHighlight](#DocumentHighlight) literals.\r
- */\r
-var DocumentHighlight;\r
-(function (DocumentHighlight) {\r
- /**\r
- * Create a DocumentHighlight object.\r
- * @param range The range the highlight applies to.\r
- */\r
- function create(range, kind) {\r
- var result = { range: range };\r
- if (Is.number(kind)) {\r
- result.kind = kind;\r
- }\r
- return result;\r
- }\r
- DocumentHighlight.create = create;\r
-})(DocumentHighlight || (DocumentHighlight = {}));\r
-/**\r
- * A symbol kind.\r
- */\r
-var SymbolKind;\r
-(function (SymbolKind) {\r
- SymbolKind.File = 1;\r
- SymbolKind.Module = 2;\r
- SymbolKind.Namespace = 3;\r
- SymbolKind.Package = 4;\r
- SymbolKind.Class = 5;\r
- SymbolKind.Method = 6;\r
- SymbolKind.Property = 7;\r
- SymbolKind.Field = 8;\r
- SymbolKind.Constructor = 9;\r
- SymbolKind.Enum = 10;\r
- SymbolKind.Interface = 11;\r
- SymbolKind.Function = 12;\r
- SymbolKind.Variable = 13;\r
- SymbolKind.Constant = 14;\r
- SymbolKind.String = 15;\r
- SymbolKind.Number = 16;\r
- SymbolKind.Boolean = 17;\r
- SymbolKind.Array = 18;\r
- SymbolKind.Object = 19;\r
- SymbolKind.Key = 20;\r
- SymbolKind.Null = 21;\r
- SymbolKind.EnumMember = 22;\r
- SymbolKind.Struct = 23;\r
- SymbolKind.Event = 24;\r
- SymbolKind.Operator = 25;\r
- SymbolKind.TypeParameter = 26;\r
-})(SymbolKind || (SymbolKind = {}));\r
-/**\r
- * Symbol tags are extra annotations that tweak the rendering of a symbol.\r
- * @since 3.15\r
- */\r
-var SymbolTag;\r
-(function (SymbolTag) {\r
- /**\r
- * Render a symbol as obsolete, usually using a strike-out.\r
- */\r
- SymbolTag.Deprecated = 1;\r
-})(SymbolTag || (SymbolTag = {}));\r
-var SymbolInformation;\r
-(function (SymbolInformation) {\r
- /**\r
- * Creates a new symbol information literal.\r
- *\r
- * @param name The name of the symbol.\r
- * @param kind The kind of the symbol.\r
- * @param range The range of the location of the symbol.\r
- * @param uri The resource of the location of symbol, defaults to the current document.\r
- * @param containerName The name of the symbol containing the symbol.\r
- */\r
- function create(name, kind, range, uri, containerName) {\r
- var result = {\r
- name: name,\r
- kind: kind,\r
- location: { uri: uri, range: range }\r
- };\r
- if (containerName) {\r
- result.containerName = containerName;\r
- }\r
- return result;\r
- }\r
- SymbolInformation.create = create;\r
-})(SymbolInformation || (SymbolInformation = {}));\r
-var DocumentSymbol;\r
-(function (DocumentSymbol) {\r
- /**\r
- * Creates a new symbol information literal.\r
- *\r
- * @param name The name of the symbol.\r
- * @param detail The detail of the symbol.\r
- * @param kind The kind of the symbol.\r
- * @param range The range of the symbol.\r
- * @param selectionRange The selectionRange of the symbol.\r
- * @param children Children of the symbol.\r
- */\r
- function create(name, detail, kind, range, selectionRange, children) {\r
- var result = {\r
- name: name,\r
- detail: detail,\r
- kind: kind,\r
- range: range,\r
- selectionRange: selectionRange\r
- };\r
- if (children !== void 0) {\r
- result.children = children;\r
- }\r
- return result;\r
- }\r
- DocumentSymbol.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return candidate &&\r
- Is.string(candidate.name) && Is.number(candidate.kind) &&\r
- Range.is(candidate.range) && Range.is(candidate.selectionRange) &&\r
- (candidate.detail === void 0 || Is.string(candidate.detail)) &&\r
- (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&\r
- (candidate.children === void 0 || Array.isArray(candidate.children));\r
- }\r
- DocumentSymbol.is = is;\r
-})(DocumentSymbol || (DocumentSymbol = {}));\r
-/**\r
- * A set of predefined code action kinds\r
- */\r
-var CodeActionKind;\r
-(function (CodeActionKind) {\r
- /**\r
- * Empty kind.\r
- */\r
- CodeActionKind.Empty = '';\r
- /**\r
- * Base kind for quickfix actions: 'quickfix'\r
- */\r
- CodeActionKind.QuickFix = 'quickfix';\r
- /**\r
- * Base kind for refactoring actions: 'refactor'\r
- */\r
- CodeActionKind.Refactor = 'refactor';\r
- /**\r
- * Base kind for refactoring extraction actions: 'refactor.extract'\r
- *\r
- * Example extract actions:\r
- *\r
- * - Extract method\r
- * - Extract function\r
- * - Extract variable\r
- * - Extract interface from class\r
- * - ...\r
- */\r
- CodeActionKind.RefactorExtract = 'refactor.extract';\r
- /**\r
- * Base kind for refactoring inline actions: 'refactor.inline'\r
- *\r
- * Example inline actions:\r
- *\r
- * - Inline function\r
- * - Inline variable\r
- * - Inline constant\r
- * - ...\r
- */\r
- CodeActionKind.RefactorInline = 'refactor.inline';\r
- /**\r
- * Base kind for refactoring rewrite actions: 'refactor.rewrite'\r
- *\r
- * Example rewrite actions:\r
- *\r
- * - Convert JavaScript function to class\r
- * - Add or remove parameter\r
- * - Encapsulate field\r
- * - Make method static\r
- * - Move method to base class\r
- * - ...\r
- */\r
- CodeActionKind.RefactorRewrite = 'refactor.rewrite';\r
- /**\r
- * Base kind for source actions: `source`\r
- *\r
- * Source code actions apply to the entire file.\r
- */\r
- CodeActionKind.Source = 'source';\r
- /**\r
- * Base kind for an organize imports source action: `source.organizeImports`\r
- */\r
- CodeActionKind.SourceOrganizeImports = 'source.organizeImports';\r
- /**\r
- * Base kind for auto-fix source actions: `source.fixAll`.\r
- *\r
- * Fix all actions automatically fix errors that have a clear fix that do not require user input.\r
- * They should not suppress errors or perform unsafe fixes such as generating new types or classes.\r
- *\r
- * @since 3.15.0\r
- */\r
- CodeActionKind.SourceFixAll = 'source.fixAll';\r
-})(CodeActionKind || (CodeActionKind = {}));\r
-/**\r
- * The CodeActionContext namespace provides helper functions to work with\r
- * [CodeActionContext](#CodeActionContext) literals.\r
- */\r
-var CodeActionContext;\r
-(function (CodeActionContext) {\r
- /**\r
- * Creates a new CodeActionContext literal.\r
- */\r
- function create(diagnostics, only) {\r
- var result = { diagnostics: diagnostics };\r
- if (only !== void 0 && only !== null) {\r
- result.only = only;\r
- }\r
- return result;\r
- }\r
- CodeActionContext.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));\r
- }\r
- CodeActionContext.is = is;\r
-})(CodeActionContext || (CodeActionContext = {}));\r
-var CodeAction;\r
-(function (CodeAction) {\r
- function create(title, commandOrEdit, kind) {\r
- var result = { title: title };\r
- if (Command.is(commandOrEdit)) {\r
- result.command = commandOrEdit;\r
- }\r
- else {\r
- result.edit = commandOrEdit;\r
- }\r
- if (kind !== void 0) {\r
- result.kind = kind;\r
- }\r
- return result;\r
- }\r
- CodeAction.create = create;\r
- function is(value) {\r
- var candidate = value;\r
- return candidate && Is.string(candidate.title) &&\r
- (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&\r
- (candidate.kind === void 0 || Is.string(candidate.kind)) &&\r
- (candidate.edit !== void 0 || candidate.command !== void 0) &&\r
- (candidate.command === void 0 || Command.is(candidate.command)) &&\r
- (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&\r
- (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));\r
- }\r
- CodeAction.is = is;\r
-})(CodeAction || (CodeAction = {}));\r
-/**\r
- * The CodeLens namespace provides helper functions to work with\r
- * [CodeLens](#CodeLens) literals.\r
- */\r
-var CodeLens;\r
-(function (CodeLens) {\r
- /**\r
- * Creates a new CodeLens literal.\r
- */\r
- function create(range, data) {\r
- var result = { range: range };\r
- if (Is.defined(data)) {\r
- result.data = data;\r
- }\r
- return result;\r
- }\r
- CodeLens.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));\r
- }\r
- CodeLens.is = is;\r
-})(CodeLens || (CodeLens = {}));\r
-/**\r
- * The FormattingOptions namespace provides helper functions to work with\r
- * [FormattingOptions](#FormattingOptions) literals.\r
- */\r
-var FormattingOptions;\r
-(function (FormattingOptions) {\r
- /**\r
- * Creates a new FormattingOptions literal.\r
- */\r
- function create(tabSize, insertSpaces) {\r
- return { tabSize: tabSize, insertSpaces: insertSpaces };\r
- }\r
- FormattingOptions.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);\r
- }\r
- FormattingOptions.is = is;\r
-})(FormattingOptions || (FormattingOptions = {}));\r
-/**\r
- * The DocumentLink namespace provides helper functions to work with\r
- * [DocumentLink](#DocumentLink) literals.\r
- */\r
-var DocumentLink;\r
-(function (DocumentLink) {\r
- /**\r
- * Creates a new DocumentLink literal.\r
- */\r
- function create(range, target, data) {\r
- return { range: range, target: target, data: data };\r
- }\r
- DocumentLink.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));\r
- }\r
- DocumentLink.is = is;\r
-})(DocumentLink || (DocumentLink = {}));\r
-/**\r
- * The SelectionRange namespace provides helper function to work with\r
- * SelectionRange literals.\r
- */\r
-var SelectionRange;\r
-(function (SelectionRange) {\r
- /**\r
- * Creates a new SelectionRange\r
- * @param range the range.\r
- * @param parent an optional parent.\r
- */\r
- function create(range, parent) {\r
- return { range: range, parent: parent };\r
- }\r
- SelectionRange.create = create;\r
- function is(value) {\r
- var candidate = value;\r
- return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));\r
- }\r
- SelectionRange.is = is;\r
-})(SelectionRange || (SelectionRange = {}));\r
-var EOL = ['\n', '\r\n', '\r'];\r
-/**\r
- * @deprecated Use the text document from the new vscode-languageserver-textdocument package.\r
- */\r
-var TextDocument;\r
-(function (TextDocument) {\r
- /**\r
- * Creates a new ITextDocument literal from the given uri and content.\r
- * @param uri The document's uri.\r
- * @param languageId The document's language Id.\r
- * @param content The document's content.\r
- */\r
- function create(uri, languageId, version, content) {\r
- return new FullTextDocument(uri, languageId, version, content);\r
- }\r
- TextDocument.create = create;\r
- /**\r
- * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.\r
- */\r
- function is(value) {\r
- var candidate = value;\r
- return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)\r
- && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;\r
- }\r
- TextDocument.is = is;\r
- function applyEdits(document, edits) {\r
- var text = document.getText();\r
- var sortedEdits = mergeSort(edits, function (a, b) {\r
- var diff = a.range.start.line - b.range.start.line;\r
- if (diff === 0) {\r
- return a.range.start.character - b.range.start.character;\r
- }\r
- return diff;\r
- });\r
- var lastModifiedOffset = text.length;\r
- for (var i = sortedEdits.length - 1; i >= 0; i--) {\r
- var e = sortedEdits[i];\r
- var startOffset = document.offsetAt(e.range.start);\r
- var endOffset = document.offsetAt(e.range.end);\r
- if (endOffset <= lastModifiedOffset) {\r
- text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);\r
- }\r
- else {\r
- throw new Error('Overlapping edit');\r
- }\r
- lastModifiedOffset = startOffset;\r
- }\r
- return text;\r
- }\r
- TextDocument.applyEdits = applyEdits;\r
- function mergeSort(data, compare) {\r
- if (data.length <= 1) {\r
- // sorted\r
- return data;\r
- }\r
- var p = (data.length / 2) | 0;\r
- var left = data.slice(0, p);\r
- var right = data.slice(p);\r
- mergeSort(left, compare);\r
- mergeSort(right, compare);\r
- var leftIdx = 0;\r
- var rightIdx = 0;\r
- var i = 0;\r
- while (leftIdx < left.length && rightIdx < right.length) {\r
- var ret = compare(left[leftIdx], right[rightIdx]);\r
- if (ret <= 0) {\r
- // smaller_equal -> take left to preserve order\r
- data[i++] = left[leftIdx++];\r
- }\r
- else {\r
- // greater -> take right\r
- data[i++] = right[rightIdx++];\r
- }\r
- }\r
- while (leftIdx < left.length) {\r
- data[i++] = left[leftIdx++];\r
- }\r
- while (rightIdx < right.length) {\r
- data[i++] = right[rightIdx++];\r
- }\r
- return data;\r
- }\r
-})(TextDocument || (TextDocument = {}));\r
-var FullTextDocument = /** @class */ (function () {\r
- function FullTextDocument(uri, languageId, version, content) {\r
- this._uri = uri;\r
- this._languageId = languageId;\r
- this._version = version;\r
- this._content = content;\r
- this._lineOffsets = undefined;\r
- }\r
- Object.defineProperty(FullTextDocument.prototype, "uri", {\r
- get: function () {\r
- return this._uri;\r
- },\r
- enumerable: true,\r
- configurable: true\r
- });\r
- Object.defineProperty(FullTextDocument.prototype, "languageId", {\r
- get: function () {\r
- return this._languageId;\r
- },\r
- enumerable: true,\r
- configurable: true\r
- });\r
- Object.defineProperty(FullTextDocument.prototype, "version", {\r
- get: function () {\r
- return this._version;\r
- },\r
- enumerable: true,\r
- configurable: true\r
- });\r
- FullTextDocument.prototype.getText = function (range) {\r
- if (range) {\r
- var start = this.offsetAt(range.start);\r
- var end = this.offsetAt(range.end);\r
- return this._content.substring(start, end);\r
- }\r
- return this._content;\r
- };\r
- FullTextDocument.prototype.update = function (event, version) {\r
- this._content = event.text;\r
- this._version = version;\r
- this._lineOffsets = undefined;\r
- };\r
- FullTextDocument.prototype.getLineOffsets = function () {\r
- if (this._lineOffsets === undefined) {\r
- var lineOffsets = [];\r
- var text = this._content;\r
- var isLineStart = true;\r
- for (var i = 0; i < text.length; i++) {\r
- if (isLineStart) {\r
- lineOffsets.push(i);\r
- isLineStart = false;\r
- }\r
- var ch = text.charAt(i);\r
- isLineStart = (ch === '\r' || ch === '\n');\r
- if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {\r
- i++;\r
- }\r
- }\r
- if (isLineStart && text.length > 0) {\r
- lineOffsets.push(text.length);\r
- }\r
- this._lineOffsets = lineOffsets;\r
- }\r
- return this._lineOffsets;\r
- };\r
- FullTextDocument.prototype.positionAt = function (offset) {\r
- offset = Math.max(Math.min(offset, this._content.length), 0);\r
- var lineOffsets = this.getLineOffsets();\r
- var low = 0, high = lineOffsets.length;\r
- if (high === 0) {\r
- return Position.create(0, offset);\r
- }\r
- while (low < high) {\r
- var mid = Math.floor((low + high) / 2);\r
- if (lineOffsets[mid] > offset) {\r
- high = mid;\r
- }\r
- else {\r
- low = mid + 1;\r
- }\r
- }\r
- // low is the least x for which the line offset is larger than the current offset\r
- // or array.length if no line offset is larger than the current offset\r
- var line = low - 1;\r
- return Position.create(line, offset - lineOffsets[line]);\r
- };\r
- FullTextDocument.prototype.offsetAt = function (position) {\r
- var lineOffsets = this.getLineOffsets();\r
- if (position.line >= lineOffsets.length) {\r
- return this._content.length;\r
- }\r
- else if (position.line < 0) {\r
- return 0;\r
- }\r
- var lineOffset = lineOffsets[position.line];\r
- var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;\r
- return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);\r
- };\r
- Object.defineProperty(FullTextDocument.prototype, "lineCount", {\r
- get: function () {\r
- return this.getLineOffsets().length;\r
- },\r
- enumerable: true,\r
- configurable: true\r
- });\r
- return FullTextDocument;\r
-}());\r
-var Is;\r
-(function (Is) {\r
- var toString = Object.prototype.toString;\r
- function defined(value) {\r
- return typeof value !== 'undefined';\r
- }\r
- Is.defined = defined;\r
- function undefined(value) {\r
- return typeof value === 'undefined';\r
- }\r
- Is.undefined = undefined;\r
- function boolean(value) {\r
- return value === true || value === false;\r
- }\r
- Is.boolean = boolean;\r
- function string(value) {\r
- return toString.call(value) === '[object String]';\r
- }\r
- Is.string = string;\r
- function number(value) {\r
- return toString.call(value) === '[object Number]';\r
- }\r
- Is.number = number;\r
- function func(value) {\r
- return toString.call(value) === '[object Function]';\r
- }\r
- Is.func = func;\r
- function objectLiteral(value) {\r
- // Strictly speaking class instances pass this check as well. Since the LSP\r
- // doesn't use classes we ignore this for now. If we do we need to add something\r
- // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`\r
- return value !== null && typeof value === 'object';\r
- }\r
- Is.objectLiteral = objectLiteral;\r
- function typedArray(value, check) {\r
- return Array.isArray(value) && value.every(check);\r
- }\r
- Is.typedArray = typedArray;\r
-})(Is || (Is = {}));\r
-
-
-/***/ }),
-/* 19 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const Is = __webpack_require__(20);\r
-const vscode_jsonrpc_1 = __webpack_require__(4);\r
-const messages_1 = __webpack_require__(21);\r
-const protocol_implementation_1 = __webpack_require__(22);\r
-exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;\r
-const protocol_typeDefinition_1 = __webpack_require__(23);\r
-exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;\r
-const protocol_workspaceFolders_1 = __webpack_require__(24);\r
-exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;\r
-exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;\r
-const protocol_configuration_1 = __webpack_require__(25);\r
-exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;\r
-const protocol_colorProvider_1 = __webpack_require__(26);\r
-exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;\r
-exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;\r
-const protocol_foldingRange_1 = __webpack_require__(27);\r
-exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;\r
-const protocol_declaration_1 = __webpack_require__(28);\r
-exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;\r
-const protocol_selectionRange_1 = __webpack_require__(29);\r
-exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;\r
-const protocol_progress_1 = __webpack_require__(30);\r
-exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;\r
-exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;\r
-exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;\r
-// @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
-let __noDynamicImport;\r
-/**\r
- * The DocumentFilter namespace provides helper functions to work with\r
- * [DocumentFilter](#DocumentFilter) literals.\r
- */\r
-var DocumentFilter;\r
-(function (DocumentFilter) {\r
- function is(value) {\r
- const candidate = value;\r
- return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);\r
- }\r
- DocumentFilter.is = is;\r
-})(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));\r
-/**\r
- * The DocumentSelector namespace provides helper functions to work with\r
- * [DocumentSelector](#DocumentSelector)s.\r
- */\r
-var DocumentSelector;\r
-(function (DocumentSelector) {\r
- function is(value) {\r
- if (!Array.isArray(value)) {\r
- return false;\r
- }\r
- for (let elem of value) {\r
- if (!Is.string(elem) && !DocumentFilter.is(elem)) {\r
- return false;\r
- }\r
- }\r
- return true;\r
- }\r
- DocumentSelector.is = is;\r
-})(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));\r
-/**\r
- * The `client/registerCapability` request is sent from the server to the client to register a new capability\r
- * handler on the client side.\r
- */\r
-var RegistrationRequest;\r
-(function (RegistrationRequest) {\r
- RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');\r
-})(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));\r
-/**\r
- * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability\r
- * handler on the client side.\r
- */\r
-var UnregistrationRequest;\r
-(function (UnregistrationRequest) {\r
- UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');\r
-})(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));\r
-var ResourceOperationKind;\r
-(function (ResourceOperationKind) {\r
- /**\r
- * Supports creating new files and folders.\r
- */\r
- ResourceOperationKind.Create = 'create';\r
- /**\r
- * Supports renaming existing files and folders.\r
- */\r
- ResourceOperationKind.Rename = 'rename';\r
- /**\r
- * Supports deleting existing files and folders.\r
- */\r
- ResourceOperationKind.Delete = 'delete';\r
-})(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));\r
-var FailureHandlingKind;\r
-(function (FailureHandlingKind) {\r
- /**\r
- * Applying the workspace change is simply aborted if one of the changes provided\r
- * fails. All operations executed before the failing operation stay executed.\r
- */\r
- FailureHandlingKind.Abort = 'abort';\r
- /**\r
- * All operations are executed transactional. That means they either all\r
- * succeed or no changes at all are applied to the workspace.\r
- */\r
- FailureHandlingKind.Transactional = 'transactional';\r
- /**\r
- * If the workspace edit contains only textual file changes they are executed transactional.\r
- * If resource changes (create, rename or delete file) are part of the change the failure\r
- * handling startegy is abort.\r
- */\r
- FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';\r
- /**\r
- * The client tries to undo the operations already executed. But there is no\r
- * guarantee that this is succeeding.\r
- */\r
- FailureHandlingKind.Undo = 'undo';\r
-})(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));\r
-/**\r
- * The StaticRegistrationOptions namespace provides helper functions to work with\r
- * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.\r
- */\r
-var StaticRegistrationOptions;\r
-(function (StaticRegistrationOptions) {\r
- function hasId(value) {\r
- const candidate = value;\r
- return candidate && Is.string(candidate.id) && candidate.id.length > 0;\r
- }\r
- StaticRegistrationOptions.hasId = hasId;\r
-})(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));\r
-/**\r
- * The TextDocumentRegistrationOptions namespace provides helper functions to work with\r
- * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.\r
- */\r
-var TextDocumentRegistrationOptions;\r
-(function (TextDocumentRegistrationOptions) {\r
- function is(value) {\r
- const candidate = value;\r
- return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));\r
- }\r
- TextDocumentRegistrationOptions.is = is;\r
-})(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));\r
-/**\r
- * The WorkDoneProgressOptions namespace provides helper functions to work with\r
- * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.\r
- */\r
-var WorkDoneProgressOptions;\r
-(function (WorkDoneProgressOptions) {\r
- function is(value) {\r
- const candidate = value;\r
- return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));\r
- }\r
- WorkDoneProgressOptions.is = is;\r
- function hasWorkDoneProgress(value) {\r
- const candidate = value;\r
- return candidate && Is.boolean(candidate.workDoneProgress);\r
- }\r
- WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;\r
-})(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));\r
-/**\r
- * The initialize request is sent from the client to the server.\r
- * It is sent once as the request after starting up the server.\r
- * The requests parameter is of type [InitializeParams](#InitializeParams)\r
- * the response if of type [InitializeResult](#InitializeResult) of a Thenable that\r
- * resolves to such.\r
- */\r
-var InitializeRequest;\r
-(function (InitializeRequest) {\r
- InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');\r
-})(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));\r
-/**\r
- * Known error codes for an `InitializeError`;\r
- */\r
-var InitializeError;\r
-(function (InitializeError) {\r
- /**\r
- * If the protocol version provided by the client can't be handled by the server.\r
- * @deprecated This initialize error got replaced by client capabilities. There is\r
- * no version handshake in version 3.0x\r
- */\r
- InitializeError.unknownProtocolVersion = 1;\r
-})(InitializeError = exports.InitializeError || (exports.InitializeError = {}));\r
-/**\r
- * The intialized notification is sent from the client to the\r
- * server after the client is fully initialized and the server\r
- * is allowed to send requests from the server to the client.\r
- */\r
-var InitializedNotification;\r
-(function (InitializedNotification) {\r
- InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');\r
-})(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));\r
-//---- Shutdown Method ----\r
-/**\r
- * A shutdown request is sent from the client to the server.\r
- * It is sent once when the client decides to shutdown the\r
- * server. The only notification that is sent after a shutdown request\r
- * is the exit event.\r
- */\r
-var ShutdownRequest;\r
-(function (ShutdownRequest) {\r
- ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');\r
-})(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));\r
-//---- Exit Notification ----\r
-/**\r
- * The exit event is sent from the client to the server to\r
- * ask the server to exit its process.\r
- */\r
-var ExitNotification;\r
-(function (ExitNotification) {\r
- ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');\r
-})(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));\r
-/**\r
- * The configuration change notification is sent from the client to the server\r
- * when the client's configuration has changed. The notification contains\r
- * the changed configuration as defined by the language client.\r
- */\r
-var DidChangeConfigurationNotification;\r
-(function (DidChangeConfigurationNotification) {\r
- DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');\r
-})(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));\r
-//---- Message show and log notifications ----\r
-/**\r
- * The message type\r
- */\r
-var MessageType;\r
-(function (MessageType) {\r
- /**\r
- * An error message.\r
- */\r
- MessageType.Error = 1;\r
- /**\r
- * A warning message.\r
- */\r
- MessageType.Warning = 2;\r
- /**\r
- * An information message.\r
- */\r
- MessageType.Info = 3;\r
- /**\r
- * A log message.\r
- */\r
- MessageType.Log = 4;\r
-})(MessageType = exports.MessageType || (exports.MessageType = {}));\r
-/**\r
- * The show message notification is sent from a server to a client to ask\r
- * the client to display a particular message in the user interface.\r
- */\r
-var ShowMessageNotification;\r
-(function (ShowMessageNotification) {\r
- ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');\r
-})(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));\r
-/**\r
- * The show message request is sent from the server to the client to show a message\r
- * and a set of options actions to the user.\r
- */\r
-var ShowMessageRequest;\r
-(function (ShowMessageRequest) {\r
- ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');\r
-})(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));\r
-/**\r
- * The log message notification is sent from the server to the client to ask\r
- * the client to log a particular message.\r
- */\r
-var LogMessageNotification;\r
-(function (LogMessageNotification) {\r
- LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');\r
-})(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));\r
-//---- Telemetry notification\r
-/**\r
- * The telemetry event notification is sent from the server to the client to ask\r
- * the client to log telemetry data.\r
- */\r
-var TelemetryEventNotification;\r
-(function (TelemetryEventNotification) {\r
- TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');\r
-})(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));\r
-/**\r
- * Defines how the host (editor) should sync\r
- * document changes to the language server.\r
- */\r
-var TextDocumentSyncKind;\r
-(function (TextDocumentSyncKind) {\r
- /**\r
- * Documents should not be synced at all.\r
- */\r
- TextDocumentSyncKind.None = 0;\r
- /**\r
- * Documents are synced by always sending the full content\r
- * of the document.\r
- */\r
- TextDocumentSyncKind.Full = 1;\r
- /**\r
- * Documents are synced by sending the full content on open.\r
- * After that only incremental updates to the document are\r
- * send.\r
- */\r
- TextDocumentSyncKind.Incremental = 2;\r
-})(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));\r
-/**\r
- * The document open notification is sent from the client to the server to signal\r
- * newly opened text documents. The document's truth is now managed by the client\r
- * and the server must not try to read the document's truth using the document's\r
- * uri. Open in this sense means it is managed by the client. It doesn't necessarily\r
- * mean that its content is presented in an editor. An open notification must not\r
- * be sent more than once without a corresponding close notification send before.\r
- * This means open and close notification must be balanced and the max open count\r
- * is one.\r
- */\r
-var DidOpenTextDocumentNotification;\r
-(function (DidOpenTextDocumentNotification) {\r
- DidOpenTextDocumentNotification.method = 'textDocument/didOpen';\r
- DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);\r
-})(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));\r
-/**\r
- * The document change notification is sent from the client to the server to signal\r
- * changes to a text document.\r
- */\r
-var DidChangeTextDocumentNotification;\r
-(function (DidChangeTextDocumentNotification) {\r
- DidChangeTextDocumentNotification.method = 'textDocument/didChange';\r
- DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);\r
-})(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));\r
-/**\r
- * The document close notification is sent from the client to the server when\r
- * the document got closed in the client. The document's truth now exists where\r
- * the document's uri points to (e.g. if the document's uri is a file uri the\r
- * truth now exists on disk). As with the open notification the close notification\r
- * is about managing the document's content. Receiving a close notification\r
- * doesn't mean that the document was open in an editor before. A close\r
- * notification requires a previous open notification to be sent.\r
- */\r
-var DidCloseTextDocumentNotification;\r
-(function (DidCloseTextDocumentNotification) {\r
- DidCloseTextDocumentNotification.method = 'textDocument/didClose';\r
- DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);\r
-})(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));\r
-/**\r
- * The document save notification is sent from the client to the server when\r
- * the document got saved in the client.\r
- */\r
-var DidSaveTextDocumentNotification;\r
-(function (DidSaveTextDocumentNotification) {\r
- DidSaveTextDocumentNotification.method = 'textDocument/didSave';\r
- DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);\r
-})(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));\r
-/**\r
- * Represents reasons why a text document is saved.\r
- */\r
-var TextDocumentSaveReason;\r
-(function (TextDocumentSaveReason) {\r
- /**\r
- * Manually triggered, e.g. by the user pressing save, by starting debugging,\r
- * or by an API call.\r
- */\r
- TextDocumentSaveReason.Manual = 1;\r
- /**\r
- * Automatic after a delay.\r
- */\r
- TextDocumentSaveReason.AfterDelay = 2;\r
- /**\r
- * When the editor lost focus.\r
- */\r
- TextDocumentSaveReason.FocusOut = 3;\r
-})(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));\r
-/**\r
- * A document will save notification is sent from the client to the server before\r
- * the document is actually saved.\r
- */\r
-var WillSaveTextDocumentNotification;\r
-(function (WillSaveTextDocumentNotification) {\r
- WillSaveTextDocumentNotification.method = 'textDocument/willSave';\r
- WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);\r
-})(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));\r
-/**\r
- * A document will save request is sent from the client to the server before\r
- * the document is actually saved. The request can return an array of TextEdits\r
- * which will be applied to the text document before it is saved. Please note that\r
- * clients might drop results if computing the text edits took too long or if a\r
- * server constantly fails on this request. This is done to keep the save fast and\r
- * reliable.\r
- */\r
-var WillSaveTextDocumentWaitUntilRequest;\r
-(function (WillSaveTextDocumentWaitUntilRequest) {\r
- WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';\r
- WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);\r
-})(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));\r
-/**\r
- * The watched files notification is sent from the client to the server when\r
- * the client detects changes to file watched by the language client.\r
- */\r
-var DidChangeWatchedFilesNotification;\r
-(function (DidChangeWatchedFilesNotification) {\r
- DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');\r
-})(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));\r
-/**\r
- * The file event type\r
- */\r
-var FileChangeType;\r
-(function (FileChangeType) {\r
- /**\r
- * The file got created.\r
- */\r
- FileChangeType.Created = 1;\r
- /**\r
- * The file got changed.\r
- */\r
- FileChangeType.Changed = 2;\r
- /**\r
- * The file got deleted.\r
- */\r
- FileChangeType.Deleted = 3;\r
-})(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));\r
-var WatchKind;\r
-(function (WatchKind) {\r
- /**\r
- * Interested in create events.\r
- */\r
- WatchKind.Create = 1;\r
- /**\r
- * Interested in change events\r
- */\r
- WatchKind.Change = 2;\r
- /**\r
- * Interested in delete events\r
- */\r
- WatchKind.Delete = 4;\r
-})(WatchKind = exports.WatchKind || (exports.WatchKind = {}));\r
-/**\r
- * Diagnostics notification are sent from the server to the client to signal\r
- * results of validation runs.\r
- */\r
-var PublishDiagnosticsNotification;\r
-(function (PublishDiagnosticsNotification) {\r
- PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');\r
-})(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));\r
-/**\r
- * How a completion was triggered\r
- */\r
-var CompletionTriggerKind;\r
-(function (CompletionTriggerKind) {\r
- /**\r
- * Completion was triggered by typing an identifier (24x7 code\r
- * complete), manual invocation (e.g Ctrl+Space) or via API.\r
- */\r
- CompletionTriggerKind.Invoked = 1;\r
- /**\r
- * Completion was triggered by a trigger character specified by\r
- * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.\r
- */\r
- CompletionTriggerKind.TriggerCharacter = 2;\r
- /**\r
- * Completion was re-triggered as current completion list is incomplete\r
- */\r
- CompletionTriggerKind.TriggerForIncompleteCompletions = 3;\r
-})(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));\r
-/**\r
- * Request to request completion at a given text document position. The request's\r
- * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response\r
- * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)\r
- * or a Thenable that resolves to such.\r
- *\r
- * The request can delay the computation of the [`detail`](#CompletionItem.detail)\r
- * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`\r
- * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,\r
- * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.\r
- */\r
-var CompletionRequest;\r
-(function (CompletionRequest) {\r
- CompletionRequest.method = 'textDocument/completion';\r
- CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);\r
- /** @deprecated Use CompletionRequest.type */\r
- CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));\r
-/**\r
- * Request to resolve additional information for a given completion item.The request's\r
- * parameter is of type [CompletionItem](#CompletionItem) the response\r
- * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.\r
- */\r
-var CompletionResolveRequest;\r
-(function (CompletionResolveRequest) {\r
- CompletionResolveRequest.method = 'completionItem/resolve';\r
- CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);\r
-})(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));\r
-/**\r
- * Request to request hover information at a given text document position. The request's\r
- * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of\r
- * type [Hover](#Hover) or a Thenable that resolves to such.\r
- */\r
-var HoverRequest;\r
-(function (HoverRequest) {\r
- HoverRequest.method = 'textDocument/hover';\r
- HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);\r
-})(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));\r
-/**\r
- * How a signature help was triggered.\r
- *\r
- * @since 3.15.0\r
- */\r
-var SignatureHelpTriggerKind;\r
-(function (SignatureHelpTriggerKind) {\r
- /**\r
- * Signature help was invoked manually by the user or by a command.\r
- */\r
- SignatureHelpTriggerKind.Invoked = 1;\r
- /**\r
- * Signature help was triggered by a trigger character.\r
- */\r
- SignatureHelpTriggerKind.TriggerCharacter = 2;\r
- /**\r
- * Signature help was triggered by the cursor moving or by the document content changing.\r
- */\r
- SignatureHelpTriggerKind.ContentChange = 3;\r
-})(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));\r
-var SignatureHelpRequest;\r
-(function (SignatureHelpRequest) {\r
- SignatureHelpRequest.method = 'textDocument/signatureHelp';\r
- SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);\r
-})(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));\r
-/**\r
- * A request to resolve the definition location of a symbol at a given text\r
- * document position. The request's parameter is of type [TextDocumentPosition]\r
- * (#TextDocumentPosition) the response is of either type [Definition](#Definition)\r
- * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves\r
- * to such.\r
- */\r
-var DefinitionRequest;\r
-(function (DefinitionRequest) {\r
- DefinitionRequest.method = 'textDocument/definition';\r
- DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);\r
- /** @deprecated Use DefinitionRequest.type */\r
- DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));\r
-/**\r
- * A request to resolve project-wide references for the symbol denoted\r
- * by the given text document position. The request's parameter is of\r
- * type [ReferenceParams](#ReferenceParams) the response is of type\r
- * [Location[]](#Location) or a Thenable that resolves to such.\r
- */\r
-var ReferencesRequest;\r
-(function (ReferencesRequest) {\r
- ReferencesRequest.method = 'textDocument/references';\r
- ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);\r
- /** @deprecated Use ReferencesRequest.type */\r
- ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));\r
-/**\r
- * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given\r
- * text document position. The request's parameter is of type [TextDocumentPosition]\r
- * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]\r
- * (#DocumentHighlight) or a Thenable that resolves to such.\r
- */\r
-var DocumentHighlightRequest;\r
-(function (DocumentHighlightRequest) {\r
- DocumentHighlightRequest.method = 'textDocument/documentHighlight';\r
- DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);\r
- /** @deprecated Use DocumentHighlightRequest.type */\r
- DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));\r
-/**\r
- * A request to list all symbols found in a given text document. The request's\r
- * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the\r
- * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable\r
- * that resolves to such.\r
- */\r
-var DocumentSymbolRequest;\r
-(function (DocumentSymbolRequest) {\r
- DocumentSymbolRequest.method = 'textDocument/documentSymbol';\r
- DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);\r
- /** @deprecated Use DocumentSymbolRequest.type */\r
- DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));\r
-/**\r
- * A request to provide commands for the given text document and range.\r
- */\r
-var CodeActionRequest;\r
-(function (CodeActionRequest) {\r
- CodeActionRequest.method = 'textDocument/codeAction';\r
- CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);\r
- /** @deprecated Use CodeActionRequest.type */\r
- CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));\r
-/**\r
- * A request to list project-wide symbols matching the query string given\r
- * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is\r
- * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that\r
- * resolves to such.\r
- */\r
-var WorkspaceSymbolRequest;\r
-(function (WorkspaceSymbolRequest) {\r
- WorkspaceSymbolRequest.method = 'workspace/symbol';\r
- WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);\r
- /** @deprecated Use WorkspaceSymbolRequest.type */\r
- WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));\r
-/**\r
- * A request to provide code lens for the given text document.\r
- */\r
-var CodeLensRequest;\r
-(function (CodeLensRequest) {\r
- CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');\r
- /** @deprecated Use CodeLensRequest.type */\r
- CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));\r
-/**\r
- * A request to resolve a command for a given code lens.\r
- */\r
-var CodeLensResolveRequest;\r
-(function (CodeLensResolveRequest) {\r
- CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');\r
-})(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));\r
-/**\r
- * A request to provide document links\r
- */\r
-var DocumentLinkRequest;\r
-(function (DocumentLinkRequest) {\r
- DocumentLinkRequest.method = 'textDocument/documentLink';\r
- DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);\r
- /** @deprecated Use DocumentLinkRequest.type */\r
- DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));\r
-/**\r
- * Request to resolve additional information for a given document link. The request's\r
- * parameter is of type [DocumentLink](#DocumentLink) the response\r
- * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.\r
- */\r
-var DocumentLinkResolveRequest;\r
-(function (DocumentLinkResolveRequest) {\r
- DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');\r
-})(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));\r
-/**\r
- * A request to to format a whole document.\r
- */\r
-var DocumentFormattingRequest;\r
-(function (DocumentFormattingRequest) {\r
- DocumentFormattingRequest.method = 'textDocument/formatting';\r
- DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);\r
-})(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));\r
-/**\r
- * A request to to format a range in a document.\r
- */\r
-var DocumentRangeFormattingRequest;\r
-(function (DocumentRangeFormattingRequest) {\r
- DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';\r
- DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);\r
-})(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));\r
-/**\r
- * A request to format a document on type.\r
- */\r
-var DocumentOnTypeFormattingRequest;\r
-(function (DocumentOnTypeFormattingRequest) {\r
- DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';\r
- DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);\r
-})(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));\r
-/**\r
- * A request to rename a symbol.\r
- */\r
-var RenameRequest;\r
-(function (RenameRequest) {\r
- RenameRequest.method = 'textDocument/rename';\r
- RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);\r
-})(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));\r
-/**\r
- * A request to test and perform the setup necessary for a rename.\r
- */\r
-var PrepareRenameRequest;\r
-(function (PrepareRenameRequest) {\r
- PrepareRenameRequest.method = 'textDocument/prepareRename';\r
- PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);\r
-})(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));\r
-/**\r
- * A request send from the client to the server to execute a command. The request might return\r
- * a workspace edit which the client will apply to the workspace.\r
- */\r
-var ExecuteCommandRequest;\r
-(function (ExecuteCommandRequest) {\r
- ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');\r
-})(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));\r
-/**\r
- * A request sent from the server to the client to modified certain resources.\r
- */\r
-var ApplyWorkspaceEditRequest;\r
-(function (ApplyWorkspaceEditRequest) {\r
- ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');\r
-})(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));\r
-
-
-/***/ }),
-/* 20 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-function boolean(value) {\r
- return value === true || value === false;\r
-}\r
-exports.boolean = boolean;\r
-function string(value) {\r
- return typeof value === 'string' || value instanceof String;\r
-}\r
-exports.string = string;\r
-function number(value) {\r
- return typeof value === 'number' || value instanceof Number;\r
-}\r
-exports.number = number;\r
-function error(value) {\r
- return value instanceof Error;\r
-}\r
-exports.error = error;\r
-function func(value) {\r
- return typeof value === 'function';\r
-}\r
-exports.func = func;\r
-function array(value) {\r
- return Array.isArray(value);\r
-}\r
-exports.array = array;\r
-function stringArray(value) {\r
- return array(value) && value.every(elem => string(elem));\r
-}\r
-exports.stringArray = stringArray;\r
-function typedArray(value, check) {\r
- return Array.isArray(value) && value.every(check);\r
-}\r
-exports.typedArray = typedArray;\r
-function objectLiteral(value) {\r
- // Strictly speaking class instances pass this check as well. Since the LSP\r
- // doesn't use classes we ignore this for now. If we do we need to add something\r
- // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`\r
- return value !== null && typeof value === 'object';\r
-}\r
-exports.objectLiteral = objectLiteral;\r
-
-
-/***/ }),
-/* 21 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const vscode_jsonrpc_1 = __webpack_require__(4);\r
-class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {\r
- constructor(method) {\r
- super(method);\r
- }\r
-}\r
-exports.ProtocolRequestType0 = ProtocolRequestType0;\r
-class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {\r
- constructor(method) {\r
- super(method);\r
- }\r
-}\r
-exports.ProtocolRequestType = ProtocolRequestType;\r
-class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {\r
- constructor(method) {\r
- super(method);\r
- }\r
-}\r
-exports.ProtocolNotificationType = ProtocolNotificationType;\r
-class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {\r
- constructor(method) {\r
- super(method);\r
- }\r
-}\r
-exports.ProtocolNotificationType0 = ProtocolNotificationType0;\r
-
-
-/***/ }),
-/* 22 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const vscode_jsonrpc_1 = __webpack_require__(4);\r
-const messages_1 = __webpack_require__(21);\r
-// @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
-let __noDynamicImport;\r
-/**\r
- * A request to resolve the implementation locations of a symbol at a given text\r
- * document position. The request's parameter is of type [TextDocumentPositioParams]\r
- * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a\r
- * Thenable that resolves to such.\r
- */\r
-var ImplementationRequest;\r
-(function (ImplementationRequest) {\r
- ImplementationRequest.method = 'textDocument/implementation';\r
- ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);\r
- /** @deprecated Use ImplementationRequest.type */\r
- ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));\r
-
-
-/***/ }),
-/* 23 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const vscode_jsonrpc_1 = __webpack_require__(4);\r
-const messages_1 = __webpack_require__(21);\r
-// @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
-let __noDynamicImport;\r
-/**\r
- * A request to resolve the type definition locations of a symbol at a given text\r
- * document position. The request's parameter is of type [TextDocumentPositioParams]\r
- * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a\r
- * Thenable that resolves to such.\r
- */\r
-var TypeDefinitionRequest;\r
-(function (TypeDefinitionRequest) {\r
- TypeDefinitionRequest.method = 'textDocument/typeDefinition';\r
- TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);\r
- /** @deprecated Use TypeDefinitionRequest.type */\r
- TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));\r
-
-
-/***/ }),
-/* 24 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const messages_1 = __webpack_require__(21);\r
-/**\r
- * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.\r
- */\r
-var WorkspaceFoldersRequest;\r
-(function (WorkspaceFoldersRequest) {\r
- WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');\r
-})(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));\r
-/**\r
- * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace\r
- * folder configuration changes.\r
- */\r
-var DidChangeWorkspaceFoldersNotification;\r
-(function (DidChangeWorkspaceFoldersNotification) {\r
- DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');\r
-})(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));\r
-
-
-/***/ }),
-/* 25 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const messages_1 = __webpack_require__(21);\r
-/**\r
- * The 'workspace/configuration' request is sent from the server to the client to fetch a certain\r
- * configuration setting.\r
- *\r
- * This pull model replaces the old push model were the client signaled configuration change via an\r
- * event. If the server still needs to react to configuration changes (since the server caches the\r
- * result of `workspace/configuration` requests) the server should register for an empty configuration\r
- * change event and empty the cache if such an event is received.\r
- */\r
-var ConfigurationRequest;\r
-(function (ConfigurationRequest) {\r
- ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');\r
-})(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));\r
-
-
-/***/ }),
-/* 26 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const vscode_jsonrpc_1 = __webpack_require__(4);\r
-const messages_1 = __webpack_require__(21);\r
-/**\r
- * A request to list all color symbols found in a given text document. The request's\r
- * parameter is of type [DocumentColorParams](#DocumentColorParams) the\r
- * response is of type [ColorInformation[]](#ColorInformation) or a Thenable\r
- * that resolves to such.\r
- */\r
-var DocumentColorRequest;\r
-(function (DocumentColorRequest) {\r
- DocumentColorRequest.method = 'textDocument/documentColor';\r
- DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);\r
- /** @deprecated Use DocumentColorRequest.type */\r
- DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));\r
-/**\r
- * A request to list all presentation for a color. The request's\r
- * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the\r
- * response is of type [ColorInformation[]](#ColorInformation) or a Thenable\r
- * that resolves to such.\r
- */\r
-var ColorPresentationRequest;\r
-(function (ColorPresentationRequest) {\r
- ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');\r
-})(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));\r
-
-
-/***/ }),
-/* 27 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-\r
-/*---------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- *--------------------------------------------------------------------------------------------*/\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const vscode_jsonrpc_1 = __webpack_require__(4);\r
-const messages_1 = __webpack_require__(21);\r
-/**\r
- * Enum of known range kinds\r
- */\r
-var FoldingRangeKind;\r
-(function (FoldingRangeKind) {\r
- /**\r
- * Folding range for a comment\r
- */\r
- FoldingRangeKind["Comment"] = "comment";\r
- /**\r
- * Folding range for a imports or includes\r
- */\r
- FoldingRangeKind["Imports"] = "imports";\r
- /**\r
- * Folding range for a region (e.g. `#region`)\r
- */\r
- FoldingRangeKind["Region"] = "region";\r
-})(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));\r
-/**\r
- * A request to provide folding ranges in a document. The request's\r
- * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the\r
- * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable\r
- * that resolves to such.\r
- */\r
-var FoldingRangeRequest;\r
-(function (FoldingRangeRequest) {\r
- FoldingRangeRequest.method = 'textDocument/foldingRange';\r
- FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);\r
- /** @deprecated Use FoldingRangeRequest.type */\r
- FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));\r
-
-
-/***/ }),
-/* 28 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const vscode_jsonrpc_1 = __webpack_require__(4);\r
-const messages_1 = __webpack_require__(21);\r
-// @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
-let __noDynamicImport;\r
-/**\r
- * A request to resolve the type definition locations of a symbol at a given text\r
- * document position. The request's parameter is of type [TextDocumentPositioParams]\r
- * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)\r
- * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves\r
- * to such.\r
- */\r
-var DeclarationRequest;\r
-(function (DeclarationRequest) {\r
- DeclarationRequest.method = 'textDocument/declaration';\r
- DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);\r
- /** @deprecated Use DeclarationRequest.type */\r
- DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));\r
-
-
-/***/ }),
-/* 29 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-\r
-/*---------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- *--------------------------------------------------------------------------------------------*/\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const vscode_jsonrpc_1 = __webpack_require__(4);\r
-const messages_1 = __webpack_require__(21);\r
-/**\r
- * A request to provide selection ranges in a document. The request's\r
- * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the\r
- * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable\r
- * that resolves to such.\r
- */\r
-var SelectionRangeRequest;\r
-(function (SelectionRangeRequest) {\r
- SelectionRangeRequest.method = 'textDocument/selectionRange';\r
- SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);\r
- /** @deprecated Use SelectionRangeRequest.type */\r
- SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
-})(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));\r
-
-
-/***/ }),
-/* 30 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const vscode_jsonrpc_1 = __webpack_require__(4);\r
-const messages_1 = __webpack_require__(21);\r
-var WorkDoneProgress;\r
-(function (WorkDoneProgress) {\r
- WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();\r
-})(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));\r
-/**\r
- * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress\r
- * reporting from the server.\r
- */\r
-var WorkDoneProgressCreateRequest;\r
-(function (WorkDoneProgressCreateRequest) {\r
- WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');\r
-})(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));\r
-/**\r
- * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress\r
- * initiated on the server side.\r
- */\r
-var WorkDoneProgressCancelNotification;\r
-(function (WorkDoneProgressCancelNotification) {\r
- WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');\r
-})(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));\r
-
-
-/***/ }),
-/* 31 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) TypeFox and others. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const messages_1 = __webpack_require__(21);\r
-/**\r
- * A request to result a `CallHierarchyItem` in a document at a given position.\r
- * Can be used as an input to a incoming or outgoing call hierarchy.\r
- *\r
- * @since 3.16.0 - Proposed state\r
- */\r
-var CallHierarchyPrepareRequest;\r
-(function (CallHierarchyPrepareRequest) {\r
- CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';\r
- CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);\r
-})(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));\r
-/**\r
- * A request to resolve the incoming calls for a given `CallHierarchyItem`.\r
- *\r
- * @since 3.16.0 - Proposed state\r
- */\r
-var CallHierarchyIncomingCallsRequest;\r
-(function (CallHierarchyIncomingCallsRequest) {\r
- CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';\r
- CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);\r
-})(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));\r
-/**\r
- * A request to resolve the outgoing calls for a given `CallHierarchyItem`.\r
- *\r
- * @since 3.16.0 - Proposed state\r
- */\r
-var CallHierarchyOutgoingCallsRequest;\r
-(function (CallHierarchyOutgoingCallsRequest) {\r
- CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';\r
- CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);\r
-})(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));\r
-
-
-/***/ }),
-/* 32 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* --------------------------------------------------------------------------------------------\r
- * Copyright (c) Microsoft Corporation. All rights reserved.\r
- * Licensed under the MIT License. See License.txt in the project root for license information.\r
- * ------------------------------------------------------------------------------------------ */\r
-\r
-Object.defineProperty(exports, "__esModule", { value: true });\r
-const messages_1 = __webpack_require__(21);\r
-/**\r
- * A set of predefined token types. This set is not fixed\r
- * an clients can specify additional token types via the\r
- * corresponding client capabilities.\r
- *\r
- * @since 3.16.0 - Proposed state\r
- */\r
-var SemanticTokenTypes;\r
-(function (SemanticTokenTypes) {\r
- SemanticTokenTypes["comment"] = "comment";\r
- SemanticTokenTypes["keyword"] = "keyword";\r
- SemanticTokenTypes["string"] = "string";\r
- SemanticTokenTypes["number"] = "number";\r
- SemanticTokenTypes["regexp"] = "regexp";\r
- SemanticTokenTypes["operator"] = "operator";\r
- SemanticTokenTypes["namespace"] = "namespace";\r
- SemanticTokenTypes["type"] = "type";\r
- SemanticTokenTypes["struct"] = "struct";\r
- SemanticTokenTypes["class"] = "class";\r
- SemanticTokenTypes["interface"] = "interface";\r
- SemanticTokenTypes["enum"] = "enum";\r
- SemanticTokenTypes["typeParameter"] = "typeParameter";\r
- SemanticTokenTypes["function"] = "function";\r
- SemanticTokenTypes["member"] = "member";\r
- SemanticTokenTypes["property"] = "property";\r
- SemanticTokenTypes["macro"] = "macro";\r
- SemanticTokenTypes["variable"] = "variable";\r
- SemanticTokenTypes["parameter"] = "parameter";\r
- SemanticTokenTypes["label"] = "label";\r
-})(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));\r
-/**\r
- * A set of predefined token modifiers. This set is not fixed\r
- * an clients can specify additional token types via the\r
- * corresponding client capabilities.\r
- *\r
- * @since 3.16.0 - Proposed state\r
- */\r
-var SemanticTokenModifiers;\r
-(function (SemanticTokenModifiers) {\r
- SemanticTokenModifiers["documentation"] = "documentation";\r
- SemanticTokenModifiers["declaration"] = "declaration";\r
- SemanticTokenModifiers["definition"] = "definition";\r
- SemanticTokenModifiers["reference"] = "reference";\r
- SemanticTokenModifiers["static"] = "static";\r
- SemanticTokenModifiers["abstract"] = "abstract";\r
- SemanticTokenModifiers["deprecated"] = "deprecated";\r
- SemanticTokenModifiers["async"] = "async";\r
- SemanticTokenModifiers["volatile"] = "volatile";\r
- SemanticTokenModifiers["readonly"] = "readonly";\r
-})(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));\r
-/**\r
- * @since 3.16.0 - Proposed state\r
- */\r
-var SemanticTokens;\r
-(function (SemanticTokens) {\r
- function is(value) {\r
- const candidate = value;\r
- return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&\r
- Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');\r
- }\r
- SemanticTokens.is = is;\r
-})(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));\r
-/**\r
- * @since 3.16.0 - Proposed state\r
- */\r
-var SemanticTokensRequest;\r
-(function (SemanticTokensRequest) {\r
- SemanticTokensRequest.method = 'textDocument/semanticTokens';\r
- SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);\r
-})(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));\r
-/**\r
- * @since 3.16.0 - Proposed state\r
- */\r
-var SemanticTokensEditsRequest;\r
-(function (SemanticTokensEditsRequest) {\r
- SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';\r
- SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);\r
-})(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));\r
-/**\r
- * @since 3.16.0 - Proposed state\r
- */\r
-var SemanticTokensRangeRequest;\r
-(function (SemanticTokensRangeRequest) {\r
- SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';\r
- SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);\r
-})(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));\r
-
-
-/***/ }),
-/* 33 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
+ };
+ exports2.AbstractMessageBuffer = AbstractMessageBuffer;
});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const coc_nvim_1 = __webpack_require__(1);
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const languageProvider_1 = __importDefault(__webpack_require__(34));
-const PConst = __importStar(__webpack_require__(39));
-const typescriptServiceClient_1 = __importDefault(__webpack_require__(117));
-const typeConverters = __importStar(__webpack_require__(37));
-const typingsStatus_1 = __importStar(__webpack_require__(139));
-// Style check diagnostics that can be reported as warnings
-const styleCheckDiagnostics = [
- 6133,
- 6138,
- 7027,
- 7028,
- 7029,
- 7030 // not all code paths return a value
-];
-class TypeScriptServiceClientHost {
- constructor(descriptions, pluginManager) {
- this.languages = [];
- this.languagePerId = new Map();
- this.disposables = [];
- this.reportStyleCheckAsWarnings = true;
- let timer;
- const handleProjectChange = () => {
- if (timer)
- clearTimeout(timer);
- timer = setTimeout(() => {
- this.triggerAllDiagnostics();
- }, 1500);
- };
- const configFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/[tj]sconfig.json');
- this.disposables.push(configFileWatcher);
- configFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
- configFileWatcher.onDidDelete(this.reloadProjects, this, this.disposables);
- configFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
- const packageFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/package.json');
- packageFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
- packageFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
- this.client = new typescriptServiceClient_1.default(pluginManager);
- this.disposables.push(this.client);
- this.client.onDiagnosticsReceived(({ kind, resource, diagnostics }) => {
- this.diagnosticsReceived(kind, resource, diagnostics);
- }, null, this.disposables);
- this.client.onConfigDiagnosticsReceived(diag => {
- let { body } = diag;
- if (body) {
- let { configFile, diagnostics } = body;
- let uri = coc_nvim_1.Uri.file(configFile);
- if (diagnostics.length == 0) {
- this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), []);
- }
- else {
- let diagnosticList = diagnostics.map(o => {
- let { text, code, category, start, end } = o;
- let range;
- if (!start || !end) {
- range = vscode_languageserver_protocol_1.Range.create(vscode_languageserver_protocol_1.Position.create(0, 0), vscode_languageserver_protocol_1.Position.create(0, 1));
- }
- else {
- range = vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1);
- }
- let severity = category == 'error' ? vscode_languageserver_protocol_1.DiagnosticSeverity.Error : vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
- return vscode_languageserver_protocol_1.Diagnostic.create(range, text, severity, code);
- });
- this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), diagnosticList);
- }
- }
- }, null, this.disposables);
- this.typingsStatus = new typingsStatus_1.default(this.client);
- this.ataProgressReporter = new typingsStatus_1.AtaProgressReporter(this.client);
- for (const description of descriptions) { // tslint:disable-line
- const manager = new languageProvider_1.default(this.client, description, this.typingsStatus);
- this.languages.push(manager);
- this.disposables.push(manager);
- this.languagePerId.set(description.id, manager);
- }
- this.client.ensureServiceStarted();
- this.client.onTsServerStarted(() => {
- this.triggerAllDiagnostics();
- });
- coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
- this.configurationChanged();
+
+// node_modules/vscode-jsonrpc/lib/node/ril.js
+var require_ril = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ var ral_1 = require_ral();
+ var util_1 = require("util");
+ var disposable_1 = require_disposable();
+ var messageBuffer_1 = require_messageBuffer();
+ var MessageBuffer = class extends messageBuffer_1.AbstractMessageBuffer {
+ constructor(encoding = "utf-8") {
+ super(encoding);
+ }
+ emptyBuffer() {
+ return MessageBuffer.emptyBuffer;
+ }
+ fromString(value, encoding) {
+ return Buffer.from(value, encoding);
+ }
+ toString(value, encoding) {
+ if (value instanceof Buffer) {
+ return value.toString(encoding);
+ } else {
+ return new util_1.TextDecoder(encoding).decode(value);
+ }
}
- dispose() {
- coc_nvim_1.disposeAll(this.disposables);
- this.typingsStatus.dispose();
- this.ataProgressReporter.dispose();
+ asNative(buffer, length) {
+ if (length === void 0) {
+ return buffer instanceof Buffer ? buffer : Buffer.from(buffer);
+ } else {
+ return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length);
+ }
}
- reset() {
- for (let lang of this.languages) {
- lang.fileConfigurationManager.reset();
- }
+ allocNative(length) {
+ return Buffer.allocUnsafe(length);
}
- get serviceClient() {
- return this.client;
+ };
+ MessageBuffer.emptyBuffer = Buffer.allocUnsafe(0);
+ var ReadableStreamWrapper = class {
+ constructor(stream) {
+ this.stream = stream;
}
- reloadProjects() {
- this.client.execute('reloadProjects', null, vscode_languageserver_protocol_1.CancellationToken.None);
- this.triggerAllDiagnostics();
+ onClose(listener) {
+ this.stream.on("close", listener);
+ return disposable_1.Disposable.create(() => this.stream.off("close", listener));
}
- // typescript or javascript
- getProvider(languageId) {
- return this.languagePerId.get(languageId);
+ onError(listener) {
+ this.stream.on("error", listener);
+ return disposable_1.Disposable.create(() => this.stream.off("error", listener));
}
- configurationChanged() {
- const config = coc_nvim_1.workspace.getConfiguration('tsserver');
- this.reportStyleCheckAsWarnings = config.get('reportStyleChecksAsWarnings', true);
+ onEnd(listener) {
+ this.stream.on("end", listener);
+ return disposable_1.Disposable.create(() => this.stream.off("end", listener));
}
- findLanguage(resource) {
- try {
- return this.languages.find(language => language.handles(resource));
- }
- catch (_a) {
- return null;
- }
+ onData(listener) {
+ this.stream.on("data", listener);
+ return disposable_1.Disposable.create(() => this.stream.off("data", listener));
}
- handles(uri) {
- return this.findLanguage(coc_nvim_1.Uri.parse(uri)) != null;
+ };
+ var WritableStreamWrapper = class {
+ constructor(stream) {
+ this.stream = stream;
}
- triggerAllDiagnostics() {
- for (const language of this.languagePerId.values()) {
- language.triggerAllDiagnostics();
- }
+ onClose(listener) {
+ this.stream.on("close", listener);
+ return disposable_1.Disposable.create(() => this.stream.off("close", listener));
}
- diagnosticsReceived(kind, resource, diagnostics) {
- const language = this.findLanguage(resource);
- if (language) {
- language.diagnosticsReceived(kind, resource, this.createMarkerDatas(diagnostics));
- }
+ onError(listener) {
+ this.stream.on("error", listener);
+ return disposable_1.Disposable.create(() => this.stream.off("error", listener));
}
- createMarkerDatas(diagnostics) {
- return diagnostics.map(tsDiag => this.tsDiagnosticToLspDiagnostic(tsDiag));
+ onEnd(listener) {
+ this.stream.on("end", listener);
+ return disposable_1.Disposable.create(() => this.stream.off("end", listener));
}
- tsDiagnosticToLspDiagnostic(diagnostic) {
- const { start, end, text } = diagnostic;
- const range = {
- start: typeConverters.Position.fromLocation(start),
- end: typeConverters.Position.fromLocation(end)
+ write(data, encoding) {
+ return new Promise((resolve, reject) => {
+ const callback = (error) => {
+ if (error === void 0 || error === null) {
+ resolve();
+ } else {
+ reject(error);
+ }
};
- let relatedInformation;
- if (diagnostic.relatedInformation) {
- relatedInformation = diagnostic.relatedInformation.map(o => {
- let { span, message } = o;
- return {
- location: typeConverters.Location.fromTextSpan(this.client.toResource(span.file), span),
- message
- };
- });
+ if (typeof data === "string") {
+ this.stream.write(data, encoding, callback);
+ } else {
+ this.stream.write(data, callback);
+ }
+ });
+ }
+ end() {
+ this.stream.end();
+ }
+ };
+ var _ril = Object.freeze({
+ messageBuffer: Object.freeze({
+ create: (encoding) => new MessageBuffer(encoding)
+ }),
+ applicationJson: Object.freeze({
+ encoder: Object.freeze({
+ name: "application/json",
+ encode: (msg, options) => {
+ try {
+ return Promise.resolve(Buffer.from(JSON.stringify(msg, void 0, 0), options.charset));
+ } catch (err) {
+ return Promise.reject(err);
+ }
}
- return {
- range,
- message: text,
- code: diagnostic.code ? diagnostic.code : null,
- severity: this.getDiagnosticSeverity(diagnostic),
- reportUnnecessary: diagnostic.reportsUnnecessary,
- source: diagnostic.source || 'tsserver',
- relatedInformation
- };
- }
- getDiagnosticSeverity(diagnostic) {
- if (this.reportStyleCheckAsWarnings &&
- this.isStyleCheckDiagnostic(diagnostic.code) &&
- diagnostic.category === PConst.DiagnosticCategory.error) {
- return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
- }
- switch (diagnostic.category) {
- case PConst.DiagnosticCategory.error:
- return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
- case PConst.DiagnosticCategory.warning:
- return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
- case PConst.DiagnosticCategory.suggestion:
- return vscode_languageserver_protocol_1.DiagnosticSeverity.Information;
- default:
- return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
+ }),
+ decoder: Object.freeze({
+ name: "application/json",
+ decode: (buffer, options) => {
+ try {
+ if (buffer instanceof Buffer) {
+ return Promise.resolve(JSON.parse(buffer.toString(options.charset)));
+ } else {
+ return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer)));
+ }
+ } catch (err) {
+ return Promise.reject(err);
+ }
}
+ })
+ }),
+ stream: Object.freeze({
+ asReadableStream: (stream) => new ReadableStreamWrapper(stream),
+ asWritableStream: (stream) => new WritableStreamWrapper(stream)
+ }),
+ console,
+ timer: Object.freeze({
+ setTimeout(callback, ms, ...args) {
+ return setTimeout(callback, ms, ...args);
+ },
+ clearTimeout(handle) {
+ clearTimeout(handle);
+ },
+ setImmediate(callback, ...args) {
+ return setImmediate(callback, ...args);
+ },
+ clearImmediate(handle) {
+ clearImmediate(handle);
+ }
+ })
+ });
+ function RIL() {
+ return _ril;
+ }
+ (function(RIL2) {
+ function install() {
+ ral_1.default.install(_ril);
}
- isStyleCheckDiagnostic(code) {
- return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false;
- }
-}
-exports.default = TypeScriptServiceClientHost;
-
+ RIL2.install = install;
+ })(RIL || (RIL = {}));
+ exports2.default = RIL;
+});
-/***/ }),
-/* 34 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/vscode-jsonrpc/lib/common/is.js
+var require_is = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.stringArray = exports2.array = exports2.func = exports2.error = exports2.number = exports2.string = exports2.boolean = void 0;
+ function boolean2(value) {
+ return value === true || value === false;
+ }
+ exports2.boolean = boolean2;
+ function string2(value) {
+ return typeof value === "string" || value instanceof String;
+ }
+ exports2.string = string2;
+ function number(value) {
+ return typeof value === "number" || value instanceof Number;
+ }
+ exports2.number = number;
+ function error(value) {
+ return value instanceof Error;
+ }
+ exports2.error = error;
+ function func(value) {
+ return typeof value === "function";
+ }
+ exports2.func = func;
+ function array(value) {
+ return Array.isArray(value);
+ }
+ exports2.array = array;
+ function stringArray(value) {
+ return array(value) && value.every((elem) => string2(elem));
+ }
+ exports2.stringArray = stringArray;
+});
-"use strict";
+// node_modules/vscode-jsonrpc/lib/common/messages.js
+var require_messages = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.isResponseMessage = exports2.isNotificationMessage = exports2.isRequestMessage = exports2.NotificationType9 = exports2.NotificationType8 = exports2.NotificationType7 = exports2.NotificationType6 = exports2.NotificationType5 = exports2.NotificationType4 = exports2.NotificationType3 = exports2.NotificationType2 = exports2.NotificationType1 = exports2.NotificationType0 = exports2.NotificationType = exports2.RequestType9 = exports2.RequestType8 = exports2.RequestType7 = exports2.RequestType6 = exports2.RequestType5 = exports2.RequestType4 = exports2.RequestType3 = exports2.RequestType2 = exports2.RequestType1 = exports2.RequestType = exports2.RequestType0 = exports2.AbstractMessageSignature = exports2.ParameterStructures = exports2.ResponseError = exports2.ErrorCodes = void 0;
+ var is2 = require_is();
+ var ErrorCodes;
+ (function(ErrorCodes2) {
+ ErrorCodes2.ParseError = -32700;
+ ErrorCodes2.InvalidRequest = -32600;
+ ErrorCodes2.MethodNotFound = -32601;
+ ErrorCodes2.InvalidParams = -32602;
+ ErrorCodes2.InternalError = -32603;
+ ErrorCodes2.jsonrpcReservedErrorRangeStart = -32099;
+ ErrorCodes2.serverErrorStart = ErrorCodes2.jsonrpcReservedErrorRangeStart;
+ ErrorCodes2.MessageWriteError = -32099;
+ ErrorCodes2.MessageReadError = -32098;
+ ErrorCodes2.ServerNotInitialized = -32002;
+ ErrorCodes2.UnknownErrorCode = -32001;
+ ErrorCodes2.jsonrpcReservedErrorRangeEnd = -32e3;
+ ErrorCodes2.serverErrorEnd = ErrorCodes2.jsonrpcReservedErrorRangeEnd;
+ })(ErrorCodes = exports2.ErrorCodes || (exports2.ErrorCodes = {}));
+ var ResponseError = class extends Error {
+ constructor(code, message, data) {
+ super(message);
+ this.code = is2.number(code) ? code : ErrorCodes.UnknownErrorCode;
+ this.data = data;
+ Object.setPrototypeOf(this, ResponseError.prototype);
+ }
+ toJson() {
+ return {
+ code: this.code,
+ message: this.message,
+ data: this.data
+ };
+ }
+ };
+ exports2.ResponseError = ResponseError;
+ var ParameterStructures = class {
+ constructor(kind) {
+ this.kind = kind;
+ }
+ static is(value) {
+ return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition;
+ }
+ toString() {
+ return this.kind;
+ }
+ };
+ exports2.ParameterStructures = ParameterStructures;
+ ParameterStructures.auto = new ParameterStructures("auto");
+ ParameterStructures.byPosition = new ParameterStructures("byPosition");
+ ParameterStructures.byName = new ParameterStructures("byName");
+ var AbstractMessageSignature = class {
+ constructor(method, numberOfParams) {
+ this.method = method;
+ this.numberOfParams = numberOfParams;
+ }
+ get parameterStructures() {
+ return ParameterStructures.auto;
+ }
+ };
+ exports2.AbstractMessageSignature = AbstractMessageSignature;
+ var RequestType0 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 0);
+ }
+ };
+ exports2.RequestType0 = RequestType0;
+ var RequestType = class extends AbstractMessageSignature {
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
+ super(method, 1);
+ this._parameterStructures = _parameterStructures;
+ }
+ get parameterStructures() {
+ return this._parameterStructures;
+ }
+ };
+ exports2.RequestType = RequestType;
+ var RequestType1 = class extends AbstractMessageSignature {
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
+ super(method, 1);
+ this._parameterStructures = _parameterStructures;
+ }
+ get parameterStructures() {
+ return this._parameterStructures;
+ }
+ };
+ exports2.RequestType1 = RequestType1;
+ var RequestType2 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 2);
+ }
+ };
+ exports2.RequestType2 = RequestType2;
+ var RequestType3 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 3);
+ }
+ };
+ exports2.RequestType3 = RequestType3;
+ var RequestType4 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 4);
+ }
+ };
+ exports2.RequestType4 = RequestType4;
+ var RequestType5 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 5);
+ }
+ };
+ exports2.RequestType5 = RequestType5;
+ var RequestType6 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 6);
+ }
+ };
+ exports2.RequestType6 = RequestType6;
+ var RequestType7 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 7);
+ }
+ };
+ exports2.RequestType7 = RequestType7;
+ var RequestType8 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 8);
+ }
+ };
+ exports2.RequestType8 = RequestType8;
+ var RequestType9 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 9);
+ }
+ };
+ exports2.RequestType9 = RequestType9;
+ var NotificationType = class extends AbstractMessageSignature {
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
+ super(method, 1);
+ this._parameterStructures = _parameterStructures;
+ }
+ get parameterStructures() {
+ return this._parameterStructures;
+ }
+ };
+ exports2.NotificationType = NotificationType;
+ var NotificationType0 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 0);
+ }
+ };
+ exports2.NotificationType0 = NotificationType0;
+ var NotificationType1 = class extends AbstractMessageSignature {
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
+ super(method, 1);
+ this._parameterStructures = _parameterStructures;
+ }
+ get parameterStructures() {
+ return this._parameterStructures;
+ }
+ };
+ exports2.NotificationType1 = NotificationType1;
+ var NotificationType2 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 2);
+ }
+ };
+ exports2.NotificationType2 = NotificationType2;
+ var NotificationType3 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 3);
+ }
+ };
+ exports2.NotificationType3 = NotificationType3;
+ var NotificationType4 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 4);
+ }
+ };
+ exports2.NotificationType4 = NotificationType4;
+ var NotificationType5 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 5);
+ }
+ };
+ exports2.NotificationType5 = NotificationType5;
+ var NotificationType6 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 6);
+ }
+ };
+ exports2.NotificationType6 = NotificationType6;
+ var NotificationType7 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 7);
+ }
+ };
+ exports2.NotificationType7 = NotificationType7;
+ var NotificationType8 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 8);
+ }
+ };
+ exports2.NotificationType8 = NotificationType8;
+ var NotificationType9 = class extends AbstractMessageSignature {
+ constructor(method) {
+ super(method, 9);
+ }
+ };
+ exports2.NotificationType9 = NotificationType9;
+ function isRequestMessage(message) {
+ const candidate = message;
+ return candidate && is2.string(candidate.method) && (is2.string(candidate.id) || is2.number(candidate.id));
+ }
+ exports2.isRequestMessage = isRequestMessage;
+ function isNotificationMessage(message) {
+ const candidate = message;
+ return candidate && is2.string(candidate.method) && message.id === void 0;
+ }
+ exports2.isNotificationMessage = isNotificationMessage;
+ function isResponseMessage(message) {
+ const candidate = message;
+ return candidate && (candidate.result !== void 0 || !!candidate.error) && (is2.string(candidate.id) || is2.number(candidate.id) || candidate.id === null);
+ }
+ exports2.isResponseMessage = isResponseMessage;
+});
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const coc_nvim_1 = __webpack_require__(1);
-const baseCodeLensProvider_1 = __webpack_require__(35);
-const completionItemProvider_1 = __importDefault(__webpack_require__(38));
-const definitionProvider_1 = __importDefault(__webpack_require__(88));
-const directiveCommentCompletions_1 = __importDefault(__webpack_require__(89));
-const documentHighlight_1 = __importDefault(__webpack_require__(90));
-const documentSymbol_1 = __importDefault(__webpack_require__(92));
-const fileConfigurationManager_1 = __importDefault(__webpack_require__(93));
-const folding_1 = __importDefault(__webpack_require__(94));
-const formatting_1 = __importDefault(__webpack_require__(95));
-const hover_1 = __importDefault(__webpack_require__(96));
-const implementationsCodeLens_1 = __importDefault(__webpack_require__(97));
-// import TagCompletionProvider from './features/tagCompletion'
-const quickfix_1 = __importDefault(__webpack_require__(98));
-const importFix_1 = __importDefault(__webpack_require__(99));
-const refactor_1 = __importDefault(__webpack_require__(101));
-const references_1 = __importDefault(__webpack_require__(102));
-const referencesCodeLens_1 = __importDefault(__webpack_require__(103));
-const rename_1 = __importDefault(__webpack_require__(104));
-const signatureHelp_1 = __importDefault(__webpack_require__(105));
-const updatePathOnRename_1 = __importDefault(__webpack_require__(106));
-const watchBuild_1 = __importDefault(__webpack_require__(108));
-const workspaceSymbols_1 = __importDefault(__webpack_require__(109));
-const smartSelect_1 = __importDefault(__webpack_require__(110));
-const moduleInstall_1 = __importDefault(__webpack_require__(111));
-const api_1 = __importDefault(__webpack_require__(40));
-const organizeImports_1 = __webpack_require__(114);
-const suggestionSetting = 'suggestionActions.enabled';
-class LanguageProvider {
- constructor(client, description, typingsStatus) {
- this.client = client;
- this.description = description;
- this.disposables = [];
- this.fileConfigurationManager = new fileConfigurationManager_1.default(client);
- coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
- this.configurationChanged();
- let initialized = false;
- client.onTsServerStarted(() => __awaiter(this, void 0, void 0, function* () {
- if (!initialized) {
- initialized = true;
- this.registerProviders(client, typingsStatus);
- }
- else {
- this.client.diagnosticsManager.reInitialize();
- }
- }));
- }
- configurationChanged() {
- const config = coc_nvim_1.workspace.getConfiguration(this.id, null);
- this.client.diagnosticsManager.setEnableSuggestions(this.id, config.get(suggestionSetting, true));
+// node_modules/vscode-jsonrpc/lib/common/events.js
+var require_events = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.Emitter = exports2.Event = void 0;
+ var ral_1 = require_ral();
+ var Event5;
+ (function(Event6) {
+ const _disposable = {dispose() {
+ }};
+ Event6.None = function() {
+ return _disposable;
+ };
+ })(Event5 = exports2.Event || (exports2.Event = {}));
+ var CallbackList = class {
+ add(callback, context = null, bucket) {
+ if (!this._callbacks) {
+ this._callbacks = [];
+ this._contexts = [];
+ }
+ this._callbacks.push(callback);
+ this._contexts.push(context);
+ if (Array.isArray(bucket)) {
+ bucket.push({dispose: () => this.remove(callback, context)});
+ }
}
- dispose() {
- coc_nvim_1.disposeAll(this.disposables);
- }
- registerProviders(client, typingsStatus) {
- let languageIds = this.description.modeIds;
- this.disposables.push(coc_nvim_1.languages.registerCompletionItemProvider(`tsserver-${this.description.id}`, 'TSC', languageIds, new completionItemProvider_1.default(client, typingsStatus, this.fileConfigurationManager, this.description.id), completionItemProvider_1.default.triggerCharacters));
- if (this.client.apiVersion.gte(api_1.default.v230)) {
- this.disposables.push(coc_nvim_1.languages.registerCompletionItemProvider(`${this.description.id}-directive`, 'TSC', languageIds, new directiveCommentCompletions_1.default(client), ['@']));
- }
- let definitionProvider = new definitionProvider_1.default(client);
- this.disposables.push(coc_nvim_1.languages.registerDefinitionProvider(languageIds, definitionProvider));
- this.disposables.push(coc_nvim_1.languages.registerTypeDefinitionProvider(languageIds, definitionProvider));
- this.disposables.push(coc_nvim_1.languages.registerImplementationProvider(languageIds, definitionProvider));
- this.disposables.push(coc_nvim_1.languages.registerReferencesProvider(languageIds, new references_1.default(client)));
- this.disposables.push(coc_nvim_1.languages.registerHoverProvider(languageIds, new hover_1.default(client)));
- this.disposables.push(coc_nvim_1.languages.registerDocumentHighlightProvider(languageIds, new documentHighlight_1.default(this.client)));
- this.disposables.push(coc_nvim_1.languages.registerSignatureHelpProvider(languageIds, new signatureHelp_1.default(client), ['(', ',', '<', ')']));
- this.disposables.push(coc_nvim_1.languages.registerDocumentSymbolProvider(languageIds, new documentSymbol_1.default(client)));
- this.disposables.push(coc_nvim_1.languages.registerWorkspaceSymbolProvider(languageIds, new workspaceSymbols_1.default(client, languageIds)));
- this.disposables.push(coc_nvim_1.languages.registerRenameProvider(languageIds, new rename_1.default(client)));
- let formatProvider = new formatting_1.default(client, this.fileConfigurationManager);
- this.disposables.push(coc_nvim_1.languages.registerDocumentFormatProvider(languageIds, formatProvider));
- this.disposables.push(coc_nvim_1.languages.registerDocumentRangeFormatProvider(languageIds, formatProvider));
- this.disposables.push(coc_nvim_1.languages.registerOnTypeFormattingEditProvider(languageIds, formatProvider, [';', '}', '\n', String.fromCharCode(27)]));
- // this.disposables.push(
- // new ProjectError(client, commandManager)
- // )
- if (this.client.apiVersion.gte(api_1.default.v280)) {
- this.disposables.push(coc_nvim_1.languages.registerFoldingRangeProvider(languageIds, new folding_1.default(this.client)));
- this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new organizeImports_1.OrganizeImportsCodeActionProvider(this.client, this.fileConfigurationManager), `tsserver-${this.description.id}`, [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]));
- }
- let { fileConfigurationManager } = this;
- let conf = fileConfigurationManager.getLanguageConfiguration(this.id);
- if (this.client.apiVersion.gte(api_1.default.v290)
- && conf.get('updateImportsOnFileMove.enable')) {
- this.disposables.push(new updatePathOnRename_1.default(client, this.fileConfigurationManager, this.id));
- }
- if (this.client.apiVersion.gte(api_1.default.v240)) {
- this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new refactor_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.Refactor]));
- }
- this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new moduleInstall_1.default(client), 'tsserver'));
- this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new quickfix_1.default(client), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
- this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new importFix_1.default(this.client.bufferSyncSupport), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
- let cachedResponse = new baseCodeLensProvider_1.CachedNavTreeResponse();
- if (this.client.apiVersion.gte(api_1.default.v206)
- && conf.get('referencesCodeLens.enable')) {
- this.disposables.push(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new referencesCodeLens_1.default(client, cachedResponse)));
- }
- if (this.client.apiVersion.gte(api_1.default.v220)
- && conf.get('implementationsCodeLens.enable')) {
- this.disposables.push(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new implementationsCodeLens_1.default(client, cachedResponse)));
- }
- if (this.client.apiVersion.gte(api_1.default.v350)) {
- this.disposables.push(coc_nvim_1.languages.registerSelectionRangeProvider(languageIds, new smartSelect_1.default(this.client)));
- }
- if (this.description.id == 'typescript') {
- // this.client.apiVersion
- this.disposables.push(new watchBuild_1.default(coc_nvim_1.commands, this.client));
- }
- // if (this.client.apiVersion.gte(API.v300)) {
- // this.disposables.push(
- // languages.registerCompletionItemProvider(
- // `tsserver-${this.description.id}-tag`,
- // 'TSC',
- // languageIds,
- // new TagCompletionProvider(client),
- // ['>']
- // )
- // )
- // }
- }
- handles(resource) {
- let { modeIds, configFile } = this.description;
- if (resource.toString().endsWith(configFile)) {
- return true;
- }
- let doc = coc_nvim_1.workspace.getDocument(resource.toString());
- if (doc && modeIds.indexOf(doc.filetype) !== -1) {
- return true;
- }
- let str = resource.toString();
- if (this.id === 'typescript' && /\.ts(x)?$/.test(str)) {
- return true;
+ remove(callback, context = null) {
+ if (!this._callbacks) {
+ return;
+ }
+ let foundCallbackWithDifferentContext = false;
+ for (let i = 0, len = this._callbacks.length; i < len; i++) {
+ if (this._callbacks[i] === callback) {
+ if (this._contexts[i] === context) {
+ this._callbacks.splice(i, 1);
+ this._contexts.splice(i, 1);
+ return;
+ } else {
+ foundCallbackWithDifferentContext = true;
+ }
}
- if (this.id === 'javascript' && /\.js(x)?$/.test(str)) {
- return true;
+ }
+ if (foundCallbackWithDifferentContext) {
+ throw new Error("When adding a listener with a context, you should remove it with the same context");
+ }
+ }
+ invoke(...args) {
+ if (!this._callbacks) {
+ return [];
+ }
+ const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
+ for (let i = 0, len = callbacks.length; i < len; i++) {
+ try {
+ ret.push(callbacks[i].apply(contexts[i], args));
+ } catch (e) {
+ ral_1.default().console.error(e);
}
- return false;
+ }
+ return ret;
}
- get id() {
- return this.description.id;
+ isEmpty() {
+ return !this._callbacks || this._callbacks.length === 0;
}
- get diagnosticSource() {
- return this.description.diagnosticSource;
+ dispose() {
+ this._callbacks = void 0;
+ this._contexts = void 0;
+ }
+ };
+ var Emitter6 = class {
+ constructor(_options) {
+ this._options = _options;
+ }
+ get event() {
+ if (!this._event) {
+ this._event = (listener, thisArgs, disposables) => {
+ if (!this._callbacks) {
+ this._callbacks = new CallbackList();
+ }
+ if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
+ this._options.onFirstListenerAdd(this);
+ }
+ this._callbacks.add(listener, thisArgs);
+ const result = {
+ dispose: () => {
+ if (!this._callbacks) {
+ return;
+ }
+ this._callbacks.remove(listener, thisArgs);
+ result.dispose = Emitter6._noop;
+ if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
+ this._options.onLastListenerRemove(this);
+ }
+ }
+ };
+ if (Array.isArray(disposables)) {
+ disposables.push(result);
+ }
+ return result;
+ };
+ }
+ return this._event;
}
- triggerAllDiagnostics() {
- this.client.bufferSyncSupport.requestAllDiagnostics();
+ fire(event) {
+ if (this._callbacks) {
+ this._callbacks.invoke.call(this._callbacks, event);
+ }
}
- diagnosticsReceived(diagnosticsKind, file, diagnostics) {
- if (!this.client.bufferSyncSupport.shouldValidate(file.toString())) {
- return;
- }
- const config = coc_nvim_1.workspace.getConfiguration(this.id, file.toString());
- const reportUnnecessary = config.get('showUnused', true);
- this.client.diagnosticsManager.diagnosticsReceived(diagnosticsKind, file.toString(), diagnostics.filter(diag => {
- if (!reportUnnecessary) {
- diag.tags = undefined;
- if (diag.reportUnnecessary && diag.severity === vscode_languageserver_protocol_1.DiagnosticSeverity.Information) {
- return false;
- }
- }
- return true;
- }));
+ dispose() {
+ if (this._callbacks) {
+ this._callbacks.dispose();
+ this._callbacks = void 0;
+ }
}
-}
-exports.default = LanguageProvider;
-
-
-/***/ }),
-/* 35 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
+ };
+ exports2.Emitter = Emitter6;
+ Emitter6._noop = function() {
+ };
});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
+
+// node_modules/vscode-jsonrpc/lib/common/cancellation.js
+var require_cancellation = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.CancellationTokenSource = exports2.CancellationToken = void 0;
+ var ral_1 = require_ral();
+ var Is = require_is();
+ var events_1 = require_events();
+ var CancellationToken20;
+ (function(CancellationToken21) {
+ CancellationToken21.None = Object.freeze({
+ isCancellationRequested: false,
+ onCancellationRequested: events_1.Event.None
});
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.TypeScriptBaseCodeLensProvider = exports.CachedNavTreeResponse = void 0;
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const regexp_1 = __webpack_require__(36);
-const typeConverters = __importStar(__webpack_require__(37));
-class CachedNavTreeResponse {
+ CancellationToken21.Cancelled = Object.freeze({
+ isCancellationRequested: true,
+ onCancellationRequested: events_1.Event.None
+ });
+ function is2(value) {
+ const candidate = value;
+ return candidate && (candidate === CancellationToken21.None || candidate === CancellationToken21.Cancelled || Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
+ }
+ CancellationToken21.is = is2;
+ })(CancellationToken20 = exports2.CancellationToken || (exports2.CancellationToken = {}));
+ var shortcutEvent = Object.freeze(function(callback, context) {
+ const handle = ral_1.default().timer.setTimeout(callback.bind(context), 0);
+ return {dispose() {
+ ral_1.default().timer.clearTimeout(handle);
+ }};
+ });
+ var MutableToken = class {
constructor() {
- this.version = -1;
- this.document = '';
+ this._isCancelled = false;
}
- execute(document, f) {
- if (this.matches(document)) {
- return this.response;
+ cancel() {
+ if (!this._isCancelled) {
+ this._isCancelled = true;
+ if (this._emitter) {
+ this._emitter.fire(void 0);
+ this.dispose();
}
- return this.update(document, f());
+ }
}
- matches(document) {
- return (this.version === document.version &&
- this.document === document.uri.toString());
+ get isCancellationRequested() {
+ return this._isCancelled;
}
- update(document, response) {
- this.response = response;
- this.version = document.version;
- this.document = document.uri.toString();
- return response;
+ get onCancellationRequested() {
+ if (this._isCancelled) {
+ return shortcutEvent;
+ }
+ if (!this._emitter) {
+ this._emitter = new events_1.Emitter();
+ }
+ return this._emitter.event;
}
-}
-exports.CachedNavTreeResponse = CachedNavTreeResponse;
-class TypeScriptBaseCodeLensProvider {
- constructor(client, cachedResponse) {
- this.client = client;
- this.cachedResponse = cachedResponse;
- this.onDidChangeCodeLensesEmitter = new vscode_languageserver_protocol_1.Emitter();
- }
- get onDidChangeCodeLenses() {
- return this.onDidChangeCodeLensesEmitter.event;
- }
- provideCodeLenses(document, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(document.uri);
- if (!filepath) {
- return [];
- }
- try {
- const response = yield this.cachedResponse.execute(document, () => this.client.execute('navtree', { file: filepath }, token));
- if (!response) {
- return [];
- }
- const tree = response.body;
- const referenceableSpans = [];
- if (tree && tree.childItems) {
- tree.childItems.forEach(item => this.walkNavTree(document, item, null, referenceableSpans));
- }
- return referenceableSpans.map(range => {
- return {
- range,
- data: { uri: document.uri }
- };
- });
- }
- catch (_a) {
- return [];
- }
- });
+ dispose() {
+ if (this._emitter) {
+ this._emitter.dispose();
+ this._emitter = void 0;
+ }
}
- walkNavTree(document, item, parent, results) {
- if (!item) {
- return;
+ };
+ var CancellationTokenSource4 = class {
+ get token() {
+ if (!this._token) {
+ this._token = new MutableToken();
+ }
+ return this._token;
+ }
+ cancel() {
+ if (!this._token) {
+ this._token = CancellationToken20.Cancelled;
+ } else {
+ this._token.cancel();
+ }
+ }
+ dispose() {
+ if (!this._token) {
+ this._token = CancellationToken20.None;
+ } else if (this._token instanceof MutableToken) {
+ this._token.dispose();
+ }
+ }
+ };
+ exports2.CancellationTokenSource = CancellationTokenSource4;
+});
+
+// node_modules/vscode-jsonrpc/lib/common/messageReader.js
+var require_messageReader = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.ReadableStreamMessageReader = exports2.AbstractMessageReader = exports2.MessageReader = void 0;
+ var ral_1 = require_ral();
+ var Is = require_is();
+ var events_1 = require_events();
+ var MessageReader;
+ (function(MessageReader2) {
+ function is2(value) {
+ let candidate = value;
+ return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) && Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
+ }
+ MessageReader2.is = is2;
+ })(MessageReader = exports2.MessageReader || (exports2.MessageReader = {}));
+ var AbstractMessageReader = class {
+ constructor() {
+ this.errorEmitter = new events_1.Emitter();
+ this.closeEmitter = new events_1.Emitter();
+ this.partialMessageEmitter = new events_1.Emitter();
+ }
+ dispose() {
+ this.errorEmitter.dispose();
+ this.closeEmitter.dispose();
+ }
+ get onError() {
+ return this.errorEmitter.event;
+ }
+ fireError(error) {
+ this.errorEmitter.fire(this.asError(error));
+ }
+ get onClose() {
+ return this.closeEmitter.event;
+ }
+ fireClose() {
+ this.closeEmitter.fire(void 0);
+ }
+ get onPartialMessage() {
+ return this.partialMessageEmitter.event;
+ }
+ firePartialMessage(info) {
+ this.partialMessageEmitter.fire(info);
+ }
+ asError(error) {
+ if (error instanceof Error) {
+ return error;
+ } else {
+ return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
+ }
+ }
+ };
+ exports2.AbstractMessageReader = AbstractMessageReader;
+ var ResolvedMessageReaderOptions;
+ (function(ResolvedMessageReaderOptions2) {
+ function fromOptions(options) {
+ var _a;
+ let charset;
+ let result;
+ let contentDecoder;
+ const contentDecoders = new Map();
+ let contentTypeDecoder;
+ const contentTypeDecoders = new Map();
+ if (options === void 0 || typeof options === "string") {
+ charset = options !== null && options !== void 0 ? options : "utf-8";
+ } else {
+ charset = (_a = options.charset) !== null && _a !== void 0 ? _a : "utf-8";
+ if (options.contentDecoder !== void 0) {
+ contentDecoder = options.contentDecoder;
+ contentDecoders.set(contentDecoder.name, contentDecoder);
+ }
+ if (options.contentDecoders !== void 0) {
+ for (const decoder of options.contentDecoders) {
+ contentDecoders.set(decoder.name, decoder);
+ }
}
- const range = this.extractSymbol(document, item, parent);
- if (range) {
- results.push(range);
+ if (options.contentTypeDecoder !== void 0) {
+ contentTypeDecoder = options.contentTypeDecoder;
+ contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
}
- if (item.childItems) {
- item.childItems.forEach(child => this.walkNavTree(document, child, item, results));
+ if (options.contentTypeDecoders !== void 0) {
+ for (const decoder of options.contentTypeDecoders) {
+ contentTypeDecoders.set(decoder.name, decoder);
+ }
}
- }
- getSymbolRange(document, item) {
- if (!item) {
- return null;
+ }
+ if (contentTypeDecoder === void 0) {
+ contentTypeDecoder = ral_1.default().applicationJson.decoder;
+ contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
+ }
+ return {charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders};
+ }
+ ResolvedMessageReaderOptions2.fromOptions = fromOptions;
+ })(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
+ var ReadableStreamMessageReader = class extends AbstractMessageReader {
+ constructor(readable, options) {
+ super();
+ this.readable = readable;
+ this.options = ResolvedMessageReaderOptions.fromOptions(options);
+ this.buffer = ral_1.default().messageBuffer.create(this.options.charset);
+ this._partialMessageTimeout = 1e4;
+ this.nextMessageLength = -1;
+ this.messageToken = 0;
+ }
+ set partialMessageTimeout(timeout) {
+ this._partialMessageTimeout = timeout;
+ }
+ get partialMessageTimeout() {
+ return this._partialMessageTimeout;
+ }
+ listen(callback) {
+ this.nextMessageLength = -1;
+ this.messageToken = 0;
+ this.partialMessageTimer = void 0;
+ this.callback = callback;
+ const result = this.readable.onData((data) => {
+ this.onData(data);
+ });
+ this.readable.onError((error) => this.fireError(error));
+ this.readable.onClose(() => this.fireClose());
+ return result;
+ }
+ onData(data) {
+ this.buffer.append(data);
+ while (true) {
+ if (this.nextMessageLength === -1) {
+ const headers = this.buffer.tryReadHeaders();
+ if (!headers) {
+ return;
+ }
+ const contentLength = headers.get("Content-Length");
+ if (!contentLength) {
+ throw new Error("Header must provide a Content-Length property.");
+ }
+ const length = parseInt(contentLength);
+ if (isNaN(length)) {
+ throw new Error("Content-Length value must be a number.");
+ }
+ this.nextMessageLength = length;
}
- // TS 3.0+ provides a span for just the symbol
- if (item.nameSpan) {
- return typeConverters.Range.fromTextSpan(item.nameSpan);
+ const body = this.buffer.tryReadBody(this.nextMessageLength);
+ if (body === void 0) {
+ this.setPartialMessageTimer();
+ return;
}
- // In older versions, we have to calculate this manually. See #23924
- const span = item.spans && item.spans[0];
- if (!span) {
- return null;
+ this.clearPartialMessageTimer();
+ this.nextMessageLength = -1;
+ let p;
+ if (this.options.contentDecoder !== void 0) {
+ p = this.options.contentDecoder.decode(body);
+ } else {
+ p = Promise.resolve(body);
+ }
+ p.then((value) => {
+ this.options.contentTypeDecoder.decode(value, this.options).then((msg) => {
+ this.callback(msg);
+ }, (error) => {
+ this.fireError(error);
+ });
+ }, (error) => {
+ this.fireError(error);
+ });
+ }
+ }
+ clearPartialMessageTimer() {
+ if (this.partialMessageTimer) {
+ ral_1.default().timer.clearTimeout(this.partialMessageTimer);
+ this.partialMessageTimer = void 0;
+ }
+ }
+ setPartialMessageTimer() {
+ this.clearPartialMessageTimer();
+ if (this._partialMessageTimeout <= 0) {
+ return;
+ }
+ this.partialMessageTimer = ral_1.default().timer.setTimeout((token, timeout) => {
+ this.partialMessageTimer = void 0;
+ if (token === this.messageToken) {
+ this.firePartialMessage({messageToken: token, waitingTime: timeout});
+ this.setPartialMessageTimer();
}
- const range = typeConverters.Range.fromTextSpan(span);
- const text = document.getText(range);
- const identifierMatch = new RegExp(`^(.*?(\\b|\\W))${regexp_1.escapeRegExp(item.text || '')}(\\b|\\W)`, 'gm');
- const match = identifierMatch.exec(text);
- const prefixLength = match ? match.index + match[1].length : 0;
- const startOffset = document.offsetAt(range.start) + prefixLength;
- return {
- start: document.positionAt(startOffset),
- end: document.positionAt(startOffset + item.text.length)
- };
+ }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
}
-}
-exports.TypeScriptBaseCodeLensProvider = TypeScriptBaseCodeLensProvider;
-
-
-/***/ }),
-/* 36 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"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.escapeRegExp = void 0;
-function escapeRegExp(text) {
- return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
-}
-exports.escapeRegExp = escapeRegExp;
-
-
-/***/ }),
-/* 37 */
-/***/ (function(module, exports, __webpack_require__) {
+ };
+ exports2.ReadableStreamMessageReader = ReadableStreamMessageReader;
+});
-"use strict";
+// node_modules/vscode-jsonrpc/lib/common/semaphore.js
+var require_semaphore = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.Semaphore = void 0;
+ var ral_1 = require_ral();
+ var Semaphore = class {
+ constructor(capacity = 1) {
+ if (capacity <= 0) {
+ throw new Error("Capacity must be greater than 0");
+ }
+ this._capacity = capacity;
+ this._active = 0;
+ this._waiting = [];
+ }
+ lock(thunk) {
+ return new Promise((resolve, reject) => {
+ this._waiting.push({thunk, resolve, reject});
+ this.runNext();
+ });
+ }
+ get active() {
+ return this._active;
+ }
+ runNext() {
+ if (this._waiting.length === 0 || this._active === this._capacity) {
+ return;
+ }
+ ral_1.default().timer.setImmediate(() => this.doRunNext());
+ }
+ doRunNext() {
+ if (this._waiting.length === 0 || this._active === this._capacity) {
+ return;
+ }
+ const next = this._waiting.shift();
+ this._active++;
+ if (this._active > this._capacity) {
+ throw new Error(`To many thunks active`);
+ }
+ try {
+ const result = next.thunk();
+ if (result instanceof Promise) {
+ result.then((value) => {
+ this._active--;
+ next.resolve(value);
+ this.runNext();
+ }, (err) => {
+ this._active--;
+ next.reject(err);
+ this.runNext();
+ });
+ } else {
+ this._active--;
+ next.resolve(result);
+ this.runNext();
+ }
+ } catch (err) {
+ this._active--;
+ next.reject(err);
+ this.runNext();
+ }
+ }
+ };
+ exports2.Semaphore = Semaphore;
+});
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.WorkspaceEdit = exports.TextEdit = exports.Location = exports.Position = exports.Range = void 0;
-var Range;
-(function (Range) {
- Range.fromTextSpan = (span) => {
- return {
- start: {
- line: span.start.line - 1,
- character: span.start.offset - 1
- },
- end: {
- line: span.end.line - 1,
- character: span.end.offset - 1
- }
- };
- };
- Range.toFormattingRequestArgs = (file, range) => ({
- file,
- line: range.start.line + 1,
- offset: range.start.character + 1,
- endLine: range.end.line + 1,
- endOffset: range.end.character + 1
- });
- Range.toFileRangeRequestArgs = (file, range) => ({
- file,
- startLine: range.start.line + 1,
- startOffset: range.start.character + 1,
- endLine: range.end.line + 1,
- endOffset: range.end.character + 1
- });
-})(Range = exports.Range || (exports.Range = {}));
-var Position;
-(function (Position) {
- Position.fromLocation = (tslocation) => {
- return {
- line: tslocation.line - 1,
- character: tslocation.offset - 1
- };
- };
- Position.toLocation = (position) => ({
- line: position.line + 1,
- offset: position.character + 1,
- });
- Position.toFileLocationRequestArgs = (file, position) => ({
- file,
- line: position.line + 1,
- offset: position.character + 1
- });
-})(Position = exports.Position || (exports.Position = {}));
-var Location;
-(function (Location) {
- Location.fromTextSpan = (uri, tsTextSpan) => {
- return {
- uri,
- range: Range.fromTextSpan(tsTextSpan)
- };
- };
-})(Location = exports.Location || (exports.Location = {}));
-var TextEdit;
-(function (TextEdit) {
- TextEdit.fromCodeEdit = (edit) => {
- return {
- range: Range.fromTextSpan(edit),
- newText: edit.newText
- };
- };
-})(TextEdit = exports.TextEdit || (exports.TextEdit = {}));
-var WorkspaceEdit;
-(function (WorkspaceEdit) {
- function fromFileCodeEdits(client, edits) {
- let changes = {};
- for (const edit of edits) {
- let uri = client.toResource(edit.fileName);
- changes[uri] = edit.textChanges.map(change => {
- return TextEdit.fromCodeEdit(change);
- });
- }
- return { changes };
- }
- WorkspaceEdit.fromFileCodeEdits = fromFileCodeEdits;
-})(WorkspaceEdit = exports.WorkspaceEdit || (exports.WorkspaceEdit = {}));
-
-
-/***/ }),
-/* 38 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const coc_nvim_1 = __webpack_require__(1);
-const PConst = __importStar(__webpack_require__(39));
-const api_1 = __importDefault(__webpack_require__(40));
-const codeAction_1 = __webpack_require__(84);
-const completionItem_1 = __webpack_require__(85);
-const Previewer = __importStar(__webpack_require__(86));
-const typeConverters = __importStar(__webpack_require__(37));
-const SnippetString_1 = __importDefault(__webpack_require__(87));
-class ApplyCompletionCodeActionCommand {
- constructor(client) {
- this.client = client;
- this.id = ApplyCompletionCodeActionCommand.ID;
- }
- // apply code action on complete
- execute(codeActions) {
- return __awaiter(this, void 0, void 0, function* () {
- if (codeActions.length === 0) {
- return;
- }
- if (codeActions.length === 1) {
- yield codeAction_1.applyCodeAction(this.client, codeActions[0]);
- return;
- }
- const idx = yield coc_nvim_1.workspace.showQuickpick(codeActions.map(o => o.description), 'Select code action to apply');
- if (idx < 0)
- return;
- const action = codeActions[idx];
- yield codeAction_1.applyCodeAction(this.client, action);
- return;
- });
- }
-}
-ApplyCompletionCodeActionCommand.ID = '_typescript.applyCompletionCodeAction';
-class TypeScriptCompletionItemProvider {
- constructor(client, typingsStatus, fileConfigurationManager, languageId) {
- this.client = client;
- this.typingsStatus = typingsStatus;
- this.fileConfigurationManager = fileConfigurationManager;
- this.setCompleteOption(languageId);
- coc_nvim_1.commands.register(new ApplyCompletionCodeActionCommand(this.client));
- coc_nvim_1.workspace.onDidChangeConfiguration(_e => {
- this.setCompleteOption(languageId);
- });
- }
- setCompleteOption(languageId) {
- this.completeOption = this.fileConfigurationManager.getCompleteOptions(languageId);
- }
- /**
- * Get completionItems
- *
- * @public
- * @param {TextDocument} document
- * @param {Position} position
- * @param {CancellationToken} token
- * @param {string} triggerCharacter
- * @returns {Promise<CompletionItem[]>}
- */
- provideCompletionItems(document, position, token, context) {
- return __awaiter(this, void 0, void 0, function* () {
- if (this.typingsStatus.isAcquiringTypings) {
- return Promise.resolve({
- isIncomplete: true,
- items: [{
- label: 'Acquiring typings...',
- detail: 'Acquiring typings definitions for IntelliSense.'
- }]
- });
- }
- let { uri } = document;
- const file = this.client.toPath(document.uri);
- if (!file)
- return null;
- let preText = document.getText({
- start: { line: position.line, character: 0 },
- end: position
- });
- let { triggerCharacter, option } = context;
- if (!this.shouldTrigger(triggerCharacter, preText, option)) {
- return null;
- }
- const { completeOption } = this;
- const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { includeExternalModuleExports: completeOption.autoImports, includeInsertTextCompletions: true, triggerCharacter: this.getTsTriggerCharacter(context), includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions });
- let entries;
- let dotAccessorContext;
- let isNewIdentifierLocation = true;
- let isMemberCompletion = false;
- let isIncomplete = false;
- const isInValidCommitCharacterContext = this.isInValidCommitCharacterContext(document, position);
- if (this.client.apiVersion.gte(api_1.default.v300)) {
- try {
- const response = yield this.client.interruptGetErr(() => this.client.execute('completionInfo', args, token));
- if (response.type !== 'response' || !response.body) {
- return null;
- }
- isNewIdentifierLocation = response.body.isNewIdentifierLocation;
- isMemberCompletion = response.body.isMemberCompletion;
- if (isMemberCompletion) {
- const dotMatch = preText.slice(0, position.character).match(/\??\.\s*$/) || undefined;
- if (dotMatch) {
- const range = vscode_languageserver_protocol_1.Range.create({
- line: position.line,
- character: position.character - dotMatch.length
- }, position);
- const text = document.getText(range);
- dotAccessorContext = { range, text };
- }
- }
- isIncomplete = response.metadata && response.metadata.isIncomplete;
- entries = response.body.entries;
- }
- catch (e) {
- if (e.message == 'No content available.') {
- return null;
- }
- throw e;
- }
- }
- else {
- const response = yield this.client.interruptGetErr(() => this.client.execute('completions', args, token));
- if (response.type !== 'response' || !response.body) {
- return null;
- }
- entries = response.body;
- }
- const completionItems = [];
- for (const element of entries) {
- if (shouldExcludeCompletionEntry(element, completeOption)) {
- continue;
- }
- const item = completionItem_1.convertCompletionEntry(element, uri, position, {
- isNewIdentifierLocation,
- isMemberCompletion,
- enableCallCompletions: completeOption.completeFunctionCalls,
- isInValidCommitCharacterContext,
- dotAccessorContext,
- });
- completionItems.push(item);
- }
- return { isIncomplete, items: completionItems };
- });
- }
- getTsTriggerCharacter(context) {
- // return context.triggerCharacter as Proto.CompletionsTriggerCharacter
- switch (context.triggerCharacter) {
- case '@': // Workaround for https://github.com/Microsoft/TypeScript/issues/27321
- return this.client.apiVersion.gte(api_1.default.v310) && this.client.apiVersion.lt(api_1.default.v320) ? undefined : '@';
- case '#': // Workaround for https://github.com/microsoft/TypeScript/issues/36367
- return this.client.apiVersion.lt(api_1.default.v381) ? undefined : '#';
- case '.':
- case '"':
- case '\'':
- case '`':
- case '/':
- case '<':
- return context.triggerCharacter;
- }
- return undefined;
- }
- /**
- * Resolve complete item, could have documentation added
- *
- * @public
- * @param {CompletionItem} item
- * @param {CancellationToken} token
- * @returns {Promise<CompletionItem>}
- */
- resolveCompletionItem(item, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (item == null)
- return undefined;
- let { uri, position, source } = item.data;
- const filepath = this.client.toPath(uri);
- if (!filepath)
- return undefined;
- let document = coc_nvim_1.workspace.getDocument(uri);
- if (!document)
- return undefined;
- const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(filepath, position)), { entryNames: [
- source
- ? { name: item.label, source }
- : item.label
- ] });
- let response;
- try {
- response = yield this.client.interruptGetErr(() => this.client.execute('completionEntryDetails', args, token));
- }
- catch (_a) {
- return item;
- }
- if (response.type !== 'response' || !response.body) {
- return item;
- }
- const details = response.body;
- if (!details || !details.length || !details[0]) {
- return item;
- }
- const detail = details[0];
- if (!item.detail && detail.displayParts.length) {
- item.detail = Previewer.plain(detail.displayParts);
- }
- item.documentation = this.getDocumentation(detail);
- const { command, additionalTextEdits } = this.getCodeActions(detail, filepath);
- if (command)
- item.command = command;
- item.additionalTextEdits = additionalTextEdits;
- if (detail && item.insertTextFormat == vscode_languageserver_protocol_1.InsertTextFormat.Snippet) {
- const shouldCompleteFunction = yield this.isValidFunctionCompletionContext(filepath, position, token);
- if (shouldCompleteFunction) {
- this.createSnippetOfFunctionCall(item, detail);
- }
- }
- return item;
- });
- }
- getCodeActions(detail, filepath) {
- if (!detail.codeActions || !detail.codeActions.length) {
- return {};
- }
- // Try to extract out the additionalTextEdits for the current file.
- // Also check if we still have to apply other workspace edits
- const additionalTextEdits = [];
- let hasRemainingCommandsOrEdits = false;
- for (const tsAction of detail.codeActions) {
- if (tsAction.commands) {
- hasRemainingCommandsOrEdits = true;
- }
- // Convert all edits in the current file using `additionalTextEdits`
- if (tsAction.changes) {
- for (const change of tsAction.changes) {
- if (change.fileName === filepath) {
- additionalTextEdits.push(...change.textChanges.map(typeConverters.TextEdit.fromCodeEdit));
- }
- else {
- hasRemainingCommandsOrEdits = true;
- }
- }
- }
- }
- let command = null;
- if (hasRemainingCommandsOrEdits) {
- // Create command that applies all edits not in the current file.
- command = {
- title: '',
- command: ApplyCompletionCodeActionCommand.ID,
- arguments: [
- detail.codeActions.map((x) => ({
- commands: x.commands,
- description: x.description,
- changes: x.changes.filter(x => x.fileName !== filepath)
- }))
- ]
- };
- }
- return {
- command,
- additionalTextEdits: additionalTextEdits.length
- ? additionalTextEdits
- : undefined
- };
+// node_modules/vscode-jsonrpc/lib/common/messageWriter.js
+var require_messageWriter = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.WriteableStreamMessageWriter = exports2.AbstractMessageWriter = exports2.MessageWriter = void 0;
+ var ral_1 = require_ral();
+ var Is = require_is();
+ var semaphore_1 = require_semaphore();
+ var events_1 = require_events();
+ var ContentLength2 = "Content-Length: ";
+ var CRLF = "\r\n";
+ var MessageWriter;
+ (function(MessageWriter2) {
+ function is2(value) {
+ let candidate = value;
+ return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) && Is.func(candidate.onError) && Is.func(candidate.write);
+ }
+ MessageWriter2.is = is2;
+ })(MessageWriter = exports2.MessageWriter || (exports2.MessageWriter = {}));
+ var AbstractMessageWriter = class {
+ constructor() {
+ this.errorEmitter = new events_1.Emitter();
+ this.closeEmitter = new events_1.Emitter();
}
- shouldTrigger(triggerCharacter, pre, option) {
- if (triggerCharacter && this.client.apiVersion.lt(api_1.default.v290)) {
- if (triggerCharacter === '@') {
- // trigger in string
- if (option.synname && /string/i.test(option.synname)) {
- return true;
- }
- // make sure we are in something that looks like the start of a jsdoc comment
- if (!pre.match(/^\s*\*[ ]?@/) && !pre.match(/\/\*\*+[ ]?@/)) {
- return false;
- }
- }
- else if (triggerCharacter === '<') {
- return false;
- }
- }
- return true;
+ dispose() {
+ this.errorEmitter.dispose();
+ this.closeEmitter.dispose();
}
- // complete item documentation
- getDocumentation(detail) {
- let documentation = '';
- if (detail.source) {
- const importPath = `'${Previewer.plain(detail.source)}'`;
- const autoImportLabel = `Auto import from ${importPath}`;
- documentation += `${autoImportLabel}\n`;
- }
- let parts = [
- Previewer.plain(detail.documentation),
- Previewer.tagsMarkdownPreview(detail.tags)
- ];
- parts = parts.filter(s => s && s.trim() != '');
- documentation += parts.join('\n\n');
- if (documentation.length) {
- return {
- kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
- value: documentation
- };
- }
- return undefined;
- }
- createSnippetOfFunctionCall(item, detail) {
- let { displayParts } = detail;
- const parameterListParts = completionItem_1.getParameterListParts(displayParts);
- const snippet = new SnippetString_1.default();
- snippet.appendText(`${item.insertText || item.label}(`);
- appendJoinedPlaceholders(snippet, parameterListParts.parts, ', ');
- if (parameterListParts.hasOptionalParameters) {
- snippet.appendTabstop();
- }
- snippet.appendText(')');
- snippet.appendTabstop(0);
- item.insertText = snippet.value;
- }
- isValidFunctionCompletionContext(filepath, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- // Workaround for https://github.com/Microsoft/TypeScript/issues/12677
- // Don't complete function calls inside of destructive assigments or imports
- try {
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
- const response = yield this.client.execute('quickinfo', args, token);
- if (response.type !== 'response') {
- return true;
- }
- const { body } = response;
- switch (body && body.kind) {
- case 'var':
- case 'let':
- case 'const':
- case 'alias':
- return false;
- default:
- return true;
- }
- }
- catch (e) {
- return true;
- }
- });
+ get onError() {
+ return this.errorEmitter.event;
}
- isInValidCommitCharacterContext(document, position) {
- if (this.client.apiVersion.lt(api_1.default.v320)) {
- // Workaround for https://github.com/Microsoft/TypeScript/issues/27742
- // Only enable dot completions when previous character not a dot preceded by whitespace.
- // Prevents incorrectly completing while typing spread operators.
- if (position.character > 1) {
- const preText = document.getText(vscode_languageserver_protocol_1.Range.create(position.line, 0, position.line, position.character));
- return preText.match(/(\s|^)\.$/ig) === null;
- }
- }
- return true;
+ fireError(error, message, count) {
+ this.errorEmitter.fire([this.asError(error), message, count]);
}
-}
-exports.default = TypeScriptCompletionItemProvider;
-TypeScriptCompletionItemProvider.triggerCharacters = ['.', '"', '\'', '`', '/', '@', '<', '#'];
-function shouldExcludeCompletionEntry(element, completionConfiguration) {
- return ((!completionConfiguration.names && element.kind === PConst.Kind.warning)
- || (!completionConfiguration.paths &&
- (element.kind === PConst.Kind.directory || element.kind === PConst.Kind.script || element.kind === PConst.Kind.externalModuleName))
- || (!completionConfiguration.autoImports && element.hasAction));
-}
-function appendJoinedPlaceholders(snippet, parts, joiner) {
- for (let i = 0; i < parts.length; ++i) {
- const paramterPart = parts[i];
- snippet.appendPlaceholder(paramterPart.text);
- if (i !== parts.length - 1) {
- snippet.appendText(joiner);
- }
+ get onClose() {
+ return this.closeEmitter.event;
}
-}
-
-
-/***/ }),
-/* 39 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"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.DisplayPartKind = exports.KindModifiers = exports.DiagnosticCategory = exports.Kind = void 0;
-class Kind {
-}
-exports.Kind = Kind;
-Kind.alias = 'alias';
-Kind.callSignature = 'call';
-Kind.class = 'class';
-Kind.const = 'const';
-Kind.constructorImplementation = 'constructor';
-Kind.constructSignature = 'construct';
-Kind.directory = 'directory';
-Kind.enum = 'enum';
-Kind.enumMember = 'enum member';
-Kind.externalModuleName = 'external module name';
-Kind.function = 'function';
-Kind.indexSignature = 'index';
-Kind.interface = 'interface';
-Kind.keyword = 'keyword';
-Kind.let = 'let';
-Kind.localFunction = 'local function';
-Kind.localVariable = 'local var';
-Kind.method = 'method';
-Kind.memberGetAccessor = 'getter';
-Kind.memberSetAccessor = 'setter';
-Kind.memberVariable = 'property';
-Kind.module = 'module';
-Kind.primitiveType = 'primitive type';
-Kind.script = 'script';
-Kind.type = 'type';
-Kind.variable = 'var';
-Kind.warning = 'warning';
-Kind.string = 'string';
-Kind.parameter = 'parameter';
-Kind.typeParameter = 'type parameter';
-class DiagnosticCategory {
-}
-exports.DiagnosticCategory = DiagnosticCategory;
-DiagnosticCategory.error = 'error';
-DiagnosticCategory.warning = 'warning';
-DiagnosticCategory.suggestion = 'suggestion';
-class KindModifiers {
-}
-exports.KindModifiers = KindModifiers;
-KindModifiers.optional = 'optional';
-KindModifiers.color = 'color';
-KindModifiers.dtsFile = '.d.ts';
-KindModifiers.tsFile = '.ts';
-KindModifiers.tsxFile = '.tsx';
-KindModifiers.jsFile = '.js';
-KindModifiers.jsxFile = '.jsx';
-KindModifiers.jsonFile = '.json';
-KindModifiers.fileExtensionKindModifiers = [
- KindModifiers.dtsFile,
- KindModifiers.tsFile,
- KindModifiers.tsxFile,
- KindModifiers.jsFile,
- KindModifiers.jsxFile,
- KindModifiers.jsonFile,
-];
-class DisplayPartKind {
-}
-exports.DisplayPartKind = DisplayPartKind;
-DisplayPartKind.functionName = 'functionName';
-DisplayPartKind.methodName = 'methodName';
-DisplayPartKind.parameterName = 'parameterName';
-DisplayPartKind.propertyName = 'propertyName';
-DisplayPartKind.punctuation = 'punctuation';
-DisplayPartKind.text = 'text';
-
-
-/***/ }),
-/* 40 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const semver = __importStar(__webpack_require__(41));
-class API {
- constructor(versionString, version) {
- this.versionString = versionString;
- this.version = version;
- }
- static fromSimpleString(value) {
- return new API(value, value);
- }
- static fromVersionString(versionString) {
- let version = semver.valid(versionString);
- if (!version) {
- return new API('invalid version', '1.0.0');
- }
- // Cut off any prerelease tag since we sometimes consume those on purpose.
- const index = versionString.indexOf('-');
- if (index >= 0) {
- version = version.substr(0, index);
- }
- return new API(versionString, version);
- }
- gte(other) {
- return semver.gte(this.version, other.version);
- }
- lt(other) {
- return !this.gte(other);
+ fireClose() {
+ this.closeEmitter.fire(void 0);
}
-}
-exports.default = API;
-API.defaultVersion = API.fromSimpleString('1.0.0');
-API.v203 = API.fromSimpleString('2.0.3');
-API.v206 = API.fromSimpleString('2.0.6');
-API.v208 = API.fromSimpleString('2.0.8');
-API.v213 = API.fromSimpleString('2.1.3');
-API.v220 = API.fromSimpleString('2.2.0');
-API.v222 = API.fromSimpleString('2.2.2');
-API.v230 = API.fromSimpleString('2.3.0');
-API.v234 = API.fromSimpleString('2.3.4');
-API.v240 = API.fromSimpleString('2.4.0');
-API.v250 = API.fromSimpleString('2.5.0');
-API.v260 = API.fromSimpleString('2.6.0');
-API.v270 = API.fromSimpleString('2.7.0');
-API.v280 = API.fromSimpleString('2.8.0');
-API.v290 = API.fromSimpleString('2.9.0');
-API.v291 = API.fromSimpleString('2.9.1');
-API.v292 = API.fromSimpleString('2.9.2');
-API.v300 = API.fromSimpleString('3.0.0');
-API.v310 = API.fromSimpleString('3.1.0');
-API.v314 = API.fromSimpleString('3.1.4');
-API.v320 = API.fromSimpleString('3.2.0');
-API.v330 = API.fromSimpleString('3.3.0');
-API.v333 = API.fromSimpleString('3.3.3');
-API.v340 = API.fromSimpleString('3.4.0');
-API.v345 = API.fromSimpleString('3.4.5');
-API.v350 = API.fromSimpleString('3.5.0');
-API.v380 = API.fromSimpleString('3.8.0');
-API.v381 = API.fromSimpleString('3.8.1');
-API.v390 = API.fromSimpleString('3.9.0');
-
-
-/***/ }),
-/* 41 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// just pre-load all the stuff that index.js lazily exports
-const internalRe = __webpack_require__(42)
-module.exports = {
- re: internalRe.re,
- src: internalRe.src,
- tokens: internalRe.t,
- SEMVER_SPEC_VERSION: __webpack_require__(43).SEMVER_SPEC_VERSION,
- SemVer: __webpack_require__(45),
- compareIdentifiers: __webpack_require__(46).compareIdentifiers,
- rcompareIdentifiers: __webpack_require__(46).rcompareIdentifiers,
- parse: __webpack_require__(47),
- valid: __webpack_require__(48),
- clean: __webpack_require__(49),
- inc: __webpack_require__(50),
- diff: __webpack_require__(51),
- major: __webpack_require__(54),
- minor: __webpack_require__(55),
- patch: __webpack_require__(56),
- prerelease: __webpack_require__(57),
- compare: __webpack_require__(53),
- rcompare: __webpack_require__(58),
- compareLoose: __webpack_require__(59),
- compareBuild: __webpack_require__(60),
- sort: __webpack_require__(61),
- rsort: __webpack_require__(62),
- gt: __webpack_require__(63),
- lt: __webpack_require__(64),
- eq: __webpack_require__(52),
- neq: __webpack_require__(65),
- gte: __webpack_require__(66),
- lte: __webpack_require__(67),
- cmp: __webpack_require__(68),
- coerce: __webpack_require__(69),
- Comparator: __webpack_require__(70),
- Range: __webpack_require__(71),
- satisfies: __webpack_require__(72),
- toComparators: __webpack_require__(73),
- maxSatisfying: __webpack_require__(74),
- minSatisfying: __webpack_require__(75),
- minVersion: __webpack_require__(76),
- validRange: __webpack_require__(77),
- outside: __webpack_require__(78),
- gtr: __webpack_require__(79),
- ltr: __webpack_require__(80),
- intersects: __webpack_require__(81),
- simplifyRange: __webpack_require__(82),
- subset: __webpack_require__(83),
-}
-
-
-/***/ }),
-/* 42 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(43)
-const debug = __webpack_require__(44)
-exports = module.exports = {}
-
-// The actual regexps go on exports.re
-const re = exports.re = []
-const src = exports.src = []
-const t = exports.t = {}
-let R = 0
-
-const createToken = (name, value, isGlobal) => {
- const index = R++
- debug(index, value)
- t[name] = index
- src[index] = value
- re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
-}
-
-// The following Regular Expressions can be used for tokenizing,
-// validating, and parsing SemVer version strings.
-
-// ## Numeric Identifier
-// A single `0`, or a non-zero digit followed by zero or more digits.
-
-createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
-createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+')
-
-// ## Non-numeric Identifier
-// Zero or more digits, followed by a letter or hyphen, and then zero or
-// more letters, digits, or hyphens.
-
-createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*')
-
-// ## Main Version
-// Three dot-separated numeric identifiers.
-
-createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
- `(${src[t.NUMERICIDENTIFIER]})\\.` +
- `(${src[t.NUMERICIDENTIFIER]})`)
-
-createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
- `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
- `(${src[t.NUMERICIDENTIFIERLOOSE]})`)
-
-// ## Pre-release Version Identifier
-// A numeric identifier, or a non-numeric identifier.
-
-createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
-}|${src[t.NONNUMERICIDENTIFIER]})`)
-
-createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
-}|${src[t.NONNUMERICIDENTIFIER]})`)
-
-// ## Pre-release Version
-// Hyphen, followed by one or more dot-separated pre-release version
-// identifiers.
-
-createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
-}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
-
-createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
-}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
-
-// ## Build Metadata Identifier
-// Any combination of digits, letters, or hyphens.
-
-createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')
-
-// ## Build Metadata
-// Plus sign, followed by one or more period-separated build metadata
-// identifiers.
-
-createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
-}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
-
-// ## Full Version String
-// A main version, followed optionally by a pre-release version and
-// build metadata.
-
-// Note that the only major, minor, patch, and pre-release sections of
-// the version string are capturing groups. The build metadata is not a
-// capturing group, because it should not ever be used in version
-// comparison.
-
-createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
-}${src[t.PRERELEASE]}?${
- src[t.BUILD]}?`)
-
-createToken('FULL', `^${src[t.FULLPLAIN]}$`)
-
-// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
-// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
-// common in the npm registry.
-createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
-}${src[t.PRERELEASELOOSE]}?${
- src[t.BUILD]}?`)
-
-createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
-
-createToken('GTLT', '((?:<|>)?=?)')
-
-// Something like "2.*" or "1.2.x".
-// Note that "x.x" is a valid xRange identifer, meaning "any version"
-// Only the first item is strictly required.
-createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
-createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
-
-createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
- `(?:${src[t.PRERELEASE]})?${
- src[t.BUILD]}?` +
- `)?)?`)
-
-createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
- `(?:${src[t.PRERELEASELOOSE]})?${
- src[t.BUILD]}?` +
- `)?)?`)
-
-createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
-createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
-
-// Coercion.
-// Extract anything that could conceivably be a part of a valid semver
-createToken('COERCE', `${'(^|[^\\d])' +
- '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
- `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
- `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
- `(?:$|[^\\d])`)
-createToken('COERCERTL', src[t.COERCE], true)
-
-// Tilde ranges.
-// Meaning is "reasonably at or greater than"
-createToken('LONETILDE', '(?:~>?)')
-
-createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
-exports.tildeTrimReplace = '$1~'
-
-createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
-createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
-
-// Caret ranges.
-// Meaning is "at least and backwards compatible with"
-createToken('LONECARET', '(?:\\^)')
-
-createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
-exports.caretTrimReplace = '$1^'
-
-createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
-createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
-
-// A simple gt/lt/eq thing, or just "" to indicate "any version"
-createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
-createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
-
-// An expression to strip any whitespace between the gtlt and the thing
-// it modifies, so that `> 1.2.3` ==> `>1.2.3`
-createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
-}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
-exports.comparatorTrimReplace = '$1$2$3'
-
-// Something like `1.2.3 - 1.2.4`
-// Note that these all use the loose form, because they'll be
-// checked against either the strict or loose comparator form
-// later.
-createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
- `\\s+-\\s+` +
- `(${src[t.XRANGEPLAIN]})` +
- `\\s*$`)
-
-createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
- `\\s+-\\s+` +
- `(${src[t.XRANGEPLAINLOOSE]})` +
- `\\s*$`)
-
-// Star ranges basically just allow anything at all.
-createToken('STAR', '(<|>)?=?\\s*\\*')
-// >=0.0.0 is like a star
-createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$')
-createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$')
-
-
-/***/ }),
-/* 43 */
-/***/ (function(module, exports) {
-
-// Note: this is the semver.org version of the spec that it implements
-// Not necessarily the package version of this code.
-const SEMVER_SPEC_VERSION = '2.0.0'
-
-const MAX_LENGTH = 256
-const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
- /* istanbul ignore next */ 9007199254740991
-
-// Max safe segment length for coercion.
-const MAX_SAFE_COMPONENT_LENGTH = 16
-
-module.exports = {
- SEMVER_SPEC_VERSION,
- MAX_LENGTH,
- MAX_SAFE_INTEGER,
- MAX_SAFE_COMPONENT_LENGTH
-}
-
-
-/***/ }),
-/* 44 */
-/***/ (function(module, exports) {
-
-const debug = (
- typeof process === 'object' &&
- process.env &&
- process.env.NODE_DEBUG &&
- /\bsemver\b/i.test(process.env.NODE_DEBUG)
-) ? (...args) => console.error('SEMVER', ...args)
- : () => {}
-
-module.exports = debug
-
-
-/***/ }),
-/* 45 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const debug = __webpack_require__(44)
-const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(43)
-const { re, t } = __webpack_require__(42)
-
-const { compareIdentifiers } = __webpack_require__(46)
-class SemVer {
- constructor (version, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
+ asError(error) {
+ if (error instanceof Error) {
+ return error;
+ } else {
+ return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
}
}
- if (version instanceof SemVer) {
- if (version.loose === !!options.loose &&
- version.includePrerelease === !!options.includePrerelease) {
- return version
+ };
+ exports2.AbstractMessageWriter = AbstractMessageWriter;
+ var ResolvedMessageWriterOptions;
+ (function(ResolvedMessageWriterOptions2) {
+ function fromOptions(options) {
+ var _a, _b;
+ if (options === void 0 || typeof options === "string") {
+ return {charset: options !== null && options !== void 0 ? options : "utf-8", contentTypeEncoder: ral_1.default().applicationJson.encoder};
} else {
- version = version.version
+ return {charset: (_a = options.charset) !== null && _a !== void 0 ? _a : "utf-8", contentEncoder: options.contentEncoder, contentTypeEncoder: (_b = options.contentTypeEncoder) !== null && _b !== void 0 ? _b : ral_1.default().applicationJson.encoder};
}
- } else if (typeof version !== 'string') {
- throw new TypeError(`Invalid Version: ${version}`)
}
-
- if (version.length > MAX_LENGTH) {
- throw new TypeError(
- `version is longer than ${MAX_LENGTH} characters`
- )
+ ResolvedMessageWriterOptions2.fromOptions = fromOptions;
+ })(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
+ var WriteableStreamMessageWriter = class extends AbstractMessageWriter {
+ constructor(writable, options) {
+ super();
+ this.writable = writable;
+ this.options = ResolvedMessageWriterOptions.fromOptions(options);
+ this.errorCount = 0;
+ this.writeSemaphore = new semaphore_1.Semaphore(1);
+ this.writable.onError((error) => this.fireError(error));
+ this.writable.onClose(() => this.fireClose());
+ }
+ async write(msg) {
+ return this.writeSemaphore.lock(async () => {
+ const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
+ if (this.options.contentEncoder !== void 0) {
+ return this.options.contentEncoder.encode(buffer);
+ } else {
+ return buffer;
+ }
+ });
+ return payload.then((buffer) => {
+ const headers = [];
+ headers.push(ContentLength2, buffer.byteLength.toString(), CRLF);
+ headers.push(CRLF);
+ return this.doWrite(msg, headers, buffer);
+ }, (error) => {
+ this.fireError(error);
+ throw error;
+ });
+ });
}
-
- debug('SemVer', version, options)
- this.options = options
- this.loose = !!options.loose
- // this isn't actually relevant for versions, but keep it so that we
- // don't run into trouble passing this.options around.
- this.includePrerelease = !!options.includePrerelease
-
- const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
-
- if (!m) {
- throw new TypeError(`Invalid Version: ${version}`)
+ async doWrite(msg, headers, data) {
+ try {
+ await this.writable.write(headers.join(""), "ascii");
+ return this.writable.write(data);
+ } catch (error) {
+ this.handleError(error, msg);
+ return Promise.reject(error);
+ }
}
-
- this.raw = version
-
- // these are actually numbers
- this.major = +m[1]
- this.minor = +m[2]
- this.patch = +m[3]
-
- if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
- throw new TypeError('Invalid major version')
+ handleError(error, msg) {
+ this.errorCount++;
+ this.fireError(error, msg, this.errorCount);
}
-
- if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
- throw new TypeError('Invalid minor version')
+ end() {
+ this.writable.end();
}
+ };
+ exports2.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
+});
- if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
- throw new TypeError('Invalid patch version')
+// node_modules/vscode-jsonrpc/lib/common/linkedMap.js
+var require_linkedMap = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.LRUCache = exports2.LinkedMap = exports2.Touch = void 0;
+ var Touch;
+ (function(Touch2) {
+ Touch2.None = 0;
+ Touch2.First = 1;
+ Touch2.AsOld = Touch2.First;
+ Touch2.Last = 2;
+ Touch2.AsNew = Touch2.Last;
+ })(Touch = exports2.Touch || (exports2.Touch = {}));
+ var LinkedMap = class {
+ constructor() {
+ this[Symbol.toStringTag] = "LinkedMap";
+ this._map = new Map();
+ this._head = void 0;
+ this._tail = void 0;
+ this._size = 0;
+ this._state = 0;
}
-
- // numberify any prerelease numeric ids
- if (!m[4]) {
- this.prerelease = []
- } else {
- this.prerelease = m[4].split('.').map((id) => {
- if (/^[0-9]+$/.test(id)) {
- const num = +id
- if (num >= 0 && num < MAX_SAFE_INTEGER) {
- return num
- }
- }
- return id
- })
+ clear() {
+ this._map.clear();
+ this._head = void 0;
+ this._tail = void 0;
+ this._size = 0;
+ this._state++;
}
-
- this.build = m[5] ? m[5].split('.') : []
- this.format()
- }
-
- format () {
- this.version = `${this.major}.${this.minor}.${this.patch}`
- if (this.prerelease.length) {
- this.version += `-${this.prerelease.join('.')}`
+ isEmpty() {
+ return !this._head && !this._tail;
}
- return this.version
- }
-
- toString () {
- return this.version
- }
-
- compare (other) {
- debug('SemVer.compare', this.version, this.options, other)
- if (!(other instanceof SemVer)) {
- if (typeof other === 'string' && other === this.version) {
- return 0
- }
- other = new SemVer(other, this.options)
+ get size() {
+ return this._size;
}
-
- if (other.version === this.version) {
- return 0
+ get first() {
+ var _a;
+ return (_a = this._head) === null || _a === void 0 ? void 0 : _a.value;
}
-
- return this.compareMain(other) || this.comparePre(other)
- }
-
- compareMain (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
+ get last() {
+ var _a;
+ return (_a = this._tail) === null || _a === void 0 ? void 0 : _a.value;
}
-
- return (
- compareIdentifiers(this.major, other.major) ||
- compareIdentifiers(this.minor, other.minor) ||
- compareIdentifiers(this.patch, other.patch)
- )
- }
-
- comparePre (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
+ has(key) {
+ return this._map.has(key);
}
-
- // NOT having a prerelease is > having one
- if (this.prerelease.length && !other.prerelease.length) {
- return -1
- } else if (!this.prerelease.length && other.prerelease.length) {
- return 1
- } else if (!this.prerelease.length && !other.prerelease.length) {
- return 0
+ get(key, touch = Touch.None) {
+ const item = this._map.get(key);
+ if (!item) {
+ return void 0;
+ }
+ if (touch !== Touch.None) {
+ this.touch(item, touch);
+ }
+ return item.value;
}
-
- let i = 0
- do {
- const a = this.prerelease[i]
- const b = other.prerelease[i]
- debug('prerelease compare', i, a, b)
- if (a === undefined && b === undefined) {
- return 0
- } else if (b === undefined) {
- return 1
- } else if (a === undefined) {
- return -1
- } else if (a === b) {
- continue
+ set(key, value, touch = Touch.None) {
+ let item = this._map.get(key);
+ if (item) {
+ item.value = value;
+ if (touch !== Touch.None) {
+ this.touch(item, touch);
+ }
} else {
- return compareIdentifiers(a, b)
+ item = {key, value, next: void 0, previous: void 0};
+ switch (touch) {
+ case Touch.None:
+ this.addItemLast(item);
+ break;
+ case Touch.First:
+ this.addItemFirst(item);
+ break;
+ case Touch.Last:
+ this.addItemLast(item);
+ break;
+ default:
+ this.addItemLast(item);
+ break;
+ }
+ this._map.set(key, item);
+ this._size++;
}
- } while (++i)
- }
-
- compareBuild (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
+ return this;
}
-
- let i = 0
- do {
- const a = this.build[i]
- const b = other.build[i]
- debug('prerelease compare', i, a, b)
- if (a === undefined && b === undefined) {
- return 0
- } else if (b === undefined) {
- return 1
- } else if (a === undefined) {
- return -1
- } else if (a === b) {
- continue
- } else {
- return compareIdentifiers(a, b)
- }
- } while (++i)
- }
-
- // preminor will bump the version up to the next minor release, and immediately
- // down to pre-release. premajor and prepatch work the same way.
- inc (release, identifier) {
- switch (release) {
- case 'premajor':
- this.prerelease.length = 0
- this.patch = 0
- this.minor = 0
- this.major++
- this.inc('pre', identifier)
- break
- case 'preminor':
- this.prerelease.length = 0
- this.patch = 0
- this.minor++
- this.inc('pre', identifier)
- break
- case 'prepatch':
- // If this is already a prerelease, it will bump to the next version
- // drop any prereleases that might already exist, since they are not
- // relevant at this point.
- this.prerelease.length = 0
- this.inc('patch', identifier)
- this.inc('pre', identifier)
- break
- // If the input is a non-prerelease version, this acts the same as
- // prepatch.
- case 'prerelease':
- if (this.prerelease.length === 0) {
- this.inc('patch', identifier)
- }
- this.inc('pre', identifier)
- break
-
- case 'major':
- // If this is a pre-major version, bump up to the same major version.
- // Otherwise increment major.
- // 1.0.0-5 bumps to 1.0.0
- // 1.1.0 bumps to 2.0.0
- if (
- this.minor !== 0 ||
- this.patch !== 0 ||
- this.prerelease.length === 0
- ) {
- this.major++
- }
- this.minor = 0
- this.patch = 0
- this.prerelease = []
- break
- case 'minor':
- // If this is a pre-minor version, bump up to the same minor version.
- // Otherwise increment minor.
- // 1.2.0-5 bumps to 1.2.0
- // 1.2.1 bumps to 1.3.0
- if (this.patch !== 0 || this.prerelease.length === 0) {
- this.minor++
- }
- this.patch = 0
- this.prerelease = []
- break
- case 'patch':
- // If this is not a pre-release version, it will increment the patch.
- // If it is a pre-release it will bump up to the same patch version.
- // 1.2.0-5 patches to 1.2.0
- // 1.2.0 patches to 1.2.1
- if (this.prerelease.length === 0) {
- this.patch++
- }
- this.prerelease = []
- break
- // This probably shouldn't be used publicly.
- // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
- case 'pre':
- if (this.prerelease.length === 0) {
- this.prerelease = [0]
+ delete(key) {
+ return !!this.remove(key);
+ }
+ remove(key) {
+ const item = this._map.get(key);
+ if (!item) {
+ return void 0;
+ }
+ this._map.delete(key);
+ this.removeItem(item);
+ this._size--;
+ return item.value;
+ }
+ shift() {
+ if (!this._head && !this._tail) {
+ return void 0;
+ }
+ if (!this._head || !this._tail) {
+ throw new Error("Invalid list");
+ }
+ const item = this._head;
+ this._map.delete(item.key);
+ this.removeItem(item);
+ this._size--;
+ return item.value;
+ }
+ forEach(callbackfn, thisArg) {
+ const state = this._state;
+ let current = this._head;
+ while (current) {
+ if (thisArg) {
+ callbackfn.bind(thisArg)(current.value, current.key, this);
} else {
- let i = this.prerelease.length
- while (--i >= 0) {
- if (typeof this.prerelease[i] === 'number') {
- this.prerelease[i]++
- i = -2
- }
+ callbackfn(current.value, current.key, this);
+ }
+ if (this._state !== state) {
+ throw new Error(`LinkedMap got modified during iteration.`);
+ }
+ current = current.next;
+ }
+ }
+ keys() {
+ const map = this;
+ const state = this._state;
+ let current = this._head;
+ const iterator = {
+ [Symbol.iterator]() {
+ return iterator;
+ },
+ next() {
+ if (map._state !== state) {
+ throw new Error(`LinkedMap got modified during iteration.`);
}
- if (i === -1) {
- // didn't increment anything
- this.prerelease.push(0)
+ if (current) {
+ const result = {value: current.key, done: false};
+ current = current.next;
+ return result;
+ } else {
+ return {value: void 0, done: true};
}
}
- if (identifier) {
- // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
- // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
- if (this.prerelease[0] === identifier) {
- if (isNaN(this.prerelease[1])) {
- this.prerelease = [identifier, 0]
- }
+ };
+ return iterator;
+ }
+ values() {
+ const map = this;
+ const state = this._state;
+ let current = this._head;
+ const iterator = {
+ [Symbol.iterator]() {
+ return iterator;
+ },
+ next() {
+ if (map._state !== state) {
+ throw new Error(`LinkedMap got modified during iteration.`);
+ }
+ if (current) {
+ const result = {value: current.value, done: false};
+ current = current.next;
+ return result;
} else {
- this.prerelease = [identifier, 0]
+ return {value: void 0, done: true};
}
}
- break
-
- default:
- throw new Error(`invalid increment argument: ${release}`)
+ };
+ return iterator;
+ }
+ entries() {
+ const map = this;
+ const state = this._state;
+ let current = this._head;
+ const iterator = {
+ [Symbol.iterator]() {
+ return iterator;
+ },
+ next() {
+ if (map._state !== state) {
+ throw new Error(`LinkedMap got modified during iteration.`);
+ }
+ if (current) {
+ const result = {value: [current.key, current.value], done: false};
+ current = current.next;
+ return result;
+ } else {
+ return {value: void 0, done: true};
+ }
+ }
+ };
+ return iterator;
}
- this.format()
- this.raw = this.version
- return this
- }
-}
-
-module.exports = SemVer
-
-
-/***/ }),
-/* 46 */
-/***/ (function(module, exports) {
-
-const numeric = /^[0-9]+$/
-const compareIdentifiers = (a, b) => {
- const anum = numeric.test(a)
- const bnum = numeric.test(b)
-
- if (anum && bnum) {
- a = +a
- b = +b
- }
-
- return a === b ? 0
- : (anum && !bnum) ? -1
- : (bnum && !anum) ? 1
- : a < b ? -1
- : 1
-}
-
-const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
-
-module.exports = {
- compareIdentifiers,
- rcompareIdentifiers
-}
-
-
-/***/ }),
-/* 47 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const {MAX_LENGTH} = __webpack_require__(43)
-const { re, t } = __webpack_require__(42)
-const SemVer = __webpack_require__(45)
-
-const parse = (version, options) => {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
+ [Symbol.iterator]() {
+ return this.entries();
}
- }
-
- if (version instanceof SemVer) {
- return version
- }
-
- if (typeof version !== 'string') {
- return null
- }
-
- if (version.length > MAX_LENGTH) {
- return null
- }
-
- const r = options.loose ? re[t.LOOSE] : re[t.FULL]
- if (!r.test(version)) {
- return null
- }
-
- try {
- return new SemVer(version, options)
- } catch (er) {
- return null
- }
-}
-
-module.exports = parse
-
-
-/***/ }),
-/* 48 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const parse = __webpack_require__(47)
-const valid = (version, options) => {
- const v = parse(version, options)
- return v ? v.version : null
-}
-module.exports = valid
-
-
-/***/ }),
-/* 49 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const parse = __webpack_require__(47)
-const clean = (version, options) => {
- const s = parse(version.trim().replace(/^[=v]+/, ''), options)
- return s ? s.version : null
-}
-module.exports = clean
-
-
-/***/ }),
-/* 50 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const SemVer = __webpack_require__(45)
-
-const inc = (version, release, options, identifier) => {
- if (typeof (options) === 'string') {
- identifier = options
- options = undefined
- }
-
- try {
- return new SemVer(version, options).inc(release, identifier).version
- } catch (er) {
- return null
- }
-}
-module.exports = inc
-
-
-/***/ }),
-/* 51 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const parse = __webpack_require__(47)
-const eq = __webpack_require__(52)
-
-const diff = (version1, version2) => {
- if (eq(version1, version2)) {
- return null
- } else {
- const v1 = parse(version1)
- const v2 = parse(version2)
- const hasPre = v1.prerelease.length || v2.prerelease.length
- const prefix = hasPre ? 'pre' : ''
- const defaultResult = hasPre ? 'prerelease' : ''
- for (const key in v1) {
- if (key === 'major' || key === 'minor' || key === 'patch') {
- if (v1[key] !== v2[key]) {
- return prefix + key
+ trimOld(newSize) {
+ if (newSize >= this.size) {
+ return;
+ }
+ if (newSize === 0) {
+ this.clear();
+ return;
+ }
+ let current = this._head;
+ let currentSize = this.size;
+ while (current && currentSize > newSize) {
+ this._map.delete(current.key);
+ current = current.next;
+ currentSize--;
+ }
+ this._head = current;
+ this._size = currentSize;
+ if (current) {
+ current.previous = void 0;
+ }
+ this._state++;
+ }
+ addItemFirst(item) {
+ if (!this._head && !this._tail) {
+ this._tail = item;
+ } else if (!this._head) {
+ throw new Error("Invalid list");
+ } else {
+ item.next = this._head;
+ this._head.previous = item;
+ }
+ this._head = item;
+ this._state++;
+ }
+ addItemLast(item) {
+ if (!this._head && !this._tail) {
+ this._head = item;
+ } else if (!this._tail) {
+ throw new Error("Invalid list");
+ } else {
+ item.previous = this._tail;
+ this._tail.next = item;
+ }
+ this._tail = item;
+ this._state++;
+ }
+ removeItem(item) {
+ if (item === this._head && item === this._tail) {
+ this._head = void 0;
+ this._tail = void 0;
+ } else if (item === this._head) {
+ if (!item.next) {
+ throw new Error("Invalid list");
+ }
+ item.next.previous = void 0;
+ this._head = item.next;
+ } else if (item === this._tail) {
+ if (!item.previous) {
+ throw new Error("Invalid list");
+ }
+ item.previous.next = void 0;
+ this._tail = item.previous;
+ } else {
+ const next = item.next;
+ const previous = item.previous;
+ if (!next || !previous) {
+ throw new Error("Invalid list");
}
+ next.previous = previous;
+ previous.next = next;
}
+ item.next = void 0;
+ item.previous = void 0;
+ this._state++;
}
- return defaultResult // may be undefined
- }
-}
-module.exports = diff
-
-
-/***/ }),
-/* 52 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const compare = __webpack_require__(53)
-const eq = (a, b, loose) => compare(a, b, loose) === 0
-module.exports = eq
-
-
-/***/ }),
-/* 53 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const SemVer = __webpack_require__(45)
-const compare = (a, b, loose) =>
- new SemVer(a, loose).compare(new SemVer(b, loose))
-
-module.exports = compare
-
-
-/***/ }),
-/* 54 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const SemVer = __webpack_require__(45)
-const major = (a, loose) => new SemVer(a, loose).major
-module.exports = major
-
-
-/***/ }),
-/* 55 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const SemVer = __webpack_require__(45)
-const minor = (a, loose) => new SemVer(a, loose).minor
-module.exports = minor
-
-
-/***/ }),
-/* 56 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const SemVer = __webpack_require__(45)
-const patch = (a, loose) => new SemVer(a, loose).patch
-module.exports = patch
-
-
-/***/ }),
-/* 57 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const parse = __webpack_require__(47)
-const prerelease = (version, options) => {
- const parsed = parse(version, options)
- return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
-}
-module.exports = prerelease
-
-
-/***/ }),
-/* 58 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const compare = __webpack_require__(53)
-const rcompare = (a, b, loose) => compare(b, a, loose)
-module.exports = rcompare
-
-
-/***/ }),
-/* 59 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const compare = __webpack_require__(53)
-const compareLoose = (a, b) => compare(a, b, true)
-module.exports = compareLoose
-
-
-/***/ }),
-/* 60 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const SemVer = __webpack_require__(45)
-const compareBuild = (a, b, loose) => {
- const versionA = new SemVer(a, loose)
- const versionB = new SemVer(b, loose)
- return versionA.compare(versionB) || versionA.compareBuild(versionB)
-}
-module.exports = compareBuild
-
-
-/***/ }),
-/* 61 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const compareBuild = __webpack_require__(60)
-const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
-module.exports = sort
-
-
-/***/ }),
-/* 62 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const compareBuild = __webpack_require__(60)
-const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
-module.exports = rsort
-
-
-/***/ }),
-/* 63 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const compare = __webpack_require__(53)
-const gt = (a, b, loose) => compare(a, b, loose) > 0
-module.exports = gt
-
-
-/***/ }),
-/* 64 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const compare = __webpack_require__(53)
-const lt = (a, b, loose) => compare(a, b, loose) < 0
-module.exports = lt
-
-
-/***/ }),
-/* 65 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const compare = __webpack_require__(53)
-const neq = (a, b, loose) => compare(a, b, loose) !== 0
-module.exports = neq
-
-
-/***/ }),
-/* 66 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const compare = __webpack_require__(53)
-const gte = (a, b, loose) => compare(a, b, loose) >= 0
-module.exports = gte
-
-
-/***/ }),
-/* 67 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const compare = __webpack_require__(53)
-const lte = (a, b, loose) => compare(a, b, loose) <= 0
-module.exports = lte
-
-
-/***/ }),
-/* 68 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const eq = __webpack_require__(52)
-const neq = __webpack_require__(65)
-const gt = __webpack_require__(63)
-const gte = __webpack_require__(66)
-const lt = __webpack_require__(64)
-const lte = __webpack_require__(67)
-
-const cmp = (a, op, b, loose) => {
- switch (op) {
- case '===':
- if (typeof a === 'object')
- a = a.version
- if (typeof b === 'object')
- b = b.version
- return a === b
-
- case '!==':
- if (typeof a === 'object')
- a = a.version
- if (typeof b === 'object')
- b = b.version
- return a !== b
-
- case '':
- case '=':
- case '==':
- return eq(a, b, loose)
-
- case '!=':
- return neq(a, b, loose)
-
- case '>':
- return gt(a, b, loose)
-
- case '>=':
- return gte(a, b, loose)
-
- case '<':
- return lt(a, b, loose)
-
- case '<=':
- return lte(a, b, loose)
-
- default:
- throw new TypeError(`Invalid operator: ${op}`)
- }
-}
-module.exports = cmp
-
-
-/***/ }),
-/* 69 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const SemVer = __webpack_require__(45)
-const parse = __webpack_require__(47)
-const {re, t} = __webpack_require__(42)
-
-const coerce = (version, options) => {
- if (version instanceof SemVer) {
- return version
- }
-
- if (typeof version === 'number') {
- version = String(version)
- }
-
- if (typeof version !== 'string') {
- return null
- }
-
- options = options || {}
-
- let match = null
- if (!options.rtl) {
- match = version.match(re[t.COERCE])
- } else {
- // Find the right-most coercible string that does not share
- // a terminus with a more left-ward coercible string.
- // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
- //
- // Walk through the string checking with a /g regexp
- // Manually set the index so as to pick up overlapping matches.
- // Stop when we get a match that ends at the string end, since no
- // coercible string can be more right-ward without the same terminus.
- let next
- while ((next = re[t.COERCERTL].exec(version)) &&
- (!match || match.index + match[0].length !== version.length)
- ) {
- if (!match ||
- next.index + next[0].length !== match.index + match[0].length) {
- match = next
- }
- re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
- }
- // leave it in a clean state
- re[t.COERCERTL].lastIndex = -1
- }
-
- if (match === null)
- return null
-
- return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
-}
-module.exports = coerce
-
-
-/***/ }),
-/* 70 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const ANY = Symbol('SemVer ANY')
-// hoisted class for cyclic dependency
-class Comparator {
- static get ANY () {
- return ANY
- }
- constructor (comp, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
+ touch(item, touch) {
+ if (!this._head || !this._tail) {
+ throw new Error("Invalid list");
+ }
+ if (touch !== Touch.First && touch !== Touch.Last) {
+ return;
+ }
+ if (touch === Touch.First) {
+ if (item === this._head) {
+ return;
+ }
+ const next = item.next;
+ const previous = item.previous;
+ if (item === this._tail) {
+ previous.next = void 0;
+ this._tail = previous;
+ } else {
+ next.previous = previous;
+ previous.next = next;
+ }
+ item.previous = void 0;
+ item.next = this._head;
+ this._head.previous = item;
+ this._head = item;
+ this._state++;
+ } else if (touch === Touch.Last) {
+ if (item === this._tail) {
+ return;
+ }
+ const next = item.next;
+ const previous = item.previous;
+ if (item === this._head) {
+ next.previous = void 0;
+ this._head = next;
+ } else {
+ next.previous = previous;
+ previous.next = next;
+ }
+ item.next = void 0;
+ item.previous = this._tail;
+ this._tail.next = item;
+ this._tail = item;
+ this._state++;
}
}
-
- if (comp instanceof Comparator) {
- if (comp.loose === !!options.loose) {
- return comp
- } else {
- comp = comp.value
+ toJSON() {
+ const data = [];
+ this.forEach((value, key) => {
+ data.push([key, value]);
+ });
+ return data;
+ }
+ fromJSON(data) {
+ this.clear();
+ for (const [key, value] of data) {
+ this.set(key, value);
}
}
-
- debug('comparator', comp, options)
- this.options = options
- this.loose = !!options.loose
- this.parse(comp)
-
- if (this.semver === ANY) {
- this.value = ''
- } else {
- this.value = this.operator + this.semver.version
+ };
+ exports2.LinkedMap = LinkedMap;
+ var LRUCache = class extends LinkedMap {
+ constructor(limit, ratio = 1) {
+ super();
+ this._limit = limit;
+ this._ratio = Math.min(Math.max(0, ratio), 1);
}
-
- debug('comp', this)
- }
-
- parse (comp) {
- const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
- const m = comp.match(r)
-
- if (!m) {
- throw new TypeError(`Invalid comparator: ${comp}`)
+ get limit() {
+ return this._limit;
}
-
- this.operator = m[1] !== undefined ? m[1] : ''
- if (this.operator === '=') {
- this.operator = ''
+ set limit(limit) {
+ this._limit = limit;
+ this.checkTrim();
}
-
- // if it literally is just '>' or '' then allow anything.
- if (!m[2]) {
- this.semver = ANY
- } else {
- this.semver = new SemVer(m[2], this.options.loose)
+ get ratio() {
+ return this._ratio;
}
- }
-
- toString () {
- return this.value
- }
-
- test (version) {
- debug('Comparator.test', version, this.options.loose)
-
- if (this.semver === ANY || version === ANY) {
- return true
+ set ratio(ratio) {
+ this._ratio = Math.min(Math.max(0, ratio), 1);
+ this.checkTrim();
}
-
- if (typeof version === 'string') {
- try {
- version = new SemVer(version, this.options)
- } catch (er) {
- return false
+ get(key, touch = Touch.AsNew) {
+ return super.get(key, touch);
+ }
+ peek(key) {
+ return super.get(key, Touch.None);
+ }
+ set(key, value) {
+ super.set(key, value, Touch.Last);
+ this.checkTrim();
+ return this;
+ }
+ checkTrim() {
+ if (this.size > this._limit) {
+ this.trimOld(Math.round(this._limit * this._ratio));
}
}
+ };
+ exports2.LRUCache = LRUCache;
+});
- return cmp(version, this.operator, this.semver, this.options)
- }
-
- intersects (comp, options) {
- if (!(comp instanceof Comparator)) {
- throw new TypeError('a Comparator is required')
+// node_modules/vscode-jsonrpc/lib/common/connection.js
+var require_connection = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.createMessageConnection = exports2.ConnectionOptions = exports2.CancellationStrategy = exports2.CancellationSenderStrategy = exports2.CancellationReceiverStrategy = exports2.ConnectionStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.Trace = exports2.NullLogger = exports2.ProgressType = void 0;
+ var ral_1 = require_ral();
+ var Is = require_is();
+ var messages_1 = require_messages();
+ var linkedMap_1 = require_linkedMap();
+ var events_1 = require_events();
+ var cancellation_1 = require_cancellation();
+ var CancelNotification;
+ (function(CancelNotification2) {
+ CancelNotification2.type = new messages_1.NotificationType("$/cancelRequest");
+ })(CancelNotification || (CancelNotification = {}));
+ var ProgressNotification;
+ (function(ProgressNotification2) {
+ ProgressNotification2.type = new messages_1.NotificationType("$/progress");
+ })(ProgressNotification || (ProgressNotification = {}));
+ var ProgressType = class {
+ constructor() {
}
-
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
+ };
+ exports2.ProgressType = ProgressType;
+ var StarRequestHandler;
+ (function(StarRequestHandler2) {
+ function is2(value) {
+ return Is.func(value);
+ }
+ StarRequestHandler2.is = is2;
+ })(StarRequestHandler || (StarRequestHandler = {}));
+ exports2.NullLogger = Object.freeze({
+ error: () => {
+ },
+ warn: () => {
+ },
+ info: () => {
+ },
+ log: () => {
+ }
+ });
+ var Trace2;
+ (function(Trace3) {
+ Trace3[Trace3["Off"] = 0] = "Off";
+ Trace3[Trace3["Messages"] = 1] = "Messages";
+ Trace3[Trace3["Verbose"] = 2] = "Verbose";
+ })(Trace2 = exports2.Trace || (exports2.Trace = {}));
+ (function(Trace3) {
+ function fromString(value) {
+ if (!Is.string(value)) {
+ return Trace3.Off;
+ }
+ value = value.toLowerCase();
+ switch (value) {
+ case "off":
+ return Trace3.Off;
+ case "messages":
+ return Trace3.Messages;
+ case "verbose":
+ return Trace3.Verbose;
+ default:
+ return Trace3.Off;
}
}
-
- if (this.operator === '') {
- if (this.value === '') {
- return true
- }
- return new Range(comp.value, options).test(this.value)
- } else if (comp.operator === '') {
- if (comp.value === '') {
- return true
- }
- return new Range(this.value, options).test(comp.semver)
- }
-
- const sameDirectionIncreasing =
- (this.operator === '>=' || this.operator === '>') &&
- (comp.operator === '>=' || comp.operator === '>')
- const sameDirectionDecreasing =
- (this.operator === '<=' || this.operator === '<') &&
- (comp.operator === '<=' || comp.operator === '<')
- const sameSemVer = this.semver.version === comp.semver.version
- const differentDirectionsInclusive =
- (this.operator === '>=' || this.operator === '<=') &&
- (comp.operator === '>=' || comp.operator === '<=')
- const oppositeDirectionsLessThan =
- cmp(this.semver, '<', comp.semver, options) &&
- (this.operator === '>=' || this.operator === '>') &&
- (comp.operator === '<=' || comp.operator === '<')
- const oppositeDirectionsGreaterThan =
- cmp(this.semver, '>', comp.semver, options) &&
- (this.operator === '<=' || this.operator === '<') &&
- (comp.operator === '>=' || comp.operator === '>')
-
- return (
- sameDirectionIncreasing ||
- sameDirectionDecreasing ||
- (sameSemVer && differentDirectionsInclusive) ||
- oppositeDirectionsLessThan ||
- oppositeDirectionsGreaterThan
- )
- }
-}
-
-module.exports = Comparator
-
-const {re, t} = __webpack_require__(42)
-const cmp = __webpack_require__(68)
-const debug = __webpack_require__(44)
-const SemVer = __webpack_require__(45)
-const Range = __webpack_require__(71)
-
-
-/***/ }),
-/* 71 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// hoisted class for cyclic dependency
-class Range {
- constructor (range, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
+ Trace3.fromString = fromString;
+ function toString2(value) {
+ switch (value) {
+ case Trace3.Off:
+ return "off";
+ case Trace3.Messages:
+ return "messages";
+ case Trace3.Verbose:
+ return "verbose";
+ default:
+ return "off";
}
}
-
- if (range instanceof Range) {
- if (
- range.loose === !!options.loose &&
- range.includePrerelease === !!options.includePrerelease
- ) {
- return range
+ Trace3.toString = toString2;
+ })(Trace2 = exports2.Trace || (exports2.Trace = {}));
+ var TraceFormat;
+ (function(TraceFormat2) {
+ TraceFormat2["Text"] = "text";
+ TraceFormat2["JSON"] = "json";
+ })(TraceFormat = exports2.TraceFormat || (exports2.TraceFormat = {}));
+ (function(TraceFormat2) {
+ function fromString(value) {
+ value = value.toLowerCase();
+ if (value === "json") {
+ return TraceFormat2.JSON;
} else {
- return new Range(range.raw, options)
+ return TraceFormat2.Text;
}
}
-
- if (range instanceof Comparator) {
- // just put it in the set and return
- this.raw = range.value
- this.set = [[range]]
- this.format()
- return this
+ TraceFormat2.fromString = fromString;
+ })(TraceFormat = exports2.TraceFormat || (exports2.TraceFormat = {}));
+ var SetTraceNotification;
+ (function(SetTraceNotification2) {
+ SetTraceNotification2.type = new messages_1.NotificationType("$/setTrace");
+ })(SetTraceNotification = exports2.SetTraceNotification || (exports2.SetTraceNotification = {}));
+ var LogTraceNotification;
+ (function(LogTraceNotification2) {
+ LogTraceNotification2.type = new messages_1.NotificationType("$/logTrace");
+ })(LogTraceNotification = exports2.LogTraceNotification || (exports2.LogTraceNotification = {}));
+ var ConnectionErrors;
+ (function(ConnectionErrors2) {
+ ConnectionErrors2[ConnectionErrors2["Closed"] = 1] = "Closed";
+ ConnectionErrors2[ConnectionErrors2["Disposed"] = 2] = "Disposed";
+ ConnectionErrors2[ConnectionErrors2["AlreadyListening"] = 3] = "AlreadyListening";
+ })(ConnectionErrors = exports2.ConnectionErrors || (exports2.ConnectionErrors = {}));
+ var ConnectionError = class extends Error {
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ Object.setPrototypeOf(this, ConnectionError.prototype);
+ }
+ };
+ exports2.ConnectionError = ConnectionError;
+ var ConnectionStrategy;
+ (function(ConnectionStrategy2) {
+ function is2(value) {
+ const candidate = value;
+ return candidate && Is.func(candidate.cancelUndispatched);
+ }
+ ConnectionStrategy2.is = is2;
+ })(ConnectionStrategy = exports2.ConnectionStrategy || (exports2.ConnectionStrategy = {}));
+ var CancellationReceiverStrategy;
+ (function(CancellationReceiverStrategy2) {
+ CancellationReceiverStrategy2.Message = Object.freeze({
+ createCancellationTokenSource(_) {
+ return new cancellation_1.CancellationTokenSource();
+ }
+ });
+ function is2(value) {
+ const candidate = value;
+ return candidate && Is.func(candidate.createCancellationTokenSource);
+ }
+ CancellationReceiverStrategy2.is = is2;
+ })(CancellationReceiverStrategy = exports2.CancellationReceiverStrategy || (exports2.CancellationReceiverStrategy = {}));
+ var CancellationSenderStrategy;
+ (function(CancellationSenderStrategy2) {
+ CancellationSenderStrategy2.Message = Object.freeze({
+ sendCancellation(conn, id) {
+ conn.sendNotification(CancelNotification.type, {id});
+ },
+ cleanup(_) {
+ }
+ });
+ function is2(value) {
+ const candidate = value;
+ return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);
+ }
+ CancellationSenderStrategy2.is = is2;
+ })(CancellationSenderStrategy = exports2.CancellationSenderStrategy || (exports2.CancellationSenderStrategy = {}));
+ var CancellationStrategy;
+ (function(CancellationStrategy2) {
+ CancellationStrategy2.Message = Object.freeze({
+ receiver: CancellationReceiverStrategy.Message,
+ sender: CancellationSenderStrategy.Message
+ });
+ function is2(value) {
+ const candidate = value;
+ return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
+ }
+ CancellationStrategy2.is = is2;
+ })(CancellationStrategy = exports2.CancellationStrategy || (exports2.CancellationStrategy = {}));
+ var ConnectionOptions;
+ (function(ConnectionOptions2) {
+ function is2(value) {
+ const candidate = value;
+ return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy));
+ }
+ ConnectionOptions2.is = is2;
+ })(ConnectionOptions = exports2.ConnectionOptions || (exports2.ConnectionOptions = {}));
+ var ConnectionState;
+ (function(ConnectionState2) {
+ ConnectionState2[ConnectionState2["New"] = 1] = "New";
+ ConnectionState2[ConnectionState2["Listening"] = 2] = "Listening";
+ ConnectionState2[ConnectionState2["Closed"] = 3] = "Closed";
+ ConnectionState2[ConnectionState2["Disposed"] = 4] = "Disposed";
+ })(ConnectionState || (ConnectionState = {}));
+ function createMessageConnection(messageReader, messageWriter, _logger, options) {
+ const logger = _logger !== void 0 ? _logger : exports2.NullLogger;
+ let sequenceNumber = 0;
+ let notificationSquenceNumber = 0;
+ let unknownResponseSquenceNumber = 0;
+ const version = "2.0";
+ let starRequestHandler = void 0;
+ const requestHandlers = Object.create(null);
+ let starNotificationHandler = void 0;
+ const notificationHandlers = Object.create(null);
+ const progressHandlers = new Map();
+ let timer;
+ let messageQueue = new linkedMap_1.LinkedMap();
+ let responsePromises = Object.create(null);
+ let requestTokens = Object.create(null);
+ let trace = Trace2.Off;
+ let traceFormat = TraceFormat.Text;
+ let tracer;
+ let state = ConnectionState.New;
+ const errorEmitter = new events_1.Emitter();
+ const closeEmitter = new events_1.Emitter();
+ const unhandledNotificationEmitter = new events_1.Emitter();
+ const unhandledProgressEmitter = new events_1.Emitter();
+ const disposeEmitter = new events_1.Emitter();
+ const cancellationStrategy = options && options.cancellationStrategy ? options.cancellationStrategy : CancellationStrategy.Message;
+ function createRequestQueueKey(id) {
+ if (id === null) {
+ throw new Error(`Can't send requests with id null since the response can't be correlated.`);
+ }
+ return "req-" + id.toString();
}
-
- this.options = options
- this.loose = !!options.loose
- this.includePrerelease = !!options.includePrerelease
-
- // First, split based on boolean or ||
- this.raw = range
- this.set = range
- .split(/\s*\|\|\s*/)
- // map the range to a 2d array of comparators
- .map(range => this.parseRange(range.trim()))
- // throw out any comparator lists that are empty
- // this generally means that it was not a valid range, which is allowed
- // in loose mode, but will still throw if the WHOLE range is invalid.
- .filter(c => c.length)
-
- if (!this.set.length) {
- throw new TypeError(`Invalid SemVer Range: ${range}`)
+ function createResponseQueueKey(id) {
+ if (id === null) {
+ return "res-unknown-" + (++unknownResponseSquenceNumber).toString();
+ } else {
+ return "res-" + id.toString();
+ }
}
-
- this.format()
- }
-
- format () {
- this.range = this.set
- .map((comps) => {
- return comps.join(' ').trim()
- })
- .join('||')
- .trim()
- return this.range
- }
-
- toString () {
- return this.range
- }
-
- parseRange (range) {
- const loose = this.options.loose
- range = range.trim()
- // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
- const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
- range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
- debug('hyphen replace', range)
- // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
- range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
- debug('comparator trim', range, re[t.COMPARATORTRIM])
-
- // `~ 1.2.3` => `~1.2.3`
- range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
-
- // `^ 1.2.3` => `^1.2.3`
- range = range.replace(re[t.CARETTRIM], caretTrimReplace)
-
- // normalize spaces
- range = range.split(/\s+/).join(' ')
-
- // At this point, the range is completely trimmed and
- // ready to be split into comparators.
-
- const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
- return range
- .split(' ')
- .map(comp => parseComparator(comp, this.options))
- .join(' ')
- .split(/\s+/)
- .map(comp => replaceGTE0(comp, this.options))
- // in loose mode, throw out any that are not valid comparators
- .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)
- .map(comp => new Comparator(comp, this.options))
- }
-
- intersects (range, options) {
- if (!(range instanceof Range)) {
- throw new TypeError('a Range is required')
- }
-
- return this.set.some((thisComparators) => {
- return (
- isSatisfiable(thisComparators, options) &&
- range.set.some((rangeComparators) => {
- return (
- isSatisfiable(rangeComparators, options) &&
- thisComparators.every((thisComparator) => {
- return rangeComparators.every((rangeComparator) => {
- return thisComparator.intersects(rangeComparator, options)
- })
- })
- )
- })
- )
- })
- }
-
- // if ANY of the sets match ALL of its comparators, then pass
- test (version) {
- if (!version) {
- return false
+ function createNotificationQueueKey() {
+ return "not-" + (++notificationSquenceNumber).toString();
}
-
- if (typeof version === 'string') {
- try {
- version = new SemVer(version, this.options)
- } catch (er) {
- return false
+ function addMessageToQueue(queue, message) {
+ if (messages_1.isRequestMessage(message)) {
+ queue.set(createRequestQueueKey(message.id), message);
+ } else if (messages_1.isResponseMessage(message)) {
+ queue.set(createResponseQueueKey(message.id), message);
+ } else {
+ queue.set(createNotificationQueueKey(), message);
}
}
-
- for (let i = 0; i < this.set.length; i++) {
- if (testSet(this.set[i], version, this.options)) {
- return true
+ function cancelUndispatched(_message) {
+ return void 0;
+ }
+ function isListening() {
+ return state === ConnectionState.Listening;
+ }
+ function isClosed() {
+ return state === ConnectionState.Closed;
+ }
+ function isDisposed() {
+ return state === ConnectionState.Disposed;
+ }
+ function closeHandler() {
+ if (state === ConnectionState.New || state === ConnectionState.Listening) {
+ state = ConnectionState.Closed;
+ closeEmitter.fire(void 0);
}
}
- return false
- }
-}
-module.exports = Range
-
-const Comparator = __webpack_require__(70)
-const debug = __webpack_require__(44)
-const SemVer = __webpack_require__(45)
-const {
- re,
- t,
- comparatorTrimReplace,
- tildeTrimReplace,
- caretTrimReplace
-} = __webpack_require__(42)
-
-// take a set of comparators and determine whether there
-// exists a version which can satisfy it
-const isSatisfiable = (comparators, options) => {
- let result = true
- const remainingComparators = comparators.slice()
- let testComparator = remainingComparators.pop()
-
- while (result && remainingComparators.length) {
- result = remainingComparators.every((otherComparator) => {
- return testComparator.intersects(otherComparator, options)
- })
-
- testComparator = remainingComparators.pop()
- }
-
- return result
-}
-
-// comprised of xranges, tildes, stars, and gtlt's at this point.
-// already replaced the hyphen ranges
-// turn into a set of JUST comparators.
-const parseComparator = (comp, options) => {
- debug('comp', comp, options)
- comp = replaceCarets(comp, options)
- debug('caret', comp)
- comp = replaceTildes(comp, options)
- debug('tildes', comp)
- comp = replaceXRanges(comp, options)
- debug('xrange', comp)
- comp = replaceStars(comp, options)
- debug('stars', comp)
- return comp
-}
-
-const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
-
-// ~, ~> --> * (any, kinda silly)
-// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
-// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
-// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
-// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
-// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
-const replaceTildes = (comp, options) =>
- comp.trim().split(/\s+/).map((comp) => {
- return replaceTilde(comp, options)
- }).join(' ')
-
-const replaceTilde = (comp, options) => {
- const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
- return comp.replace(r, (_, M, m, p, pr) => {
- debug('tilde', comp, _, M, m, p, pr)
- let ret
-
- if (isX(M)) {
- ret = ''
- } else if (isX(m)) {
- ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
- } else if (isX(p)) {
- // ~1.2 == >=1.2.0 <1.3.0-0
- ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
- } else if (pr) {
- debug('replaceTilde pr', pr)
- ret = `>=${M}.${m}.${p}-${pr
- } <${M}.${+m + 1}.0-0`
- } else {
- // ~1.2.3 == >=1.2.3 <1.3.0-0
- ret = `>=${M}.${m}.${p
- } <${M}.${+m + 1}.0-0`
+ function readErrorHandler(error) {
+ errorEmitter.fire([error, void 0, void 0]);
}
-
- debug('tilde return', ret)
- return ret
- })
-}
-
-// ^ --> * (any, kinda silly)
-// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
-// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
-// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
-// ^1.2.3 --> >=1.2.3 <2.0.0-0
-// ^1.2.0 --> >=1.2.0 <2.0.0-0
-const replaceCarets = (comp, options) =>
- comp.trim().split(/\s+/).map((comp) => {
- return replaceCaret(comp, options)
- }).join(' ')
-
-const replaceCaret = (comp, options) => {
- debug('caret', comp, options)
- const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
- const z = options.includePrerelease ? '-0' : ''
- return comp.replace(r, (_, M, m, p, pr) => {
- debug('caret', comp, _, M, m, p, pr)
- let ret
-
- if (isX(M)) {
- ret = ''
- } else if (isX(m)) {
- ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
- } else if (isX(p)) {
- if (M === '0') {
- ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
- } else {
- ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
- }
- } else if (pr) {
- debug('replaceCaret pr', pr)
- if (M === '0') {
- if (m === '0') {
- ret = `>=${M}.${m}.${p}-${pr
- } <${M}.${m}.${+p + 1}-0`
- } else {
- ret = `>=${M}.${m}.${p}-${pr
- } <${M}.${+m + 1}.0-0`
- }
- } else {
- ret = `>=${M}.${m}.${p}-${pr
- } <${+M + 1}.0.0-0`
+ function writeErrorHandler(data) {
+ errorEmitter.fire(data);
+ }
+ messageReader.onClose(closeHandler);
+ messageReader.onError(readErrorHandler);
+ messageWriter.onClose(closeHandler);
+ messageWriter.onError(writeErrorHandler);
+ function triggerMessageQueue() {
+ if (timer || messageQueue.size === 0) {
+ return;
}
- } else {
- debug('no pr')
- if (M === '0') {
- if (m === '0') {
- ret = `>=${M}.${m}.${p
- }${z} <${M}.${m}.${+p + 1}-0`
+ timer = ral_1.default().timer.setImmediate(() => {
+ timer = void 0;
+ processMessageQueue();
+ });
+ }
+ function processMessageQueue() {
+ if (messageQueue.size === 0) {
+ return;
+ }
+ const message = messageQueue.shift();
+ try {
+ if (messages_1.isRequestMessage(message)) {
+ handleRequest(message);
+ } else if (messages_1.isNotificationMessage(message)) {
+ handleNotification(message);
+ } else if (messages_1.isResponseMessage(message)) {
+ handleResponse(message);
} else {
- ret = `>=${M}.${m}.${p
- }${z} <${M}.${+m + 1}.0-0`
+ handleInvalidMessage(message);
}
- } else {
- ret = `>=${M}.${m}.${p
- } <${+M + 1}.0.0-0`
+ } finally {
+ triggerMessageQueue();
}
}
-
- debug('caret return', ret)
- return ret
- })
-}
-
-const replaceXRanges = (comp, options) => {
- debug('replaceXRanges', comp, options)
- return comp.split(/\s+/).map((comp) => {
- return replaceXRange(comp, options)
- }).join(' ')
-}
-
-const replaceXRange = (comp, options) => {
- comp = comp.trim()
- const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
- return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
- debug('xRange', comp, ret, gtlt, M, m, p, pr)
- const xM = isX(M)
- const xm = xM || isX(m)
- const xp = xm || isX(p)
- const anyX = xp
-
- if (gtlt === '=' && anyX) {
- gtlt = ''
- }
-
- // if we're including prereleases in the match, then we need
- // to fix this to -0, the lowest possible prerelease value
- pr = options.includePrerelease ? '-0' : ''
-
- if (xM) {
- if (gtlt === '>' || gtlt === '<') {
- // nothing is allowed
- ret = '<0.0.0-0'
- } else {
- // nothing is forbidden
- ret = '*'
+ const callback = (message) => {
+ try {
+ if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
+ const key = createRequestQueueKey(message.params.id);
+ const toCancel = messageQueue.get(key);
+ if (messages_1.isRequestMessage(toCancel)) {
+ const strategy = options === null || options === void 0 ? void 0 : options.connectionStrategy;
+ const response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
+ if (response && (response.error !== void 0 || response.result !== void 0)) {
+ messageQueue.delete(key);
+ response.id = toCancel.id;
+ traceSendingResponse(response, message.method, Date.now());
+ messageWriter.write(response);
+ return;
+ }
+ }
+ }
+ addMessageToQueue(messageQueue, message);
+ } finally {
+ triggerMessageQueue();
}
- } else if (gtlt && anyX) {
- // we know patch is an x, because we have any x at all.
- // replace X with 0
- if (xm) {
- m = 0
+ };
+ function handleRequest(requestMessage) {
+ if (isDisposed()) {
+ return;
}
- p = 0
-
- if (gtlt === '>') {
- // >1 => >=2.0.0
- // >1.2 => >=1.3.0
- gtlt = '>='
- if (xm) {
- M = +M + 1
- m = 0
- p = 0
- } else {
- m = +m + 1
- p = 0
- }
- } else if (gtlt === '<=') {
- // <=0.7.x is actually <0.8.0, since any 0.7.x should
- // pass. Similarly, <=7.x is actually <8.0.0, etc.
- gtlt = '<'
- if (xm) {
- M = +M + 1
+ function reply(resultOrError, method, startTime2) {
+ const message = {
+ jsonrpc: version,
+ id: requestMessage.id
+ };
+ if (resultOrError instanceof messages_1.ResponseError) {
+ message.error = resultOrError.toJson();
} else {
- m = +m + 1
+ message.result = resultOrError === void 0 ? null : resultOrError;
}
+ traceSendingResponse(message, method, startTime2);
+ messageWriter.write(message);
}
+ function replyError(error, method, startTime2) {
+ const message = {
+ jsonrpc: version,
+ id: requestMessage.id,
+ error: error.toJson()
+ };
+ traceSendingResponse(message, method, startTime2);
+ messageWriter.write(message);
+ }
+ function replySuccess(result, method, startTime2) {
+ if (result === void 0) {
+ result = null;
+ }
+ const message = {
+ jsonrpc: version,
+ id: requestMessage.id,
+ result
+ };
+ traceSendingResponse(message, method, startTime2);
+ messageWriter.write(message);
+ }
+ traceReceivedRequest(requestMessage);
+ const element = requestHandlers[requestMessage.method];
+ let type;
+ let requestHandler;
+ if (element) {
+ type = element.type;
+ requestHandler = element.handler;
+ }
+ const startTime = Date.now();
+ if (requestHandler || starRequestHandler) {
+ const tokenKey = String(requestMessage.id);
+ const cancellationSource = cancellationStrategy.receiver.createCancellationTokenSource(tokenKey);
+ requestTokens[tokenKey] = cancellationSource;
+ try {
+ let handlerResult;
+ if (requestHandler) {
+ if (requestMessage.params === void 0) {
+ if (type !== void 0 && type.numberOfParams !== 0) {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but recevied none.`), requestMessage.method, startTime);
+ return;
+ }
+ handlerResult = requestHandler(cancellationSource.token);
+ } else if (Array.isArray(requestMessage.params)) {
+ if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byName) {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);
+ return;
+ }
+ handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);
+ } else {
+ if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);
+ return;
+ }
+ handlerResult = requestHandler(requestMessage.params, cancellationSource.token);
+ }
+ } else if (starRequestHandler) {
+ handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
+ }
+ const promise = handlerResult;
+ if (!handlerResult) {
+ delete requestTokens[tokenKey];
+ replySuccess(handlerResult, requestMessage.method, startTime);
+ } else if (promise.then) {
+ promise.then((resultOrError) => {
+ delete requestTokens[tokenKey];
+ reply(resultOrError, requestMessage.method, startTime);
+ }, (error) => {
+ delete requestTokens[tokenKey];
+ if (error instanceof messages_1.ResponseError) {
+ replyError(error, requestMessage.method, startTime);
+ } else if (error && Is.string(error.message)) {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
+ } else {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
+ }
+ });
+ } else {
+ delete requestTokens[tokenKey];
+ reply(handlerResult, requestMessage.method, startTime);
+ }
+ } catch (error) {
+ delete requestTokens[tokenKey];
+ if (error instanceof messages_1.ResponseError) {
+ reply(error, requestMessage.method, startTime);
+ } else if (error && Is.string(error.message)) {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
+ } else {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
+ }
+ }
+ } else {
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
+ }
+ }
+ function handleResponse(responseMessage) {
+ if (isDisposed()) {
+ return;
+ }
+ if (responseMessage.id === null) {
+ if (responseMessage.error) {
+ logger.error(`Received response message without id: Error is:
+${JSON.stringify(responseMessage.error, void 0, 4)}`);
+ } else {
+ logger.error(`Received response message without id. No further error information provided.`);
+ }
+ } else {
+ const key = String(responseMessage.id);
+ const responsePromise = responsePromises[key];
+ traceReceivedResponse(responseMessage, responsePromise);
+ if (responsePromise) {
+ delete responsePromises[key];
+ try {
+ if (responseMessage.error) {
+ const error = responseMessage.error;
+ responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
+ } else if (responseMessage.result !== void 0) {
+ responsePromise.resolve(responseMessage.result);
+ } else {
+ throw new Error("Should never happen.");
+ }
+ } catch (error) {
+ if (error.message) {
+ logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
+ } else {
+ logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
+ }
+ }
+ }
+ }
+ }
+ function handleNotification(message) {
+ if (isDisposed()) {
+ return;
+ }
+ let type = void 0;
+ let notificationHandler;
+ if (message.method === CancelNotification.type.method) {
+ notificationHandler = (params) => {
+ const id = params.id;
+ const source = requestTokens[String(id)];
+ if (source) {
+ source.cancel();
+ }
+ };
+ } else {
+ const element = notificationHandlers[message.method];
+ if (element) {
+ notificationHandler = element.handler;
+ type = element.type;
+ }
+ }
+ if (notificationHandler || starNotificationHandler) {
+ try {
+ traceReceivedNotification(message);
+ if (notificationHandler) {
+ if (message.params === void 0) {
+ if (type !== void 0) {
+ if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) {
+ logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but recevied none.`);
+ }
+ }
+ notificationHandler();
+ } else if (Array.isArray(message.params)) {
+ if (type !== void 0) {
+ if (type.parameterStructures === messages_1.ParameterStructures.byName) {
+ logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`);
+ }
+ if (type.numberOfParams !== message.params.length) {
+ logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${message.params.length} argumennts`);
+ }
+ }
+ notificationHandler(...message.params);
+ } else {
+ if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
+ logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`);
+ }
+ notificationHandler(message.params);
+ }
+ } else if (starNotificationHandler) {
+ starNotificationHandler(message.method, message.params);
+ }
+ } catch (error) {
+ if (error.message) {
+ logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
+ } else {
+ logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
+ }
+ }
+ } else {
+ unhandledNotificationEmitter.fire(message);
+ }
+ }
+ function handleInvalidMessage(message) {
+ if (!message) {
+ logger.error("Received empty message.");
+ return;
+ }
+ logger.error(`Received message which is neither a response nor a notification message:
+${JSON.stringify(message, null, 4)}`);
+ const responseMessage = message;
+ if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
+ const key = String(responseMessage.id);
+ const responseHandler = responsePromises[key];
+ if (responseHandler) {
+ responseHandler.reject(new Error("The received response has neither a result nor an error property."));
+ }
+ }
+ }
+ function traceSendingRequest(message) {
+ if (trace === Trace2.Off || !tracer) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = void 0;
+ if (trace === Trace2.Verbose && message.params) {
+ data = `Params: ${JSON.stringify(message.params, null, 4)}
- if (gtlt === '<')
- pr = '-0'
-
- ret = `${gtlt + M}.${m}.${p}${pr}`
- } else if (xm) {
- ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
- } else if (xp) {
- ret = `>=${M}.${m}.0${pr
- } <${M}.${+m + 1}.0-0`
- }
-
- debug('xRange return', ret)
-
- return ret
- })
-}
-
-// Because * is AND-ed with everything else in the comparator,
-// and '' means "any version", just remove the *s entirely.
-const replaceStars = (comp, options) => {
- debug('replaceStars', comp, options)
- // Looseness is ignored here. star is always as loose as it gets!
- return comp.trim().replace(re[t.STAR], '')
-}
-
-const replaceGTE0 = (comp, options) => {
- debug('replaceGTE0', comp, options)
- return comp.trim()
- .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
-}
-
-// This function is passed to string.replace(re[t.HYPHENRANGE])
-// M, m, patch, prerelease, build
-// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
-// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
-// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
-const hyphenReplace = incPr => ($0,
- from, fM, fm, fp, fpr, fb,
- to, tM, tm, tp, tpr, tb) => {
- if (isX(fM)) {
- from = ''
- } else if (isX(fm)) {
- from = `>=${fM}.0.0${incPr ? '-0' : ''}`
- } else if (isX(fp)) {
- from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
- } else if (fpr) {
- from = `>=${from}`
- } else {
- from = `>=${from}${incPr ? '-0' : ''}`
- }
-
- if (isX(tM)) {
- to = ''
- } else if (isX(tm)) {
- to = `<${+tM + 1}.0.0-0`
- } else if (isX(tp)) {
- to = `<${tM}.${+tm + 1}.0-0`
- } else if (tpr) {
- to = `<=${tM}.${tm}.${tp}-${tpr}`
- } else if (incPr) {
- to = `<${tM}.${tm}.${+tp + 1}-0`
- } else {
- to = `<=${to}`
- }
-
- return (`${from} ${to}`).trim()
-}
+`;
+ }
+ tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
+ } else {
+ logLSPMessage("send-request", message);
+ }
+ }
+ function traceSendingNotification(message) {
+ if (trace === Trace2.Off || !tracer) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = void 0;
+ if (trace === Trace2.Verbose) {
+ if (message.params) {
+ data = `Params: ${JSON.stringify(message.params, null, 4)}
-const testSet = (set, version, options) => {
- for (let i = 0; i < set.length; i++) {
- if (!set[i].test(version)) {
- return false
+`;
+ } else {
+ data = "No parameters provided.\n\n";
+ }
+ }
+ tracer.log(`Sending notification '${message.method}'.`, data);
+ } else {
+ logLSPMessage("send-notification", message);
+ }
}
- }
+ function traceSendingResponse(message, method, startTime) {
+ if (trace === Trace2.Off || !tracer) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = void 0;
+ if (trace === Trace2.Verbose) {
+ if (message.error && message.error.data) {
+ data = `Error data: ${JSON.stringify(message.error.data, null, 4)}
- if (version.prerelease.length && !options.includePrerelease) {
- // Find the set of versions that are allowed to have prereleases
- // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
- // That should allow `1.2.3-pr.2` to pass.
- // However, `1.2.4-alpha.notready` should NOT be allowed,
- // even though it's within the range set by the comparators.
- for (let i = 0; i < set.length; i++) {
- debug(set[i].semver)
- if (set[i].semver === Comparator.ANY) {
- continue
+`;
+ } else {
+ if (message.result) {
+ data = `Result: ${JSON.stringify(message.result, null, 4)}
+
+`;
+ } else if (message.error === void 0) {
+ data = "No result returned.\n\n";
+ }
+ }
+ }
+ tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
+ } else {
+ logLSPMessage("send-response", message);
}
+ }
+ function traceReceivedRequest(message) {
+ if (trace === Trace2.Off || !tracer) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = void 0;
+ if (trace === Trace2.Verbose && message.params) {
+ data = `Params: ${JSON.stringify(message.params, null, 4)}
- if (set[i].semver.prerelease.length > 0) {
- const allowed = set[i].semver
- if (allowed.major === version.major &&
- allowed.minor === version.minor &&
- allowed.patch === version.patch) {
- return true
+`;
}
+ tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
+ } else {
+ logLSPMessage("receive-request", message);
}
}
+ function traceReceivedNotification(message) {
+ if (trace === Trace2.Off || !tracer || message.method === LogTraceNotification.type.method) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = void 0;
+ if (trace === Trace2.Verbose) {
+ if (message.params) {
+ data = `Params: ${JSON.stringify(message.params, null, 4)}
- // Version has a -pre, but it's not one of the ones we like.
- return false
+`;
+ } else {
+ data = "No parameters provided.\n\n";
+ }
+ }
+ tracer.log(`Received notification '${message.method}'.`, data);
+ } else {
+ logLSPMessage("receive-notification", message);
+ }
+ }
+ function traceReceivedResponse(message, responsePromise) {
+ if (trace === Trace2.Off || !tracer) {
+ return;
+ }
+ if (traceFormat === TraceFormat.Text) {
+ let data = void 0;
+ if (trace === Trace2.Verbose) {
+ if (message.error && message.error.data) {
+ data = `Error data: ${JSON.stringify(message.error.data, null, 4)}
+
+`;
+ } else {
+ if (message.result) {
+ data = `Result: ${JSON.stringify(message.result, null, 4)}
+
+`;
+ } else if (message.error === void 0) {
+ data = "No result returned.\n\n";
+ }
+ }
+ }
+ if (responsePromise) {
+ const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : "";
+ tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
+ } else {
+ tracer.log(`Received response ${message.id} without active response promise.`, data);
+ }
+ } else {
+ logLSPMessage("receive-response", message);
+ }
+ }
+ function logLSPMessage(type, message) {
+ if (!tracer || trace === Trace2.Off) {
+ return;
+ }
+ const lspMessage = {
+ isLSPMessage: true,
+ type,
+ message,
+ timestamp: Date.now()
+ };
+ tracer.log(lspMessage);
+ }
+ function throwIfClosedOrDisposed() {
+ if (isClosed()) {
+ throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed.");
+ }
+ if (isDisposed()) {
+ throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed.");
+ }
+ }
+ function throwIfListening() {
+ if (isListening()) {
+ throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening");
+ }
+ }
+ function throwIfNotListening() {
+ if (!isListening()) {
+ throw new Error("Call listen() first.");
+ }
+ }
+ function undefinedToNull(param) {
+ if (param === void 0) {
+ return null;
+ } else {
+ return param;
+ }
+ }
+ function nullToUndefined(param) {
+ if (param === null) {
+ return void 0;
+ } else {
+ return param;
+ }
+ }
+ function isNamedParam(param) {
+ return param !== void 0 && param !== null && !Array.isArray(param) && typeof param === "object";
+ }
+ function computeSingleParam(parameterStructures, param) {
+ switch (parameterStructures) {
+ case messages_1.ParameterStructures.auto:
+ if (isNamedParam(param)) {
+ return nullToUndefined(param);
+ } else {
+ return [undefinedToNull(param)];
+ }
+ break;
+ case messages_1.ParameterStructures.byName:
+ if (!isNamedParam(param)) {
+ throw new Error(`Recevied parameters by name but param is not an object literal.`);
+ }
+ return nullToUndefined(param);
+ case messages_1.ParameterStructures.byPosition:
+ return [undefinedToNull(param)];
+ default:
+ throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);
+ }
+ }
+ function computeMessageParams(type, params) {
+ let result;
+ const numberOfParams = type.numberOfParams;
+ switch (numberOfParams) {
+ case 0:
+ result = void 0;
+ break;
+ case 1:
+ result = computeSingleParam(type.parameterStructures, params[0]);
+ break;
+ default:
+ result = [];
+ for (let i = 0; i < params.length && i < numberOfParams; i++) {
+ result.push(undefinedToNull(params[i]));
+ }
+ if (params.length < numberOfParams) {
+ for (let i = params.length; i < numberOfParams; i++) {
+ result.push(null);
+ }
+ }
+ break;
+ }
+ return result;
+ }
+ const connection = {
+ sendNotification: (type, ...args) => {
+ throwIfClosedOrDisposed();
+ let method;
+ let messageParams;
+ if (Is.string(type)) {
+ method = type;
+ const first = args[0];
+ let paramStart = 0;
+ let parameterStructures = messages_1.ParameterStructures.auto;
+ if (messages_1.ParameterStructures.is(first)) {
+ paramStart = 1;
+ parameterStructures = first;
+ }
+ let paramEnd = args.length;
+ const numberOfParams = paramEnd - paramStart;
+ switch (numberOfParams) {
+ case 0:
+ messageParams = void 0;
+ break;
+ case 1:
+ messageParams = computeSingleParam(parameterStructures, args[paramStart]);
+ break;
+ default:
+ if (parameterStructures === messages_1.ParameterStructures.byName) {
+ throw new Error(`Recevied ${numberOfParams} parameters for 'by Name' notification parameter structure.`);
+ }
+ messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
+ break;
+ }
+ } else {
+ const params = args;
+ method = type.method;
+ messageParams = computeMessageParams(type, params);
+ }
+ const notificationMessage = {
+ jsonrpc: version,
+ method,
+ params: messageParams
+ };
+ traceSendingNotification(notificationMessage);
+ messageWriter.write(notificationMessage);
+ },
+ onNotification: (type, handler) => {
+ throwIfClosedOrDisposed();
+ let method;
+ if (Is.func(type)) {
+ starNotificationHandler = type;
+ } else if (handler) {
+ if (Is.string(type)) {
+ method = type;
+ notificationHandlers[type] = {type: void 0, handler};
+ } else {
+ method = type.method;
+ notificationHandlers[type.method] = {type, handler};
+ }
+ }
+ return {
+ dispose: () => {
+ if (method !== void 0) {
+ delete notificationHandlers[method];
+ } else {
+ starNotificationHandler = void 0;
+ }
+ }
+ };
+ },
+ onProgress: (_type, token, handler) => {
+ if (progressHandlers.has(token)) {
+ throw new Error(`Progress handler for token ${token} already registered`);
+ }
+ progressHandlers.set(token, handler);
+ return {
+ dispose: () => {
+ progressHandlers.delete(token);
+ }
+ };
+ },
+ sendProgress: (_type, token, value) => {
+ connection.sendNotification(ProgressNotification.type, {token, value});
+ },
+ onUnhandledProgress: unhandledProgressEmitter.event,
+ sendRequest: (type, ...args) => {
+ throwIfClosedOrDisposed();
+ throwIfNotListening();
+ let method;
+ let messageParams;
+ let token = void 0;
+ if (Is.string(type)) {
+ method = type;
+ const first = args[0];
+ const last = args[args.length - 1];
+ let paramStart = 0;
+ let parameterStructures = messages_1.ParameterStructures.auto;
+ if (messages_1.ParameterStructures.is(first)) {
+ paramStart = 1;
+ parameterStructures = first;
+ }
+ let paramEnd = args.length;
+ if (cancellation_1.CancellationToken.is(last)) {
+ paramEnd = paramEnd - 1;
+ token = last;
+ }
+ const numberOfParams = paramEnd - paramStart;
+ switch (numberOfParams) {
+ case 0:
+ messageParams = void 0;
+ break;
+ case 1:
+ messageParams = computeSingleParam(parameterStructures, args[paramStart]);
+ break;
+ default:
+ if (parameterStructures === messages_1.ParameterStructures.byName) {
+ throw new Error(`Recevied ${numberOfParams} parameters for 'by Name' request parameter structure.`);
+ }
+ messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
+ break;
+ }
+ } else {
+ const params = args;
+ method = type.method;
+ messageParams = computeMessageParams(type, params);
+ const numberOfParams = type.numberOfParams;
+ token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : void 0;
+ }
+ const id = sequenceNumber++;
+ let disposable;
+ if (token) {
+ disposable = token.onCancellationRequested(() => {
+ cancellationStrategy.sender.sendCancellation(connection, id);
+ });
+ }
+ const result = new Promise((resolve, reject) => {
+ const requestMessage = {
+ jsonrpc: version,
+ id,
+ method,
+ params: messageParams
+ };
+ const resolveWithCleanup = (r) => {
+ resolve(r);
+ cancellationStrategy.sender.cleanup(id);
+ disposable === null || disposable === void 0 ? void 0 : disposable.dispose();
+ };
+ const rejectWithCleanup = (r) => {
+ reject(r);
+ cancellationStrategy.sender.cleanup(id);
+ disposable === null || disposable === void 0 ? void 0 : disposable.dispose();
+ };
+ let responsePromise = {method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup};
+ traceSendingRequest(requestMessage);
+ try {
+ messageWriter.write(requestMessage);
+ } catch (e) {
+ responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : "Unknown reason"));
+ responsePromise = null;
+ }
+ if (responsePromise) {
+ responsePromises[String(id)] = responsePromise;
+ }
+ });
+ return result;
+ },
+ onRequest: (type, handler) => {
+ throwIfClosedOrDisposed();
+ let method = null;
+ if (StarRequestHandler.is(type)) {
+ method = void 0;
+ starRequestHandler = type;
+ } else if (Is.string(type)) {
+ method = null;
+ if (handler !== void 0) {
+ method = type;
+ requestHandlers[type] = {handler, type: void 0};
+ }
+ } else {
+ if (handler !== void 0) {
+ method = type.method;
+ requestHandlers[type.method] = {type, handler};
+ }
+ }
+ return {
+ dispose: () => {
+ if (method === null) {
+ return;
+ }
+ if (method !== void 0) {
+ delete requestHandlers[method];
+ } else {
+ starRequestHandler = void 0;
+ }
+ }
+ };
+ },
+ trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
+ let _sendNotification = false;
+ let _traceFormat = TraceFormat.Text;
+ if (sendNotificationOrTraceOptions !== void 0) {
+ if (Is.boolean(sendNotificationOrTraceOptions)) {
+ _sendNotification = sendNotificationOrTraceOptions;
+ } else {
+ _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
+ _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
+ }
+ }
+ trace = _value;
+ traceFormat = _traceFormat;
+ if (trace === Trace2.Off) {
+ tracer = void 0;
+ } else {
+ tracer = _tracer;
+ }
+ if (_sendNotification && !isClosed() && !isDisposed()) {
+ connection.sendNotification(SetTraceNotification.type, {value: Trace2.toString(_value)});
+ }
+ },
+ onError: errorEmitter.event,
+ onClose: closeEmitter.event,
+ onUnhandledNotification: unhandledNotificationEmitter.event,
+ onDispose: disposeEmitter.event,
+ end: () => {
+ messageWriter.end();
+ },
+ dispose: () => {
+ if (isDisposed()) {
+ return;
+ }
+ state = ConnectionState.Disposed;
+ disposeEmitter.fire(void 0);
+ const error = new Error("Connection got disposed.");
+ Object.keys(responsePromises).forEach((key) => {
+ responsePromises[key].reject(error);
+ });
+ responsePromises = Object.create(null);
+ requestTokens = Object.create(null);
+ messageQueue = new linkedMap_1.LinkedMap();
+ if (Is.func(messageWriter.dispose)) {
+ messageWriter.dispose();
+ }
+ if (Is.func(messageReader.dispose)) {
+ messageReader.dispose();
+ }
+ },
+ listen: () => {
+ throwIfClosedOrDisposed();
+ throwIfListening();
+ state = ConnectionState.Listening;
+ messageReader.listen(callback);
+ },
+ inspect: () => {
+ ral_1.default().console.log("inspect");
+ }
+ };
+ connection.onNotification(LogTraceNotification.type, (params) => {
+ if (trace === Trace2.Off || !tracer) {
+ return;
+ }
+ tracer.log(params.message, trace === Trace2.Verbose ? params.verbose : void 0);
+ });
+ connection.onNotification(ProgressNotification.type, (params) => {
+ const handler = progressHandlers.get(params.token);
+ if (handler) {
+ handler(params.value);
+ } else {
+ unhandledProgressEmitter.fire(params);
+ }
+ });
+ return connection;
}
+ exports2.createMessageConnection = createMessageConnection;
+});
- return true
-}
+// node_modules/vscode-jsonrpc/lib/common/api.js
+var require_api = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.CancellationSenderStrategy = exports2.CancellationReceiverStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.Trace = exports2.ProgressType = exports2.createMessageConnection = exports2.NullLogger = exports2.ConnectionOptions = exports2.ConnectionStrategy = exports2.WriteableStreamMessageWriter = exports2.AbstractMessageWriter = exports2.MessageWriter = exports2.ReadableStreamMessageReader = exports2.AbstractMessageReader = exports2.MessageReader = exports2.CancellationToken = exports2.CancellationTokenSource = exports2.Emitter = exports2.Event = exports2.Disposable = exports2.ParameterStructures = exports2.NotificationType9 = exports2.NotificationType8 = exports2.NotificationType7 = exports2.NotificationType6 = exports2.NotificationType5 = exports2.NotificationType4 = exports2.NotificationType3 = exports2.NotificationType2 = exports2.NotificationType1 = exports2.NotificationType0 = exports2.NotificationType = exports2.ErrorCodes = exports2.ResponseError = exports2.RequestType9 = exports2.RequestType8 = exports2.RequestType7 = exports2.RequestType6 = exports2.RequestType5 = exports2.RequestType4 = exports2.RequestType3 = exports2.RequestType2 = exports2.RequestType1 = exports2.RequestType0 = exports2.RequestType = exports2.RAL = void 0;
+ exports2.CancellationStrategy = void 0;
+ var messages_1 = require_messages();
+ Object.defineProperty(exports2, "RequestType", {enumerable: true, get: function() {
+ return messages_1.RequestType;
+ }});
+ Object.defineProperty(exports2, "RequestType0", {enumerable: true, get: function() {
+ return messages_1.RequestType0;
+ }});
+ Object.defineProperty(exports2, "RequestType1", {enumerable: true, get: function() {
+ return messages_1.RequestType1;
+ }});
+ Object.defineProperty(exports2, "RequestType2", {enumerable: true, get: function() {
+ return messages_1.RequestType2;
+ }});
+ Object.defineProperty(exports2, "RequestType3", {enumerable: true, get: function() {
+ return messages_1.RequestType3;
+ }});
+ Object.defineProperty(exports2, "RequestType4", {enumerable: true, get: function() {
+ return messages_1.RequestType4;
+ }});
+ Object.defineProperty(exports2, "RequestType5", {enumerable: true, get: function() {
+ return messages_1.RequestType5;
+ }});
+ Object.defineProperty(exports2, "RequestType6", {enumerable: true, get: function() {
+ return messages_1.RequestType6;
+ }});
+ Object.defineProperty(exports2, "RequestType7", {enumerable: true, get: function() {
+ return messages_1.RequestType7;
+ }});
+ Object.defineProperty(exports2, "RequestType8", {enumerable: true, get: function() {
+ return messages_1.RequestType8;
+ }});
+ Object.defineProperty(exports2, "RequestType9", {enumerable: true, get: function() {
+ return messages_1.RequestType9;
+ }});
+ Object.defineProperty(exports2, "ResponseError", {enumerable: true, get: function() {
+ return messages_1.ResponseError;
+ }});
+ Object.defineProperty(exports2, "ErrorCodes", {enumerable: true, get: function() {
+ return messages_1.ErrorCodes;
+ }});
+ Object.defineProperty(exports2, "NotificationType", {enumerable: true, get: function() {
+ return messages_1.NotificationType;
+ }});
+ Object.defineProperty(exports2, "NotificationType0", {enumerable: true, get: function() {
+ return messages_1.NotificationType0;
+ }});
+ Object.defineProperty(exports2, "NotificationType1", {enumerable: true, get: function() {
+ return messages_1.NotificationType1;
+ }});
+ Object.defineProperty(exports2, "NotificationType2", {enumerable: true, get: function() {
+ return messages_1.NotificationType2;
+ }});
+ Object.defineProperty(exports2, "NotificationType3", {enumerable: true, get: function() {
+ return messages_1.NotificationType3;
+ }});
+ Object.defineProperty(exports2, "NotificationType4", {enumerable: true, get: function() {
+ return messages_1.NotificationType4;
+ }});
+ Object.defineProperty(exports2, "NotificationType5", {enumerable: true, get: function() {
+ return messages_1.NotificationType5;
+ }});
+ Object.defineProperty(exports2, "NotificationType6", {enumerable: true, get: function() {
+ return messages_1.NotificationType6;
+ }});
+ Object.defineProperty(exports2, "NotificationType7", {enumerable: true, get: function() {
+ return messages_1.NotificationType7;
+ }});
+ Object.defineProperty(exports2, "NotificationType8", {enumerable: true, get: function() {
+ return messages_1.NotificationType8;
+ }});
+ Object.defineProperty(exports2, "NotificationType9", {enumerable: true, get: function() {
+ return messages_1.NotificationType9;
+ }});
+ Object.defineProperty(exports2, "ParameterStructures", {enumerable: true, get: function() {
+ return messages_1.ParameterStructures;
+ }});
+ var disposable_1 = require_disposable();
+ Object.defineProperty(exports2, "Disposable", {enumerable: true, get: function() {
+ return disposable_1.Disposable;
+ }});
+ var events_1 = require_events();
+ Object.defineProperty(exports2, "Event", {enumerable: true, get: function() {
+ return events_1.Event;
+ }});
+ Object.defineProperty(exports2, "Emitter", {enumerable: true, get: function() {
+ return events_1.Emitter;
+ }});
+ var cancellation_1 = require_cancellation();
+ Object.defineProperty(exports2, "CancellationTokenSource", {enumerable: true, get: function() {
+ return cancellation_1.CancellationTokenSource;
+ }});
+ Object.defineProperty(exports2, "CancellationToken", {enumerable: true, get: function() {
+ return cancellation_1.CancellationToken;
+ }});
+ var messageReader_1 = require_messageReader();
+ Object.defineProperty(exports2, "MessageReader", {enumerable: true, get: function() {
+ return messageReader_1.MessageReader;
+ }});
+ Object.defineProperty(exports2, "AbstractMessageReader", {enumerable: true, get: function() {
+ return messageReader_1.AbstractMessageReader;
+ }});
+ Object.defineProperty(exports2, "ReadableStreamMessageReader", {enumerable: true, get: function() {
+ return messageReader_1.ReadableStreamMessageReader;
+ }});
+ var messageWriter_1 = require_messageWriter();
+ Object.defineProperty(exports2, "MessageWriter", {enumerable: true, get: function() {
+ return messageWriter_1.MessageWriter;
+ }});
+ Object.defineProperty(exports2, "AbstractMessageWriter", {enumerable: true, get: function() {
+ return messageWriter_1.AbstractMessageWriter;
+ }});
+ Object.defineProperty(exports2, "WriteableStreamMessageWriter", {enumerable: true, get: function() {
+ return messageWriter_1.WriteableStreamMessageWriter;
+ }});
+ var connection_1 = require_connection();
+ Object.defineProperty(exports2, "ConnectionStrategy", {enumerable: true, get: function() {
+ return connection_1.ConnectionStrategy;
+ }});
+ Object.defineProperty(exports2, "ConnectionOptions", {enumerable: true, get: function() {
+ return connection_1.ConnectionOptions;
+ }});
+ Object.defineProperty(exports2, "NullLogger", {enumerable: true, get: function() {
+ return connection_1.NullLogger;
+ }});
+ Object.defineProperty(exports2, "createMessageConnection", {enumerable: true, get: function() {
+ return connection_1.createMessageConnection;
+ }});
+ Object.defineProperty(exports2, "ProgressType", {enumerable: true, get: function() {
+ return connection_1.ProgressType;
+ }});
+ Object.defineProperty(exports2, "Trace", {enumerable: true, get: function() {
+ return connection_1.Trace;
+ }});
+ Object.defineProperty(exports2, "TraceFormat", {enumerable: true, get: function() {
+ return connection_1.TraceFormat;
+ }});
+ Object.defineProperty(exports2, "SetTraceNotification", {enumerable: true, get: function() {
+ return connection_1.SetTraceNotification;
+ }});
+ Object.defineProperty(exports2, "LogTraceNotification", {enumerable: true, get: function() {
+ return connection_1.LogTraceNotification;
+ }});
+ Object.defineProperty(exports2, "ConnectionErrors", {enumerable: true, get: function() {
+ return connection_1.ConnectionErrors;
+ }});
+ Object.defineProperty(exports2, "ConnectionError", {enumerable: true, get: function() {
+ return connection_1.ConnectionError;
+ }});
+ Object.defineProperty(exports2, "CancellationReceiverStrategy", {enumerable: true, get: function() {
+ return connection_1.CancellationReceiverStrategy;
+ }});
+ Object.defineProperty(exports2, "CancellationSenderStrategy", {enumerable: true, get: function() {
+ return connection_1.CancellationSenderStrategy;
+ }});
+ Object.defineProperty(exports2, "CancellationStrategy", {enumerable: true, get: function() {
+ return connection_1.CancellationStrategy;
+ }});
+ var ral_1 = require_ral();
+ exports2.RAL = ral_1.default;
+});
+// node_modules/vscode-jsonrpc/lib/node/main.js
+var require_main = __commonJS((exports2) => {
+ "use strict";
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
+ if (k2 === void 0)
+ k2 = k;
+ Object.defineProperty(o, k2, {enumerable: true, get: function() {
+ return m[k];
+ }});
+ } : function(o, m, k, k2) {
+ if (k2 === void 0)
+ k2 = k;
+ o[k2] = m[k];
+ });
+ var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
+ for (var p in m)
+ if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p))
+ __createBinding(exports3, m, p);
+ };
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.createMessageConnection = exports2.createServerSocketTransport = exports2.createClientSocketTransport = exports2.createServerPipeTransport = exports2.createClientPipeTransport = exports2.generateRandomPipeName = exports2.StreamMessageWriter = exports2.StreamMessageReader = exports2.SocketMessageWriter = exports2.SocketMessageReader = exports2.IPCMessageWriter = exports2.IPCMessageReader = void 0;
+ var ril_1 = require_ril();
+ ril_1.default.install();
+ var api_1 = require_api();
+ var path9 = require("path");
+ var os3 = require("os");
+ var crypto_1 = require("crypto");
+ var net_1 = require("net");
+ __exportStar2(require_api(), exports2);
+ var IPCMessageReader = class extends api_1.AbstractMessageReader {
+ constructor(process2) {
+ super();
+ this.process = process2;
+ let eventEmitter = this.process;
+ eventEmitter.on("error", (error) => this.fireError(error));
+ eventEmitter.on("close", () => this.fireClose());
+ }
+ listen(callback) {
+ this.process.on("message", callback);
+ return api_1.Disposable.create(() => this.process.off("message", callback));
+ }
+ };
+ exports2.IPCMessageReader = IPCMessageReader;
+ var IPCMessageWriter = class extends api_1.AbstractMessageWriter {
+ constructor(process2) {
+ super();
+ this.process = process2;
+ this.errorCount = 0;
+ let eventEmitter = this.process;
+ eventEmitter.on("error", (error) => this.fireError(error));
+ eventEmitter.on("close", () => this.fireClose);
+ }
+ write(msg) {
+ try {
+ if (typeof this.process.send === "function") {
+ this.process.send(msg, void 0, void 0, (error) => {
+ if (error) {
+ this.errorCount++;
+ this.handleError(error, msg);
+ } else {
+ this.errorCount = 0;
+ }
+ });
+ }
+ return Promise.resolve();
+ } catch (error) {
+ this.handleError(error, msg);
+ return Promise.reject(error);
+ }
+ }
+ handleError(error, msg) {
+ this.errorCount++;
+ this.fireError(error, msg, this.errorCount);
+ }
+ end() {
+ }
+ };
+ exports2.IPCMessageWriter = IPCMessageWriter;
+ var SocketMessageReader = class extends api_1.ReadableStreamMessageReader {
+ constructor(socket, encoding = "utf-8") {
+ super(ril_1.default().stream.asReadableStream(socket), encoding);
+ }
+ };
+ exports2.SocketMessageReader = SocketMessageReader;
+ var SocketMessageWriter = class extends api_1.WriteableStreamMessageWriter {
+ constructor(socket, options) {
+ super(ril_1.default().stream.asWritableStream(socket), options);
+ this.socket = socket;
+ }
+ dispose() {
+ super.dispose();
+ this.socket.destroy();
+ }
+ };
+ exports2.SocketMessageWriter = SocketMessageWriter;
+ var StreamMessageReader = class extends api_1.ReadableStreamMessageReader {
+ constructor(readble, encoding) {
+ super(ril_1.default().stream.asReadableStream(readble), encoding);
+ }
+ };
+ exports2.StreamMessageReader = StreamMessageReader;
+ var StreamMessageWriter = class extends api_1.WriteableStreamMessageWriter {
+ constructor(writable, options) {
+ super(ril_1.default().stream.asWritableStream(writable), options);
+ }
+ };
+ exports2.StreamMessageWriter = StreamMessageWriter;
+ var XDG_RUNTIME_DIR = process.env["XDG_RUNTIME_DIR"];
+ var safeIpcPathLengths = new Map([
+ ["linux", 107],
+ ["darwin", 103]
+ ]);
+ function generateRandomPipeName() {
+ const randomSuffix = crypto_1.randomBytes(21).toString("hex");
+ if (process.platform === "win32") {
+ return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
+ }
+ let result;
+ if (XDG_RUNTIME_DIR) {
+ result = path9.join(XDG_RUNTIME_DIR, `vscode-ipc-${randomSuffix}.sock`);
+ } else {
+ result = path9.join(os3.tmpdir(), `vscode-${randomSuffix}.sock`);
+ }
+ const limit = safeIpcPathLengths.get(process.platform);
+ if (limit !== void 0 && result.length >= limit) {
+ ril_1.default().console.warn(`WARNING: IPC handle "${result}" is longer than ${limit} characters.`);
+ }
+ return result;
+ }
+ exports2.generateRandomPipeName = generateRandomPipeName;
+ function createClientPipeTransport(pipeName, encoding = "utf-8") {
+ let connectResolve;
+ const connected = new Promise((resolve, _reject) => {
+ connectResolve = resolve;
+ });
+ return new Promise((resolve, reject) => {
+ let server = net_1.createServer((socket) => {
+ server.close();
+ connectResolve([
+ new SocketMessageReader(socket, encoding),
+ new SocketMessageWriter(socket, encoding)
+ ]);
+ });
+ server.on("error", reject);
+ server.listen(pipeName, () => {
+ server.removeListener("error", reject);
+ resolve({
+ onConnected: () => {
+ return connected;
+ }
+ });
+ });
+ });
+ }
+ exports2.createClientPipeTransport = createClientPipeTransport;
+ function createServerPipeTransport(pipeName, encoding = "utf-8") {
+ const socket = net_1.createConnection(pipeName);
+ return [
+ new SocketMessageReader(socket, encoding),
+ new SocketMessageWriter(socket, encoding)
+ ];
+ }
+ exports2.createServerPipeTransport = createServerPipeTransport;
+ function createClientSocketTransport(port, encoding = "utf-8") {
+ let connectResolve;
+ const connected = new Promise((resolve, _reject) => {
+ connectResolve = resolve;
+ });
+ return new Promise((resolve, reject) => {
+ const server = net_1.createServer((socket) => {
+ server.close();
+ connectResolve([
+ new SocketMessageReader(socket, encoding),
+ new SocketMessageWriter(socket, encoding)
+ ]);
+ });
+ server.on("error", reject);
+ server.listen(port, "127.0.0.1", () => {
+ server.removeListener("error", reject);
+ resolve({
+ onConnected: () => {
+ return connected;
+ }
+ });
+ });
+ });
+ }
+ exports2.createClientSocketTransport = createClientSocketTransport;
+ function createServerSocketTransport(port, encoding = "utf-8") {
+ const socket = net_1.createConnection(port, "127.0.0.1");
+ return [
+ new SocketMessageReader(socket, encoding),
+ new SocketMessageWriter(socket, encoding)
+ ];
+ }
+ exports2.createServerSocketTransport = createServerSocketTransport;
+ function isReadableStream(value) {
+ const candidate = value;
+ return candidate.read !== void 0 && candidate.addListener !== void 0;
+ }
+ function isWritableStream(value) {
+ const candidate = value;
+ return candidate.write !== void 0 && candidate.addListener !== void 0;
+ }
+ function createMessageConnection(input, output, logger, options) {
+ if (!logger) {
+ logger = api_1.NullLogger;
+ }
+ const reader = isReadableStream(input) ? new StreamMessageReader(input) : input;
+ const writer = isWritableStream(output) ? new StreamMessageWriter(output) : output;
+ if (api_1.ConnectionStrategy.is(options)) {
+ options = {connectionStrategy: options};
+ }
+ return api_1.createMessageConnection(reader, writer, logger, options);
+ }
+ exports2.createMessageConnection = createMessageConnection;
+});
-/***/ }),
-/* 72 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/vscode-jsonrpc/node.js
+var require_node = __commonJS((exports2, module2) => {
+ "use strict";
+ module2.exports = require_main();
+});
-const Range = __webpack_require__(71)
-const satisfies = (version, range, options) => {
- try {
- range = new Range(range, options)
- } catch (er) {
- return false
+// node_modules/vscode-languageserver-types/lib/esm/main.js
+var require_main2 = __commonJS((exports2) => {
+ __export(exports2, {
+ AnnotatedTextEdit: () => AnnotatedTextEdit,
+ ChangeAnnotation: () => ChangeAnnotation,
+ ChangeAnnotationIdentifier: () => ChangeAnnotationIdentifier,
+ CodeAction: () => CodeAction6,
+ CodeActionContext: () => CodeActionContext6,
+ CodeActionKind: () => CodeActionKind6,
+ CodeDescription: () => CodeDescription,
+ CodeLens: () => CodeLens2,
+ Color: () => Color,
+ ColorInformation: () => ColorInformation,
+ ColorPresentation: () => ColorPresentation,
+ Command: () => Command5,
+ CompletionItem: () => CompletionItem4,
+ CompletionItemKind: () => CompletionItemKind3,
+ CompletionItemTag: () => CompletionItemTag2,
+ CompletionList: () => CompletionList3,
+ CreateFile: () => CreateFile,
+ DeleteFile: () => DeleteFile,
+ Diagnostic: () => Diagnostic6,
+ DiagnosticRelatedInformation: () => DiagnosticRelatedInformation2,
+ DiagnosticSeverity: () => DiagnosticSeverity3,
+ DiagnosticTag: () => DiagnosticTag3,
+ DocumentHighlight: () => DocumentHighlight2,
+ DocumentHighlightKind: () => DocumentHighlightKind2,
+ DocumentLink: () => DocumentLink,
+ DocumentSymbol: () => DocumentSymbol2,
+ EOL: () => EOL,
+ FoldingRange: () => FoldingRange2,
+ FoldingRangeKind: () => FoldingRangeKind,
+ FormattingOptions: () => FormattingOptions,
+ Hover: () => Hover,
+ InsertReplaceEdit: () => InsertReplaceEdit,
+ InsertTextFormat: () => InsertTextFormat3,
+ InsertTextMode: () => InsertTextMode,
+ Location: () => Location4,
+ LocationLink: () => LocationLink,
+ MarkedString: () => MarkedString,
+ MarkupContent: () => MarkupContent3,
+ MarkupKind: () => MarkupKind3,
+ OptionalVersionedTextDocumentIdentifier: () => OptionalVersionedTextDocumentIdentifier,
+ ParameterInformation: () => ParameterInformation,
+ Position: () => Position10,
+ Range: () => Range17,
+ RenameFile: () => RenameFile,
+ SelectionRange: () => SelectionRange,
+ SignatureInformation: () => SignatureInformation,
+ SymbolInformation: () => SymbolInformation2,
+ SymbolKind: () => SymbolKind5,
+ SymbolTag: () => SymbolTag4,
+ TextDocument: () => TextDocument13,
+ TextDocumentEdit: () => TextDocumentEdit,
+ TextDocumentIdentifier: () => TextDocumentIdentifier,
+ TextDocumentItem: () => TextDocumentItem,
+ TextEdit: () => TextEdit6,
+ VersionedTextDocumentIdentifier: () => VersionedTextDocumentIdentifier,
+ WorkspaceChange: () => WorkspaceChange,
+ WorkspaceEdit: () => WorkspaceEdit6,
+ integer: () => integer,
+ uinteger: () => uinteger
+ });
+ "use strict";
+ var integer;
+ (function(integer2) {
+ integer2.MIN_VALUE = -2147483648;
+ integer2.MAX_VALUE = 2147483647;
+ })(integer || (integer = {}));
+ var uinteger;
+ (function(uinteger2) {
+ uinteger2.MIN_VALUE = 0;
+ uinteger2.MAX_VALUE = 2147483647;
+ })(uinteger || (uinteger = {}));
+ var Position10;
+ (function(Position11) {
+ function create(line, character) {
+ if (line === Number.MAX_VALUE) {
+ line = uinteger.MAX_VALUE;
+ }
+ if (character === Number.MAX_VALUE) {
+ character = uinteger.MAX_VALUE;
+ }
+ return {line, character};
+ }
+ Position11.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character);
+ }
+ Position11.is = is2;
+ })(Position10 || (Position10 = {}));
+ var Range17;
+ (function(Range18) {
+ function create(one, two, three, four) {
+ if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) {
+ return {start: Position10.create(one, two), end: Position10.create(three, four)};
+ } else if (Position10.is(one) && Position10.is(two)) {
+ return {start: one, end: two};
+ } else {
+ throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
+ }
+ }
+ Range18.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.objectLiteral(candidate) && Position10.is(candidate.start) && Position10.is(candidate.end);
+ }
+ Range18.is = is2;
+ })(Range17 || (Range17 = {}));
+ var Location4;
+ (function(Location5) {
+ function create(uri, range) {
+ return {uri, range};
+ }
+ Location5.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Range17.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
+ }
+ Location5.is = is2;
+ })(Location4 || (Location4 = {}));
+ var LocationLink;
+ (function(LocationLink2) {
+ function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
+ return {targetUri, targetRange, targetSelectionRange, originSelectionRange};
+ }
+ LocationLink2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Range17.is(candidate.targetRange) && Is.string(candidate.targetUri) && (Range17.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange)) && (Range17.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
+ }
+ LocationLink2.is = is2;
+ })(LocationLink || (LocationLink = {}));
+ var Color;
+ (function(Color2) {
+ function create(red, green, blue, alpha) {
+ return {
+ red,
+ green,
+ blue,
+ alpha
+ };
+ }
+ Color2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1);
+ }
+ Color2.is = is2;
+ })(Color || (Color = {}));
+ var ColorInformation;
+ (function(ColorInformation2) {
+ function create(range, color) {
+ return {
+ range,
+ color
+ };
+ }
+ ColorInformation2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Range17.is(candidate.range) && Color.is(candidate.color);
+ }
+ ColorInformation2.is = is2;
+ })(ColorInformation || (ColorInformation = {}));
+ var ColorPresentation;
+ (function(ColorPresentation2) {
+ function create(label, textEdit, additionalTextEdits) {
+ return {
+ label,
+ textEdit,
+ additionalTextEdits
+ };
+ }
+ ColorPresentation2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit6.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit6.is));
+ }
+ ColorPresentation2.is = is2;
+ })(ColorPresentation || (ColorPresentation = {}));
+ var FoldingRangeKind;
+ (function(FoldingRangeKind2) {
+ FoldingRangeKind2["Comment"] = "comment";
+ FoldingRangeKind2["Imports"] = "imports";
+ FoldingRangeKind2["Region"] = "region";
+ })(FoldingRangeKind || (FoldingRangeKind = {}));
+ var FoldingRange2;
+ (function(FoldingRange3) {
+ function create(startLine, endLine, startCharacter, endCharacter, kind) {
+ var result = {
+ startLine,
+ endLine
+ };
+ if (Is.defined(startCharacter)) {
+ result.startCharacter = startCharacter;
+ }
+ if (Is.defined(endCharacter)) {
+ result.endCharacter = endCharacter;
+ }
+ if (Is.defined(kind)) {
+ result.kind = kind;
+ }
+ return result;
+ }
+ FoldingRange3.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
+ }
+ FoldingRange3.is = is2;
+ })(FoldingRange2 || (FoldingRange2 = {}));
+ var DiagnosticRelatedInformation2;
+ (function(DiagnosticRelatedInformation3) {
+ function create(location, message) {
+ return {
+ location,
+ message
+ };
+ }
+ DiagnosticRelatedInformation3.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Location4.is(candidate.location) && Is.string(candidate.message);
+ }
+ DiagnosticRelatedInformation3.is = is2;
+ })(DiagnosticRelatedInformation2 || (DiagnosticRelatedInformation2 = {}));
+ var DiagnosticSeverity3;
+ (function(DiagnosticSeverity4) {
+ DiagnosticSeverity4.Error = 1;
+ DiagnosticSeverity4.Warning = 2;
+ DiagnosticSeverity4.Information = 3;
+ DiagnosticSeverity4.Hint = 4;
+ })(DiagnosticSeverity3 || (DiagnosticSeverity3 = {}));
+ var DiagnosticTag3;
+ (function(DiagnosticTag4) {
+ DiagnosticTag4.Unnecessary = 1;
+ DiagnosticTag4.Deprecated = 2;
+ })(DiagnosticTag3 || (DiagnosticTag3 = {}));
+ var CodeDescription;
+ (function(CodeDescription2) {
+ function is2(value) {
+ var candidate = value;
+ return candidate !== void 0 && candidate !== null && Is.string(candidate.href);
+ }
+ CodeDescription2.is = is2;
+ })(CodeDescription || (CodeDescription = {}));
+ var Diagnostic6;
+ (function(Diagnostic7) {
+ function create(range, message, severity, code, source, relatedInformation) {
+ var result = {range, message};
+ if (Is.defined(severity)) {
+ result.severity = severity;
+ }
+ if (Is.defined(code)) {
+ result.code = code;
+ }
+ if (Is.defined(source)) {
+ result.source = source;
+ }
+ if (Is.defined(relatedInformation)) {
+ result.relatedInformation = relatedInformation;
+ }
+ return result;
+ }
+ Diagnostic7.create = create;
+ function is2(value) {
+ var _a;
+ var candidate = value;
+ return Is.defined(candidate) && Range17.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation2.is));
+ }
+ Diagnostic7.is = is2;
+ })(Diagnostic6 || (Diagnostic6 = {}));
+ var Command5;
+ (function(Command6) {
+ function create(title, command) {
+ var args = [];
+ for (var _i = 2; _i < arguments.length; _i++) {
+ args[_i - 2] = arguments[_i];
+ }
+ var result = {title, command};
+ if (Is.defined(args) && args.length > 0) {
+ result.arguments = args;
+ }
+ return result;
+ }
+ Command6.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
+ }
+ Command6.is = is2;
+ })(Command5 || (Command5 = {}));
+ var TextEdit6;
+ (function(TextEdit7) {
+ function replace(range, newText) {
+ return {range, newText};
+ }
+ TextEdit7.replace = replace;
+ function insert(position, newText) {
+ return {range: {start: position, end: position}, newText};
+ }
+ TextEdit7.insert = insert;
+ function del(range) {
+ return {range, newText: ""};
+ }
+ TextEdit7.del = del;
+ function is2(value) {
+ var candidate = value;
+ return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range17.is(candidate.range);
+ }
+ TextEdit7.is = is2;
+ })(TextEdit6 || (TextEdit6 = {}));
+ var ChangeAnnotation;
+ (function(ChangeAnnotation2) {
+ function create(label, needsConfirmation, description) {
+ var result = {label};
+ if (needsConfirmation !== void 0) {
+ result.needsConfirmation = needsConfirmation;
+ }
+ if (description !== void 0) {
+ result.description = description;
+ }
+ return result;
+ }
+ ChangeAnnotation2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return candidate !== void 0 && Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === void 0) && (Is.string(candidate.description) || candidate.description === void 0);
+ }
+ ChangeAnnotation2.is = is2;
+ })(ChangeAnnotation || (ChangeAnnotation = {}));
+ var ChangeAnnotationIdentifier;
+ (function(ChangeAnnotationIdentifier2) {
+ function is2(value) {
+ var candidate = value;
+ return typeof candidate === "string";
+ }
+ ChangeAnnotationIdentifier2.is = is2;
+ })(ChangeAnnotationIdentifier || (ChangeAnnotationIdentifier = {}));
+ var AnnotatedTextEdit;
+ (function(AnnotatedTextEdit2) {
+ function replace(range, newText, annotation) {
+ return {range, newText, annotationId: annotation};
+ }
+ AnnotatedTextEdit2.replace = replace;
+ function insert(position, newText, annotation) {
+ return {range: {start: position, end: position}, newText, annotationId: annotation};
+ }
+ AnnotatedTextEdit2.insert = insert;
+ function del(range, annotation) {
+ return {range, newText: "", annotationId: annotation};
+ }
+ AnnotatedTextEdit2.del = del;
+ function is2(value) {
+ var candidate = value;
+ return TextEdit6.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId));
+ }
+ AnnotatedTextEdit2.is = is2;
+ })(AnnotatedTextEdit || (AnnotatedTextEdit = {}));
+ var TextDocumentEdit;
+ (function(TextDocumentEdit2) {
+ function create(textDocument, edits) {
+ return {textDocument, edits};
+ }
+ TextDocumentEdit2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits);
+ }
+ TextDocumentEdit2.is = is2;
+ })(TextDocumentEdit || (TextDocumentEdit = {}));
+ var CreateFile;
+ (function(CreateFile2) {
+ function create(uri, options, annotation) {
+ var result = {
+ kind: "create",
+ uri
+ };
+ if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
+ result.options = options;
+ }
+ if (annotation !== void 0) {
+ result.annotationId = annotation;
+ }
+ return result;
+ }
+ CreateFile2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return candidate && candidate.kind === "create" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
+ }
+ CreateFile2.is = is2;
+ })(CreateFile || (CreateFile = {}));
+ var RenameFile;
+ (function(RenameFile2) {
+ function create(oldUri, newUri, options, annotation) {
+ var result = {
+ kind: "rename",
+ oldUri,
+ newUri
+ };
+ if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
+ result.options = options;
+ }
+ if (annotation !== void 0) {
+ result.annotationId = annotation;
+ }
+ return result;
+ }
+ RenameFile2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return candidate && candidate.kind === "rename" && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
+ }
+ RenameFile2.is = is2;
+ })(RenameFile || (RenameFile = {}));
+ var DeleteFile;
+ (function(DeleteFile2) {
+ function create(uri, options, annotation) {
+ var result = {
+ kind: "delete",
+ uri
+ };
+ if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
+ result.options = options;
+ }
+ if (annotation !== void 0) {
+ result.annotationId = annotation;
+ }
+ return result;
+ }
+ DeleteFile2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return candidate && candidate.kind === "delete" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
+ }
+ DeleteFile2.is = is2;
+ })(DeleteFile || (DeleteFile = {}));
+ var WorkspaceEdit6;
+ (function(WorkspaceEdit7) {
+ function is2(value) {
+ var candidate = value;
+ return candidate && (candidate.changes !== void 0 || candidate.documentChanges !== void 0) && (candidate.documentChanges === void 0 || candidate.documentChanges.every(function(change) {
+ if (Is.string(change.kind)) {
+ return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
+ } else {
+ return TextDocumentEdit.is(change);
+ }
+ }));
+ }
+ WorkspaceEdit7.is = is2;
+ })(WorkspaceEdit6 || (WorkspaceEdit6 = {}));
+ var TextEditChangeImpl = function() {
+ function TextEditChangeImpl2(edits, changeAnnotations) {
+ this.edits = edits;
+ this.changeAnnotations = changeAnnotations;
+ }
+ TextEditChangeImpl2.prototype.insert = function(position, newText, annotation) {
+ var edit;
+ var id;
+ if (annotation === void 0) {
+ edit = TextEdit6.insert(position, newText);
+ } else if (ChangeAnnotationIdentifier.is(annotation)) {
+ id = annotation;
+ edit = AnnotatedTextEdit.insert(position, newText, annotation);
+ } else {
+ this.assertChangeAnnotations(this.changeAnnotations);
+ id = this.changeAnnotations.manage(annotation);
+ edit = AnnotatedTextEdit.insert(position, newText, id);
+ }
+ this.edits.push(edit);
+ if (id !== void 0) {
+ return id;
+ }
+ };
+ TextEditChangeImpl2.prototype.replace = function(range, newText, annotation) {
+ var edit;
+ var id;
+ if (annotation === void 0) {
+ edit = TextEdit6.replace(range, newText);
+ } else if (ChangeAnnotationIdentifier.is(annotation)) {
+ id = annotation;
+ edit = AnnotatedTextEdit.replace(range, newText, annotation);
+ } else {
+ this.assertChangeAnnotations(this.changeAnnotations);
+ id = this.changeAnnotations.manage(annotation);
+ edit = AnnotatedTextEdit.replace(range, newText, id);
+ }
+ this.edits.push(edit);
+ if (id !== void 0) {
+ return id;
+ }
+ };
+ TextEditChangeImpl2.prototype.delete = function(range, annotation) {
+ var edit;
+ var id;
+ if (annotation === void 0) {
+ edit = TextEdit6.del(range);
+ } else if (ChangeAnnotationIdentifier.is(annotation)) {
+ id = annotation;
+ edit = AnnotatedTextEdit.del(range, annotation);
+ } else {
+ this.assertChangeAnnotations(this.changeAnnotations);
+ id = this.changeAnnotations.manage(annotation);
+ edit = AnnotatedTextEdit.del(range, id);
+ }
+ this.edits.push(edit);
+ if (id !== void 0) {
+ return id;
+ }
+ };
+ TextEditChangeImpl2.prototype.add = function(edit) {
+ this.edits.push(edit);
+ };
+ TextEditChangeImpl2.prototype.all = function() {
+ return this.edits;
+ };
+ TextEditChangeImpl2.prototype.clear = function() {
+ this.edits.splice(0, this.edits.length);
+ };
+ TextEditChangeImpl2.prototype.assertChangeAnnotations = function(value) {
+ if (value === void 0) {
+ throw new Error("Text edit change is not configured to manage change annotations.");
+ }
+ };
+ return TextEditChangeImpl2;
+ }();
+ var ChangeAnnotations = function() {
+ function ChangeAnnotations2(annotations) {
+ this._annotations = annotations === void 0 ? Object.create(null) : annotations;
+ this._counter = 0;
+ this._size = 0;
+ }
+ ChangeAnnotations2.prototype.all = function() {
+ return this._annotations;
+ };
+ Object.defineProperty(ChangeAnnotations2.prototype, "size", {
+ get: function() {
+ return this._size;
+ },
+ enumerable: false,
+ configurable: true
+ });
+ ChangeAnnotations2.prototype.manage = function(idOrAnnotation, annotation) {
+ var id;
+ if (ChangeAnnotationIdentifier.is(idOrAnnotation)) {
+ id = idOrAnnotation;
+ } else {
+ id = this.nextId();
+ annotation = idOrAnnotation;
+ }
+ if (this._annotations[id] !== void 0) {
+ throw new Error("Id " + id + " is already in use.");
+ }
+ if (annotation === void 0) {
+ throw new Error("No annotation provided for id " + id);
+ }
+ this._annotations[id] = annotation;
+ this._size++;
+ return id;
+ };
+ ChangeAnnotations2.prototype.nextId = function() {
+ this._counter++;
+ return this._counter.toString();
+ };
+ return ChangeAnnotations2;
+ }();
+ var WorkspaceChange = function() {
+ function WorkspaceChange2(workspaceEdit) {
+ var _this = this;
+ this._textEditChanges = Object.create(null);
+ if (workspaceEdit !== void 0) {
+ this._workspaceEdit = workspaceEdit;
+ if (workspaceEdit.documentChanges) {
+ this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations);
+ workspaceEdit.changeAnnotations = this._changeAnnotations.all();
+ workspaceEdit.documentChanges.forEach(function(change) {
+ if (TextDocumentEdit.is(change)) {
+ var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations);
+ _this._textEditChanges[change.textDocument.uri] = textEditChange;
+ }
+ });
+ } else if (workspaceEdit.changes) {
+ Object.keys(workspaceEdit.changes).forEach(function(key) {
+ var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
+ _this._textEditChanges[key] = textEditChange;
+ });
+ }
+ } else {
+ this._workspaceEdit = {};
+ }
+ }
+ Object.defineProperty(WorkspaceChange2.prototype, "edit", {
+ get: function() {
+ this.initDocumentChanges();
+ if (this._changeAnnotations !== void 0) {
+ if (this._changeAnnotations.size === 0) {
+ this._workspaceEdit.changeAnnotations = void 0;
+ } else {
+ this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
+ }
+ }
+ return this._workspaceEdit;
+ },
+ enumerable: false,
+ configurable: true
+ });
+ WorkspaceChange2.prototype.getTextEditChange = function(key) {
+ if (OptionalVersionedTextDocumentIdentifier.is(key)) {
+ this.initDocumentChanges();
+ if (this._workspaceEdit.documentChanges === void 0) {
+ throw new Error("Workspace edit is not configured for document changes.");
+ }
+ var textDocument = {uri: key.uri, version: key.version};
+ var result = this._textEditChanges[textDocument.uri];
+ if (!result) {
+ var edits = [];
+ var textDocumentEdit = {
+ textDocument,
+ edits
+ };
+ this._workspaceEdit.documentChanges.push(textDocumentEdit);
+ result = new TextEditChangeImpl(edits, this._changeAnnotations);
+ this._textEditChanges[textDocument.uri] = result;
+ }
+ return result;
+ } else {
+ this.initChanges();
+ if (this._workspaceEdit.changes === void 0) {
+ throw new Error("Workspace edit is not configured for normal text edit changes.");
+ }
+ var result = this._textEditChanges[key];
+ if (!result) {
+ var edits = [];
+ this._workspaceEdit.changes[key] = edits;
+ result = new TextEditChangeImpl(edits);
+ this._textEditChanges[key] = result;
+ }
+ return result;
+ }
+ };
+ WorkspaceChange2.prototype.initDocumentChanges = function() {
+ if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) {
+ this._changeAnnotations = new ChangeAnnotations();
+ this._workspaceEdit.documentChanges = [];
+ this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
+ }
+ };
+ WorkspaceChange2.prototype.initChanges = function() {
+ if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) {
+ this._workspaceEdit.changes = Object.create(null);
+ }
+ };
+ WorkspaceChange2.prototype.createFile = function(uri, optionsOrAnnotation, options) {
+ this.initDocumentChanges();
+ if (this._workspaceEdit.documentChanges === void 0) {
+ throw new Error("Workspace edit is not configured for document changes.");
+ }
+ var annotation;
+ if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
+ annotation = optionsOrAnnotation;
+ } else {
+ options = optionsOrAnnotation;
+ }
+ var operation;
+ var id;
+ if (annotation === void 0) {
+ operation = CreateFile.create(uri, options);
+ } else {
+ id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
+ operation = CreateFile.create(uri, options, id);
+ }
+ this._workspaceEdit.documentChanges.push(operation);
+ if (id !== void 0) {
+ return id;
+ }
+ };
+ WorkspaceChange2.prototype.renameFile = function(oldUri, newUri, optionsOrAnnotation, options) {
+ this.initDocumentChanges();
+ if (this._workspaceEdit.documentChanges === void 0) {
+ throw new Error("Workspace edit is not configured for document changes.");
+ }
+ var annotation;
+ if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
+ annotation = optionsOrAnnotation;
+ } else {
+ options = optionsOrAnnotation;
+ }
+ var operation;
+ var id;
+ if (annotation === void 0) {
+ operation = RenameFile.create(oldUri, newUri, options);
+ } else {
+ id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
+ operation = RenameFile.create(oldUri, newUri, options, id);
+ }
+ this._workspaceEdit.documentChanges.push(operation);
+ if (id !== void 0) {
+ return id;
+ }
+ };
+ WorkspaceChange2.prototype.deleteFile = function(uri, optionsOrAnnotation, options) {
+ this.initDocumentChanges();
+ if (this._workspaceEdit.documentChanges === void 0) {
+ throw new Error("Workspace edit is not configured for document changes.");
+ }
+ var annotation;
+ if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
+ annotation = optionsOrAnnotation;
+ } else {
+ options = optionsOrAnnotation;
+ }
+ var operation;
+ var id;
+ if (annotation === void 0) {
+ operation = DeleteFile.create(uri, options);
+ } else {
+ id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
+ operation = DeleteFile.create(uri, options, id);
+ }
+ this._workspaceEdit.documentChanges.push(operation);
+ if (id !== void 0) {
+ return id;
+ }
+ };
+ return WorkspaceChange2;
+ }();
+ var TextDocumentIdentifier;
+ (function(TextDocumentIdentifier2) {
+ function create(uri) {
+ return {uri};
+ }
+ TextDocumentIdentifier2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Is.string(candidate.uri);
+ }
+ TextDocumentIdentifier2.is = is2;
+ })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
+ var VersionedTextDocumentIdentifier;
+ (function(VersionedTextDocumentIdentifier2) {
+ function create(uri, version) {
+ return {uri, version};
+ }
+ VersionedTextDocumentIdentifier2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version);
+ }
+ VersionedTextDocumentIdentifier2.is = is2;
+ })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
+ var OptionalVersionedTextDocumentIdentifier;
+ (function(OptionalVersionedTextDocumentIdentifier2) {
+ function create(uri, version) {
+ return {uri, version};
+ }
+ OptionalVersionedTextDocumentIdentifier2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version));
+ }
+ OptionalVersionedTextDocumentIdentifier2.is = is2;
+ })(OptionalVersionedTextDocumentIdentifier || (OptionalVersionedTextDocumentIdentifier = {}));
+ var TextDocumentItem;
+ (function(TextDocumentItem2) {
+ function create(uri, languageId, version, text) {
+ return {uri, languageId, version, text};
+ }
+ TextDocumentItem2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text);
+ }
+ TextDocumentItem2.is = is2;
+ })(TextDocumentItem || (TextDocumentItem = {}));
+ var MarkupKind3;
+ (function(MarkupKind4) {
+ MarkupKind4.PlainText = "plaintext";
+ MarkupKind4.Markdown = "markdown";
+ })(MarkupKind3 || (MarkupKind3 = {}));
+ (function(MarkupKind4) {
+ function is2(value) {
+ var candidate = value;
+ return candidate === MarkupKind4.PlainText || candidate === MarkupKind4.Markdown;
+ }
+ MarkupKind4.is = is2;
+ })(MarkupKind3 || (MarkupKind3 = {}));
+ var MarkupContent3;
+ (function(MarkupContent4) {
+ function is2(value) {
+ var candidate = value;
+ return Is.objectLiteral(value) && MarkupKind3.is(candidate.kind) && Is.string(candidate.value);
+ }
+ MarkupContent4.is = is2;
+ })(MarkupContent3 || (MarkupContent3 = {}));
+ var CompletionItemKind3;
+ (function(CompletionItemKind4) {
+ CompletionItemKind4.Text = 1;
+ CompletionItemKind4.Method = 2;
+ CompletionItemKind4.Function = 3;
+ CompletionItemKind4.Constructor = 4;
+ CompletionItemKind4.Field = 5;
+ CompletionItemKind4.Variable = 6;
+ CompletionItemKind4.Class = 7;
+ CompletionItemKind4.Interface = 8;
+ CompletionItemKind4.Module = 9;
+ CompletionItemKind4.Property = 10;
+ CompletionItemKind4.Unit = 11;
+ CompletionItemKind4.Value = 12;
+ CompletionItemKind4.Enum = 13;
+ CompletionItemKind4.Keyword = 14;
+ CompletionItemKind4.Snippet = 15;
+ CompletionItemKind4.Color = 16;
+ CompletionItemKind4.File = 17;
+ CompletionItemKind4.Reference = 18;
+ CompletionItemKind4.Folder = 19;
+ CompletionItemKind4.EnumMember = 20;
+ CompletionItemKind4.Constant = 21;
+ CompletionItemKind4.Struct = 22;
+ CompletionItemKind4.Event = 23;
+ CompletionItemKind4.Operator = 24;
+ CompletionItemKind4.TypeParameter = 25;
+ })(CompletionItemKind3 || (CompletionItemKind3 = {}));
+ var InsertTextFormat3;
+ (function(InsertTextFormat4) {
+ InsertTextFormat4.PlainText = 1;
+ InsertTextFormat4.Snippet = 2;
+ })(InsertTextFormat3 || (InsertTextFormat3 = {}));
+ var CompletionItemTag2;
+ (function(CompletionItemTag3) {
+ CompletionItemTag3.Deprecated = 1;
+ })(CompletionItemTag2 || (CompletionItemTag2 = {}));
+ var InsertReplaceEdit;
+ (function(InsertReplaceEdit2) {
+ function create(newText, insert, replace) {
+ return {newText, insert, replace};
+ }
+ InsertReplaceEdit2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return candidate && Is.string(candidate.newText) && Range17.is(candidate.insert) && Range17.is(candidate.replace);
+ }
+ InsertReplaceEdit2.is = is2;
+ })(InsertReplaceEdit || (InsertReplaceEdit = {}));
+ var InsertTextMode;
+ (function(InsertTextMode2) {
+ InsertTextMode2.asIs = 1;
+ InsertTextMode2.adjustIndentation = 2;
+ })(InsertTextMode || (InsertTextMode = {}));
+ var CompletionItem4;
+ (function(CompletionItem5) {
+ function create(label) {
+ return {label};
+ }
+ CompletionItem5.create = create;
+ })(CompletionItem4 || (CompletionItem4 = {}));
+ var CompletionList3;
+ (function(CompletionList4) {
+ function create(items, isIncomplete) {
+ return {items: items ? items : [], isIncomplete: !!isIncomplete};
+ }
+ CompletionList4.create = create;
+ })(CompletionList3 || (CompletionList3 = {}));
+ var MarkedString;
+ (function(MarkedString2) {
+ function fromPlainText(plainText) {
+ return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&");
+ }
+ MarkedString2.fromPlainText = fromPlainText;
+ function is2(value) {
+ var candidate = value;
+ return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value);
+ }
+ MarkedString2.is = is2;
+ })(MarkedString || (MarkedString = {}));
+ var Hover;
+ (function(Hover2) {
+ function is2(value) {
+ var candidate = value;
+ return !!candidate && Is.objectLiteral(candidate) && (MarkupContent3.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range17.is(value.range));
+ }
+ Hover2.is = is2;
+ })(Hover || (Hover = {}));
+ var ParameterInformation;
+ (function(ParameterInformation2) {
+ function create(label, documentation) {
+ return documentation ? {label, documentation} : {label};
+ }
+ ParameterInformation2.create = create;
+ })(ParameterInformation || (ParameterInformation = {}));
+ var SignatureInformation;
+ (function(SignatureInformation2) {
+ function create(label, documentation) {
+ var parameters = [];
+ for (var _i = 2; _i < arguments.length; _i++) {
+ parameters[_i - 2] = arguments[_i];
+ }
+ var result = {label};
+ if (Is.defined(documentation)) {
+ result.documentation = documentation;
+ }
+ if (Is.defined(parameters)) {
+ result.parameters = parameters;
+ } else {
+ result.parameters = [];
+ }
+ return result;
+ }
+ SignatureInformation2.create = create;
+ })(SignatureInformation || (SignatureInformation = {}));
+ var DocumentHighlightKind2;
+ (function(DocumentHighlightKind3) {
+ DocumentHighlightKind3.Text = 1;
+ DocumentHighlightKind3.Read = 2;
+ DocumentHighlightKind3.Write = 3;
+ })(DocumentHighlightKind2 || (DocumentHighlightKind2 = {}));
+ var DocumentHighlight2;
+ (function(DocumentHighlight3) {
+ function create(range, kind) {
+ var result = {range};
+ if (Is.number(kind)) {
+ result.kind = kind;
+ }
+ return result;
+ }
+ DocumentHighlight3.create = create;
+ })(DocumentHighlight2 || (DocumentHighlight2 = {}));
+ var SymbolKind5;
+ (function(SymbolKind6) {
+ SymbolKind6.File = 1;
+ SymbolKind6.Module = 2;
+ SymbolKind6.Namespace = 3;
+ SymbolKind6.Package = 4;
+ SymbolKind6.Class = 5;
+ SymbolKind6.Method = 6;
+ SymbolKind6.Property = 7;
+ SymbolKind6.Field = 8;
+ SymbolKind6.Constructor = 9;
+ SymbolKind6.Enum = 10;
+ SymbolKind6.Interface = 11;
+ SymbolKind6.Function = 12;
+ SymbolKind6.Variable = 13;
+ SymbolKind6.Constant = 14;
+ SymbolKind6.String = 15;
+ SymbolKind6.Number = 16;
+ SymbolKind6.Boolean = 17;
+ SymbolKind6.Array = 18;
+ SymbolKind6.Object = 19;
+ SymbolKind6.Key = 20;
+ SymbolKind6.Null = 21;
+ SymbolKind6.EnumMember = 22;
+ SymbolKind6.Struct = 23;
+ SymbolKind6.Event = 24;
+ SymbolKind6.Operator = 25;
+ SymbolKind6.TypeParameter = 26;
+ })(SymbolKind5 || (SymbolKind5 = {}));
+ var SymbolTag4;
+ (function(SymbolTag5) {
+ SymbolTag5.Deprecated = 1;
+ })(SymbolTag4 || (SymbolTag4 = {}));
+ var SymbolInformation2;
+ (function(SymbolInformation3) {
+ function create(name, kind, range, uri, containerName) {
+ var result = {
+ name,
+ kind,
+ location: {uri, range}
+ };
+ if (containerName) {
+ result.containerName = containerName;
+ }
+ return result;
+ }
+ SymbolInformation3.create = create;
+ })(SymbolInformation2 || (SymbolInformation2 = {}));
+ var DocumentSymbol2;
+ (function(DocumentSymbol3) {
+ function create(name, detail, kind, range, selectionRange, children) {
+ var result = {
+ name,
+ detail,
+ kind,
+ range,
+ selectionRange
+ };
+ if (children !== void 0) {
+ result.children = children;
+ }
+ return result;
+ }
+ DocumentSymbol3.create = create;
+ function is2(value) {
+ var candidate = value;
+ return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range17.is(candidate.range) && Range17.is(candidate.selectionRange) && (candidate.detail === void 0 || Is.string(candidate.detail)) && (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) && (candidate.children === void 0 || Array.isArray(candidate.children)) && (candidate.tags === void 0 || Array.isArray(candidate.tags));
+ }
+ DocumentSymbol3.is = is2;
+ })(DocumentSymbol2 || (DocumentSymbol2 = {}));
+ var CodeActionKind6;
+ (function(CodeActionKind7) {
+ CodeActionKind7.Empty = "";
+ CodeActionKind7.QuickFix = "quickfix";
+ CodeActionKind7.Refactor = "refactor";
+ CodeActionKind7.RefactorExtract = "refactor.extract";
+ CodeActionKind7.RefactorInline = "refactor.inline";
+ CodeActionKind7.RefactorRewrite = "refactor.rewrite";
+ CodeActionKind7.Source = "source";
+ CodeActionKind7.SourceOrganizeImports = "source.organizeImports";
+ CodeActionKind7.SourceFixAll = "source.fixAll";
+ })(CodeActionKind6 || (CodeActionKind6 = {}));
+ var CodeActionContext6;
+ (function(CodeActionContext7) {
+ function create(diagnostics, only) {
+ var result = {diagnostics};
+ if (only !== void 0 && only !== null) {
+ result.only = only;
+ }
+ return result;
+ }
+ CodeActionContext7.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic6.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
+ }
+ CodeActionContext7.is = is2;
+ })(CodeActionContext6 || (CodeActionContext6 = {}));
+ var CodeAction6;
+ (function(CodeAction7) {
+ function create(title, kindOrCommandOrEdit, kind) {
+ var result = {title};
+ var checkKind = true;
+ if (typeof kindOrCommandOrEdit === "string") {
+ checkKind = false;
+ result.kind = kindOrCommandOrEdit;
+ } else if (Command5.is(kindOrCommandOrEdit)) {
+ result.command = kindOrCommandOrEdit;
+ } else {
+ result.edit = kindOrCommandOrEdit;
+ }
+ if (checkKind && kind !== void 0) {
+ result.kind = kind;
+ }
+ return result;
+ }
+ CodeAction7.create = create;
+ function is2(value) {
+ var candidate = value;
+ return candidate && Is.string(candidate.title) && (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic6.is)) && (candidate.kind === void 0 || Is.string(candidate.kind)) && (candidate.edit !== void 0 || candidate.command !== void 0) && (candidate.command === void 0 || Command5.is(candidate.command)) && (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) && (candidate.edit === void 0 || WorkspaceEdit6.is(candidate.edit));
+ }
+ CodeAction7.is = is2;
+ })(CodeAction6 || (CodeAction6 = {}));
+ var CodeLens2;
+ (function(CodeLens3) {
+ function create(range, data) {
+ var result = {range};
+ if (Is.defined(data)) {
+ result.data = data;
+ }
+ return result;
+ }
+ CodeLens3.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Range17.is(candidate.range) && (Is.undefined(candidate.command) || Command5.is(candidate.command));
+ }
+ CodeLens3.is = is2;
+ })(CodeLens2 || (CodeLens2 = {}));
+ var FormattingOptions;
+ (function(FormattingOptions2) {
+ function create(tabSize, insertSpaces) {
+ return {tabSize, insertSpaces};
+ }
+ FormattingOptions2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
+ }
+ FormattingOptions2.is = is2;
+ })(FormattingOptions || (FormattingOptions = {}));
+ var DocumentLink;
+ (function(DocumentLink2) {
+ function create(range, target, data) {
+ return {range, target, data};
+ }
+ DocumentLink2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Range17.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
+ }
+ DocumentLink2.is = is2;
+ })(DocumentLink || (DocumentLink = {}));
+ var SelectionRange;
+ (function(SelectionRange2) {
+ function create(range, parent) {
+ return {range, parent};
+ }
+ SelectionRange2.create = create;
+ function is2(value) {
+ var candidate = value;
+ return candidate !== void 0 && Range17.is(candidate.range) && (candidate.parent === void 0 || SelectionRange2.is(candidate.parent));
+ }
+ SelectionRange2.is = is2;
+ })(SelectionRange || (SelectionRange = {}));
+ var EOL = ["\n", "\r\n", "\r"];
+ var TextDocument13;
+ (function(TextDocument14) {
+ function create(uri, languageId, version, content) {
+ return new FullTextDocument(uri, languageId, version, content);
+ }
+ TextDocument14.create = create;
+ function is2(value) {
+ var candidate = value;
+ return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
+ }
+ TextDocument14.is = is2;
+ function applyEdits(document, edits) {
+ var text = document.getText();
+ var sortedEdits = mergeSort(edits, function(a, b) {
+ var diff = a.range.start.line - b.range.start.line;
+ if (diff === 0) {
+ return a.range.start.character - b.range.start.character;
+ }
+ return diff;
+ });
+ var lastModifiedOffset = text.length;
+ for (var i = sortedEdits.length - 1; i >= 0; i--) {
+ var e = sortedEdits[i];
+ var startOffset = document.offsetAt(e.range.start);
+ var endOffset = document.offsetAt(e.range.end);
+ if (endOffset <= lastModifiedOffset) {
+ text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
+ } else {
+ throw new Error("Overlapping edit");
+ }
+ lastModifiedOffset = startOffset;
+ }
+ return text;
+ }
+ TextDocument14.applyEdits = applyEdits;
+ function mergeSort(data, compare) {
+ if (data.length <= 1) {
+ return data;
+ }
+ var p = data.length / 2 | 0;
+ var left = data.slice(0, p);
+ var right = data.slice(p);
+ mergeSort(left, compare);
+ mergeSort(right, compare);
+ var leftIdx = 0;
+ var rightIdx = 0;
+ var i = 0;
+ while (leftIdx < left.length && rightIdx < right.length) {
+ var ret = compare(left[leftIdx], right[rightIdx]);
+ if (ret <= 0) {
+ data[i++] = left[leftIdx++];
+ } else {
+ data[i++] = right[rightIdx++];
+ }
+ }
+ while (leftIdx < left.length) {
+ data[i++] = left[leftIdx++];
+ }
+ while (rightIdx < right.length) {
+ data[i++] = right[rightIdx++];
+ }
+ return data;
+ }
+ })(TextDocument13 || (TextDocument13 = {}));
+ var FullTextDocument = function() {
+ function FullTextDocument2(uri, languageId, version, content) {
+ this._uri = uri;
+ this._languageId = languageId;
+ this._version = version;
+ this._content = content;
+ this._lineOffsets = void 0;
+ }
+ Object.defineProperty(FullTextDocument2.prototype, "uri", {
+ get: function() {
+ return this._uri;
+ },
+ enumerable: false,
+ configurable: true
+ });
+ Object.defineProperty(FullTextDocument2.prototype, "languageId", {
+ get: function() {
+ return this._languageId;
+ },
+ enumerable: false,
+ configurable: true
+ });
+ Object.defineProperty(FullTextDocument2.prototype, "version", {
+ get: function() {
+ return this._version;
+ },
+ enumerable: false,
+ configurable: true
+ });
+ FullTextDocument2.prototype.getText = function(range) {
+ if (range) {
+ var start = this.offsetAt(range.start);
+ var end = this.offsetAt(range.end);
+ return this._content.substring(start, end);
+ }
+ return this._content;
+ };
+ FullTextDocument2.prototype.update = function(event, version) {
+ this._content = event.text;
+ this._version = version;
+ this._lineOffsets = void 0;
+ };
+ FullTextDocument2.prototype.getLineOffsets = function() {
+ if (this._lineOffsets === void 0) {
+ var lineOffsets = [];
+ var text = this._content;
+ var isLineStart = true;
+ for (var i = 0; i < text.length; i++) {
+ if (isLineStart) {
+ lineOffsets.push(i);
+ isLineStart = false;
+ }
+ var ch = text.charAt(i);
+ isLineStart = ch === "\r" || ch === "\n";
+ if (ch === "\r" && i + 1 < text.length && text.charAt(i + 1) === "\n") {
+ i++;
+ }
+ }
+ if (isLineStart && text.length > 0) {
+ lineOffsets.push(text.length);
+ }
+ this._lineOffsets = lineOffsets;
+ }
+ return this._lineOffsets;
+ };
+ FullTextDocument2.prototype.positionAt = function(offset) {
+ offset = Math.max(Math.min(offset, this._content.length), 0);
+ var lineOffsets = this.getLineOffsets();
+ var low = 0, high = lineOffsets.length;
+ if (high === 0) {
+ return Position10.create(0, offset);
+ }
+ while (low < high) {
+ var mid = Math.floor((low + high) / 2);
+ if (lineOffsets[mid] > offset) {
+ high = mid;
+ } else {
+ low = mid + 1;
+ }
+ }
+ var line = low - 1;
+ return Position10.create(line, offset - lineOffsets[line]);
+ };
+ FullTextDocument2.prototype.offsetAt = function(position) {
+ var lineOffsets = this.getLineOffsets();
+ if (position.line >= lineOffsets.length) {
+ return this._content.length;
+ } else if (position.line < 0) {
+ return 0;
+ }
+ var lineOffset = lineOffsets[position.line];
+ var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
+ return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
+ };
+ Object.defineProperty(FullTextDocument2.prototype, "lineCount", {
+ get: function() {
+ return this.getLineOffsets().length;
+ },
+ enumerable: false,
+ configurable: true
+ });
+ return FullTextDocument2;
+ }();
+ var Is;
+ (function(Is2) {
+ var toString2 = Object.prototype.toString;
+ function defined(value) {
+ return typeof value !== "undefined";
+ }
+ Is2.defined = defined;
+ function undefined2(value) {
+ return typeof value === "undefined";
+ }
+ Is2.undefined = undefined2;
+ function boolean2(value) {
+ return value === true || value === false;
+ }
+ Is2.boolean = boolean2;
+ function string2(value) {
+ return toString2.call(value) === "[object String]";
+ }
+ Is2.string = string2;
+ function number(value) {
+ return toString2.call(value) === "[object Number]";
+ }
+ Is2.number = number;
+ function numberRange(value, min, max) {
+ return toString2.call(value) === "[object Number]" && min <= value && value <= max;
+ }
+ Is2.numberRange = numberRange;
+ function integer2(value) {
+ return toString2.call(value) === "[object Number]" && -2147483648 <= value && value <= 2147483647;
+ }
+ Is2.integer = integer2;
+ function uinteger2(value) {
+ return toString2.call(value) === "[object Number]" && 0 <= value && value <= 2147483647;
+ }
+ Is2.uinteger = uinteger2;
+ function func(value) {
+ return toString2.call(value) === "[object Function]";
+ }
+ Is2.func = func;
+ function objectLiteral(value) {
+ return value !== null && typeof value === "object";
+ }
+ Is2.objectLiteral = objectLiteral;
+ function typedArray(value, check) {
+ return Array.isArray(value) && value.every(check);
+ }
+ Is2.typedArray = typedArray;
+ })(Is || (Is = {}));
+});
+
+// node_modules/vscode-languageserver-protocol/lib/common/messages.js
+var require_messages2 = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.ProtocolNotificationType = exports2.ProtocolNotificationType0 = exports2.ProtocolRequestType = exports2.ProtocolRequestType0 = exports2.RegistrationType = void 0;
+ var vscode_jsonrpc_1 = require_main();
+ var RegistrationType = class {
+ constructor(method) {
+ this.method = method;
+ }
+ };
+ exports2.RegistrationType = RegistrationType;
+ var ProtocolRequestType0 = class extends vscode_jsonrpc_1.RequestType0 {
+ constructor(method) {
+ super(method);
+ }
+ };
+ exports2.ProtocolRequestType0 = ProtocolRequestType0;
+ var ProtocolRequestType = class extends vscode_jsonrpc_1.RequestType {
+ constructor(method) {
+ super(method, vscode_jsonrpc_1.ParameterStructures.byName);
+ }
+ };
+ exports2.ProtocolRequestType = ProtocolRequestType;
+ var ProtocolNotificationType0 = class extends vscode_jsonrpc_1.NotificationType0 {
+ constructor(method) {
+ super(method);
+ }
+ };
+ exports2.ProtocolNotificationType0 = ProtocolNotificationType0;
+ var ProtocolNotificationType = class extends vscode_jsonrpc_1.NotificationType {
+ constructor(method) {
+ super(method, vscode_jsonrpc_1.ParameterStructures.byName);
+ }
+ };
+ exports2.ProtocolNotificationType = ProtocolNotificationType;
+});
+
+// node_modules/vscode-languageserver-protocol/lib/common/utils/is.js
+var require_is2 = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.objectLiteral = exports2.typedArray = exports2.stringArray = exports2.array = exports2.func = exports2.error = exports2.number = exports2.string = exports2.boolean = void 0;
+ function boolean2(value) {
+ return value === true || value === false;
}
- return range.test(version)
-}
-module.exports = satisfies
+ exports2.boolean = boolean2;
+ function string2(value) {
+ return typeof value === "string" || value instanceof String;
+ }
+ exports2.string = string2;
+ function number(value) {
+ return typeof value === "number" || value instanceof Number;
+ }
+ exports2.number = number;
+ function error(value) {
+ return value instanceof Error;
+ }
+ exports2.error = error;
+ function func(value) {
+ return typeof value === "function";
+ }
+ exports2.func = func;
+ function array(value) {
+ return Array.isArray(value);
+ }
+ exports2.array = array;
+ function stringArray(value) {
+ return array(value) && value.every((elem) => string2(elem));
+ }
+ exports2.stringArray = stringArray;
+ function typedArray(value, check) {
+ return Array.isArray(value) && value.every(check);
+ }
+ exports2.typedArray = typedArray;
+ function objectLiteral(value) {
+ return value !== null && typeof value === "object";
+ }
+ exports2.objectLiteral = objectLiteral;
+});
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js
+var require_protocol_implementation = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.ImplementationRequest = void 0;
+ var messages_1 = require_messages2();
+ var ImplementationRequest;
+ (function(ImplementationRequest2) {
+ ImplementationRequest2.method = "textDocument/implementation";
+ ImplementationRequest2.type = new messages_1.ProtocolRequestType(ImplementationRequest2.method);
+ })(ImplementationRequest = exports2.ImplementationRequest || (exports2.ImplementationRequest = {}));
+});
-/***/ }),
-/* 73 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js
+var require_protocol_typeDefinition = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.TypeDefinitionRequest = void 0;
+ var messages_1 = require_messages2();
+ var TypeDefinitionRequest;
+ (function(TypeDefinitionRequest2) {
+ TypeDefinitionRequest2.method = "textDocument/typeDefinition";
+ TypeDefinitionRequest2.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest2.method);
+ })(TypeDefinitionRequest = exports2.TypeDefinitionRequest || (exports2.TypeDefinitionRequest = {}));
+});
-const Range = __webpack_require__(71)
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolders.js
+var require_protocol_workspaceFolders = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.DidChangeWorkspaceFoldersNotification = exports2.WorkspaceFoldersRequest = void 0;
+ var messages_1 = require_messages2();
+ var WorkspaceFoldersRequest;
+ (function(WorkspaceFoldersRequest2) {
+ WorkspaceFoldersRequest2.type = new messages_1.ProtocolRequestType0("workspace/workspaceFolders");
+ })(WorkspaceFoldersRequest = exports2.WorkspaceFoldersRequest || (exports2.WorkspaceFoldersRequest = {}));
+ var DidChangeWorkspaceFoldersNotification;
+ (function(DidChangeWorkspaceFoldersNotification2) {
+ DidChangeWorkspaceFoldersNotification2.type = new messages_1.ProtocolNotificationType("workspace/didChangeWorkspaceFolders");
+ })(DidChangeWorkspaceFoldersNotification = exports2.DidChangeWorkspaceFoldersNotification || (exports2.DidChangeWorkspaceFoldersNotification = {}));
+});
-// Mostly just for testing and legacy API reasons
-const toComparators = (range, options) =>
- new Range(range, options).set
- .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js
+var require_protocol_configuration = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.ConfigurationRequest = void 0;
+ var messages_1 = require_messages2();
+ var ConfigurationRequest;
+ (function(ConfigurationRequest2) {
+ ConfigurationRequest2.type = new messages_1.ProtocolRequestType("workspace/configuration");
+ })(ConfigurationRequest = exports2.ConfigurationRequest || (exports2.ConfigurationRequest = {}));
+});
-module.exports = toComparators
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js
+var require_protocol_colorProvider = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.ColorPresentationRequest = exports2.DocumentColorRequest = void 0;
+ var messages_1 = require_messages2();
+ var DocumentColorRequest;
+ (function(DocumentColorRequest2) {
+ DocumentColorRequest2.method = "textDocument/documentColor";
+ DocumentColorRequest2.type = new messages_1.ProtocolRequestType(DocumentColorRequest2.method);
+ })(DocumentColorRequest = exports2.DocumentColorRequest || (exports2.DocumentColorRequest = {}));
+ var ColorPresentationRequest;
+ (function(ColorPresentationRequest2) {
+ ColorPresentationRequest2.type = new messages_1.ProtocolRequestType("textDocument/colorPresentation");
+ })(ColorPresentationRequest = exports2.ColorPresentationRequest || (exports2.ColorPresentationRequest = {}));
+});
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js
+var require_protocol_foldingRange = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.FoldingRangeRequest = exports2.FoldingRangeKind = void 0;
+ var messages_1 = require_messages2();
+ var FoldingRangeKind;
+ (function(FoldingRangeKind2) {
+ FoldingRangeKind2["Comment"] = "comment";
+ FoldingRangeKind2["Imports"] = "imports";
+ FoldingRangeKind2["Region"] = "region";
+ })(FoldingRangeKind = exports2.FoldingRangeKind || (exports2.FoldingRangeKind = {}));
+ var FoldingRangeRequest;
+ (function(FoldingRangeRequest2) {
+ FoldingRangeRequest2.method = "textDocument/foldingRange";
+ FoldingRangeRequest2.type = new messages_1.ProtocolRequestType(FoldingRangeRequest2.method);
+ })(FoldingRangeRequest = exports2.FoldingRangeRequest || (exports2.FoldingRangeRequest = {}));
+});
-/***/ }),
-/* 74 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js
+var require_protocol_declaration = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.DeclarationRequest = void 0;
+ var messages_1 = require_messages2();
+ var DeclarationRequest;
+ (function(DeclarationRequest2) {
+ DeclarationRequest2.method = "textDocument/declaration";
+ DeclarationRequest2.type = new messages_1.ProtocolRequestType(DeclarationRequest2.method);
+ })(DeclarationRequest = exports2.DeclarationRequest || (exports2.DeclarationRequest = {}));
+});
-const SemVer = __webpack_require__(45)
-const Range = __webpack_require__(71)
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js
+var require_protocol_selectionRange = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.SelectionRangeRequest = void 0;
+ var messages_1 = require_messages2();
+ var SelectionRangeRequest;
+ (function(SelectionRangeRequest2) {
+ SelectionRangeRequest2.method = "textDocument/selectionRange";
+ SelectionRangeRequest2.type = new messages_1.ProtocolRequestType(SelectionRangeRequest2.method);
+ })(SelectionRangeRequest = exports2.SelectionRangeRequest || (exports2.SelectionRangeRequest = {}));
+});
-const maxSatisfying = (versions, range, options) => {
- let max = null
- let maxSV = null
- let rangeObj = null
- try {
- rangeObj = new Range(range, options)
- } catch (er) {
- return null
- }
- versions.forEach((v) => {
- if (rangeObj.test(v)) {
- // satisfies(v, range, options)
- if (!max || maxSV.compare(v) === -1) {
- // compare(max, v, true)
- max = v
- maxSV = new SemVer(max, options)
- }
- }
- })
- return max
-}
-module.exports = maxSatisfying
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js
+var require_protocol_progress = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCreateRequest = exports2.WorkDoneProgress = void 0;
+ var vscode_jsonrpc_1 = require_main();
+ var messages_1 = require_messages2();
+ var WorkDoneProgress;
+ (function(WorkDoneProgress2) {
+ WorkDoneProgress2.type = new vscode_jsonrpc_1.ProgressType();
+ function is2(value) {
+ return value === WorkDoneProgress2.type;
+ }
+ WorkDoneProgress2.is = is2;
+ })(WorkDoneProgress = exports2.WorkDoneProgress || (exports2.WorkDoneProgress = {}));
+ var WorkDoneProgressCreateRequest;
+ (function(WorkDoneProgressCreateRequest2) {
+ WorkDoneProgressCreateRequest2.type = new messages_1.ProtocolRequestType("window/workDoneProgress/create");
+ })(WorkDoneProgressCreateRequest = exports2.WorkDoneProgressCreateRequest || (exports2.WorkDoneProgressCreateRequest = {}));
+ var WorkDoneProgressCancelNotification;
+ (function(WorkDoneProgressCancelNotification2) {
+ WorkDoneProgressCancelNotification2.type = new messages_1.ProtocolNotificationType("window/workDoneProgress/cancel");
+ })(WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCancelNotification || (exports2.WorkDoneProgressCancelNotification = {}));
+});
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js
+var require_protocol_callHierarchy = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyIncomingCallsRequest = exports2.CallHierarchyPrepareRequest = void 0;
+ var messages_1 = require_messages2();
+ var CallHierarchyPrepareRequest;
+ (function(CallHierarchyPrepareRequest2) {
+ CallHierarchyPrepareRequest2.method = "textDocument/prepareCallHierarchy";
+ CallHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest2.method);
+ })(CallHierarchyPrepareRequest = exports2.CallHierarchyPrepareRequest || (exports2.CallHierarchyPrepareRequest = {}));
+ var CallHierarchyIncomingCallsRequest;
+ (function(CallHierarchyIncomingCallsRequest2) {
+ CallHierarchyIncomingCallsRequest2.method = "callHierarchy/incomingCalls";
+ CallHierarchyIncomingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest2.method);
+ })(CallHierarchyIncomingCallsRequest = exports2.CallHierarchyIncomingCallsRequest || (exports2.CallHierarchyIncomingCallsRequest = {}));
+ var CallHierarchyOutgoingCallsRequest;
+ (function(CallHierarchyOutgoingCallsRequest2) {
+ CallHierarchyOutgoingCallsRequest2.method = "callHierarchy/outgoingCalls";
+ CallHierarchyOutgoingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest2.method);
+ })(CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyOutgoingCallsRequest || (exports2.CallHierarchyOutgoingCallsRequest = {}));
+});
-/***/ }),
-/* 75 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js
+var require_protocol_semanticTokens = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.SemanticTokensRefreshRequest = exports2.SemanticTokensRangeRequest = exports2.SemanticTokensDeltaRequest = exports2.SemanticTokensRequest = exports2.SemanticTokensRegistrationType = exports2.TokenFormat = exports2.SemanticTokens = exports2.SemanticTokenModifiers = exports2.SemanticTokenTypes = void 0;
+ var messages_1 = require_messages2();
+ var SemanticTokenTypes;
+ (function(SemanticTokenTypes2) {
+ SemanticTokenTypes2["namespace"] = "namespace";
+ SemanticTokenTypes2["type"] = "type";
+ SemanticTokenTypes2["class"] = "class";
+ SemanticTokenTypes2["enum"] = "enum";
+ SemanticTokenTypes2["interface"] = "interface";
+ SemanticTokenTypes2["struct"] = "struct";
+ SemanticTokenTypes2["typeParameter"] = "typeParameter";
+ SemanticTokenTypes2["parameter"] = "parameter";
+ SemanticTokenTypes2["variable"] = "variable";
+ SemanticTokenTypes2["property"] = "property";
+ SemanticTokenTypes2["enumMember"] = "enumMember";
+ SemanticTokenTypes2["event"] = "event";
+ SemanticTokenTypes2["function"] = "function";
+ SemanticTokenTypes2["method"] = "method";
+ SemanticTokenTypes2["macro"] = "macro";
+ SemanticTokenTypes2["keyword"] = "keyword";
+ SemanticTokenTypes2["modifier"] = "modifier";
+ SemanticTokenTypes2["comment"] = "comment";
+ SemanticTokenTypes2["string"] = "string";
+ SemanticTokenTypes2["number"] = "number";
+ SemanticTokenTypes2["regexp"] = "regexp";
+ SemanticTokenTypes2["operator"] = "operator";
+ })(SemanticTokenTypes = exports2.SemanticTokenTypes || (exports2.SemanticTokenTypes = {}));
+ var SemanticTokenModifiers;
+ (function(SemanticTokenModifiers2) {
+ SemanticTokenModifiers2["declaration"] = "declaration";
+ SemanticTokenModifiers2["definition"] = "definition";
+ SemanticTokenModifiers2["readonly"] = "readonly";
+ SemanticTokenModifiers2["static"] = "static";
+ SemanticTokenModifiers2["deprecated"] = "deprecated";
+ SemanticTokenModifiers2["abstract"] = "abstract";
+ SemanticTokenModifiers2["async"] = "async";
+ SemanticTokenModifiers2["modification"] = "modification";
+ SemanticTokenModifiers2["documentation"] = "documentation";
+ SemanticTokenModifiers2["defaultLibrary"] = "defaultLibrary";
+ })(SemanticTokenModifiers = exports2.SemanticTokenModifiers || (exports2.SemanticTokenModifiers = {}));
+ var SemanticTokens;
+ (function(SemanticTokens2) {
+ function is2(value) {
+ const candidate = value;
+ return candidate !== void 0 && (candidate.resultId === void 0 || typeof candidate.resultId === "string") && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === "number");
+ }
+ SemanticTokens2.is = is2;
+ })(SemanticTokens = exports2.SemanticTokens || (exports2.SemanticTokens = {}));
+ var TokenFormat;
+ (function(TokenFormat2) {
+ TokenFormat2.Relative = "relative";
+ })(TokenFormat = exports2.TokenFormat || (exports2.TokenFormat = {}));
+ var SemanticTokensRegistrationType;
+ (function(SemanticTokensRegistrationType2) {
+ SemanticTokensRegistrationType2.method = "textDocument/semanticTokens";
+ SemanticTokensRegistrationType2.type = new messages_1.RegistrationType(SemanticTokensRegistrationType2.method);
+ })(SemanticTokensRegistrationType = exports2.SemanticTokensRegistrationType || (exports2.SemanticTokensRegistrationType = {}));
+ var SemanticTokensRequest;
+ (function(SemanticTokensRequest2) {
+ SemanticTokensRequest2.method = "textDocument/semanticTokens/full";
+ SemanticTokensRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRequest2.method);
+ })(SemanticTokensRequest = exports2.SemanticTokensRequest || (exports2.SemanticTokensRequest = {}));
+ var SemanticTokensDeltaRequest;
+ (function(SemanticTokensDeltaRequest2) {
+ SemanticTokensDeltaRequest2.method = "textDocument/semanticTokens/full/delta";
+ SemanticTokensDeltaRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensDeltaRequest2.method);
+ })(SemanticTokensDeltaRequest = exports2.SemanticTokensDeltaRequest || (exports2.SemanticTokensDeltaRequest = {}));
+ var SemanticTokensRangeRequest;
+ (function(SemanticTokensRangeRequest2) {
+ SemanticTokensRangeRequest2.method = "textDocument/semanticTokens/range";
+ SemanticTokensRangeRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest2.method);
+ })(SemanticTokensRangeRequest = exports2.SemanticTokensRangeRequest || (exports2.SemanticTokensRangeRequest = {}));
+ var SemanticTokensRefreshRequest;
+ (function(SemanticTokensRefreshRequest2) {
+ SemanticTokensRefreshRequest2.method = `workspace/semanticTokens/refresh`;
+ SemanticTokensRefreshRequest2.type = new messages_1.ProtocolRequestType0(SemanticTokensRefreshRequest2.method);
+ })(SemanticTokensRefreshRequest = exports2.SemanticTokensRefreshRequest || (exports2.SemanticTokensRefreshRequest = {}));
+});
-const SemVer = __webpack_require__(45)
-const Range = __webpack_require__(71)
-const minSatisfying = (versions, range, options) => {
- let min = null
- let minSV = null
- let rangeObj = null
- try {
- rangeObj = new Range(range, options)
- } catch (er) {
- return null
- }
- versions.forEach((v) => {
- if (rangeObj.test(v)) {
- // satisfies(v, range, options)
- if (!min || minSV.compare(v) === 1) {
- // compare(min, v, true)
- min = v
- minSV = new SemVer(min, options)
- }
- }
- })
- return min
-}
-module.exports = minSatisfying
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js
+var require_protocol_showDocument = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.ShowDocumentRequest = void 0;
+ var messages_1 = require_messages2();
+ var ShowDocumentRequest;
+ (function(ShowDocumentRequest2) {
+ ShowDocumentRequest2.method = "window/showDocument";
+ ShowDocumentRequest2.type = new messages_1.ProtocolRequestType(ShowDocumentRequest2.method);
+ })(ShowDocumentRequest = exports2.ShowDocumentRequest || (exports2.ShowDocumentRequest = {}));
+});
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js
+var require_protocol_linkedEditingRange = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.LinkedEditingRangeRequest = void 0;
+ var messages_1 = require_messages2();
+ var LinkedEditingRangeRequest;
+ (function(LinkedEditingRangeRequest2) {
+ LinkedEditingRangeRequest2.method = "textDocument/linkedEditingRange";
+ LinkedEditingRangeRequest2.type = new messages_1.ProtocolRequestType(LinkedEditingRangeRequest2.method);
+ })(LinkedEditingRangeRequest = exports2.LinkedEditingRangeRequest || (exports2.LinkedEditingRangeRequest = {}));
+});
-/***/ }),
-/* 76 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js
+var require_protocol_fileOperations = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.WillDeleteFilesRequest = exports2.DidDeleteFilesNotification = exports2.DidRenameFilesNotification = exports2.WillRenameFilesRequest = exports2.DidCreateFilesNotification = exports2.WillCreateFilesRequest = exports2.FileOperationPatternKind = void 0;
+ var messages_1 = require_messages2();
+ var FileOperationPatternKind;
+ (function(FileOperationPatternKind2) {
+ FileOperationPatternKind2.file = "file";
+ FileOperationPatternKind2.folder = "folder";
+ })(FileOperationPatternKind = exports2.FileOperationPatternKind || (exports2.FileOperationPatternKind = {}));
+ var WillCreateFilesRequest;
+ (function(WillCreateFilesRequest2) {
+ WillCreateFilesRequest2.method = "workspace/willCreateFiles";
+ WillCreateFilesRequest2.type = new messages_1.ProtocolRequestType(WillCreateFilesRequest2.method);
+ })(WillCreateFilesRequest = exports2.WillCreateFilesRequest || (exports2.WillCreateFilesRequest = {}));
+ var DidCreateFilesNotification;
+ (function(DidCreateFilesNotification2) {
+ DidCreateFilesNotification2.method = "workspace/didCreateFiles";
+ DidCreateFilesNotification2.type = new messages_1.ProtocolNotificationType(DidCreateFilesNotification2.method);
+ })(DidCreateFilesNotification = exports2.DidCreateFilesNotification || (exports2.DidCreateFilesNotification = {}));
+ var WillRenameFilesRequest;
+ (function(WillRenameFilesRequest2) {
+ WillRenameFilesRequest2.method = "workspace/willRenameFiles";
+ WillRenameFilesRequest2.type = new messages_1.ProtocolRequestType(WillRenameFilesRequest2.method);
+ })(WillRenameFilesRequest = exports2.WillRenameFilesRequest || (exports2.WillRenameFilesRequest = {}));
+ var DidRenameFilesNotification;
+ (function(DidRenameFilesNotification2) {
+ DidRenameFilesNotification2.method = "workspace/didRenameFiles";
+ DidRenameFilesNotification2.type = new messages_1.ProtocolNotificationType(DidRenameFilesNotification2.method);
+ })(DidRenameFilesNotification = exports2.DidRenameFilesNotification || (exports2.DidRenameFilesNotification = {}));
+ var DidDeleteFilesNotification;
+ (function(DidDeleteFilesNotification2) {
+ DidDeleteFilesNotification2.method = "workspace/didDeleteFiles";
+ DidDeleteFilesNotification2.type = new messages_1.ProtocolNotificationType(DidDeleteFilesNotification2.method);
+ })(DidDeleteFilesNotification = exports2.DidDeleteFilesNotification || (exports2.DidDeleteFilesNotification = {}));
+ var WillDeleteFilesRequest;
+ (function(WillDeleteFilesRequest2) {
+ WillDeleteFilesRequest2.method = "workspace/willDeleteFiles";
+ WillDeleteFilesRequest2.type = new messages_1.ProtocolRequestType(WillDeleteFilesRequest2.method);
+ })(WillDeleteFilesRequest = exports2.WillDeleteFilesRequest || (exports2.WillDeleteFilesRequest = {}));
+});
-const SemVer = __webpack_require__(45)
-const Range = __webpack_require__(71)
-const gt = __webpack_require__(63)
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js
+var require_protocol_moniker = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.MonikerRequest = exports2.MonikerKind = exports2.UniquenessLevel = void 0;
+ var messages_1 = require_messages2();
+ var UniquenessLevel;
+ (function(UniquenessLevel2) {
+ UniquenessLevel2["document"] = "document";
+ UniquenessLevel2["project"] = "project";
+ UniquenessLevel2["group"] = "group";
+ UniquenessLevel2["scheme"] = "scheme";
+ UniquenessLevel2["global"] = "global";
+ })(UniquenessLevel = exports2.UniquenessLevel || (exports2.UniquenessLevel = {}));
+ var MonikerKind;
+ (function(MonikerKind2) {
+ MonikerKind2["import"] = "import";
+ MonikerKind2["export"] = "export";
+ MonikerKind2["local"] = "local";
+ })(MonikerKind = exports2.MonikerKind || (exports2.MonikerKind = {}));
+ var MonikerRequest;
+ (function(MonikerRequest2) {
+ MonikerRequest2.method = "textDocument/moniker";
+ MonikerRequest2.type = new messages_1.ProtocolRequestType(MonikerRequest2.method);
+ })(MonikerRequest = exports2.MonikerRequest || (exports2.MonikerRequest = {}));
+});
-const minVersion = (range, loose) => {
- range = new Range(range, loose)
+// node_modules/vscode-languageserver-protocol/lib/common/protocol.js
+var require_protocol = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.DocumentLinkRequest = exports2.CodeLensRefreshRequest = exports2.CodeLensResolveRequest = exports2.CodeLensRequest = exports2.WorkspaceSymbolRequest = exports2.CodeActionResolveRequest = exports2.CodeActionRequest = exports2.DocumentSymbolRequest = exports2.DocumentHighlightRequest = exports2.ReferencesRequest = exports2.DefinitionRequest = exports2.SignatureHelpRequest = exports2.SignatureHelpTriggerKind = exports2.HoverRequest = exports2.CompletionResolveRequest = exports2.CompletionRequest = exports2.CompletionTriggerKind = exports2.PublishDiagnosticsNotification = exports2.WatchKind = exports2.FileChangeType = exports2.DidChangeWatchedFilesNotification = exports2.WillSaveTextDocumentWaitUntilRequest = exports2.WillSaveTextDocumentNotification = exports2.TextDocumentSaveReason = exports2.DidSaveTextDocumentNotification = exports2.DidCloseTextDocumentNotification = exports2.DidChangeTextDocumentNotification = exports2.TextDocumentContentChangeEvent = exports2.DidOpenTextDocumentNotification = exports2.TextDocumentSyncKind = exports2.TelemetryEventNotification = exports2.LogMessageNotification = exports2.ShowMessageRequest = exports2.ShowMessageNotification = exports2.MessageType = exports2.DidChangeConfigurationNotification = exports2.ExitNotification = exports2.ShutdownRequest = exports2.InitializedNotification = exports2.InitializeError = exports2.InitializeRequest = exports2.WorkDoneProgressOptions = exports2.TextDocumentRegistrationOptions = exports2.StaticRegistrationOptions = exports2.FailureHandlingKind = exports2.ResourceOperationKind = exports2.UnregistrationRequest = exports2.RegistrationRequest = exports2.DocumentSelector = exports2.DocumentFilter = void 0;
+ exports2.MonikerRequest = exports2.MonikerKind = exports2.UniquenessLevel = exports2.WillDeleteFilesRequest = exports2.DidDeleteFilesNotification = exports2.WillRenameFilesRequest = exports2.DidRenameFilesNotification = exports2.WillCreateFilesRequest = exports2.DidCreateFilesNotification = exports2.FileOperationPatternKind = exports2.LinkedEditingRangeRequest = exports2.ShowDocumentRequest = exports2.SemanticTokensRegistrationType = exports2.SemanticTokensRefreshRequest = exports2.SemanticTokensRangeRequest = exports2.SemanticTokensDeltaRequest = exports2.SemanticTokensRequest = exports2.TokenFormat = exports2.SemanticTokens = exports2.SemanticTokenModifiers = exports2.SemanticTokenTypes = exports2.CallHierarchyPrepareRequest = exports2.CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyIncomingCallsRequest = exports2.WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCreateRequest = exports2.WorkDoneProgress = exports2.SelectionRangeRequest = exports2.DeclarationRequest = exports2.FoldingRangeRequest = exports2.ColorPresentationRequest = exports2.DocumentColorRequest = exports2.ConfigurationRequest = exports2.DidChangeWorkspaceFoldersNotification = exports2.WorkspaceFoldersRequest = exports2.TypeDefinitionRequest = exports2.ImplementationRequest = exports2.ApplyWorkspaceEditRequest = exports2.ExecuteCommandRequest = exports2.PrepareRenameRequest = exports2.RenameRequest = exports2.PrepareSupportDefaultBehavior = exports2.DocumentOnTypeFormattingRequest = exports2.DocumentRangeFormattingRequest = exports2.DocumentFormattingRequest = exports2.DocumentLinkResolveRequest = void 0;
+ var Is = require_is2();
+ var messages_1 = require_messages2();
+ var protocol_implementation_1 = require_protocol_implementation();
+ Object.defineProperty(exports2, "ImplementationRequest", {enumerable: true, get: function() {
+ return protocol_implementation_1.ImplementationRequest;
+ }});
+ var protocol_typeDefinition_1 = require_protocol_typeDefinition();
+ Object.defineProperty(exports2, "TypeDefinitionRequest", {enumerable: true, get: function() {
+ return protocol_typeDefinition_1.TypeDefinitionRequest;
+ }});
+ var protocol_workspaceFolders_1 = require_protocol_workspaceFolders();
+ Object.defineProperty(exports2, "WorkspaceFoldersRequest", {enumerable: true, get: function() {
+ return protocol_workspaceFolders_1.WorkspaceFoldersRequest;
+ }});
+ Object.defineProperty(exports2, "DidChangeWorkspaceFoldersNotification", {enumerable: true, get: function() {
+ return protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
+ }});
+ var protocol_configuration_1 = require_protocol_configuration();
+ Object.defineProperty(exports2, "ConfigurationRequest", {enumerable: true, get: function() {
+ return protocol_configuration_1.ConfigurationRequest;
+ }});
+ var protocol_colorProvider_1 = require_protocol_colorProvider();
+ Object.defineProperty(exports2, "DocumentColorRequest", {enumerable: true, get: function() {
+ return protocol_colorProvider_1.DocumentColorRequest;
+ }});
+ Object.defineProperty(exports2, "ColorPresentationRequest", {enumerable: true, get: function() {
+ return protocol_colorProvider_1.ColorPresentationRequest;
+ }});
+ var protocol_foldingRange_1 = require_protocol_foldingRange();
+ Object.defineProperty(exports2, "FoldingRangeRequest", {enumerable: true, get: function() {
+ return protocol_foldingRange_1.FoldingRangeRequest;
+ }});
+ var protocol_declaration_1 = require_protocol_declaration();
+ Object.defineProperty(exports2, "DeclarationRequest", {enumerable: true, get: function() {
+ return protocol_declaration_1.DeclarationRequest;
+ }});
+ var protocol_selectionRange_1 = require_protocol_selectionRange();
+ Object.defineProperty(exports2, "SelectionRangeRequest", {enumerable: true, get: function() {
+ return protocol_selectionRange_1.SelectionRangeRequest;
+ }});
+ var protocol_progress_1 = require_protocol_progress();
+ Object.defineProperty(exports2, "WorkDoneProgress", {enumerable: true, get: function() {
+ return protocol_progress_1.WorkDoneProgress;
+ }});
+ Object.defineProperty(exports2, "WorkDoneProgressCreateRequest", {enumerable: true, get: function() {
+ return protocol_progress_1.WorkDoneProgressCreateRequest;
+ }});
+ Object.defineProperty(exports2, "WorkDoneProgressCancelNotification", {enumerable: true, get: function() {
+ return protocol_progress_1.WorkDoneProgressCancelNotification;
+ }});
+ var protocol_callHierarchy_1 = require_protocol_callHierarchy();
+ Object.defineProperty(exports2, "CallHierarchyIncomingCallsRequest", {enumerable: true, get: function() {
+ return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest;
+ }});
+ Object.defineProperty(exports2, "CallHierarchyOutgoingCallsRequest", {enumerable: true, get: function() {
+ return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest;
+ }});
+ Object.defineProperty(exports2, "CallHierarchyPrepareRequest", {enumerable: true, get: function() {
+ return protocol_callHierarchy_1.CallHierarchyPrepareRequest;
+ }});
+ var protocol_semanticTokens_1 = require_protocol_semanticTokens();
+ Object.defineProperty(exports2, "SemanticTokenTypes", {enumerable: true, get: function() {
+ return protocol_semanticTokens_1.SemanticTokenTypes;
+ }});
+ Object.defineProperty(exports2, "SemanticTokenModifiers", {enumerable: true, get: function() {
+ return protocol_semanticTokens_1.SemanticTokenModifiers;
+ }});
+ Object.defineProperty(exports2, "SemanticTokens", {enumerable: true, get: function() {
+ return protocol_semanticTokens_1.SemanticTokens;
+ }});
+ Object.defineProperty(exports2, "TokenFormat", {enumerable: true, get: function() {
+ return protocol_semanticTokens_1.TokenFormat;
+ }});
+ Object.defineProperty(exports2, "SemanticTokensRequest", {enumerable: true, get: function() {
+ return protocol_semanticTokens_1.SemanticTokensRequest;
+ }});
+ Object.defineProperty(exports2, "SemanticTokensDeltaRequest", {enumerable: true, get: function() {
+ return protocol_semanticTokens_1.SemanticTokensDeltaRequest;
+ }});
+ Object.defineProperty(exports2, "SemanticTokensRangeRequest", {enumerable: true, get: function() {
+ return protocol_semanticTokens_1.SemanticTokensRangeRequest;
+ }});
+ Object.defineProperty(exports2, "SemanticTokensRefreshRequest", {enumerable: true, get: function() {
+ return protocol_semanticTokens_1.SemanticTokensRefreshRequest;
+ }});
+ Object.defineProperty(exports2, "SemanticTokensRegistrationType", {enumerable: true, get: function() {
+ return protocol_semanticTokens_1.SemanticTokensRegistrationType;
+ }});
+ var protocol_showDocument_1 = require_protocol_showDocument();
+ Object.defineProperty(exports2, "ShowDocumentRequest", {enumerable: true, get: function() {
+ return protocol_showDocument_1.ShowDocumentRequest;
+ }});
+ var protocol_linkedEditingRange_1 = require_protocol_linkedEditingRange();
+ Object.defineProperty(exports2, "LinkedEditingRangeRequest", {enumerable: true, get: function() {
+ return protocol_linkedEditingRange_1.LinkedEditingRangeRequest;
+ }});
+ var protocol_fileOperations_1 = require_protocol_fileOperations();
+ Object.defineProperty(exports2, "FileOperationPatternKind", {enumerable: true, get: function() {
+ return protocol_fileOperations_1.FileOperationPatternKind;
+ }});
+ Object.defineProperty(exports2, "DidCreateFilesNotification", {enumerable: true, get: function() {
+ return protocol_fileOperations_1.DidCreateFilesNotification;
+ }});
+ Object.defineProperty(exports2, "WillCreateFilesRequest", {enumerable: true, get: function() {
+ return protocol_fileOperations_1.WillCreateFilesRequest;
+ }});
+ Object.defineProperty(exports2, "DidRenameFilesNotification", {enumerable: true, get: function() {
+ return protocol_fileOperations_1.DidRenameFilesNotification;
+ }});
+ Object.defineProperty(exports2, "WillRenameFilesRequest", {enumerable: true, get: function() {
+ return protocol_fileOperations_1.WillRenameFilesRequest;
+ }});
+ Object.defineProperty(exports2, "DidDeleteFilesNotification", {enumerable: true, get: function() {
+ return protocol_fileOperations_1.DidDeleteFilesNotification;
+ }});
+ Object.defineProperty(exports2, "WillDeleteFilesRequest", {enumerable: true, get: function() {
+ return protocol_fileOperations_1.WillDeleteFilesRequest;
+ }});
+ var protocol_moniker_1 = require_protocol_moniker();
+ Object.defineProperty(exports2, "UniquenessLevel", {enumerable: true, get: function() {
+ return protocol_moniker_1.UniquenessLevel;
+ }});
+ Object.defineProperty(exports2, "MonikerKind", {enumerable: true, get: function() {
+ return protocol_moniker_1.MonikerKind;
+ }});
+ Object.defineProperty(exports2, "MonikerRequest", {enumerable: true, get: function() {
+ return protocol_moniker_1.MonikerRequest;
+ }});
+ var DocumentFilter;
+ (function(DocumentFilter2) {
+ function is2(value) {
+ const candidate = value;
+ return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
+ }
+ DocumentFilter2.is = is2;
+ })(DocumentFilter = exports2.DocumentFilter || (exports2.DocumentFilter = {}));
+ var DocumentSelector2;
+ (function(DocumentSelector3) {
+ function is2(value) {
+ if (!Array.isArray(value)) {
+ return false;
+ }
+ for (let elem of value) {
+ if (!Is.string(elem) && !DocumentFilter.is(elem)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ DocumentSelector3.is = is2;
+ })(DocumentSelector2 = exports2.DocumentSelector || (exports2.DocumentSelector = {}));
+ var RegistrationRequest;
+ (function(RegistrationRequest2) {
+ RegistrationRequest2.type = new messages_1.ProtocolRequestType("client/registerCapability");
+ })(RegistrationRequest = exports2.RegistrationRequest || (exports2.RegistrationRequest = {}));
+ var UnregistrationRequest;
+ (function(UnregistrationRequest2) {
+ UnregistrationRequest2.type = new messages_1.ProtocolRequestType("client/unregisterCapability");
+ })(UnregistrationRequest = exports2.UnregistrationRequest || (exports2.UnregistrationRequest = {}));
+ var ResourceOperationKind;
+ (function(ResourceOperationKind2) {
+ ResourceOperationKind2.Create = "create";
+ ResourceOperationKind2.Rename = "rename";
+ ResourceOperationKind2.Delete = "delete";
+ })(ResourceOperationKind = exports2.ResourceOperationKind || (exports2.ResourceOperationKind = {}));
+ var FailureHandlingKind;
+ (function(FailureHandlingKind2) {
+ FailureHandlingKind2.Abort = "abort";
+ FailureHandlingKind2.Transactional = "transactional";
+ FailureHandlingKind2.TextOnlyTransactional = "textOnlyTransactional";
+ FailureHandlingKind2.Undo = "undo";
+ })(FailureHandlingKind = exports2.FailureHandlingKind || (exports2.FailureHandlingKind = {}));
+ var StaticRegistrationOptions;
+ (function(StaticRegistrationOptions2) {
+ function hasId(value) {
+ const candidate = value;
+ return candidate && Is.string(candidate.id) && candidate.id.length > 0;
+ }
+ StaticRegistrationOptions2.hasId = hasId;
+ })(StaticRegistrationOptions = exports2.StaticRegistrationOptions || (exports2.StaticRegistrationOptions = {}));
+ var TextDocumentRegistrationOptions;
+ (function(TextDocumentRegistrationOptions2) {
+ function is2(value) {
+ const candidate = value;
+ return candidate && (candidate.documentSelector === null || DocumentSelector2.is(candidate.documentSelector));
+ }
+ TextDocumentRegistrationOptions2.is = is2;
+ })(TextDocumentRegistrationOptions = exports2.TextDocumentRegistrationOptions || (exports2.TextDocumentRegistrationOptions = {}));
+ var WorkDoneProgressOptions;
+ (function(WorkDoneProgressOptions2) {
+ function is2(value) {
+ const candidate = value;
+ return Is.objectLiteral(candidate) && (candidate.workDoneProgress === void 0 || Is.boolean(candidate.workDoneProgress));
+ }
+ WorkDoneProgressOptions2.is = is2;
+ function hasWorkDoneProgress(value) {
+ const candidate = value;
+ return candidate && Is.boolean(candidate.workDoneProgress);
+ }
+ WorkDoneProgressOptions2.hasWorkDoneProgress = hasWorkDoneProgress;
+ })(WorkDoneProgressOptions = exports2.WorkDoneProgressOptions || (exports2.WorkDoneProgressOptions = {}));
+ var InitializeRequest;
+ (function(InitializeRequest2) {
+ InitializeRequest2.type = new messages_1.ProtocolRequestType("initialize");
+ })(InitializeRequest = exports2.InitializeRequest || (exports2.InitializeRequest = {}));
+ var InitializeError;
+ (function(InitializeError2) {
+ InitializeError2.unknownProtocolVersion = 1;
+ })(InitializeError = exports2.InitializeError || (exports2.InitializeError = {}));
+ var InitializedNotification;
+ (function(InitializedNotification2) {
+ InitializedNotification2.type = new messages_1.ProtocolNotificationType("initialized");
+ })(InitializedNotification = exports2.InitializedNotification || (exports2.InitializedNotification = {}));
+ var ShutdownRequest;
+ (function(ShutdownRequest2) {
+ ShutdownRequest2.type = new messages_1.ProtocolRequestType0("shutdown");
+ })(ShutdownRequest = exports2.ShutdownRequest || (exports2.ShutdownRequest = {}));
+ var ExitNotification;
+ (function(ExitNotification2) {
+ ExitNotification2.type = new messages_1.ProtocolNotificationType0("exit");
+ })(ExitNotification = exports2.ExitNotification || (exports2.ExitNotification = {}));
+ var DidChangeConfigurationNotification;
+ (function(DidChangeConfigurationNotification2) {
+ DidChangeConfigurationNotification2.type = new messages_1.ProtocolNotificationType("workspace/didChangeConfiguration");
+ })(DidChangeConfigurationNotification = exports2.DidChangeConfigurationNotification || (exports2.DidChangeConfigurationNotification = {}));
+ var MessageType;
+ (function(MessageType2) {
+ MessageType2.Error = 1;
+ MessageType2.Warning = 2;
+ MessageType2.Info = 3;
+ MessageType2.Log = 4;
+ })(MessageType = exports2.MessageType || (exports2.MessageType = {}));
+ var ShowMessageNotification;
+ (function(ShowMessageNotification2) {
+ ShowMessageNotification2.type = new messages_1.ProtocolNotificationType("window/showMessage");
+ })(ShowMessageNotification = exports2.ShowMessageNotification || (exports2.ShowMessageNotification = {}));
+ var ShowMessageRequest;
+ (function(ShowMessageRequest2) {
+ ShowMessageRequest2.type = new messages_1.ProtocolRequestType("window/showMessageRequest");
+ })(ShowMessageRequest = exports2.ShowMessageRequest || (exports2.ShowMessageRequest = {}));
+ var LogMessageNotification;
+ (function(LogMessageNotification2) {
+ LogMessageNotification2.type = new messages_1.ProtocolNotificationType("window/logMessage");
+ })(LogMessageNotification = exports2.LogMessageNotification || (exports2.LogMessageNotification = {}));
+ var TelemetryEventNotification;
+ (function(TelemetryEventNotification2) {
+ TelemetryEventNotification2.type = new messages_1.ProtocolNotificationType("telemetry/event");
+ })(TelemetryEventNotification = exports2.TelemetryEventNotification || (exports2.TelemetryEventNotification = {}));
+ var TextDocumentSyncKind;
+ (function(TextDocumentSyncKind2) {
+ TextDocumentSyncKind2.None = 0;
+ TextDocumentSyncKind2.Full = 1;
+ TextDocumentSyncKind2.Incremental = 2;
+ })(TextDocumentSyncKind = exports2.TextDocumentSyncKind || (exports2.TextDocumentSyncKind = {}));
+ var DidOpenTextDocumentNotification;
+ (function(DidOpenTextDocumentNotification2) {
+ DidOpenTextDocumentNotification2.method = "textDocument/didOpen";
+ DidOpenTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification2.method);
+ })(DidOpenTextDocumentNotification = exports2.DidOpenTextDocumentNotification || (exports2.DidOpenTextDocumentNotification = {}));
+ var TextDocumentContentChangeEvent2;
+ (function(TextDocumentContentChangeEvent3) {
+ function isIncremental(event) {
+ let candidate = event;
+ return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range !== void 0 && (candidate.rangeLength === void 0 || typeof candidate.rangeLength === "number");
+ }
+ TextDocumentContentChangeEvent3.isIncremental = isIncremental;
+ function isFull(event) {
+ let candidate = event;
+ return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range === void 0 && candidate.rangeLength === void 0;
+ }
+ TextDocumentContentChangeEvent3.isFull = isFull;
+ })(TextDocumentContentChangeEvent2 = exports2.TextDocumentContentChangeEvent || (exports2.TextDocumentContentChangeEvent = {}));
+ var DidChangeTextDocumentNotification;
+ (function(DidChangeTextDocumentNotification2) {
+ DidChangeTextDocumentNotification2.method = "textDocument/didChange";
+ DidChangeTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification2.method);
+ })(DidChangeTextDocumentNotification = exports2.DidChangeTextDocumentNotification || (exports2.DidChangeTextDocumentNotification = {}));
+ var DidCloseTextDocumentNotification;
+ (function(DidCloseTextDocumentNotification2) {
+ DidCloseTextDocumentNotification2.method = "textDocument/didClose";
+ DidCloseTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification2.method);
+ })(DidCloseTextDocumentNotification = exports2.DidCloseTextDocumentNotification || (exports2.DidCloseTextDocumentNotification = {}));
+ var DidSaveTextDocumentNotification;
+ (function(DidSaveTextDocumentNotification2) {
+ DidSaveTextDocumentNotification2.method = "textDocument/didSave";
+ DidSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification2.method);
+ })(DidSaveTextDocumentNotification = exports2.DidSaveTextDocumentNotification || (exports2.DidSaveTextDocumentNotification = {}));
+ var TextDocumentSaveReason;
+ (function(TextDocumentSaveReason2) {
+ TextDocumentSaveReason2.Manual = 1;
+ TextDocumentSaveReason2.AfterDelay = 2;
+ TextDocumentSaveReason2.FocusOut = 3;
+ })(TextDocumentSaveReason = exports2.TextDocumentSaveReason || (exports2.TextDocumentSaveReason = {}));
+ var WillSaveTextDocumentNotification;
+ (function(WillSaveTextDocumentNotification2) {
+ WillSaveTextDocumentNotification2.method = "textDocument/willSave";
+ WillSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification2.method);
+ })(WillSaveTextDocumentNotification = exports2.WillSaveTextDocumentNotification || (exports2.WillSaveTextDocumentNotification = {}));
+ var WillSaveTextDocumentWaitUntilRequest;
+ (function(WillSaveTextDocumentWaitUntilRequest2) {
+ WillSaveTextDocumentWaitUntilRequest2.method = "textDocument/willSaveWaitUntil";
+ WillSaveTextDocumentWaitUntilRequest2.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest2.method);
+ })(WillSaveTextDocumentWaitUntilRequest = exports2.WillSaveTextDocumentWaitUntilRequest || (exports2.WillSaveTextDocumentWaitUntilRequest = {}));
+ var DidChangeWatchedFilesNotification;
+ (function(DidChangeWatchedFilesNotification2) {
+ DidChangeWatchedFilesNotification2.type = new messages_1.ProtocolNotificationType("workspace/didChangeWatchedFiles");
+ })(DidChangeWatchedFilesNotification = exports2.DidChangeWatchedFilesNotification || (exports2.DidChangeWatchedFilesNotification = {}));
+ var FileChangeType;
+ (function(FileChangeType2) {
+ FileChangeType2.Created = 1;
+ FileChangeType2.Changed = 2;
+ FileChangeType2.Deleted = 3;
+ })(FileChangeType = exports2.FileChangeType || (exports2.FileChangeType = {}));
+ var WatchKind;
+ (function(WatchKind2) {
+ WatchKind2.Create = 1;
+ WatchKind2.Change = 2;
+ WatchKind2.Delete = 4;
+ })(WatchKind = exports2.WatchKind || (exports2.WatchKind = {}));
+ var PublishDiagnosticsNotification;
+ (function(PublishDiagnosticsNotification2) {
+ PublishDiagnosticsNotification2.type = new messages_1.ProtocolNotificationType("textDocument/publishDiagnostics");
+ })(PublishDiagnosticsNotification = exports2.PublishDiagnosticsNotification || (exports2.PublishDiagnosticsNotification = {}));
+ var CompletionTriggerKind;
+ (function(CompletionTriggerKind2) {
+ CompletionTriggerKind2.Invoked = 1;
+ CompletionTriggerKind2.TriggerCharacter = 2;
+ CompletionTriggerKind2.TriggerForIncompleteCompletions = 3;
+ })(CompletionTriggerKind = exports2.CompletionTriggerKind || (exports2.CompletionTriggerKind = {}));
+ var CompletionRequest;
+ (function(CompletionRequest2) {
+ CompletionRequest2.method = "textDocument/completion";
+ CompletionRequest2.type = new messages_1.ProtocolRequestType(CompletionRequest2.method);
+ })(CompletionRequest = exports2.CompletionRequest || (exports2.CompletionRequest = {}));
+ var CompletionResolveRequest;
+ (function(CompletionResolveRequest2) {
+ CompletionResolveRequest2.method = "completionItem/resolve";
+ CompletionResolveRequest2.type = new messages_1.ProtocolRequestType(CompletionResolveRequest2.method);
+ })(CompletionResolveRequest = exports2.CompletionResolveRequest || (exports2.CompletionResolveRequest = {}));
+ var HoverRequest;
+ (function(HoverRequest2) {
+ HoverRequest2.method = "textDocument/hover";
+ HoverRequest2.type = new messages_1.ProtocolRequestType(HoverRequest2.method);
+ })(HoverRequest = exports2.HoverRequest || (exports2.HoverRequest = {}));
+ var SignatureHelpTriggerKind;
+ (function(SignatureHelpTriggerKind2) {
+ SignatureHelpTriggerKind2.Invoked = 1;
+ SignatureHelpTriggerKind2.TriggerCharacter = 2;
+ SignatureHelpTriggerKind2.ContentChange = 3;
+ })(SignatureHelpTriggerKind = exports2.SignatureHelpTriggerKind || (exports2.SignatureHelpTriggerKind = {}));
+ var SignatureHelpRequest;
+ (function(SignatureHelpRequest2) {
+ SignatureHelpRequest2.method = "textDocument/signatureHelp";
+ SignatureHelpRequest2.type = new messages_1.ProtocolRequestType(SignatureHelpRequest2.method);
+ })(SignatureHelpRequest = exports2.SignatureHelpRequest || (exports2.SignatureHelpRequest = {}));
+ var DefinitionRequest;
+ (function(DefinitionRequest2) {
+ DefinitionRequest2.method = "textDocument/definition";
+ DefinitionRequest2.type = new messages_1.ProtocolRequestType(DefinitionRequest2.method);
+ })(DefinitionRequest = exports2.DefinitionRequest || (exports2.DefinitionRequest = {}));
+ var ReferencesRequest;
+ (function(ReferencesRequest2) {
+ ReferencesRequest2.method = "textDocument/references";
+ ReferencesRequest2.type = new messages_1.ProtocolRequestType(ReferencesRequest2.method);
+ })(ReferencesRequest = exports2.ReferencesRequest || (exports2.ReferencesRequest = {}));
+ var DocumentHighlightRequest;
+ (function(DocumentHighlightRequest2) {
+ DocumentHighlightRequest2.method = "textDocument/documentHighlight";
+ DocumentHighlightRequest2.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest2.method);
+ })(DocumentHighlightRequest = exports2.DocumentHighlightRequest || (exports2.DocumentHighlightRequest = {}));
+ var DocumentSymbolRequest;
+ (function(DocumentSymbolRequest2) {
+ DocumentSymbolRequest2.method = "textDocument/documentSymbol";
+ DocumentSymbolRequest2.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest2.method);
+ })(DocumentSymbolRequest = exports2.DocumentSymbolRequest || (exports2.DocumentSymbolRequest = {}));
+ var CodeActionRequest;
+ (function(CodeActionRequest2) {
+ CodeActionRequest2.method = "textDocument/codeAction";
+ CodeActionRequest2.type = new messages_1.ProtocolRequestType(CodeActionRequest2.method);
+ })(CodeActionRequest = exports2.CodeActionRequest || (exports2.CodeActionRequest = {}));
+ var CodeActionResolveRequest;
+ (function(CodeActionResolveRequest2) {
+ CodeActionResolveRequest2.method = "codeAction/resolve";
+ CodeActionResolveRequest2.type = new messages_1.ProtocolRequestType(CodeActionResolveRequest2.method);
+ })(CodeActionResolveRequest = exports2.CodeActionResolveRequest || (exports2.CodeActionResolveRequest = {}));
+ var WorkspaceSymbolRequest;
+ (function(WorkspaceSymbolRequest2) {
+ WorkspaceSymbolRequest2.method = "workspace/symbol";
+ WorkspaceSymbolRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest2.method);
+ })(WorkspaceSymbolRequest = exports2.WorkspaceSymbolRequest || (exports2.WorkspaceSymbolRequest = {}));
+ var CodeLensRequest;
+ (function(CodeLensRequest2) {
+ CodeLensRequest2.method = "textDocument/codeLens";
+ CodeLensRequest2.type = new messages_1.ProtocolRequestType(CodeLensRequest2.method);
+ })(CodeLensRequest = exports2.CodeLensRequest || (exports2.CodeLensRequest = {}));
+ var CodeLensResolveRequest;
+ (function(CodeLensResolveRequest2) {
+ CodeLensResolveRequest2.method = "codeLens/resolve";
+ CodeLensResolveRequest2.type = new messages_1.ProtocolRequestType(CodeLensResolveRequest2.method);
+ })(CodeLensResolveRequest = exports2.CodeLensResolveRequest || (exports2.CodeLensResolveRequest = {}));
+ var CodeLensRefreshRequest;
+ (function(CodeLensRefreshRequest2) {
+ CodeLensRefreshRequest2.method = `workspace/codeLens/refresh`;
+ CodeLensRefreshRequest2.type = new messages_1.ProtocolRequestType0(CodeLensRefreshRequest2.method);
+ })(CodeLensRefreshRequest = exports2.CodeLensRefreshRequest || (exports2.CodeLensRefreshRequest = {}));
+ var DocumentLinkRequest;
+ (function(DocumentLinkRequest2) {
+ DocumentLinkRequest2.method = "textDocument/documentLink";
+ DocumentLinkRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkRequest2.method);
+ })(DocumentLinkRequest = exports2.DocumentLinkRequest || (exports2.DocumentLinkRequest = {}));
+ var DocumentLinkResolveRequest;
+ (function(DocumentLinkResolveRequest2) {
+ DocumentLinkResolveRequest2.method = "documentLink/resolve";
+ DocumentLinkResolveRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkResolveRequest2.method);
+ })(DocumentLinkResolveRequest = exports2.DocumentLinkResolveRequest || (exports2.DocumentLinkResolveRequest = {}));
+ var DocumentFormattingRequest;
+ (function(DocumentFormattingRequest2) {
+ DocumentFormattingRequest2.method = "textDocument/formatting";
+ DocumentFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest2.method);
+ })(DocumentFormattingRequest = exports2.DocumentFormattingRequest || (exports2.DocumentFormattingRequest = {}));
+ var DocumentRangeFormattingRequest;
+ (function(DocumentRangeFormattingRequest2) {
+ DocumentRangeFormattingRequest2.method = "textDocument/rangeFormatting";
+ DocumentRangeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest2.method);
+ })(DocumentRangeFormattingRequest = exports2.DocumentRangeFormattingRequest || (exports2.DocumentRangeFormattingRequest = {}));
+ var DocumentOnTypeFormattingRequest;
+ (function(DocumentOnTypeFormattingRequest2) {
+ DocumentOnTypeFormattingRequest2.method = "textDocument/onTypeFormatting";
+ DocumentOnTypeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest2.method);
+ })(DocumentOnTypeFormattingRequest = exports2.DocumentOnTypeFormattingRequest || (exports2.DocumentOnTypeFormattingRequest = {}));
+ var PrepareSupportDefaultBehavior;
+ (function(PrepareSupportDefaultBehavior2) {
+ PrepareSupportDefaultBehavior2.Identifier = 1;
+ })(PrepareSupportDefaultBehavior = exports2.PrepareSupportDefaultBehavior || (exports2.PrepareSupportDefaultBehavior = {}));
+ var RenameRequest;
+ (function(RenameRequest2) {
+ RenameRequest2.method = "textDocument/rename";
+ RenameRequest2.type = new messages_1.ProtocolRequestType(RenameRequest2.method);
+ })(RenameRequest = exports2.RenameRequest || (exports2.RenameRequest = {}));
+ var PrepareRenameRequest;
+ (function(PrepareRenameRequest2) {
+ PrepareRenameRequest2.method = "textDocument/prepareRename";
+ PrepareRenameRequest2.type = new messages_1.ProtocolRequestType(PrepareRenameRequest2.method);
+ })(PrepareRenameRequest = exports2.PrepareRenameRequest || (exports2.PrepareRenameRequest = {}));
+ var ExecuteCommandRequest;
+ (function(ExecuteCommandRequest2) {
+ ExecuteCommandRequest2.type = new messages_1.ProtocolRequestType("workspace/executeCommand");
+ })(ExecuteCommandRequest = exports2.ExecuteCommandRequest || (exports2.ExecuteCommandRequest = {}));
+ var ApplyWorkspaceEditRequest;
+ (function(ApplyWorkspaceEditRequest2) {
+ ApplyWorkspaceEditRequest2.type = new messages_1.ProtocolRequestType("workspace/applyEdit");
+ })(ApplyWorkspaceEditRequest = exports2.ApplyWorkspaceEditRequest || (exports2.ApplyWorkspaceEditRequest = {}));
+});
- let minver = new SemVer('0.0.0')
- if (range.test(minver)) {
- return minver
+// node_modules/vscode-languageserver-protocol/lib/common/connection.js
+var require_connection2 = __commonJS((exports2) => {
+ "use strict";
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.createProtocolConnection = void 0;
+ var vscode_jsonrpc_1 = require_main();
+ function createProtocolConnection(input, output, logger, options) {
+ if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) {
+ options = {connectionStrategy: options};
+ }
+ return vscode_jsonrpc_1.createMessageConnection(input, output, logger, options);
}
+ exports2.createProtocolConnection = createProtocolConnection;
+});
- minver = new SemVer('0.0.0-0')
- if (range.test(minver)) {
- return minver
+// node_modules/vscode-languageserver-protocol/lib/common/api.js
+var require_api2 = __commonJS((exports2) => {
+ "use strict";
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
+ if (k2 === void 0)
+ k2 = k;
+ Object.defineProperty(o, k2, {enumerable: true, get: function() {
+ return m[k];
+ }});
+ } : function(o, m, k, k2) {
+ if (k2 === void 0)
+ k2 = k;
+ o[k2] = m[k];
+ });
+ var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
+ for (var p in m)
+ if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p))
+ __createBinding(exports3, m, p);
+ };
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.LSPErrorCodes = exports2.createProtocolConnection = void 0;
+ __exportStar2(require_main(), exports2);
+ __exportStar2(require_main2(), exports2);
+ __exportStar2(require_messages2(), exports2);
+ __exportStar2(require_protocol(), exports2);
+ var connection_1 = require_connection2();
+ Object.defineProperty(exports2, "createProtocolConnection", {enumerable: true, get: function() {
+ return connection_1.createProtocolConnection;
+ }});
+ var LSPErrorCodes;
+ (function(LSPErrorCodes2) {
+ LSPErrorCodes2.lspReservedErrorRangeStart = -32899;
+ LSPErrorCodes2.ContentModified = -32801;
+ LSPErrorCodes2.RequestCancelled = -32800;
+ LSPErrorCodes2.lspReservedErrorRangeEnd = -32800;
+ })(LSPErrorCodes = exports2.LSPErrorCodes || (exports2.LSPErrorCodes = {}));
+});
+
+// node_modules/vscode-languageserver-protocol/lib/node/main.js
+var require_main3 = __commonJS((exports2) => {
+ "use strict";
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
+ if (k2 === void 0)
+ k2 = k;
+ Object.defineProperty(o, k2, {enumerable: true, get: function() {
+ return m[k];
+ }});
+ } : function(o, m, k, k2) {
+ if (k2 === void 0)
+ k2 = k;
+ o[k2] = m[k];
+ });
+ var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
+ for (var p in m)
+ if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p))
+ __createBinding(exports3, m, p);
+ };
+ Object.defineProperty(exports2, "__esModule", {value: true});
+ exports2.createProtocolConnection = void 0;
+ var node_1 = require_node();
+ __exportStar2(require_node(), exports2);
+ __exportStar2(require_api2(), exports2);
+ function createProtocolConnection(input, output, logger, options) {
+ return node_1.createMessageConnection(input, output, logger, options);
}
+ exports2.createProtocolConnection = createProtocolConnection;
+});
+
+// node_modules/semver/internal/constants.js
+var require_constants = __commonJS((exports2, module2) => {
+ var SEMVER_SPEC_VERSION = "2.0.0";
+ var MAX_LENGTH = 256;
+ var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
+ var MAX_SAFE_COMPONENT_LENGTH = 16;
+ module2.exports = {
+ SEMVER_SPEC_VERSION,
+ MAX_LENGTH,
+ MAX_SAFE_INTEGER,
+ MAX_SAFE_COMPONENT_LENGTH
+ };
+});
+
+// node_modules/semver/internal/debug.js
+var require_debug = __commonJS((exports2, module2) => {
+ var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
+ };
+ module2.exports = debug;
+});
- minver = null
- for (let i = 0; i < range.set.length; ++i) {
- const comparators = range.set[i]
+// node_modules/semver/internal/re.js
+var require_re = __commonJS((exports2, module2) => {
+ var {MAX_SAFE_COMPONENT_LENGTH} = require_constants();
+ var debug = require_debug();
+ exports2 = module2.exports = {};
+ var re = exports2.re = [];
+ var src = exports2.src = [];
+ var t = exports2.t = {};
+ var R = 0;
+ var createToken = (name, value, isGlobal) => {
+ const index = R++;
+ debug(index, value);
+ t[name] = index;
+ src[index] = value;
+ re[index] = new RegExp(value, isGlobal ? "g" : void 0);
+ };
+ createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
+ createToken("NUMERICIDENTIFIERLOOSE", "[0-9]+");
+ createToken("NONNUMERICIDENTIFIER", "\\d*[a-zA-Z-][a-zA-Z0-9-]*");
+ createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);
+ createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);
+ createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`);
+ createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`);
+ createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
+ createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
+ createToken("BUILDIDENTIFIER", "[0-9A-Za-z-]+");
+ createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
+ createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
+ createToken("FULL", `^${src[t.FULLPLAIN]}$`);
+ createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
+ createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);
+ createToken("GTLT", "((?:<|>)?=?)");
+ createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
+ createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
+ createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);
+ createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);
+ createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
+ createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
+ createToken("COERCE", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:$|[^\\d])`);
+ createToken("COERCERTL", src[t.COERCE], true);
+ createToken("LONETILDE", "(?:~>?)");
+ createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);
+ exports2.tildeTrimReplace = "$1~";
+ createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
+ createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
+ createToken("LONECARET", "(?:\\^)");
+ createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);
+ exports2.caretTrimReplace = "$1^";
+ createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
+ createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
+ createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
+ createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
+ createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
+ exports2.comparatorTrimReplace = "$1$2$3";
+ createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);
+ createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);
+ createToken("STAR", "(<|>)?=?\\s*\\*");
+ createToken("GTE0", "^\\s*>=\\s*0.0.0\\s*$");
+ createToken("GTE0PRE", "^\\s*>=\\s*0.0.0-0\\s*$");
+});
- comparators.forEach((comparator) => {
- // Clone to avoid manipulating the comparator's semver object.
- const compver = new SemVer(comparator.semver.version)
- switch (comparator.operator) {
- case '>':
- if (compver.prerelease.length === 0) {
- compver.patch++
+// node_modules/semver/internal/identifiers.js
+var require_identifiers = __commonJS((exports2, module2) => {
+ var numeric = /^[0-9]+$/;
+ var compareIdentifiers = (a, b) => {
+ const anum = numeric.test(a);
+ const bnum = numeric.test(b);
+ if (anum && bnum) {
+ a = +a;
+ b = +b;
+ }
+ return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
+ };
+ var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
+ module2.exports = {
+ compareIdentifiers,
+ rcompareIdentifiers
+ };
+});
+
+// node_modules/semver/classes/semver.js
+var require_semver = __commonJS((exports2, module2) => {
+ var debug = require_debug();
+ var {MAX_LENGTH, MAX_SAFE_INTEGER} = require_constants();
+ var {re, t} = require_re();
+ var {compareIdentifiers} = require_identifiers();
+ var SemVer = class {
+ constructor(version, options) {
+ if (!options || typeof options !== "object") {
+ options = {
+ loose: !!options,
+ includePrerelease: false
+ };
+ }
+ if (version instanceof SemVer) {
+ if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
+ return version;
+ } else {
+ version = version.version;
+ }
+ } else if (typeof version !== "string") {
+ throw new TypeError(`Invalid Version: ${version}`);
+ }
+ if (version.length > MAX_LENGTH) {
+ throw new TypeError(`version is longer than ${MAX_LENGTH} characters`);
+ }
+ debug("SemVer", version, options);
+ this.options = options;
+ this.loose = !!options.loose;
+ this.includePrerelease = !!options.includePrerelease;
+ const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
+ if (!m) {
+ throw new TypeError(`Invalid Version: ${version}`);
+ }
+ this.raw = version;
+ this.major = +m[1];
+ this.minor = +m[2];
+ this.patch = +m[3];
+ if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
+ throw new TypeError("Invalid major version");
+ }
+ if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
+ throw new TypeError("Invalid minor version");
+ }
+ if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
+ throw new TypeError("Invalid patch version");
+ }
+ if (!m[4]) {
+ this.prerelease = [];
+ } else {
+ this.prerelease = m[4].split(".").map((id) => {
+ if (/^[0-9]+$/.test(id)) {
+ const num = +id;
+ if (num >= 0 && num < MAX_SAFE_INTEGER) {
+ return num;
+ }
+ }
+ return id;
+ });
+ }
+ this.build = m[5] ? m[5].split(".") : [];
+ this.format();
+ }
+ format() {
+ this.version = `${this.major}.${this.minor}.${this.patch}`;
+ if (this.prerelease.length) {
+ this.version += `-${this.prerelease.join(".")}`;
+ }
+ return this.version;
+ }
+ toString() {
+ return this.version;
+ }
+ compare(other) {
+ debug("SemVer.compare", this.version, this.options, other);
+ if (!(other instanceof SemVer)) {
+ if (typeof other === "string" && other === this.version) {
+ return 0;
+ }
+ other = new SemVer(other, this.options);
+ }
+ if (other.version === this.version) {
+ return 0;
+ }
+ return this.compareMain(other) || this.comparePre(other);
+ }
+ compareMain(other) {
+ if (!(other instanceof SemVer)) {
+ other = new SemVer(other, this.options);
+ }
+ return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
+ }
+ comparePre(other) {
+ if (!(other instanceof SemVer)) {
+ other = new SemVer(other, this.options);
+ }
+ if (this.prerelease.length && !other.prerelease.length) {
+ return -1;
+ } else if (!this.prerelease.length && other.prerelease.length) {
+ return 1;
+ } else if (!this.prerelease.length && !other.prerelease.length) {
+ return 0;
+ }
+ let i = 0;
+ do {
+ const a = this.prerelease[i];
+ const b = other.prerelease[i];
+ debug("prerelease compare", i, a, b);
+ if (a === void 0 && b === void 0) {
+ return 0;
+ } else if (b === void 0) {
+ return 1;
+ } else if (a === void 0) {
+ return -1;
+ } else if (a === b) {
+ continue;
+ } else {
+ return compareIdentifiers(a, b);
+ }
+ } while (++i);
+ }
+ compareBuild(other) {
+ if (!(other instanceof SemVer)) {
+ other = new SemVer(other, this.options);
+ }
+ let i = 0;
+ do {
+ const a = this.build[i];
+ const b = other.build[i];
+ debug("prerelease compare", i, a, b);
+ if (a === void 0 && b === void 0) {
+ return 0;
+ } else if (b === void 0) {
+ return 1;
+ } else if (a === void 0) {
+ return -1;
+ } else if (a === b) {
+ continue;
+ } else {
+ return compareIdentifiers(a, b);
+ }
+ } while (++i);
+ }
+ inc(release, identifier) {
+ switch (release) {
+ case "premajor":
+ this.prerelease.length = 0;
+ this.patch = 0;
+ this.minor = 0;
+ this.major++;
+ this.inc("pre", identifier);
+ break;
+ case "preminor":
+ this.prerelease.length = 0;
+ this.patch = 0;
+ this.minor++;
+ this.inc("pre", identifier);
+ break;
+ case "prepatch":
+ this.prerelease.length = 0;
+ this.inc("patch", identifier);
+ this.inc("pre", identifier);
+ break;
+ case "prerelease":
+ if (this.prerelease.length === 0) {
+ this.inc("patch", identifier);
+ }
+ this.inc("pre", identifier);
+ break;
+ case "major":
+ if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
+ this.major++;
+ }
+ this.minor = 0;
+ this.patch = 0;
+ this.prerelease = [];
+ break;
+ case "minor":
+ if (this.patch !== 0 || this.prerelease.length === 0) {
+ this.minor++;
+ }
+ this.patch = 0;
+ this.prerelease = [];
+ break;
+ case "patch":
+ if (this.prerelease.length === 0) {
+ this.patch++;
+ }
+ this.prerelease = [];
+ break;
+ case "pre":
+ if (this.prerelease.length === 0) {
+ this.prerelease = [0];
} else {
- compver.prerelease.push(0)
+ let i = this.prerelease.length;
+ while (--i >= 0) {
+ if (typeof this.prerelease[i] === "number") {
+ this.prerelease[i]++;
+ i = -2;
+ }
+ }
+ if (i === -1) {
+ this.prerelease.push(0);
+ }
}
- compver.raw = compver.format()
- /* fallthrough */
- case '':
- case '>=':
- if (!minver || gt(minver, compver)) {
- minver = compver
+ if (identifier) {
+ if (this.prerelease[0] === identifier) {
+ if (isNaN(this.prerelease[1])) {
+ this.prerelease = [identifier, 0];
+ }
+ } else {
+ this.prerelease = [identifier, 0];
+ }
}
- break
- case '<':
- case '<=':
- /* Ignore maximum versions */
- break
- /* istanbul ignore next */
+ break;
default:
- throw new Error(`Unexpected operation: ${comparator.operator}`)
- }
- })
- }
-
- if (minver && range.test(minver)) {
- return minver
- }
-
- return null
-}
-module.exports = minVersion
-
-
-/***/ }),
-/* 77 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const Range = __webpack_require__(71)
-const validRange = (range, options) => {
- try {
- // Return '*' instead of '' so that truthiness works.
- // This will throw if it's invalid anyway
- return new Range(range, options).range || '*'
- } catch (er) {
- return null
- }
-}
-module.exports = validRange
-
-
-/***/ }),
-/* 78 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const SemVer = __webpack_require__(45)
-const Comparator = __webpack_require__(70)
-const {ANY} = Comparator
-const Range = __webpack_require__(71)
-const satisfies = __webpack_require__(72)
-const gt = __webpack_require__(63)
-const lt = __webpack_require__(64)
-const lte = __webpack_require__(67)
-const gte = __webpack_require__(66)
-
-const outside = (version, range, hilo, options) => {
- version = new SemVer(version, options)
- range = new Range(range, options)
-
- let gtfn, ltefn, ltfn, comp, ecomp
- switch (hilo) {
- case '>':
- gtfn = gt
- ltefn = lte
- ltfn = lt
- comp = '>'
- ecomp = '>='
- break
- case '<':
- gtfn = lt
- ltefn = gte
- ltfn = gt
- comp = '<'
- ecomp = '<='
- break
- default:
- throw new TypeError('Must provide a hilo val of "<" or ">"')
- }
-
- // If it satisifes the range it is not outside
- if (satisfies(version, range, options)) {
- return false
- }
-
- // From now on, variable terms are as if we're in "gtr" mode.
- // but note that everything is flipped for the "ltr" function.
-
- for (let i = 0; i < range.set.length; ++i) {
- const comparators = range.set[i]
-
- let high = null
- let low = null
-
- comparators.forEach((comparator) => {
- if (comparator.semver === ANY) {
- comparator = new Comparator('>=0.0.0')
+ throw new Error(`invalid increment argument: ${release}`);
}
- high = high || comparator
- low = low || comparator
- if (gtfn(comparator.semver, high.semver, options)) {
- high = comparator
- } else if (ltfn(comparator.semver, low.semver, options)) {
- low = comparator
- }
- })
-
- // If the edge version comparator has a operator then our version
- // isn't outside it
- if (high.operator === comp || high.operator === ecomp) {
- return false
+ this.format();
+ this.raw = this.version;
+ return this;
}
+ };
+ module2.exports = SemVer;
+});
- // If the lowest version comparator has an operator and our version
- // is less than it then it isn't higher than the range
- if ((!low.operator || low.operator === comp) &&
- ltefn(version, low.semver)) {
- return false
- } else if (low.operator === ecomp && ltfn(version, low.semver)) {
- return false
+// node_modules/semver/functions/parse.js
+var require_parse = __commonJS((exports2, module2) => {
+ var {MAX_LENGTH} = require_constants();
+ var {re, t} = require_re();
+ var SemVer = require_semver();
+ var parse = (version, options) => {
+ if (!options || typeof options !== "object") {
+ options = {
+ loose: !!options,
+ includePrerelease: false
+ };
}
- }
- return true
-}
-
-module.exports = outside
-
-
-/***/ }),
-/* 79 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// Determine if version is greater than all the versions possible in the range.
-const outside = __webpack_require__(78)
-const gtr = (version, range, options) => outside(version, range, '>', options)
-module.exports = gtr
+ if (version instanceof SemVer) {
+ return version;
+ }
+ if (typeof version !== "string") {
+ return null;
+ }
+ if (version.length > MAX_LENGTH) {
+ return null;
+ }
+ const r = options.loose ? re[t.LOOSE] : re[t.FULL];
+ if (!r.test(version)) {
+ return null;
+ }
+ try {
+ return new SemVer(version, options);
+ } catch (er) {
+ return null;
+ }
+ };
+ module2.exports = parse;
+});
+// node_modules/semver/functions/valid.js
+var require_valid = __commonJS((exports2, module2) => {
+ var parse = require_parse();
+ var valid2 = (version, options) => {
+ const v = parse(version, options);
+ return v ? v.version : null;
+ };
+ module2.exports = valid2;
+});
-/***/ }),
-/* 80 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/semver/functions/clean.js
+var require_clean = __commonJS((exports2, module2) => {
+ var parse = require_parse();
+ var clean = (version, options) => {
+ const s = parse(version.trim().replace(/^[=v]+/, ""), options);
+ return s ? s.version : null;
+ };
+ module2.exports = clean;
+});
-const outside = __webpack_require__(78)
-// Determine if version is less than all the versions possible in the range
-const ltr = (version, range, options) => outside(version, range, '<', options)
-module.exports = ltr
+// node_modules/semver/functions/inc.js
+var require_inc = __commonJS((exports2, module2) => {
+ var SemVer = require_semver();
+ var inc = (version, release, options, identifier) => {
+ if (typeof options === "string") {
+ identifier = options;
+ options = void 0;
+ }
+ try {
+ return new SemVer(version, options).inc(release, identifier).version;
+ } catch (er) {
+ return null;
+ }
+ };
+ module2.exports = inc;
+});
+// node_modules/semver/functions/compare.js
+var require_compare = __commonJS((exports2, module2) => {
+ var SemVer = require_semver();
+ var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));
+ module2.exports = compare;
+});
-/***/ }),
-/* 81 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/semver/functions/eq.js
+var require_eq = __commonJS((exports2, module2) => {
+ var compare = require_compare();
+ var eq = (a, b, loose) => compare(a, b, loose) === 0;
+ module2.exports = eq;
+});
-const Range = __webpack_require__(71)
-const intersects = (r1, r2, options) => {
- r1 = new Range(r1, options)
- r2 = new Range(r2, options)
- return r1.intersects(r2)
-}
-module.exports = intersects
-
-
-/***/ }),
-/* 82 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// given a set of versions and a range, create a "simplified" range
-// that includes the same versions that the original range does
-// If the original range is shorter than the simplified one, return that.
-const satisfies = __webpack_require__(72)
-const compare = __webpack_require__(53)
-module.exports = (versions, range, options) => {
- const set = []
- let min = null
- let prev = null
- const v = versions.sort((a, b) => compare(a, b, options))
- for (const version of v) {
- const included = satisfies(version, range, options)
- if (included) {
- prev = version
- if (!min)
- min = version
+// node_modules/semver/functions/diff.js
+var require_diff = __commonJS((exports2, module2) => {
+ var parse = require_parse();
+ var eq = require_eq();
+ var diff = (version1, version2) => {
+ if (eq(version1, version2)) {
+ return null;
} else {
- if (prev) {
- set.push([min, prev])
- }
- prev = null
- min = null
- }
- }
- if (min)
- set.push([min, null])
-
- const ranges = []
- for (const [min, max] of set) {
- if (min === max)
- ranges.push(min)
- else if (!max && min === v[0])
- ranges.push('*')
- else if (!max)
- ranges.push(`>=${min}`)
- else if (min === v[0])
- ranges.push(`<=${max}`)
- else
- ranges.push(`${min} - ${max}`)
- }
- const simplified = ranges.join(' || ')
- const original = typeof range.raw === 'string' ? range.raw : String(range)
- return simplified.length < original.length ? simplified : range
-}
-
-
-/***/ }),
-/* 83 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const Range = __webpack_require__(71)
-const { ANY } = __webpack_require__(70)
-const satisfies = __webpack_require__(72)
-const compare = __webpack_require__(53)
-
-// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
-// - Every simple range `r1, r2, ...` is a subset of some `R1, R2, ...`
-//
-// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
-// - If c is only the ANY comparator
-// - If C is only the ANY comparator, return true
-// - Else return false
-// - Let EQ be the set of = comparators in c
-// - If EQ is more than one, return true (null set)
-// - Let GT be the highest > or >= comparator in c
-// - Let LT be the lowest < or <= comparator in c
-// - If GT and LT, and GT.semver > LT.semver, return true (null set)
-// - If EQ
-// - If GT, and EQ does not satisfy GT, return true (null set)
-// - If LT, and EQ does not satisfy LT, return true (null set)
-// - If EQ satisfies every C, return true
-// - Else return false
-// - If GT
-// - If GT is lower than any > or >= comp in C, return false
-// - If GT is >=, and GT.semver does not satisfy every C, return false
-// - If LT
-// - If LT.semver is greater than that of any > comp in C, return false
-// - If LT is <=, and LT.semver does not satisfy every C, return false
-// - If any C is a = range, and GT or LT are set, return false
-// - Else return true
-
-const subset = (sub, dom, options) => {
- sub = new Range(sub, options)
- dom = new Range(dom, options)
- let sawNonNull = false
-
- OUTER: for (const simpleSub of sub.set) {
- for (const simpleDom of dom.set) {
- const isSub = simpleSubset(simpleSub, simpleDom, options)
- sawNonNull = sawNonNull || isSub !== null
- if (isSub)
- continue OUTER
- }
- // the null set is a subset of everything, but null simple ranges in
- // a complex range should be ignored. so if we saw a non-null range,
- // then we know this isn't a subset, but if EVERY simple range was null,
- // then it is a subset.
- if (sawNonNull)
- return false
- }
- return true
-}
-
-const simpleSubset = (sub, dom, options) => {
- if (sub.length === 1 && sub[0].semver === ANY)
- return dom.length === 1 && dom[0].semver === ANY
-
- const eqSet = new Set()
- let gt, lt
- for (const c of sub) {
- if (c.operator === '>' || c.operator === '>=')
- gt = higherGT(gt, c, options)
- else if (c.operator === '<' || c.operator === '<=')
- lt = lowerLT(lt, c, options)
- else
- eqSet.add(c.semver)
- }
-
- if (eqSet.size > 1)
- return null
+ const v1 = parse(version1);
+ const v2 = parse(version2);
+ const hasPre = v1.prerelease.length || v2.prerelease.length;
+ const prefix = hasPre ? "pre" : "";
+ const defaultResult = hasPre ? "prerelease" : "";
+ for (const key in v1) {
+ if (key === "major" || key === "minor" || key === "patch") {
+ if (v1[key] !== v2[key]) {
+ return prefix + key;
+ }
+ }
+ }
+ return defaultResult;
+ }
+ };
+ module2.exports = diff;
+});
- let gtltComp
- if (gt && lt) {
- gtltComp = compare(gt.semver, lt.semver, options)
- if (gtltComp > 0)
- return null
- else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<='))
- return null
- }
+// node_modules/semver/functions/major.js
+var require_major = __commonJS((exports2, module2) => {
+ var SemVer = require_semver();
+ var major = (a, loose) => new SemVer(a, loose).major;
+ module2.exports = major;
+});
- // will iterate one or zero times
- for (const eq of eqSet) {
- if (gt && !satisfies(eq, String(gt), options))
- return null
+// node_modules/semver/functions/minor.js
+var require_minor = __commonJS((exports2, module2) => {
+ var SemVer = require_semver();
+ var minor = (a, loose) => new SemVer(a, loose).minor;
+ module2.exports = minor;
+});
- if (lt && !satisfies(eq, String(lt), options))
- return null
+// node_modules/semver/functions/patch.js
+var require_patch = __commonJS((exports2, module2) => {
+ var SemVer = require_semver();
+ var patch = (a, loose) => new SemVer(a, loose).patch;
+ module2.exports = patch;
+});
- for (const c of dom) {
- if (!satisfies(eq, String(c), options))
- return false
- }
- return true
- }
-
- let higher, lower
- let hasDomLT, hasDomGT
- for (const c of dom) {
- hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
- hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
- if (gt) {
- if (c.operator === '>' || c.operator === '>=') {
- higher = higherGT(gt, c, options)
- if (higher === c)
- return false
- } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options))
- return false
- }
- if (lt) {
- if (c.operator === '<' || c.operator === '<=') {
- lower = lowerLT(lt, c, options)
- if (lower === c)
- return false
- } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options))
- return false
- }
- if (!c.operator && (lt || gt) && gtltComp !== 0)
- return false
- }
-
- // if there was a < or >, and nothing in the dom, then must be false
- // UNLESS it was limited by another range in the other direction.
- // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
- if (gt && hasDomLT && !lt && gtltComp !== 0)
- return false
-
- if (lt && hasDomGT && !gt && gtltComp !== 0)
- return false
-
- return true
-}
+// node_modules/semver/functions/prerelease.js
+var require_prerelease = __commonJS((exports2, module2) => {
+ var parse = require_parse();
+ var prerelease = (version, options) => {
+ const parsed = parse(version, options);
+ return parsed && parsed.prerelease.length ? parsed.prerelease : null;
+ };
+ module2.exports = prerelease;
+});
-// >=1.2.3 is lower than >1.2.3
-const higherGT = (a, b, options) => {
- if (!a)
- return b
- const comp = compare(a.semver, b.semver, options)
- return comp > 0 ? a
- : comp < 0 ? b
- : b.operator === '>' && a.operator === '>=' ? b
- : a
-}
+// node_modules/semver/functions/rcompare.js
+var require_rcompare = __commonJS((exports2, module2) => {
+ var compare = require_compare();
+ var rcompare = (a, b, loose) => compare(b, a, loose);
+ module2.exports = rcompare;
+});
-// <=1.2.3 is higher than <1.2.3
-const lowerLT = (a, b, options) => {
- if (!a)
- return b
- const comp = compare(a.semver, b.semver, options)
- return comp < 0 ? a
- : comp > 0 ? b
- : b.operator === '<' && a.operator === '<=' ? b
- : a
-}
+// node_modules/semver/functions/compare-loose.js
+var require_compare_loose = __commonJS((exports2, module2) => {
+ var compare = require_compare();
+ var compareLoose = (a, b) => compare(a, b, true);
+ module2.exports = compareLoose;
+});
-module.exports = subset
+// node_modules/semver/functions/compare-build.js
+var require_compare_build = __commonJS((exports2, module2) => {
+ var SemVer = require_semver();
+ var compareBuild = (a, b, loose) => {
+ const versionA = new SemVer(a, loose);
+ const versionB = new SemVer(b, loose);
+ return versionA.compare(versionB) || versionA.compareBuild(versionB);
+ };
+ module2.exports = compareBuild;
+});
+// node_modules/semver/functions/sort.js
+var require_sort = __commonJS((exports2, module2) => {
+ var compareBuild = require_compare_build();
+ var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
+ module2.exports = sort;
+});
-/***/ }),
-/* 84 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/semver/functions/rsort.js
+var require_rsort = __commonJS((exports2, module2) => {
+ var compareBuild = require_compare_build();
+ var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
+ module2.exports = rsort;
+});
-"use strict";
+// node_modules/semver/functions/gt.js
+var require_gt = __commonJS((exports2, module2) => {
+ var compare = require_compare();
+ var gt = (a, b, loose) => compare(a, b, loose) > 0;
+ module2.exports = gt;
+});
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
+// node_modules/semver/functions/lt.js
+var require_lt = __commonJS((exports2, module2) => {
+ var compare = require_compare();
+ var lt = (a, b, loose) => compare(a, b, loose) < 0;
+ module2.exports = lt;
});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.applyCodeActionCommands = exports.applyCodeAction = exports.getEditForCodeAction = void 0;
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const coc_nvim_1 = __webpack_require__(1);
-const typeConverters = __importStar(__webpack_require__(37));
-function getEditForCodeAction(client, action) {
- return action.changes && action.changes.length
- ? typeConverters.WorkspaceEdit.fromFileCodeEdits(client, action.changes)
- : undefined;
-}
-exports.getEditForCodeAction = getEditForCodeAction;
-function applyCodeAction(client, action) {
- return __awaiter(this, void 0, void 0, function* () {
- const workspaceEdit = getEditForCodeAction(client, action);
- if (workspaceEdit) {
- if (!(yield coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
- return false;
- }
- }
- return applyCodeActionCommands(client, action);
- });
-}
-exports.applyCodeAction = applyCodeAction;
-function applyCodeActionCommands(client, action) {
- return __awaiter(this, void 0, void 0, function* () {
- // make sure there is command
- if (action.commands && action.commands.length) {
- for (const command of action.commands) {
- const response = yield client.execute('applyCodeActionCommand', { command }, vscode_languageserver_protocol_1.CancellationToken.None);
- if (!response || response.type != 'response' || !response.body) {
- return false;
- }
- }
- }
- return true;
- });
-}
-exports.applyCodeActionCommands = applyCodeActionCommands;
+// node_modules/semver/functions/neq.js
+var require_neq = __commonJS((exports2, module2) => {
+ var compare = require_compare();
+ var neq = (a, b, loose) => compare(a, b, loose) !== 0;
+ module2.exports = neq;
+});
-/***/ }),
-/* 85 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/semver/functions/gte.js
+var require_gte = __commonJS((exports2, module2) => {
+ var compare = require_compare();
+ var gte2 = (a, b, loose) => compare(a, b, loose) >= 0;
+ module2.exports = gte2;
+});
-"use strict";
+// node_modules/semver/functions/lte.js
+var require_lte = __commonJS((exports2, module2) => {
+ var compare = require_compare();
+ var lte = (a, b, loose) => compare(a, b, loose) <= 0;
+ module2.exports = lte;
+});
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
+// node_modules/semver/functions/cmp.js
+var require_cmp = __commonJS((exports2, module2) => {
+ var eq = require_eq();
+ var neq = require_neq();
+ var gt = require_gt();
+ var gte2 = require_gte();
+ var lt = require_lt();
+ var lte = require_lte();
+ var cmp = (a, op, b, loose) => {
+ switch (op) {
+ case "===":
+ if (typeof a === "object")
+ a = a.version;
+ if (typeof b === "object")
+ b = b.version;
+ return a === b;
+ case "!==":
+ if (typeof a === "object")
+ a = a.version;
+ if (typeof b === "object")
+ b = b.version;
+ return a !== b;
+ case "":
+ case "=":
+ case "==":
+ return eq(a, b, loose);
+ case "!=":
+ return neq(a, b, loose);
+ case ">":
+ return gt(a, b, loose);
+ case ">=":
+ return gte2(a, b, loose);
+ case "<":
+ return lt(a, b, loose);
+ case "<=":
+ return lte(a, b, loose);
+ default:
+ throw new TypeError(`Invalid operator: ${op}`);
+ }
+ };
+ module2.exports = cmp;
});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.getParameterListParts = exports.convertCompletionEntry = void 0;
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const PConst = __importStar(__webpack_require__(39));
-function convertCompletionEntry(tsEntry, uri, position, context) {
- let label = tsEntry.name;
- let sortText = tsEntry.sortText;
- let preselect = false;
- let detail;
- if (tsEntry.isRecommended) {
- preselect = true;
- }
- if (tsEntry.source) {
- // De-prioritze auto-imports https://github.com/Microsoft/vscode/issues/40311
- sortText = '\uffff' + sortText;
- }
- else {
- sortText = tsEntry.sortText;
- }
- let kind = convertKind(tsEntry.kind);
- let insertTextFormat = (context.enableCallCompletions &&
- (kind === vscode_languageserver_protocol_1.CompletionItemKind.Function ||
- kind === vscode_languageserver_protocol_1.CompletionItemKind.Method)) ? vscode_languageserver_protocol_1.InsertTextFormat.Snippet : vscode_languageserver_protocol_1.InsertTextFormat.PlainText;
- let insertText = tsEntry.insertText;
- let commitCharacters = getCommitCharacters(tsEntry, context);
- let textEdit = null;
- if (tsEntry.replacementSpan) {
- let { start, end } = tsEntry.replacementSpan;
- if (start.line == end.line) {
- textEdit = {
- range: vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1),
- newText: insertText || label
- };
- }
- }
- if (tsEntry.kindModifiers) {
- const kindModifiers = new Set(tsEntry.kindModifiers.split(/,|\s+/g));
- if (kindModifiers.has(PConst.KindModifiers.optional)) {
- insertText = label;
- label += '?';
- }
- if (kindModifiers.has(PConst.KindModifiers.color)) {
- kind = vscode_languageserver_protocol_1.CompletionItemKind.Color;
- }
- if (tsEntry.kind === PConst.Kind.script) {
- for (const extModifier of PConst.KindModifiers.fileExtensionKindModifiers) {
- if (kindModifiers.has(extModifier)) {
- if (tsEntry.name.toLowerCase().endsWith(extModifier)) {
- detail = tsEntry.name;
- }
- else {
- detail = tsEntry.name + extModifier;
- }
- break;
- }
- }
- }
+
+// node_modules/semver/functions/coerce.js
+var require_coerce = __commonJS((exports2, module2) => {
+ var SemVer = require_semver();
+ var parse = require_parse();
+ var {re, t} = require_re();
+ var coerce = (version, options) => {
+ if (version instanceof SemVer) {
+ return version;
}
- return {
- label,
- insertText,
- textEdit,
- kind,
- preselect,
- insertTextFormat,
- sortText,
- commitCharacters,
- detail,
- data: {
- uri,
- position,
- source: tsEntry.source || ''
- }
- };
-}
-exports.convertCompletionEntry = convertCompletionEntry;
-function convertKind(kind) {
- switch (kind) {
- case PConst.Kind.primitiveType:
- case PConst.Kind.keyword:
- return vscode_languageserver_protocol_1.CompletionItemKind.Keyword;
- case PConst.Kind.const:
- return vscode_languageserver_protocol_1.CompletionItemKind.Constant;
- case PConst.Kind.let:
- case PConst.Kind.variable:
- case PConst.Kind.localVariable:
- case PConst.Kind.alias:
- return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
- case PConst.Kind.memberVariable:
- case PConst.Kind.memberGetAccessor:
- case PConst.Kind.memberSetAccessor:
- return vscode_languageserver_protocol_1.CompletionItemKind.Field;
- case PConst.Kind.function:
- return vscode_languageserver_protocol_1.CompletionItemKind.Function;
- case PConst.Kind.method:
- case PConst.Kind.constructSignature:
- case PConst.Kind.callSignature:
- case PConst.Kind.indexSignature:
- return vscode_languageserver_protocol_1.CompletionItemKind.Method;
- case PConst.Kind.enum:
- return vscode_languageserver_protocol_1.CompletionItemKind.Enum;
- case PConst.Kind.module:
- case PConst.Kind.externalModuleName:
- return vscode_languageserver_protocol_1.CompletionItemKind.Module;
- case PConst.Kind.class:
- case PConst.Kind.type:
- return vscode_languageserver_protocol_1.CompletionItemKind.Class;
- case PConst.Kind.interface:
- return vscode_languageserver_protocol_1.CompletionItemKind.Interface;
- case PConst.Kind.warning:
- case PConst.Kind.script:
- return vscode_languageserver_protocol_1.CompletionItemKind.File;
- case PConst.Kind.directory:
- return vscode_languageserver_protocol_1.CompletionItemKind.Folder;
- }
- return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
-}
-function getCommitCharacters(tsEntry, context) {
- if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
- return undefined;
- }
- const commitCharacters = [];
- switch (tsEntry.kind) {
- case PConst.Kind.memberGetAccessor:
- case PConst.Kind.memberSetAccessor:
- case PConst.Kind.constructSignature:
- case PConst.Kind.callSignature:
- case PConst.Kind.indexSignature:
- case PConst.Kind.enum:
- case PConst.Kind.interface:
- commitCharacters.push('.', ';');
- break;
- case PConst.Kind.module:
- case PConst.Kind.alias:
- case PConst.Kind.const:
- case PConst.Kind.let:
- case PConst.Kind.variable:
- case PConst.Kind.localVariable:
- case PConst.Kind.memberVariable:
- case PConst.Kind.class:
- case PConst.Kind.function:
- case PConst.Kind.method:
- case PConst.Kind.keyword:
- case PConst.Kind.parameter:
- commitCharacters.push('.', ',', ';');
- if (context.enableCallCompletions) {
- commitCharacters.push('(');
- }
- break;
+ if (typeof version === "number") {
+ version = String(version);
}
- return commitCharacters.length === 0 ? undefined : commitCharacters;
-}
-function getParameterListParts(displayParts) {
- const parts = [];
- let isInMethod = false;
- let hasOptionalParameters = false;
- let parenCount = 0;
- let braceCount = 0;
- outer: for (let i = 0; i < displayParts.length; ++i) {
- const part = displayParts[i];
- switch (part.kind) {
- case PConst.DisplayPartKind.methodName:
- case PConst.DisplayPartKind.functionName:
- case PConst.DisplayPartKind.text:
- case PConst.DisplayPartKind.propertyName:
- if (parenCount === 0 && braceCount === 0) {
- isInMethod = true;
- }
- break;
- case PConst.DisplayPartKind.parameterName:
- if (parenCount === 1 && braceCount === 0 && isInMethod) {
- // Only take top level paren names
- const next = displayParts[i + 1];
- // Skip optional parameters
- const nameIsFollowedByOptionalIndicator = next && next.text === '?';
- if (!nameIsFollowedByOptionalIndicator) {
- parts.push(part);
- }
- hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator;
- }
- break;
- case PConst.DisplayPartKind.punctuation:
- if (part.text === '(') {
- ++parenCount;
- }
- else if (part.text === ')') {
- --parenCount;
- if (parenCount <= 0 && isInMethod) {
- break outer;
- }
- }
- else if (part.text === '...' && parenCount === 1) {
- // Found rest parmeter. Do not fill in any further arguments
- hasOptionalParameters = true;
- break outer;
- }
- else if (part.text === '{') {
- ++braceCount;
- }
- else if (part.text === '}') {
- --braceCount;
- }
- break;
+ if (typeof version !== "string") {
+ return null;
+ }
+ options = options || {};
+ let match = null;
+ if (!options.rtl) {
+ match = version.match(re[t.COERCE]);
+ } else {
+ let next;
+ while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) {
+ if (!match || next.index + next[0].length !== match.index + match[0].length) {
+ match = next;
}
+ re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
+ }
+ re[t.COERCERTL].lastIndex = -1;
}
- return { hasOptionalParameters, parts };
-}
-exports.getParameterListParts = getParameterListParts;
-
-
-/***/ }),
-/* 86 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
+ if (match === null)
+ return null;
+ return parse(`${match[2]}.${match[3] || "0"}.${match[4] || "0"}`, options);
+ };
+ module2.exports = coerce;
+});
-/*---------------------------------------------------------------------------------------------
- * 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.markdownDocumentation = exports.tagsMarkdownPreview = exports.plain = void 0;
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-function getTagBodyText(tag) {
- if (!tag.text) {
- return undefined;
- }
- switch (tag.name) {
- case 'example':
- case 'default':
- // Convert to markdown code block if it not already one
- if (tag.text.match(/^\s*[~`]{3}/g)) {
- return tag.text;
- }
- return '```\n' + tag.text + '\n```';
- }
- return tag.text;
-}
-function getTagDocumentation(tag) {
- switch (tag.name) {
- case 'param':
- const body = (tag.text || '').split(/^([\w\.]+)\s*/);
- if (body && body.length === 3) {
- const param = body[1];
- const doc = body[2];
- const label = `*@${tag.name}* \`${param}\``;
- if (!doc) {
- return label;
- }
- return label + (doc.match(/\r\n|\n/g) ? '\n' + doc : ` — ${doc}`);
- }
+// node_modules/semver/classes/range.js
+var require_range = __commonJS((exports2, module2) => {
+ var Range17 = class {
+ constructor(range, options) {
+ if (!options || typeof options !== "object") {
+ options = {
+ loose: !!options,
+ includePrerelease: false
+ };
+ }
+ if (range instanceof Range17) {
+ if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
+ return range;
+ } else {
+ return new Range17(range.raw, options);
+ }
+ }
+ if (range instanceof Comparator) {
+ this.raw = range.value;
+ this.set = [[range]];
+ this.format();
+ return this;
+ }
+ this.options = options;
+ this.loose = !!options.loose;
+ this.includePrerelease = !!options.includePrerelease;
+ this.raw = range;
+ this.set = range.split(/\s*\|\|\s*/).map((range2) => this.parseRange(range2.trim())).filter((c) => c.length);
+ if (!this.set.length) {
+ throw new TypeError(`Invalid SemVer Range: ${range}`);
+ }
+ this.format();
+ }
+ format() {
+ this.range = this.set.map((comps) => {
+ return comps.join(" ").trim();
+ }).join("||").trim();
+ return this.range;
+ }
+ toString() {
+ return this.range;
+ }
+ parseRange(range) {
+ const loose = this.options.loose;
+ range = range.trim();
+ const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
+ range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
+ debug("hyphen replace", range);
+ range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
+ debug("comparator trim", range, re[t.COMPARATORTRIM]);
+ range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
+ range = range.replace(re[t.CARETTRIM], caretTrimReplace);
+ range = range.split(/\s+/).join(" ");
+ const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
+ return range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)).filter(this.options.loose ? (comp) => !!comp.match(compRe) : () => true).map((comp) => new Comparator(comp, this.options));
+ }
+ intersects(range, options) {
+ if (!(range instanceof Range17)) {
+ throw new TypeError("a Range is required");
+ }
+ return this.set.some((thisComparators) => {
+ return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
+ return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
+ return rangeComparators.every((rangeComparator) => {
+ return thisComparator.intersects(rangeComparator, options);
+ });
+ });
+ });
+ });
}
- // Generic tag
- const label = `*@${tag.name}*`;
- const text = getTagBodyText(tag);
- if (!text) {
- return label;
+ test(version) {
+ if (!version) {
+ return false;
+ }
+ if (typeof version === "string") {
+ try {
+ version = new SemVer(version, this.options);
+ } catch (er) {
+ return false;
+ }
+ }
+ for (let i = 0; i < this.set.length; i++) {
+ if (testSet(this.set[i], version, this.options)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ };
+ module2.exports = Range17;
+ var Comparator = require_comparator();
+ var debug = require_debug();
+ var SemVer = require_semver();
+ var {
+ re,
+ t,
+ comparatorTrimReplace,
+ tildeTrimReplace,
+ caretTrimReplace
+ } = require_re();
+ var isSatisfiable = (comparators, options) => {
+ let result = true;
+ const remainingComparators = comparators.slice();
+ let testComparator = remainingComparators.pop();
+ while (result && remainingComparators.length) {
+ result = remainingComparators.every((otherComparator) => {
+ return testComparator.intersects(otherComparator, options);
+ });
+ testComparator = remainingComparators.pop();
}
- return label + (text.match(/\r\n|\n/g) ? '\n' + text : ` — ${text}`);
-}
-function plain(parts) {
- if (!parts || !parts.length)
- return '';
- return parts.map(part => part.text).join('');
-}
-exports.plain = plain;
-function tagsMarkdownPreview(tags) {
- return (tags || []).map(getTagDocumentation).join(' \n\n');
-}
-exports.tagsMarkdownPreview = tagsMarkdownPreview;
-function markdownDocumentation(documentation, tags) {
- let out = plain(documentation);
- const tagsPreview = tagsMarkdownPreview(tags);
- if (tagsPreview) {
- out = out + ('\n\n' + tagsPreview);
+ return result;
+ };
+ var parseComparator = (comp, options) => {
+ debug("comp", comp, options);
+ comp = replaceCarets(comp, options);
+ debug("caret", comp);
+ comp = replaceTildes(comp, options);
+ debug("tildes", comp);
+ comp = replaceXRanges(comp, options);
+ debug("xrange", comp);
+ comp = replaceStars(comp, options);
+ debug("stars", comp);
+ return comp;
+ };
+ var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
+ var replaceTildes = (comp, options) => comp.trim().split(/\s+/).map((comp2) => {
+ return replaceTilde(comp2, options);
+ }).join(" ");
+ var replaceTilde = (comp, options) => {
+ const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
+ return comp.replace(r, (_, M, m, p, pr) => {
+ debug("tilde", comp, _, M, m, p, pr);
+ let ret;
+ if (isX(M)) {
+ ret = "";
+ } else if (isX(m)) {
+ ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
+ } else if (isX(p)) {
+ ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
+ } else if (pr) {
+ debug("replaceTilde pr", pr);
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
+ } else {
+ ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
+ }
+ debug("tilde return", ret);
+ return ret;
+ });
+ };
+ var replaceCarets = (comp, options) => comp.trim().split(/\s+/).map((comp2) => {
+ return replaceCaret(comp2, options);
+ }).join(" ");
+ var replaceCaret = (comp, options) => {
+ debug("caret", comp, options);
+ const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
+ const z = options.includePrerelease ? "-0" : "";
+ return comp.replace(r, (_, M, m, p, pr) => {
+ debug("caret", comp, _, M, m, p, pr);
+ let ret;
+ if (isX(M)) {
+ ret = "";
+ } else if (isX(m)) {
+ ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
+ } else if (isX(p)) {
+ if (M === "0") {
+ ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
+ } else {
+ ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
+ }
+ } else if (pr) {
+ debug("replaceCaret pr", pr);
+ if (M === "0") {
+ if (m === "0") {
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
+ } else {
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
+ }
+ } else {
+ ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
+ }
+ } else {
+ debug("no pr");
+ if (M === "0") {
+ if (m === "0") {
+ ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
+ } else {
+ ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
+ }
+ } else {
+ ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
+ }
+ }
+ debug("caret return", ret);
+ return ret;
+ });
+ };
+ var replaceXRanges = (comp, options) => {
+ debug("replaceXRanges", comp, options);
+ return comp.split(/\s+/).map((comp2) => {
+ return replaceXRange(comp2, options);
+ }).join(" ");
+ };
+ var replaceXRange = (comp, options) => {
+ comp = comp.trim();
+ const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
+ return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
+ debug("xRange", comp, ret, gtlt, M, m, p, pr);
+ const xM = isX(M);
+ const xm = xM || isX(m);
+ const xp = xm || isX(p);
+ const anyX = xp;
+ if (gtlt === "=" && anyX) {
+ gtlt = "";
+ }
+ pr = options.includePrerelease ? "-0" : "";
+ if (xM) {
+ if (gtlt === ">" || gtlt === "<") {
+ ret = "<0.0.0-0";
+ } else {
+ ret = "*";
+ }
+ } else if (gtlt && anyX) {
+ if (xm) {
+ m = 0;
+ }
+ p = 0;
+ if (gtlt === ">") {
+ gtlt = ">=";
+ if (xm) {
+ M = +M + 1;
+ m = 0;
+ p = 0;
+ } else {
+ m = +m + 1;
+ p = 0;
+ }
+ } else if (gtlt === "<=") {
+ gtlt = "<";
+ if (xm) {
+ M = +M + 1;
+ } else {
+ m = +m + 1;
+ }
+ }
+ if (gtlt === "<")
+ pr = "-0";
+ ret = `${gtlt + M}.${m}.${p}${pr}`;
+ } else if (xm) {
+ ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
+ } else if (xp) {
+ ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
+ }
+ debug("xRange return", ret);
+ return ret;
+ });
+ };
+ var replaceStars = (comp, options) => {
+ debug("replaceStars", comp, options);
+ return comp.trim().replace(re[t.STAR], "");
+ };
+ var replaceGTE0 = (comp, options) => {
+ debug("replaceGTE0", comp, options);
+ return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
+ };
+ var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => {
+ if (isX(fM)) {
+ from = "";
+ } else if (isX(fm)) {
+ from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
+ } else if (isX(fp)) {
+ from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
+ } else if (fpr) {
+ from = `>=${from}`;
+ } else {
+ from = `>=${from}${incPr ? "-0" : ""}`;
+ }
+ if (isX(tM)) {
+ to = "";
+ } else if (isX(tm)) {
+ to = `<${+tM + 1}.0.0-0`;
+ } else if (isX(tp)) {
+ to = `<${tM}.${+tm + 1}.0-0`;
+ } else if (tpr) {
+ to = `<=${tM}.${tm}.${tp}-${tpr}`;
+ } else if (incPr) {
+ to = `<${tM}.${tm}.${+tp + 1}-0`;
+ } else {
+ to = `<=${to}`;
}
- return {
- kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
- value: out
- };
-}
-exports.markdownDocumentation = markdownDocumentation;
-
-
-/***/ }),
-/* 87 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", { value: true });
-class SnippetString {
- constructor(value) {
- this._tabstop = 1;
- this.value = value || '';
+ return `${from} ${to}`.trim();
+ };
+ var testSet = (set, version, options) => {
+ for (let i = 0; i < set.length; i++) {
+ if (!set[i].test(version)) {
+ return false;
+ }
}
- static isSnippetString(thing) {
- if (thing instanceof SnippetString) {
- return true;
+ if (version.prerelease.length && !options.includePrerelease) {
+ for (let i = 0; i < set.length; i++) {
+ debug(set[i].semver);
+ if (set[i].semver === Comparator.ANY) {
+ continue;
}
- if (!thing) {
- return false;
+ if (set[i].semver.prerelease.length > 0) {
+ const allowed = set[i].semver;
+ if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
+ return true;
+ }
}
- return typeof thing.value === 'string';
- }
- static _escape(value) {
- return value.replace(/\$|}|\\/g, '\\$&');
+ }
+ return false;
}
- appendText(str) {
- this.value += SnippetString._escape(str);
- return this;
+ return true;
+ };
+});
+
+// node_modules/semver/classes/comparator.js
+var require_comparator = __commonJS((exports2, module2) => {
+ var ANY = Symbol("SemVer ANY");
+ var Comparator = class {
+ static get ANY() {
+ return ANY;
+ }
+ constructor(comp, options) {
+ if (!options || typeof options !== "object") {
+ options = {
+ loose: !!options,
+ includePrerelease: false
+ };
+ }
+ if (comp instanceof Comparator) {
+ if (comp.loose === !!options.loose) {
+ return comp;
+ } else {
+ comp = comp.value;
+ }
+ }
+ debug("comparator", comp, options);
+ this.options = options;
+ this.loose = !!options.loose;
+ this.parse(comp);
+ if (this.semver === ANY) {
+ this.value = "";
+ } else {
+ this.value = this.operator + this.semver.version;
+ }
+ debug("comp", this);
}
- appendTabstop(n = this._tabstop++) {
- this.value += '$';
- this.value += n;
- return this;
+ parse(comp) {
+ const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
+ const m = comp.match(r);
+ if (!m) {
+ throw new TypeError(`Invalid comparator: ${comp}`);
+ }
+ this.operator = m[1] !== void 0 ? m[1] : "";
+ if (this.operator === "=") {
+ this.operator = "";
+ }
+ if (!m[2]) {
+ this.semver = ANY;
+ } else {
+ this.semver = new SemVer(m[2], this.options.loose);
+ }
}
- appendPlaceholder(value, n = this._tabstop++) {
- if (typeof value === 'function') {
- const nested = new SnippetString();
- nested._tabstop = this._tabstop;
- value(nested);
- this._tabstop = nested._tabstop;
- value = nested.value;
- }
- else {
- value = SnippetString._escape(value);
- }
- this.value += '${';
- this.value += n;
- this.value += ':';
- this.value += value;
- this.value += '}';
- return this;
+ toString() {
+ return this.value;
}
- appendVariable(name, defaultValue) {
- if (typeof defaultValue === 'function') {
- const nested = new SnippetString();
- nested._tabstop = this._tabstop;
- defaultValue(nested);
- this._tabstop = nested._tabstop;
- defaultValue = nested.value;
+ test(version) {
+ debug("Comparator.test", version, this.options.loose);
+ if (this.semver === ANY || version === ANY) {
+ return true;
+ }
+ if (typeof version === "string") {
+ try {
+ version = new SemVer(version, this.options);
+ } catch (er) {
+ return false;
}
- else if (typeof defaultValue === 'string') {
- defaultValue = defaultValue.replace(/\$|}/g, '\\$&');
+ }
+ return cmp(version, this.operator, this.semver, this.options);
+ }
+ intersects(comp, options) {
+ if (!(comp instanceof Comparator)) {
+ throw new TypeError("a Comparator is required");
+ }
+ if (!options || typeof options !== "object") {
+ options = {
+ loose: !!options,
+ includePrerelease: false
+ };
+ }
+ if (this.operator === "") {
+ if (this.value === "") {
+ return true;
}
- this.value += '${';
- this.value += name;
- if (defaultValue) {
- this.value += ':';
- this.value += defaultValue;
+ return new Range17(comp.value, options).test(this.value);
+ } else if (comp.operator === "") {
+ if (comp.value === "") {
+ return true;
}
- this.value += '}';
- return this;
- }
-}
-exports.default = SnippetString;
-
+ return new Range17(this.value, options).test(comp.semver);
+ }
+ const sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">");
+ const sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<");
+ const sameSemVer = this.semver.version === comp.semver.version;
+ const differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<=");
+ const oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, options) && (this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<");
+ const oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, options) && (this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">");
+ return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
+ }
+ };
+ module2.exports = Comparator;
+ var {re, t} = require_re();
+ var cmp = require_cmp();
+ var debug = require_debug();
+ var SemVer = require_semver();
+ var Range17 = require_range();
+});
-/***/ }),
-/* 88 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/semver/functions/satisfies.js
+var require_satisfies = __commonJS((exports2, module2) => {
+ var Range17 = require_range();
+ var satisfies = (version, range, options) => {
+ try {
+ range = new Range17(range, options);
+ } catch (er) {
+ return false;
+ }
+ return range.test(version);
+ };
+ module2.exports = satisfies;
+});
-"use strict";
+// node_modules/semver/ranges/to-comparators.js
+var require_to_comparators = __commonJS((exports2, module2) => {
+ var Range17 = require_range();
+ var toComparators = (range, options) => new Range17(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" "));
+ module2.exports = toComparators;
+});
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
+// node_modules/semver/ranges/max-satisfying.js
+var require_max_satisfying = __commonJS((exports2, module2) => {
+ var SemVer = require_semver();
+ var Range17 = require_range();
+ var maxSatisfying = (versions, range, options) => {
+ let max = null;
+ let maxSV = null;
+ let rangeObj = null;
+ try {
+ rangeObj = new Range17(range, options);
+ } catch (er) {
+ return null;
+ }
+ versions.forEach((v) => {
+ if (rangeObj.test(v)) {
+ if (!max || maxSV.compare(v) === -1) {
+ max = v;
+ maxSV = new SemVer(max, options);
+ }
+ }
+ });
+ return max;
+ };
+ module2.exports = maxSatisfying;
});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
+
+// node_modules/semver/ranges/min-satisfying.js
+var require_min_satisfying = __commonJS((exports2, module2) => {
+ var SemVer = require_semver();
+ var Range17 = require_range();
+ var minSatisfying = (versions, range, options) => {
+ let min = null;
+ let minSV = null;
+ let rangeObj = null;
+ try {
+ rangeObj = new Range17(range, options);
+ } catch (er) {
+ return null;
+ }
+ versions.forEach((v) => {
+ if (rangeObj.test(v)) {
+ if (!min || minSV.compare(v) === 1) {
+ min = v;
+ minSV = new SemVer(min, options);
+ }
+ }
});
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const typeConverters = __importStar(__webpack_require__(37));
-class TypeScriptDefinitionProvider {
- constructor(client) {
- this.client = client;
- }
- getSymbolLocations(definitionType, document, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(document.uri);
- if (!filepath) {
- return undefined;
- }
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
- try {
- const response = yield this.client.execute(definitionType, args, token);
- const locations = (response.type == 'response' && response.body) || [];
- return locations.map(location => typeConverters.Location.fromTextSpan(this.client.toResource(location.file), location));
- }
- catch (_a) {
- return [];
+ return min;
+ };
+ module2.exports = minSatisfying;
+});
+
+// node_modules/semver/ranges/min-version.js
+var require_min_version = __commonJS((exports2, module2) => {
+ var SemVer = require_semver();
+ var Range17 = require_range();
+ var gt = require_gt();
+ var minVersion = (range, loose) => {
+ range = new Range17(range, loose);
+ let minver = new SemVer("0.0.0");
+ if (range.test(minver)) {
+ return minver;
+ }
+ minver = new SemVer("0.0.0-0");
+ if (range.test(minver)) {
+ return minver;
+ }
+ minver = null;
+ for (let i = 0; i < range.set.length; ++i) {
+ const comparators = range.set[i];
+ comparators.forEach((comparator) => {
+ const compver = new SemVer(comparator.semver.version);
+ switch (comparator.operator) {
+ case ">":
+ if (compver.prerelease.length === 0) {
+ compver.patch++;
+ } else {
+ compver.prerelease.push(0);
+ }
+ compver.raw = compver.format();
+ case "":
+ case ">=":
+ if (!minver || gt(minver, compver)) {
+ minver = compver;
}
- });
- }
- provideDefinition(document, position, token) {
- return this.getSymbolLocations('definition', document, position, token);
- }
- provideTypeDefinition(document, position, token) {
- return this.getSymbolLocations('typeDefinition', document, position, token);
+ break;
+ case "<":
+ case "<=":
+ break;
+ default:
+ throw new Error(`Unexpected operation: ${comparator.operator}`);
+ }
+ });
}
- provideImplementation(document, position, token) {
- return this.getSymbolLocations('implementation', document, position, token);
+ if (minver && range.test(minver)) {
+ return minver;
}
-}
-exports.default = TypeScriptDefinitionProvider;
-
-
-/***/ }),
-/* 89 */
-/***/ (function(module, exports, __webpack_require__) {
+ return null;
+ };
+ module2.exports = minVersion;
+});
-"use strict";
+// node_modules/semver/ranges/valid.js
+var require_valid2 = __commonJS((exports2, module2) => {
+ var Range17 = require_range();
+ var validRange = (range, options) => {
+ try {
+ return new Range17(range, options).range || "*";
+ } catch (er) {
+ return null;
+ }
+ };
+ module2.exports = validRange;
+});
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const coc_nvim_1 = __webpack_require__(1);
-const api_1 = __importDefault(__webpack_require__(40));
-const tsDirectives = [
- {
- value: '@ts-check',
- description: 'Enables semantic checking in a JavaScript file. Must be at the top of a file.'
- },
- {
- value: '@ts-nocheck',
- description: 'Disables semantic checking in a JavaScript file. Must be at the top of a file.'
- },
- {
- value: '@ts-ignore',
- description: 'Suppresses @ts-check errors on the next line of a file.'
- }
-];
-const tsDirectives390 = [
- ...tsDirectives,
- {
- value: '@ts-expect-error',
- description: 'Suppresses @ts-check errors on the next line of a file, expecting at least one to exist.'
- }
-];
-class DirectiveCommentCompletionProvider {
- constructor(client) {
- this.client = client;
- }
- provideCompletionItems(document, position, _token, context) {
- if (context.triggerCharacter != '@') {
- return [];
- }
- const file = this.client.toPath(document.uri);
- if (!file) {
- return [];
- }
- const doc = coc_nvim_1.workspace.getDocument(document.uri);
- const line = doc.getline(position.line);
- const prefix = line.slice(0, position.character);
- const match = prefix.match(/^\s*\/\/+\s?(@[a-zA-Z\-]*)?$/);
- if (match) {
- const directives = this.client.apiVersion.gte(api_1.default.v390)
- ? tsDirectives390
- : tsDirectives;
- let items = directives.map(directive => {
- const item = vscode_languageserver_protocol_1.CompletionItem.create(directive.value);
- item.kind = vscode_languageserver_protocol_1.CompletionItemKind.Snippet;
- item.detail = directive.description;
- item.textEdit = {
- range: vscode_languageserver_protocol_1.Range.create(position.line, Math.max(0, position.character - (match[1] ? match[1].length : 0)), position.line, position.character),
- newText: directive.value
- };
- return item;
- });
- let res = {
- isIncomplete: false,
- items
- };
- res.startcol = doc.fixStartcol(position, ['@']);
- return res;
- }
- return [];
+// node_modules/semver/ranges/outside.js
+var require_outside = __commonJS((exports2, module2) => {
+ var SemVer = require_semver();
+ var Comparator = require_comparator();
+ var {ANY} = Comparator;
+ var Range17 = require_range();
+ var satisfies = require_satisfies();
+ var gt = require_gt();
+ var lt = require_lt();
+ var lte = require_lte();
+ var gte2 = require_gte();
+ var outside = (version, range, hilo, options) => {
+ version = new SemVer(version, options);
+ range = new Range17(range, options);
+ let gtfn, ltefn, ltfn, comp, ecomp;
+ switch (hilo) {
+ case ">":
+ gtfn = gt;
+ ltefn = lte;
+ ltfn = lt;
+ comp = ">";
+ ecomp = ">=";
+ break;
+ case "<":
+ gtfn = lt;
+ ltefn = gte2;
+ ltfn = gt;
+ comp = "<";
+ ecomp = "<=";
+ break;
+ default:
+ throw new TypeError('Must provide a hilo val of "<" or ">"');
+ }
+ if (satisfies(version, range, options)) {
+ return false;
+ }
+ for (let i = 0; i < range.set.length; ++i) {
+ const comparators = range.set[i];
+ let high = null;
+ let low = null;
+ comparators.forEach((comparator) => {
+ if (comparator.semver === ANY) {
+ comparator = new Comparator(">=0.0.0");
+ }
+ high = high || comparator;
+ low = low || comparator;
+ if (gtfn(comparator.semver, high.semver, options)) {
+ high = comparator;
+ } else if (ltfn(comparator.semver, low.semver, options)) {
+ low = comparator;
+ }
+ });
+ if (high.operator === comp || high.operator === ecomp) {
+ return false;
+ }
+ if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
+ return false;
+ } else if (low.operator === ecomp && ltfn(version, low.semver)) {
+ return false;
+ }
}
-}
-exports.default = DirectiveCommentCompletionProvider;
-
-
-/***/ }),
-/* 90 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
+ return true;
+ };
+ module2.exports = outside;
+});
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
+// node_modules/semver/ranges/gtr.js
+var require_gtr = __commonJS((exports2, module2) => {
+ var outside = require_outside();
+ var gtr = (version, range, options) => outside(version, range, ">", options);
+ module2.exports = gtr;
});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const typeConverters = __importStar(__webpack_require__(37));
-const arrays_1 = __webpack_require__(91);
-class TypeScriptDocumentHighlightProvider {
- constructor(client) {
- this.client = client;
- }
- provideDocumentHighlights(resource, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const file = this.client.toPath(resource.uri);
- if (!file)
- return [];
- const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { filesToSearch: [file] });
- try {
- const response = yield this.client.execute('documentHighlights', args, token);
- if (response.type !== 'response' || !response.body) {
- return [];
- }
- return arrays_1.flatten(response.body
- .filter(highlight => highlight.file === file)
- .map(convertDocumentHighlight));
- }
- catch (_e) {
- return [];
- }
- });
- }
-}
-exports.default = TypeScriptDocumentHighlightProvider;
-function convertDocumentHighlight(highlight) {
- return highlight.highlightSpans.map(span => {
- return {
- range: typeConverters.Range.fromTextSpan(span),
- kind: span.kind === 'writtenReference' ? vscode_languageserver_protocol_1.DocumentHighlightKind.Write : vscode_languageserver_protocol_1.DocumentHighlightKind.Read
- };
- });
-}
+// node_modules/semver/ranges/ltr.js
+var require_ltr = __commonJS((exports2, module2) => {
+ var outside = require_outside();
+ var ltr = (version, range, options) => outside(version, range, "<", options);
+ module2.exports = ltr;
+});
-/***/ }),
-/* 91 */
-/***/ (function(module, exports, __webpack_require__) {
+// node_modules/semver/ranges/intersects.js
+var require_intersects = __commonJS((exports2, module2) => {
+ var Range17 = require_range();
+ var intersects = (r1, r2, options) => {
+ r1 = new Range17(r1, options);
+ r2 = new Range17(r2, options);
+ return r1.intersects(r2);
+ };
+ module2.exports = intersects;
+});
-"use strict";
+// node_modules/semver/ranges/simplify.js
+var require_simplify = __commonJS((exports2, module2) => {
+ var satisfies = require_satisfies();
+ var compare = require_compare();
+ module2.exports = (versions, range, options) => {
+ const set = [];
+ let min = null;
+ let prev = null;
+ const v = versions.sort((a, b) => compare(a, b, options));
+ for (const version of v) {
+ const included = satisfies(version, range, options);
+ if (included) {
+ prev = version;
+ if (!min)
+ min = version;
+ } else {
+ if (prev) {
+ set.push([min, prev]);
+ }
+ prev = null;
+ min = null;
+ }
+ }
+ if (min)
+ set.push([min, null]);
+ const ranges = [];
+ for (const [min2, max] of set) {
+ if (min2 === max)
+ ranges.push(min2);
+ else if (!max && min2 === v[0])
+ ranges.push("*");
+ else if (!max)
+ ranges.push(`>=${min2}`);
+ else if (min2 === v[0])
+ ranges.push(`<=${max}`);
+ else
+ ranges.push(`${min2} - ${max}`);
+ }
+ const simplified = ranges.join(" || ");
+ const original = typeof range.raw === "string" ? range.raw : String(range);
+ return simplified.length < original.length ? simplified : range;
+ };
+});
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.flatten = exports.equals = void 0;
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-function equals(one, other, itemEquals = (a, b) => a === b) {
- if (one.length !== other.length) {
- return false;
+// node_modules/semver/ranges/subset.js
+var require_subset = __commonJS((exports2, module2) => {
+ var Range17 = require_range();
+ var {ANY} = require_comparator();
+ var satisfies = require_satisfies();
+ var compare = require_compare();
+ var subset = (sub, dom, options) => {
+ sub = new Range17(sub, options);
+ dom = new Range17(dom, options);
+ let sawNonNull = false;
+ OUTER:
+ for (const simpleSub of sub.set) {
+ for (const simpleDom of dom.set) {
+ const isSub = simpleSubset(simpleSub, simpleDom, options);
+ sawNonNull = sawNonNull || isSub !== null;
+ if (isSub)
+ continue OUTER;
+ }
+ if (sawNonNull)
+ return false;
+ }
+ return true;
+ };
+ var simpleSubset = (sub, dom, options) => {
+ if (sub.length === 1 && sub[0].semver === ANY)
+ return dom.length === 1 && dom[0].semver === ANY;
+ const eqSet = new Set();
+ let gt, lt;
+ for (const c of sub) {
+ if (c.operator === ">" || c.operator === ">=")
+ gt = higherGT(gt, c, options);
+ else if (c.operator === "<" || c.operator === "<=")
+ lt = lowerLT(lt, c, options);
+ else
+ eqSet.add(c.semver);
+ }
+ if (eqSet.size > 1)
+ return null;
+ let gtltComp;
+ if (gt && lt) {
+ gtltComp = compare(gt.semver, lt.semver, options);
+ if (gtltComp > 0)
+ return null;
+ else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<="))
+ return null;
+ }
+ for (const eq of eqSet) {
+ if (gt && !satisfies(eq, String(gt), options))
+ return null;
+ if (lt && !satisfies(eq, String(lt), options))
+ return null;
+ for (const c of dom) {
+ if (!satisfies(eq, String(c), options))
+ return false;
+ }
+ return true;
}
- for (let i = 0, len = one.length; i < len; i++) {
- if (!itemEquals(one[i], other[i])) {
+ let higher, lower;
+ let hasDomLT, hasDomGT;
+ for (const c of dom) {
+ hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";
+ hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";
+ if (gt) {
+ if (c.operator === ">" || c.operator === ">=") {
+ higher = higherGT(gt, c, options);
+ if (higher === c)
return false;
- }
+ } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c), options))
+ return false;
+ }
+ if (lt) {
+ if (c.operator === "<" || c.operator === "<=") {
+ lower = lowerLT(lt, c, options);
+ if (lower === c)
+ return false;
+ } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c), options))
+ return false;
+ }
+ if (!c.operator && (lt || gt) && gtltComp !== 0)
+ return false;
}
+ if (gt && hasDomLT && !lt && gtltComp !== 0)
+ return false;
+ if (lt && hasDomGT && !gt && gtltComp !== 0)
+ return false;
return true;
-}
-exports.equals = equals;
-function flatten(arr) {
- return [].concat.apply([], arr);
-}
-exports.flatten = flatten;
-
-
-/***/ }),
-/* 92 */
-/***/ (function(module, exports, __webpack_require__) {
+ };
+ var higherGT = (a, b, options) => {
+ if (!a)
+ return b;
+ const comp = compare(a.semver, b.semver, options);
+ return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
+ };
+ var lowerLT = (a, b, options) => {
+ if (!a)
+ return b;
+ const comp = compare(a.semver, b.semver, options);
+ return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
+ };
+ module2.exports = subset;
+});
-"use strict";
+// node_modules/semver/index.js
+var require_semver2 = __commonJS((exports2, module2) => {
+ var internalRe = require_re();
+ module2.exports = {
+ re: internalRe.re,
+ src: internalRe.src,
+ tokens: internalRe.t,
+ SEMVER_SPEC_VERSION: require_constants().SEMVER_SPEC_VERSION,
+ SemVer: require_semver(),
+ compareIdentifiers: require_identifiers().compareIdentifiers,
+ rcompareIdentifiers: require_identifiers().rcompareIdentifiers,
+ parse: require_parse(),
+ valid: require_valid(),
+ clean: require_clean(),
+ inc: require_inc(),
+ diff: require_diff(),
+ major: require_major(),
+ minor: require_minor(),
+ patch: require_patch(),
+ prerelease: require_prerelease(),
+ compare: require_compare(),
+ rcompare: require_rcompare(),
+ compareLoose: require_compare_loose(),
+ compareBuild: require_compare_build(),
+ sort: require_sort(),
+ rsort: require_rsort(),
+ gt: require_gt(),
+ lt: require_lt(),
+ eq: require_eq(),
+ neq: require_neq(),
+ gte: require_gte(),
+ lte: require_lte(),
+ cmp: require_cmp(),
+ coerce: require_coerce(),
+ Comparator: require_comparator(),
+ Range: require_range(),
+ satisfies: require_satisfies(),
+ toComparators: require_to_comparators(),
+ maxSatisfying: require_max_satisfying(),
+ minSatisfying: require_min_satisfying(),
+ minVersion: require_min_version(),
+ validRange: require_valid2(),
+ outside: require_outside(),
+ gtr: require_gtr(),
+ ltr: require_ltr(),
+ intersects: require_intersects(),
+ simplifyRange: require_simplify(),
+ subset: require_subset()
+ };
+});
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
+// node_modules/isexe/windows.js
+var require_windows = __commonJS((exports2, module2) => {
+ module2.exports = isexe;
+ isexe.sync = sync;
+ var fs5 = require("fs");
+ function checkPathExt(path9, options) {
+ var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
+ if (!pathext) {
+ return true;
+ }
+ pathext = pathext.split(";");
+ if (pathext.indexOf("") !== -1) {
+ return true;
+ }
+ for (var i = 0; i < pathext.length; i++) {
+ var p = pathext[i].toLowerCase();
+ if (p && path9.substr(-p.length).toLowerCase() === p) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function checkStat(stat, path9, options) {
+ if (!stat.isSymbolicLink() && !stat.isFile()) {
+ return false;
+ }
+ return checkPathExt(path9, options);
+ }
+ function isexe(path9, options, cb) {
+ fs5.stat(path9, function(er, stat) {
+ cb(er, er ? false : checkStat(stat, path9, options));
+ });
+ }
+ function sync(path9, options) {
+ return checkStat(fs5.statSync(path9), path9, options);
+ }
});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
+
+// node_modules/isexe/mode.js
+var require_mode = __commonJS((exports2, module2) => {
+ module2.exports = isexe;
+ isexe.sync = sync;
+ var fs5 = require("fs");
+ function isexe(path9, options, cb) {
+ fs5.stat(path9, function(er, stat) {
+ cb(er, er ? false : checkStat(stat, options));
});
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const PConst = __importStar(__webpack_require__(39));
-const typeConverters = __importStar(__webpack_require__(37));
-const getSymbolKind = (kind) => {
- switch (kind) {
- case PConst.Kind.module:
- return vscode_languageserver_protocol_1.SymbolKind.Module;
- case PConst.Kind.class:
- return vscode_languageserver_protocol_1.SymbolKind.Class;
- case PConst.Kind.enum:
- return vscode_languageserver_protocol_1.SymbolKind.Enum;
- case PConst.Kind.interface:
- return vscode_languageserver_protocol_1.SymbolKind.Interface;
- case PConst.Kind.method:
- return vscode_languageserver_protocol_1.SymbolKind.Method;
- case PConst.Kind.memberVariable:
- return vscode_languageserver_protocol_1.SymbolKind.Property;
- case PConst.Kind.memberGetAccessor:
- return vscode_languageserver_protocol_1.SymbolKind.Property;
- case PConst.Kind.memberSetAccessor:
- return vscode_languageserver_protocol_1.SymbolKind.Property;
- case PConst.Kind.variable:
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- case PConst.Kind.const:
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- case PConst.Kind.localVariable:
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- case PConst.Kind.variable:
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- case PConst.Kind.constructSignature:
- case PConst.Kind.constructorImplementation:
- case PConst.Kind.function:
- case PConst.Kind.localFunction:
- return vscode_languageserver_protocol_1.SymbolKind.Function;
- }
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
-};
-class TypeScriptDocumentSymbolProvider {
- constructor(client) {
- this.client = client;
- }
- provideDocumentSymbols(resource, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(resource.uri);
- if (!filepath)
- return [];
- const args = {
- file: filepath
- };
- try {
- const response = yield this.client.execute('navtree', args, token);
- if (response.type == 'response' && response.body) {
- // The root represents the file. Ignore this when showing in the UI
- const tree = response.body;
- if (tree.childItems) {
- const result = new Array();
- tree.childItems.forEach(item => TypeScriptDocumentSymbolProvider.convertNavTree(result, item));
- return result;
- }
- }
- return [];
- }
- catch (e) {
- return [];
- }
+ }
+ function sync(path9, options) {
+ return checkStat(fs5.statSync(path9), options);
+ }
+ function checkStat(stat, options) {
+ return stat.isFile() && checkMode(stat, options);
+ }
+ function checkMode(stat, options) {
+ var mod = stat.mode;
+ var uid = stat.uid;
+ var gid = stat.gid;
+ var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
+ var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
+ var u = parseInt("100", 8);
+ var g = parseInt("010", 8);
+ var o = parseInt("001", 8);
+ var ug = u | g;
+ var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
+ return ret;
+ }
+});
+
+// node_modules/isexe/index.js
+var require_isexe = __commonJS((exports2, module2) => {
+ var fs5 = require("fs");
+ var core;
+ if (process.platform === "win32" || global.TESTING_WINDOWS) {
+ core = require_windows();
+ } else {
+ core = require_mode();
+ }
+ module2.exports = isexe;
+ isexe.sync = sync;
+ function isexe(path9, options, cb) {
+ if (typeof options === "function") {
+ cb = options;
+ options = {};
+ }
+ if (!cb) {
+ if (typeof Promise !== "function") {
+ throw new TypeError("callback not provided");
+ }
+ return new Promise(function(resolve, reject) {
+ isexe(path9, options || {}, function(er, is2) {
+ if (er) {
+ reject(er);
+ } else {
+ resolve(is2);
+ }
});
+ });
}
- static convertNavTree(bucket, item) {
- let shouldInclude = TypeScriptDocumentSymbolProvider.shouldInclueEntry(item);
- const children = new Set(item.childItems || []);
- for (const span of item.spans) {
- const range = typeConverters.Range.fromTextSpan(span);
- const symbolInfo = vscode_languageserver_protocol_1.DocumentSymbol.create(item.text, '', getSymbolKind(item.kind), range, range);
- symbolInfo.children = children.size > 0 ? [] : null;
- for (const child of children) {
- if (child.spans.some(span => !!containsRange(range, typeConverters.Range.fromTextSpan(span)))) {
- const includedChild = TypeScriptDocumentSymbolProvider.convertNavTree(symbolInfo.children, child);
- shouldInclude = shouldInclude || includedChild;
- children.delete(child);
- }
- }
- if (shouldInclude) {
- bucket.push(symbolInfo);
- }
- }
- return shouldInclude;
- }
- static shouldInclueEntry(item) {
- if (item.kind === PConst.Kind.alias) {
- return false;
+ core(path9, options || {}, function(er, is2) {
+ if (er) {
+ if (er.code === "EACCES" || options && options.ignoreErrors) {
+ er = null;
+ is2 = false;
}
- return !!(item.text &&
- item.text !== '<function>' &&
- item.text !== '<class>');
- }
-}
-exports.default = TypeScriptDocumentSymbolProvider;
-function containsRange(range, otherRange) {
- if (otherRange.start.line < range.start.line || otherRange.end.line < range.start.line) {
- return false;
- }
- if (otherRange.start.line > range.end.line || otherRange.end.line > range.end.line) {
+ }
+ cb(er, is2);
+ });
+ }
+ function sync(path9, options) {
+ try {
+ return core.sync(path9, options || {});
+ } catch (er) {
+ if (options && options.ignoreErrors || er.code === "EACCES") {
return false;
+ } else {
+ throw er;
+ }
}
- if (otherRange.start.line === range.start.line && otherRange.start.character < range.start.character) {
- return false;
+ }
+});
+
+// node_modules/which/which.js
+var require_which = __commonJS((exports2, module2) => {
+ var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
+ var path9 = require("path");
+ var COLON = isWindows ? ";" : ":";
+ var isexe = require_isexe();
+ var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), {code: "ENOENT"});
+ var getPathInfo = (cmd, opt) => {
+ const colon = opt.colon || COLON;
+ const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
+ ...isWindows ? [process.cwd()] : [],
+ ...(opt.path || process.env.PATH || "").split(colon)
+ ];
+ const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
+ const pathExt = isWindows ? pathExtExe.split(colon) : [""];
+ if (isWindows) {
+ if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
+ pathExt.unshift("");
}
- if (otherRange.end.line === range.end.line && otherRange.end.character > range.end.character) {
- return false;
+ return {
+ pathEnv,
+ pathExt,
+ pathExtExe
+ };
+ };
+ var which2 = (cmd, opt, cb) => {
+ if (typeof opt === "function") {
+ cb = opt;
+ opt = {};
+ }
+ if (!opt)
+ opt = {};
+ const {pathEnv, pathExt, pathExtExe} = getPathInfo(cmd, opt);
+ const found = [];
+ const step = (i) => new Promise((resolve, reject) => {
+ if (i === pathEnv.length)
+ return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
+ const ppRaw = pathEnv[i];
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
+ const pCmd = path9.join(pathPart, cmd);
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
+ resolve(subStep(p, i, 0));
+ });
+ const subStep = (p, i, ii) => new Promise((resolve, reject) => {
+ if (ii === pathExt.length)
+ return resolve(step(i + 1));
+ const ext = pathExt[ii];
+ isexe(p + ext, {pathExt: pathExtExe}, (er, is2) => {
+ if (!er && is2) {
+ if (opt.all)
+ found.push(p + ext);
+ else
+ return resolve(p + ext);
+ }
+ return resolve(subStep(p, i, ii + 1));
+ });
+ });
+ return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
+ };
+ var whichSync = (cmd, opt) => {
+ opt = opt || {};
+ const {pathEnv, pathExt, pathExtExe} = getPathInfo(cmd, opt);
+ const found = [];
+ for (let i = 0; i < pathEnv.length; i++) {
+ const ppRaw = pathEnv[i];
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
+ const pCmd = path9.join(pathPart, cmd);
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
+ for (let j = 0; j < pathExt.length; j++) {
+ const cur = p + pathExt[j];
+ try {
+ const is2 = isexe.sync(cur, {pathExt: pathExtExe});
+ if (is2) {
+ if (opt.all)
+ found.push(cur);
+ else
+ return cur;
+ }
+ } catch (ex) {
+ }
+ }
}
- return true;
-}
+ if (opt.all && found.length)
+ return found;
+ if (opt.nothrow)
+ return null;
+ throw getNotFoundError(cmd);
+ };
+ module2.exports = which2;
+ which2.sync = whichSync;
+});
+// src/index.ts
+__export(exports, {
+ activate: () => activate
+});
+var import_coc37 = __toModule(require("coc.nvim"));
-/***/ }),
-/* 93 */
-/***/ (function(module, exports, __webpack_require__) {
+// src/server/index.ts
+var import_coc35 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol24 = __toModule(require_main3());
-"use strict";
+// src/server/typescriptServiceClientHost.ts
+var import_coc34 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol23 = __toModule(require_main3());
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const coc_nvim_1 = __webpack_require__(1);
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const api_1 = __importDefault(__webpack_require__(40));
-function objAreEqual(a, b) {
- let keys = Object.keys(a);
- for (let i = 0; i < keys.length; i++) { // tslint:disable-line
- let key = keys[i];
- if (a[key] !== b[key]) {
- return false;
- }
+// src/utils/arrays.ts
+function equals(one, other, itemEquals = (a, b) => a === b) {
+ if (one.length !== other.length) {
+ return false;
+ }
+ for (let i = 0, len = one.length; i < len; i++) {
+ if (!itemEquals(one[i], other[i])) {
+ return false;
}
- return true;
+ }
+ return true;
}
-class FileConfigurationManager {
- constructor(client) {
- this.client = client;
- this.cachedMap = new Map();
- }
- ensureConfigurationOptions(document, insertSpaces, tabSize) {
- return __awaiter(this, void 0, void 0, function* () {
- const file = this.client.toPath(document.uri);
- let options = {
- tabSize,
- insertSpaces
- };
- let cachedOption = this.cachedMap.get(document.uri);
- const currentOptions = this.getFileOptions(options, document);
- if (cachedOption
- && objAreEqual(cachedOption.formatOptions, currentOptions.formatOptions)
- && objAreEqual(cachedOption.preferences, currentOptions.preferences))
- return;
- this.cachedMap.set(document.uri, currentOptions);
- const args = Object.assign({ file }, currentOptions);
- yield this.client.execute('configure', args, vscode_languageserver_protocol_1.CancellationToken.None);
- });
- }
- ensureConfigurationForDocument(document) {
- return __awaiter(this, void 0, void 0, function* () {
- let opts = yield coc_nvim_1.workspace.getFormatOptions(document.uri);
- return this.ensureConfigurationOptions(document, opts.insertSpaces, opts.tabSize);
- });
- }
- reset() {
- this.cachedMap.clear();
- }
- getLanguageConfiguration(languageId) {
- return coc_nvim_1.workspace.getConfiguration(languageId);
- }
- isTypeScriptDocument(languageId) {
- return languageId.startsWith('typescript');
- }
- formatEnabled(document) {
- let { languageId, uri } = document;
- let language = languageId.startsWith('typescript') ? 'typescript' : 'javascript';
- const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
- return config.get('enabled');
- }
- enableJavascript() {
- const config = coc_nvim_1.workspace.getConfiguration('tsserver');
- return !!config.get('enableJavascript');
- }
- getFileOptions(options, document) {
- const lang = this.isTypeScriptDocument(document.languageId) ? 'typescript' : 'javascript';
- return {
- formatOptions: this.getFormatOptions(options, lang, document.uri),
- preferences: this.getPreferences(lang, document.uri)
- };
- }
- getFormatOptions(options, language, uri) {
- const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
- return {
- tabSize: options.tabSize,
- indentSize: options.tabSize,
- convertTabsToSpaces: options.insertSpaces,
- // We can use \n here since the editor normalizes later on to its line endings.
- newLineCharacter: '\n',
- insertSpaceAfterCommaDelimiter: config.get('insertSpaceAfterCommaDelimiter'),
- insertSpaceAfterConstructor: config.get('insertSpaceAfterConstructor'),
- insertSpaceAfterSemicolonInForStatements: config.get('insertSpaceAfterSemicolonInForStatements'),
- insertSpaceBeforeAndAfterBinaryOperators: config.get('insertSpaceBeforeAndAfterBinaryOperators'),
- insertSpaceAfterKeywordsInControlFlowStatements: config.get('insertSpaceAfterKeywordsInControlFlowStatements'),
- insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get('insertSpaceAfterFunctionKeywordForAnonymousFunctions'),
- insertSpaceBeforeFunctionParenthesis: config.get('insertSpaceBeforeFunctionParenthesis'),
- insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis'),
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets'),
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces'),
- insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces'),
- insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces'),
- insertSpaceAfterTypeAssertion: config.get('insertSpaceAfterTypeAssertion'),
- placeOpenBraceOnNewLineForFunctions: config.get('placeOpenBraceOnNewLineForFunctions'),
- placeOpenBraceOnNewLineForControlBlocks: config.get('placeOpenBraceOnNewLineForControlBlocks'),
- semicolons: config.get('semicolons', undefined)
- };
+function flatten(arr) {
+ return [].concat.apply([], arr);
+}
+
+// src/server/features/fileConfigurationManager.ts
+var import_coc = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol = __toModule(require_main3());
+
+// src/server/utils/api.ts
+var semver = __toModule(require_semver2());
+var API2 = class {
+ constructor(versionString, version) {
+ this.versionString = versionString;
+ this.version = version;
+ }
+ static fromSimpleString(value) {
+ return new API2(value, value);
+ }
+ static fromVersionString(versionString) {
+ let version = semver.valid(versionString);
+ if (!version) {
+ return new API2("invalid version", "1.0.0");
}
- getCompleteOptions(languageId) {
- const lang = this.isTypeScriptDocument(languageId) ? 'typescript' : 'javascript';
- const config = coc_nvim_1.workspace.getConfiguration(`${lang}.suggest`);
- return {
- enabled: config.get('enabled', true),
- names: config.get('names', true),
- paths: config.get('paths', true),
- completeFunctionCalls: config.get('completeFunctionCalls', true),
- autoImports: config.get('autoImports', true),
- includeAutomaticOptionalChainCompletions: config.get('includeAutomaticOptionalChainCompletions', true)
- };
+ const index = versionString.indexOf("-");
+ if (index >= 0) {
+ version = version.substr(0, index);
}
- getPreferences(language, uri) {
- if (this.client.apiVersion.lt(api_1.default.v290)) {
- return {};
- }
- const config = coc_nvim_1.workspace.getConfiguration(`${language}.preferences`, uri);
- // getImportModuleSpecifierEndingPreference available on ts 2.9.0
- const preferences = {
- quotePreference: this.getQuoteStyle(config),
- importModuleSpecifierPreference: getImportModuleSpecifier(config),
- importModuleSpecifierEnding: getImportModuleSpecifierEndingPreference(config),
- allowTextChangesInNewFiles: uri.startsWith('file:'),
- allowRenameOfImportPath: true,
- providePrefixAndSuffixTextForRename: true,
- };
- return preferences;
+ return new API2(versionString, version);
+ }
+ gte(other) {
+ return semver.gte(this.version, other.version);
+ }
+ lt(other) {
+ return !this.gte(other);
+ }
+};
+var API = API2;
+API.defaultVersion = API2.fromSimpleString("1.0.0");
+API.v203 = API2.fromSimpleString("2.0.3");
+API.v206 = API2.fromSimpleString("2.0.6");
+API.v208 = API2.fromSimpleString("2.0.8");
+API.v213 = API2.fromSimpleString("2.1.3");
+API.v220 = API2.fromSimpleString("2.2.0");
+API.v222 = API2.fromSimpleString("2.2.2");
+API.v230 = API2.fromSimpleString("2.3.0");
+API.v234 = API2.fromSimpleString("2.3.4");
+API.v240 = API2.fromSimpleString("2.4.0");
+API.v250 = API2.fromSimpleString("2.5.0");
+API.v260 = API2.fromSimpleString("2.6.0");
+API.v270 = API2.fromSimpleString("2.7.0");
+API.v280 = API2.fromSimpleString("2.8.0");
+API.v290 = API2.fromSimpleString("2.9.0");
+API.v291 = API2.fromSimpleString("2.9.1");
+API.v292 = API2.fromSimpleString("2.9.2");
+API.v300 = API2.fromSimpleString("3.0.0");
+API.v310 = API2.fromSimpleString("3.1.0");
+API.v314 = API2.fromSimpleString("3.1.4");
+API.v320 = API2.fromSimpleString("3.2.0");
+API.v330 = API2.fromSimpleString("3.3.0");
+API.v333 = API2.fromSimpleString("3.3.3");
+API.v340 = API2.fromSimpleString("3.4.0");
+API.v345 = API2.fromSimpleString("3.4.5");
+API.v350 = API2.fromSimpleString("3.5.0");
+API.v380 = API2.fromSimpleString("3.8.0");
+API.v381 = API2.fromSimpleString("3.8.1");
+API.v390 = API2.fromSimpleString("3.9.0");
+API.v400 = API2.fromSimpleString("4.0.0");
+API.v401 = API2.fromSimpleString("4.0.1");
+API.v420 = API2.fromSimpleString("4.2.0");
+API.v430 = API2.fromSimpleString("4.3.0");
+var api_default = API;
+
+// src/server/features/fileConfigurationManager.ts
+function objAreEqual(a, b) {
+ let keys = Object.keys(a);
+ for (let i = 0; i < keys.length; i++) {
+ let key = keys[i];
+ if (a[key] !== b[key]) {
+ return false;
}
- getQuoteStyle(config) {
- let quoteStyle = config.get('quoteStyle', 'auto');
- if (this.client.apiVersion.gte(api_1.default.v333) || quoteStyle != 'auto')
- return quoteStyle;
- return 'single';
+ }
+ return true;
+}
+var FileConfigurationManager = class {
+ constructor(client) {
+ this.client = client;
+ this.cachedMap = new Map();
+ this.disposables = [];
+ import_coc.workspace.onDidCloseTextDocument((textDocument) => {
+ this.cachedMap.delete(textDocument.uri);
+ }, void 0, this.disposables);
+ }
+ async ensureConfigurationOptions(document, insertSpaces, tabSize, token) {
+ const file2 = this.client.toPath(document.uri);
+ let options = {
+ tabSize,
+ insertSpaces
+ };
+ let cachedOption = this.cachedMap.get(document.uri);
+ const currentOptions = this.getFileOptions(options, document);
+ if (cachedOption && objAreEqual(cachedOption.formatOptions, currentOptions.formatOptions) && objAreEqual(cachedOption.preferences, currentOptions.preferences))
+ return;
+ this.cachedMap.set(document.uri, currentOptions);
+ const args = {
+ file: file2,
+ ...currentOptions
+ };
+ await this.client.execute("configure", args, import_vscode_languageserver_protocol.CancellationToken.None);
+ try {
+ const response = await this.client.execute("configure", args, token);
+ if (response.type !== "response") {
+ this.cachedMap.delete(document.uri);
+ }
+ } catch (_e) {
+ this.cachedMap.delete(document.uri);
}
-}
-exports.default = FileConfigurationManager;
+ }
+ async ensureConfigurationForDocument(document, token) {
+ let opts = await import_coc.workspace.getFormatOptions(document.uri);
+ return this.ensureConfigurationOptions(document, opts.insertSpaces, opts.tabSize, token);
+ }
+ reset() {
+ this.cachedMap.clear();
+ }
+ getLanguageConfiguration(languageId) {
+ return import_coc.workspace.getConfiguration(languageId);
+ }
+ isTypeScriptDocument(languageId) {
+ return languageId.startsWith("typescript");
+ }
+ formatEnabled(document) {
+ let {languageId, uri} = document;
+ let language2 = languageId.startsWith("typescript") ? "typescript" : "javascript";
+ const config = import_coc.workspace.getConfiguration(`${language2}.format`, uri);
+ return config.get("enabled");
+ }
+ enableJavascript() {
+ const config = import_coc.workspace.getConfiguration("tsserver");
+ return !!config.get("enableJavascript");
+ }
+ getFileOptions(options, document) {
+ const lang = this.isTypeScriptDocument(document.languageId) ? "typescript" : "javascript";
+ return {
+ formatOptions: this.getFormatOptions(options, lang, document.uri),
+ preferences: this.getPreferences(lang, document.uri)
+ };
+ }
+ getFormatOptions(options, language2, uri) {
+ const config = import_coc.workspace.getConfiguration(`${language2}.format`, uri);
+ return {
+ tabSize: options.tabSize,
+ indentSize: options.tabSize,
+ convertTabsToSpaces: options.insertSpaces,
+ newLineCharacter: "\n",
+ insertSpaceAfterCommaDelimiter: config.get("insertSpaceAfterCommaDelimiter"),
+ insertSpaceAfterConstructor: config.get("insertSpaceAfterConstructor"),
+ insertSpaceAfterSemicolonInForStatements: config.get("insertSpaceAfterSemicolonInForStatements"),
+ insertSpaceBeforeAndAfterBinaryOperators: config.get("insertSpaceBeforeAndAfterBinaryOperators"),
+ insertSpaceAfterKeywordsInControlFlowStatements: config.get("insertSpaceAfterKeywordsInControlFlowStatements"),
+ insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get("insertSpaceAfterFunctionKeywordForAnonymousFunctions"),
+ insertSpaceBeforeFunctionParenthesis: config.get("insertSpaceBeforeFunctionParenthesis"),
+ insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"),
+ insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"),
+ insertSpaceAfterOpeningAndBeforeClosingEmptyBraces: config.get("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces"),
+ insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"),
+ insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"),
+ insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"),
+ insertSpaceAfterTypeAssertion: config.get("insertSpaceAfterTypeAssertion"),
+ placeOpenBraceOnNewLineForFunctions: config.get("placeOpenBraceOnNewLineForFunctions"),
+ placeOpenBraceOnNewLineForControlBlocks: config.get("placeOpenBraceOnNewLineForControlBlocks"),
+ semicolons: config.get("semicolons", void 0)
+ };
+ }
+ getCompleteOptions(languageId) {
+ const lang = this.isTypeScriptDocument(languageId) ? "typescript" : "javascript";
+ const config = import_coc.workspace.getConfiguration(`${lang}.suggest`);
+ return {
+ enabled: config.get("enabled", true),
+ names: config.get("names", true),
+ paths: config.get("paths", true),
+ completeFunctionCalls: config.get("completeFunctionCalls", true),
+ autoImports: config.get("autoImports", true),
+ importStatementSuggestions: config.get("importStatements", true),
+ includeCompletionsForImportStatements: config.get("includeCompletionsForImportStatements", true),
+ includeCompletionsWithSnippetText: config.get("includeCompletionsWithSnippetText", true),
+ includeAutomaticOptionalChainCompletions: config.get("includeAutomaticOptionalChainCompletions", true)
+ };
+ }
+ getPreferences(language2, uri) {
+ if (this.client.apiVersion.lt(api_default.v290)) {
+ return {};
+ }
+ const config = import_coc.workspace.getConfiguration(`${language2}.preferences`, uri);
+ const preferences = {
+ quotePreference: this.getQuoteStyle(config),
+ importModuleSpecifierPreference: getImportModuleSpecifier(config),
+ importModuleSpecifierEnding: getImportModuleSpecifierEndingPreference(config),
+ allowTextChangesInNewFiles: uri.startsWith("file:"),
+ allowRenameOfImportPath: true,
+ providePrefixAndSuffixTextForRename: config.get("renameShorthandProperties", true) === false ? false : config.get("useAliasesForRenames", true),
+ includeCompletionsForImportStatements: this.getCompleteOptions(language2).includeCompletionsForImportStatements,
+ includeCompletionsWithSnippetText: this.getCompleteOptions(language2).includeCompletionsWithSnippetText
+ };
+ return preferences;
+ }
+ getQuoteStyle(config) {
+ let quoteStyle = config.get("quoteStyle", "auto");
+ if (this.client.apiVersion.gte(api_default.v333) || quoteStyle != "auto")
+ return quoteStyle;
+ return "single";
+ }
+ dispose() {
+ import_coc.disposeAll(this.disposables);
+ }
+};
+var fileConfigurationManager_default = FileConfigurationManager;
function getImportModuleSpecifier(config) {
- let val = config.get('importModuleSpecifier');
- switch (val) {
- case 'relative':
- return 'relative';
- case 'non-relative':
- return 'non-relative';
- default:
- return 'auto';
- }
+ let val = config.get("importModuleSpecifier");
+ switch (val) {
+ case "project-relative":
+ return "project-relative";
+ case "relative":
+ return "relative";
+ case "non-relative":
+ return "non-relative";
+ default:
+ return void 0;
+ }
}
function getImportModuleSpecifierEndingPreference(config) {
- switch (config.get('importModuleSpecifierEnding')) {
- case 'minimal': return 'minimal';
- case 'index': return 'index';
- case 'js': return 'js';
- default: return 'auto';
- }
+ switch (config.get("importModuleSpecifierEnding")) {
+ case "minimal":
+ return "minimal";
+ case "index":
+ return "index";
+ case "js":
+ return "js";
+ default:
+ return "auto";
+ }
}
-
-/***/ }),
-/* 94 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
+// src/server/features/watchBuild.ts
+var import_coc2 = __toModule(require("coc.nvim"));
+var import_path = __toModule(require("path"));
+var import_vscode_languageserver_protocol2 = __toModule(require_main3());
+var countRegex = /Found\s+(\d+)\s+error/;
+var errorRegex = /^(.+)\((\d+),(\d+)\):\s(\w+)\sTS(\d+):\s*(.+)$/;
+var TscStatus;
+(function(TscStatus2) {
+ TscStatus2[TscStatus2["INIT"] = 0] = "INIT";
+ TscStatus2[TscStatus2["COMPILING"] = 1] = "COMPILING";
+ TscStatus2[TscStatus2["RUNNING"] = 2] = "RUNNING";
+ TscStatus2[TscStatus2["ERROR"] = 3] = "ERROR";
+})(TscStatus || (TscStatus = {}));
+var WatchProject2 = class {
+ constructor(client) {
+ this.client = client;
+ this.disposables = [];
+ this.statusItem = import_coc2.window.createStatusBarItem(1, {progress: true});
+ let task = this.task = import_coc2.workspace.createTask("TSC");
+ this.disposables.push(import_coc2.commands.registerCommand(WatchProject2.id, async () => {
+ let opts = this.options = await this.getOptions();
+ await this.start(opts);
+ }));
+ task.onExit((code) => {
+ if (code != 0) {
+ import_coc2.window.showMessage(`TSC exit with code ${code}`, "warning");
+ }
+ this.onStop();
});
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const vscode_languageserver_types_1 = __webpack_require__(18);
-const coc_nvim_1 = __webpack_require__(1);
-const typeConverters = __importStar(__webpack_require__(37));
-class TypeScriptFoldingProvider {
- constructor(client) {
- this.client = client;
- }
- provideFoldingRanges(document, _context, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const file = this.client.toPath(document.uri);
- if (!file) {
- return;
- }
- const args = { file };
- const res = yield this.client.execute('getOutliningSpans', args, token);
- if (res.type != 'response') {
- return;
- }
- const { body } = res;
- if (!body) {
- return;
- }
- return body
- .map(span => this.convertOutliningSpan(span, document))
- .filter(foldingRange => !!foldingRange);
- });
- }
- convertOutliningSpan(span, document) {
- const range = typeConverters.Range.fromTextSpan(span.textSpan);
- const kind = TypeScriptFoldingProvider.getFoldingRangeKind(span);
- // Workaround for #49904
- if (span.kind === 'comment') {
- let doc = coc_nvim_1.workspace.getDocument(document.uri);
- const line = doc.getline(range.start.line);
- if (line.match(/\/\/\s*#endregion/gi)) {
- return undefined;
- }
- }
- let { start, end } = range;
- return vscode_languageserver_types_1.FoldingRange.create(start.line, end.line, start.character, end.character, kind);
+ task.onStdout((lines) => {
+ for (let line of lines) {
+ this.onLine(line);
+ }
+ });
+ task.onStderr((lines) => {
+ import_coc2.window.showMessage(`TSC error: ` + lines.join("\n"), "error");
+ });
+ this.disposables.push(import_vscode_languageserver_protocol2.Disposable.create(() => {
+ task.dispose();
+ }));
+ this.check().catch((_e) => {
+ });
+ }
+ async check() {
+ let running = await this.task.running;
+ if (running) {
+ this.options = await this.getOptions();
+ this.statusItem.isProgress = false;
+ this.statusItem.text = "?";
+ this.statusItem.show();
+ } else {
+ this.onStop();
}
- static getFoldingRangeKind(span) {
- switch (span.kind) {
- case 'comment':
- case 'region':
- case 'imports':
- case 'code':
- return span.kind;
- default:
- return undefined;
- }
+ }
+ async start(options) {
+ await this.task.start(options);
+ }
+ onStop() {
+ this.statusItem.hide();
+ }
+ onStart() {
+ this.statusItem.text = "compiling";
+ this.statusItem.isProgress = true;
+ this.statusItem.show();
+ import_coc2.workspace.nvim.call("setqflist", [[]], true);
+ }
+ onLine(line) {
+ if (countRegex.test(line)) {
+ let ms = line.match(countRegex);
+ this.statusItem.text = ms[1] == "0" ? "\u2713" : "\u2717";
+ this.statusItem.isProgress = false;
+ } else if (WatchProject2.startTexts.findIndex((s) => line.indexOf(s) !== -1) != -1) {
+ this.onStart();
+ } else {
+ let ms = line.match(errorRegex);
+ if (!ms)
+ return;
+ let fullpath = import_path.default.join(this.options.cwd, ms[1]);
+ let uri = import_coc2.Uri.file(fullpath).toString();
+ let doc = import_coc2.workspace.getDocument(uri);
+ let bufnr = doc ? doc.bufnr : null;
+ let item = {
+ filename: fullpath,
+ lnum: Number(ms[2]),
+ col: Number(ms[3]),
+ text: `[tsc ${ms[5]}] ${ms[6]}`,
+ type: /error/i.test(ms[4]) ? "E" : "W"
+ };
+ if (bufnr)
+ item.bufnr = bufnr;
+ import_coc2.workspace.nvim.call("setqflist", [[item], "a"]);
}
-}
-exports.default = TypeScriptFoldingProvider;
-
-
-/***/ }),
-/* 95 */
-/***/ (function(module, exports, __webpack_require__) {
+ }
+ async getOptions() {
+ let {tscPath} = this.client;
+ if (!tscPath) {
+ import_coc2.window.showMessage(`Local & global tsc not found`, "error");
+ return;
+ }
+ const tsconfigPath = import_coc2.workspace.getConfiguration("tsserver").get("tsconfigPath", "tsconfig.json");
+ let find = await import_coc2.workspace.findUp([tsconfigPath]);
+ if (!find) {
+ import_coc2.window.showMessage(`${tsconfigPath} not found!`, "error");
+ return;
+ }
+ let root = import_path.default.dirname(find);
+ return {
+ cmd: tscPath,
+ args: ["-p", tsconfigPath, "--watch", "true", "--pretty", "false"],
+ cwd: root
+ };
+ }
+ dispose() {
+ import_coc2.disposeAll(this.disposables);
+ }
+};
+var WatchProject = WatchProject2;
+WatchProject.id = "tsserver.watchBuild";
+WatchProject.startTexts = ["Starting compilation in watch mode", "Starting incremental compilation"];
+var watchBuild_default = WatchProject;
-"use strict";
+// src/server/features/workspaceSymbols.ts
+var import_coc3 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol3 = __toModule(require_main3());
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
+// src/server/protocol.const.ts
+var Kind = class {
};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
+Kind.alias = "alias";
+Kind.callSignature = "call";
+Kind.class = "class";
+Kind.const = "const";
+Kind.constructorImplementation = "constructor";
+Kind.constructSignature = "construct";
+Kind.directory = "directory";
+Kind.enum = "enum";
+Kind.enumMember = "enum member";
+Kind.externalModuleName = "external module name";
+Kind.function = "function";
+Kind.indexSignature = "index";
+Kind.interface = "interface";
+Kind.keyword = "keyword";
+Kind.let = "let";
+Kind.localFunction = "local function";
+Kind.localVariable = "local var";
+Kind.method = "method";
+Kind.memberGetAccessor = "getter";
+Kind.memberSetAccessor = "setter";
+Kind.memberVariable = "property";
+Kind.module = "module";
+Kind.primitiveType = "primitive type";
+Kind.script = "script";
+Kind.type = "type";
+Kind.variable = "var";
+Kind.warning = "warning";
+Kind.string = "string";
+Kind.parameter = "parameter";
+Kind.typeParameter = "type parameter";
+var DiagnosticCategory = class {
};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const coc_nvim_1 = __webpack_require__(1);
-const typeConverters = __importStar(__webpack_require__(37));
-class TypeScriptFormattingProvider {
- constructor(client, formattingOptionsManager) {
- this.client = client;
- this.formattingOptionsManager = formattingOptionsManager;
- }
- enabled(document) {
- return this.formattingOptionsManager.formatEnabled(document);
- }
- doFormat(document, options, args, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.enabled(document))
- return [];
- yield this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize);
- try {
- const response = yield this.client.execute('format', args, token);
- if (response.type == 'response' && response.body) {
- let edits = response.body.map(typeConverters.TextEdit.fromCodeEdit);
- return edits;
- }
- }
- catch (_a) {
- // noop
- }
- return [];
- });
- }
- provideDocumentRangeFormattingEdits(document, range, options, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.enabled(document))
- return [];
- const filepath = this.client.toPath(document.uri);
- if (!filepath)
- return [];
- const args = {
- file: filepath,
- line: range.start.line + 1,
- offset: range.start.character + 1,
- endLine: range.end.line + 1,
- endOffset: range.end.character + 1
- };
- return this.doFormat(document, options, args, token);
- });
+DiagnosticCategory.error = "error";
+DiagnosticCategory.warning = "warning";
+DiagnosticCategory.suggestion = "suggestion";
+var KindModifiers2 = class {
+};
+var KindModifiers = KindModifiers2;
+KindModifiers.optional = "optional";
+KindModifiers.deprecated = "deprecated";
+KindModifiers.color = "color";
+KindModifiers.dtsFile = ".d.ts";
+KindModifiers.tsFile = ".ts";
+KindModifiers.tsxFile = ".tsx";
+KindModifiers.jsFile = ".js";
+KindModifiers.jsxFile = ".jsx";
+KindModifiers.jsonFile = ".json";
+KindModifiers.fileExtensionKindModifiers = [
+ KindModifiers2.dtsFile,
+ KindModifiers2.tsFile,
+ KindModifiers2.tsxFile,
+ KindModifiers2.jsFile,
+ KindModifiers2.jsxFile,
+ KindModifiers2.jsonFile
+];
+var DisplayPartKind = class {
+};
+DisplayPartKind.functionName = "functionName";
+DisplayPartKind.methodName = "methodName";
+DisplayPartKind.parameterName = "parameterName";
+DisplayPartKind.propertyName = "propertyName";
+DisplayPartKind.punctuation = "punctuation";
+DisplayPartKind.text = "text";
+var EventName;
+(function(EventName2) {
+ EventName2["syntaxDiag"] = "syntaxDiag";
+ EventName2["semanticDiag"] = "semanticDiag";
+ EventName2["suggestionDiag"] = "suggestionDiag";
+ EventName2["configFileDiag"] = "configFileDiag";
+ EventName2["telemetry"] = "telemetry";
+ EventName2["projectLanguageServiceState"] = "projectLanguageServiceState";
+ EventName2["projectsUpdatedInBackground"] = "projectsUpdatedInBackground";
+ EventName2["beginInstallTypes"] = "beginInstallTypes";
+ EventName2["endInstallTypes"] = "endInstallTypes";
+ EventName2["typesInstallerInitializationFailed"] = "typesInstallerInitializationFailed";
+ EventName2["surveyReady"] = "surveyReady";
+ EventName2["projectLoadingStart"] = "projectLoadingStart";
+ EventName2["projectLoadingFinish"] = "projectLoadingFinish";
+})(EventName || (EventName = {}));
+
+// src/server/utils/typeConverters.ts
+var language = __toModule(require_main3());
+var Range2;
+(function(Range17) {
+ Range17.fromTextSpan = (span) => {
+ return {
+ start: {
+ line: span.start.line - 1,
+ character: span.start.offset - 1
+ },
+ end: {
+ line: span.end.line - 1,
+ character: span.end.offset - 1
+ }
+ };
+ };
+ Range17.fromLocations = (start, end) => language.Range.create(Math.max(0, start.line - 1), Math.max(start.offset - 1, 0), Math.max(0, end.line - 1), Math.max(0, end.offset - 1));
+ Range17.toFormattingRequestArgs = (file2, range) => ({
+ file: file2,
+ line: range.start.line + 1,
+ offset: range.start.character + 1,
+ endLine: range.end.line + 1,
+ endOffset: range.end.character + 1
+ });
+ Range17.toFileRangeRequestArgs = (file2, range) => ({
+ file: file2,
+ startLine: range.start.line + 1,
+ startOffset: range.start.character + 1,
+ endLine: range.end.line + 1,
+ endOffset: range.end.character + 1
+ });
+})(Range2 || (Range2 = {}));
+var Position;
+(function(Position10) {
+ Position10.fromLocation = (tslocation) => {
+ return {
+ line: tslocation.line - 1,
+ character: tslocation.offset - 1
+ };
+ };
+ Position10.toLocation = (position) => ({
+ line: position.line + 1,
+ offset: position.character + 1
+ });
+ Position10.toFileLocationRequestArgs = (file2, position) => ({
+ file: file2,
+ line: position.line + 1,
+ offset: position.character + 1
+ });
+})(Position || (Position = {}));
+var Location2;
+(function(Location4) {
+ Location4.fromTextSpan = (uri, tsTextSpan) => {
+ return {
+ uri,
+ range: Range2.fromTextSpan(tsTextSpan)
+ };
+ };
+})(Location2 || (Location2 = {}));
+var TextEdit;
+(function(TextEdit6) {
+ TextEdit6.fromCodeEdit = (edit) => {
+ return {
+ range: Range2.fromTextSpan(edit),
+ newText: edit.newText
+ };
+ };
+})(TextEdit || (TextEdit = {}));
+var WorkspaceEdit;
+(function(WorkspaceEdit6) {
+ function fromFileCodeEdits(client, edits) {
+ let changes = {};
+ for (const edit of edits) {
+ let uri = client.toResource(edit.fileName);
+ changes[uri] = edit.textChanges.map((change) => {
+ return TextEdit.fromCodeEdit(change);
+ });
+ }
+ return {changes};
+ }
+ WorkspaceEdit6.fromFileCodeEdits = fromFileCodeEdits;
+})(WorkspaceEdit || (WorkspaceEdit = {}));
+var SymbolKind2;
+(function(SymbolKind5) {
+ function fromProtocolScriptElementKind(kind) {
+ switch (kind) {
+ case Kind.module:
+ return language.SymbolKind.Module;
+ case Kind.class:
+ return language.SymbolKind.Class;
+ case Kind.enum:
+ return language.SymbolKind.Enum;
+ case Kind.enumMember:
+ return language.SymbolKind.EnumMember;
+ case Kind.interface:
+ return language.SymbolKind.Interface;
+ case Kind.indexSignature:
+ return language.SymbolKind.Method;
+ case Kind.callSignature:
+ return language.SymbolKind.Method;
+ case Kind.method:
+ return language.SymbolKind.Method;
+ case Kind.memberVariable:
+ return language.SymbolKind.Property;
+ case Kind.memberGetAccessor:
+ return language.SymbolKind.Property;
+ case Kind.memberSetAccessor:
+ return language.SymbolKind.Property;
+ case Kind.variable:
+ return language.SymbolKind.Variable;
+ case Kind.let:
+ return language.SymbolKind.Variable;
+ case Kind.const:
+ return language.SymbolKind.Variable;
+ case Kind.localVariable:
+ return language.SymbolKind.Variable;
+ case Kind.alias:
+ return language.SymbolKind.Variable;
+ case Kind.function:
+ return language.SymbolKind.Function;
+ case Kind.localFunction:
+ return language.SymbolKind.Function;
+ case Kind.constructSignature:
+ return language.SymbolKind.Constructor;
+ case Kind.constructorImplementation:
+ return language.SymbolKind.Constructor;
+ case Kind.typeParameter:
+ return language.SymbolKind.TypeParameter;
+ case Kind.string:
+ return language.SymbolKind.String;
+ default:
+ return language.SymbolKind.Variable;
}
- provideDocumentFormattingEdits(document, options, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.enabled(document))
- return [];
- const filepath = this.client.toPath(document.uri);
- if (!filepath)
- return [];
- const args = {
- file: filepath,
- line: 1,
- offset: 1,
- endLine: document.lineCount + 1,
- endOffset: 1
- };
- return this.doFormat(document, options, args, token);
- });
+ }
+ SymbolKind5.fromProtocolScriptElementKind = fromProtocolScriptElementKind;
+})(SymbolKind2 || (SymbolKind2 = {}));
+
+// src/server/features/workspaceSymbols.ts
+function parseKindModifier(kindModifiers) {
+ return new Set(kindModifiers.split(/,|\s+/g));
+}
+function getSymbolKind(item) {
+ switch (item.kind) {
+ case "method":
+ return import_vscode_languageserver_protocol3.SymbolKind.Method;
+ case "enum":
+ return import_vscode_languageserver_protocol3.SymbolKind.Enum;
+ case "function":
+ return import_vscode_languageserver_protocol3.SymbolKind.Function;
+ case "class":
+ return import_vscode_languageserver_protocol3.SymbolKind.Class;
+ case "interface":
+ return import_vscode_languageserver_protocol3.SymbolKind.Interface;
+ case "var":
+ return import_vscode_languageserver_protocol3.SymbolKind.Variable;
+ default:
+ return import_vscode_languageserver_protocol3.SymbolKind.Variable;
+ }
+}
+var TypeScriptWorkspaceSymbolProvider = class {
+ constructor(client, languageIds) {
+ this.client = client;
+ this.languageIds = languageIds;
+ }
+ async provideWorkspaceSymbols(search, token) {
+ let filepath;
+ if (this.searchAllOpenProjects) {
+ filepath = void 0;
+ } else {
+ let uri = this.getUri();
+ filepath = uri ? this.client.toPath(uri) : void 0;
+ if (!filepath && this.client.apiVersion.lt(api_default.v390)) {
+ return [];
+ }
}
- provideOnTypeFormattingEdits(document, position, ch, options, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.enabled(document))
- return [];
- if (!this.client.configuration.formatOnType)
- return [];
- const file = this.client.toPath(document.uri);
- if (!file)
- return [];
- yield this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize);
- const doc = coc_nvim_1.workspace.getDocument(document.uri);
- const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { key: ch });
- try {
- const res = yield this.client.execute('formatonkey', args, token);
- if (res.type != 'response') {
- return [];
- }
- const { body } = res;
- const edits = body;
- const result = [];
- if (!edits) {
- return result;
- }
- for (const edit of edits) {
- const textEdit = typeConverters.TextEdit.fromCodeEdit(edit);
- const range = textEdit.range;
- // Work around for https://github.com/Microsoft/TypeScript/issues/6700.
- // Check if we have an edit at the beginning of the line which only removes white spaces and leaves
- // an empty line. Drop those edits
- if (range.start.character === 0 &&
- range.start.line === range.end.line &&
- textEdit.newText === '') {
- const lText = doc.getline(range.start.line);
- // If the edit leaves something on the line keep the edit (note that the end character is exclusive).
- // Keep it also if it removes something else than whitespace
- if (lText.trim().length > 0 || lText.length > range.end.character) {
- result.push(textEdit);
- }
- }
- else {
- result.push(textEdit);
- }
- }
- return result;
- }
- catch (_a) {
- // noop
- }
- return [];
- });
+ const args = {
+ file: filepath,
+ searchValue: search,
+ maxResultCount: 256
+ };
+ const response = await this.client.execute("navto", args, token);
+ if (response.type !== "response" || response.body == null)
+ return [];
+ const result = [];
+ for (const item of response.body) {
+ if (!item.containerName && item.kind === "alias") {
+ continue;
+ }
+ const label = TypeScriptWorkspaceSymbolProvider.getLabel(item);
+ const range = {
+ start: Position.fromLocation(item.start),
+ end: Position.fromLocation(item.end)
+ };
+ const symbolInfo = import_vscode_languageserver_protocol3.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file));
+ const kindModifiers = item.kindModifiers ? parseKindModifier(item.kindModifiers) : void 0;
+ if (kindModifiers == null ? void 0 : kindModifiers.has(KindModifiers.deprecated)) {
+ symbolInfo.tags = [import_vscode_languageserver_protocol3.SymbolTag.Deprecated];
+ }
+ result.push(symbolInfo);
}
-}
-exports.default = TypeScriptFormattingProvider;
-
-
-/***/ }),
-/* 96 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const previewer_1 = __webpack_require__(86);
-const typeConverters = __importStar(__webpack_require__(37));
-class TypeScriptHoverProvider {
- constructor(client) {
- this.client = client;
- }
- provideHover(document, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(document.uri);
- if (!filepath) {
- return undefined;
- }
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
- try {
- const response = yield this.client.interruptGetErr(() => this.client.execute('quickinfo', args, token));
- if (response && response.type == 'response' && response.body) {
- const data = response.body;
- return {
- contents: TypeScriptHoverProvider.getContents(data),
- range: typeConverters.Range.fromTextSpan(data)
- };
- }
- }
- catch (e) {
- // noop
- }
- return undefined;
- });
+ }
+ static getLabel(item) {
+ let label = item.name;
+ if (item.kind === "method" || item.kind === "function") {
+ label += "()";
}
- static getContents(data) {
- const parts = [];
- if (data.displayString) {
- parts.push({ language: 'typescript', value: data.displayString });
- }
- const tags = previewer_1.tagsMarkdownPreview(data.tags);
- parts.push(data.documentation + (tags ? '\n\n' + tags : ''));
- return parts;
+ return label;
+ }
+ getUri() {
+ const documents = import_coc3.workspace.textDocuments;
+ for (const document of documents) {
+ if (this.languageIds.indexOf(document.languageId) >= 0) {
+ return document.uri;
+ }
}
-}
-exports.default = TypeScriptHoverProvider;
+ return void 0;
+ }
+ get searchAllOpenProjects() {
+ return this.client.apiVersion.gte(api_default.v390) && import_coc3.workspace.getConfiguration("typescript").get("workspaceSymbols.scope", "allOpenProjects") === "allOpenProjects";
+ }
+};
+var workspaceSymbols_default = TypeScriptWorkspaceSymbolProvider;
+// src/server/languageProvider.ts
+var import_coc23 = __toModule(require("coc.nvim"));
+var import_path5 = __toModule(require("path"));
+var import_vscode_languageserver_protocol18 = __toModule(require_main3());
-/***/ }),
-/* 97 */
-/***/ (function(module, exports, __webpack_require__) {
+// src/server/features/baseCodeLensProvider.ts
+var import_vscode_languageserver_protocol4 = __toModule(require_main3());
-"use strict";
+// src/server/utils/regexp.ts
+function escapeRegExp(text) {
+ return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
+}
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const PConst = __importStar(__webpack_require__(39));
-const typeConverters = __importStar(__webpack_require__(37));
-const baseCodeLensProvider_1 = __webpack_require__(35);
-class TypeScriptImplementationsCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
- resolveCodeLens(codeLens, token) {
- return __awaiter(this, void 0, void 0, function* () {
- let { uri } = codeLens.data;
- let filepath = this.client.toPath(uri);
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
- try {
- const response = yield this.client.execute('implementation', args, token, true);
- if (response && response.type == 'response' && response.body) {
- const locations = response.body
- .map(reference => {
- return {
- uri: this.client.toResource(reference.file),
- range: {
- start: typeConverters.Position.fromLocation(reference.start),
- end: {
- line: reference.start.line,
- character: 0
- }
- }
- };
- })
- // Exclude original from implementations
- .filter(location => !(location.uri.toString() === uri &&
- location.range.start.line === codeLens.range.start.line &&
- location.range.start.character ===
- codeLens.range.start.character));
- codeLens.command = this.getCommand(locations, codeLens);
- return codeLens;
- }
- }
- catch (_a) {
- // noop
- }
- codeLens.command = {
- title: '0 implementations',
- command: ''
- };
- return codeLens;
- });
+// src/server/features/baseCodeLensProvider.ts
+var CachedNavTreeResponse = class {
+ constructor() {
+ this.version = -1;
+ this.document = "";
+ }
+ execute(document, f) {
+ if (this.matches(document)) {
+ return this.response;
}
- getCommand(locations, codeLens) {
- let { uri } = codeLens.data;
+ return this.update(document, f());
+ }
+ matches(document) {
+ return this.version === document.version && this.document === document.uri.toString();
+ }
+ update(document, response) {
+ this.response = response;
+ this.version = document.version;
+ this.document = document.uri.toString();
+ return response;
+ }
+};
+var TypeScriptBaseCodeLensProvider = class {
+ constructor(client, cachedResponse) {
+ this.client = client;
+ this.cachedResponse = cachedResponse;
+ this.onDidChangeCodeLensesEmitter = new import_vscode_languageserver_protocol4.Emitter();
+ }
+ get onDidChangeCodeLenses() {
+ return this.onDidChangeCodeLensesEmitter.event;
+ }
+ async provideCodeLenses(document, token) {
+ const filepath = this.client.toPath(document.uri);
+ if (!filepath) {
+ return [];
+ }
+ try {
+ const response = await this.cachedResponse.execute(document, () => this.client.execute("navtree", {file: filepath}, token));
+ if (!response) {
+ return [];
+ }
+ const tree = response.body;
+ const referenceableSpans = [];
+ if (tree && tree.childItems) {
+ tree.childItems.forEach((item) => this.walkNavTree(document, item, null, referenceableSpans));
+ }
+ return referenceableSpans.map((range) => {
return {
- title: this.getTitle(locations),
- command: locations.length ? 'editor.action.showReferences' : '',
- arguments: [uri, codeLens.range.start, locations]
+ range,
+ data: {uri: document.uri}
};
+ });
+ } catch {
+ return [];
}
- getTitle(locations) {
- return locations.length === 1 ? '1 implementation' : `${locations.length} implementations`;
- }
- extractSymbol(document, item, _parent) {
- switch (item.kind) {
- case PConst.Kind.interface:
- return super.getSymbolRange(document, item);
- case PConst.Kind.class:
- case PConst.Kind.method:
- case PConst.Kind.memberVariable:
- case PConst.Kind.memberGetAccessor:
- case PConst.Kind.memberSetAccessor:
- if (item.kindModifiers.match(/\babstract\b/g)) {
- return super.getSymbolRange(document, item);
- }
- break;
- }
- return null;
+ }
+ walkNavTree(document, item, parent, results) {
+ if (!item) {
+ return;
}
-}
-exports.default = TypeScriptImplementationsCodeLensProvider;
-
-
-/***/ }),
-/* 98 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const coc_nvim_1 = __webpack_require__(1);
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const api_1 = __importDefault(__webpack_require__(40));
-const codeAction_1 = __webpack_require__(84);
-const typeConverters = __importStar(__webpack_require__(37));
-class ApplyCodeActionCommand {
- constructor(client) {
- this.client = client;
- this.id = ApplyCodeActionCommand.ID;
- }
- execute(action) {
- return __awaiter(this, void 0, void 0, function* () {
- return codeAction_1.applyCodeActionCommands(this.client, action);
- });
+ const range = this.extractSymbol(document, item, parent);
+ if (range) {
+ results.push(range);
}
-}
-ApplyCodeActionCommand.ID = '_typescript.applyCodeActionCommand';
-class ApplyFixAllCodeAction {
- constructor(client) {
- this.client = client;
- this.id = ApplyFixAllCodeAction.ID;
- }
- execute(file, tsAction) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!tsAction.fixId) {
- return;
- }
- const args = {
- scope: {
- type: 'file',
- args: { file }
- },
- fixId: tsAction.fixId
- };
- try {
- const res = yield this.client.execute('getCombinedCodeFix', args, vscode_languageserver_protocol_1.CancellationToken.None);
- if (res.type != 'response') {
- return;
- }
- let { body } = res;
- const edit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.changes);
- yield coc_nvim_1.workspace.applyEdit(edit);
- const token = vscode_languageserver_protocol_1.CancellationToken.None;
- const { commands } = body;
- if (commands && commands.length) {
- for (const command of commands) {
- yield this.client.execute('applyCodeActionCommand', { command }, token);
- }
- }
- }
- catch (_a) {
- // noop
- }
- });
+ if (item.childItems) {
+ item.childItems.forEach((child) => this.walkNavTree(document, child, item, results));
}
-}
-ApplyFixAllCodeAction.ID = '_typescript.applyFixAllCodeAction';
-/**
- * Unique set of diagnostics keyed on diagnostic range and error code.
- */
-class DiagnosticsSet {
- constructor(_values) {
- this._values = _values;
+ }
+ getSymbolRange(document, item) {
+ if (!item) {
+ return null;
+ }
+ if (item.nameSpan) {
+ return Range2.fromTextSpan(item.nameSpan);
+ }
+ const span = item.spans && item.spans[0];
+ if (!span) {
+ return null;
+ }
+ const range = Range2.fromTextSpan(span);
+ const text = document.getText(range);
+ const identifierMatch = new RegExp(`^(.*?(\\b|\\W))${escapeRegExp(item.text || "")}(\\b|\\W)`, "gm");
+ const match = identifierMatch.exec(text);
+ const prefixLength = match ? match.index + match[1].length : 0;
+ const startOffset = document.offsetAt(range.start) + prefixLength;
+ return {
+ start: document.positionAt(startOffset),
+ end: document.positionAt(startOffset + item.text.length)
+ };
+ }
+};
+
+// src/server/features/callHierarchy.ts
+var import_coc4 = __toModule(require("coc.nvim"));
+var import_path2 = __toModule(require("path"));
+var import_vscode_languageserver_protocol5 = __toModule(require_main3());
+var TypeScriptCallHierarchySupport = class {
+ constructor(client) {
+ this.client = client;
+ }
+ async prepareCallHierarchy(document, position, token) {
+ const filepath = this.client.toOpenedFilePath(document.uri);
+ if (!filepath) {
+ return void 0;
}
- static from(diagnostics) {
- const values = new Map();
- for (const diagnostic of diagnostics) {
- values.set(DiagnosticsSet.key(diagnostic), diagnostic);
- }
- return new DiagnosticsSet(values);
+ const args = Position.toFileLocationRequestArgs(filepath, position);
+ const response = await this.client.execute("prepareCallHierarchy", args, token);
+ if (response.type !== "response" || !response.body) {
+ return void 0;
}
- static key(diagnostic) {
- const { start, end } = diagnostic.range;
- return `${diagnostic.code}-${start.line},${start.character}-${end.line},${end.character}`;
+ return Array.isArray(response.body) ? response.body.map(fromProtocolCallHierarchyItem) : fromProtocolCallHierarchyItem(response.body);
+ }
+ async provideCallHierarchyIncomingCalls(item, token) {
+ const filepath = this.client.toPath(item.uri);
+ if (!filepath) {
+ return void 0;
}
- get values() {
- return this._values.values();
+ const args = Position.toFileLocationRequestArgs(filepath, item.selectionRange.start);
+ const response = await this.client.execute("provideCallHierarchyIncomingCalls", args, token);
+ if (response.type !== "response" || !response.body) {
+ return void 0;
}
-}
-class SupportedCodeActionProvider {
- constructor(client) {
- this.client = client;
- }
- getFixableDiagnosticsForContext(context) {
- return __awaiter(this, void 0, void 0, function* () {
- const supportedActions = yield this.supportedCodeActions;
- const fixableDiagnostics = DiagnosticsSet.from(context.diagnostics.filter(diagnostic => supportedActions.has(+diagnostic.code)));
- return Array.from(fixableDiagnostics.values);
- });
+ return response.body.map(fromProtocolCallHierarchyIncomingCall);
+ }
+ async provideCallHierarchyOutgoingCalls(item, token) {
+ const filepath = this.client.toPath(item.uri);
+ if (!filepath) {
+ return void 0;
}
- get supportedCodeActions() {
- if (!this._supportedCodeActions) {
- return new Promise((resolve, reject) => {
- this.client.execute('getSupportedCodeFixes', null, vscode_languageserver_protocol_1.CancellationToken.None).then(res => {
- if (res.type !== 'response') {
- resolve(new Set());
- return;
- }
- let codes = res.body.map(code => +code).filter(code => !isNaN(code));
- resolve(new Set(codes));
- }, reject);
- });
- }
- return Promise.resolve(this._supportedCodeActions);
+ const args = Position.toFileLocationRequestArgs(filepath, item.selectionRange.start);
+ const response = await this.client.execute("provideCallHierarchyOutgoingCalls", args, token);
+ if (response.type !== "response" || !response.body) {
+ return void 0;
}
+ return response.body.map(fromProtocolCallHierarchyOutgoingCall);
+ }
+};
+TypeScriptCallHierarchySupport.minVersion = api_default.v380;
+var callHierarchy_default = TypeScriptCallHierarchySupport;
+function isSourceFileItem(item) {
+ return item.kind === Kind.script || item.kind === Kind.module && item.selectionSpan.start.line === 1 && item.selectionSpan.start.offset === 1;
+}
+function parseKindModifier2(kindModifiers) {
+ return new Set(kindModifiers.split(/,|\s+/g));
+}
+function fromProtocolCallHierarchyItem(item) {
+ var _a;
+ const useFileName = isSourceFileItem(item);
+ const name = useFileName ? import_path2.default.basename(item.file) : item.name;
+ const detail = useFileName ? import_path2.default.relative(import_coc4.workspace.cwd, import_path2.default.dirname(item.file)) : (_a = item.containerName) != null ? _a : "";
+ const result = {
+ name,
+ detail,
+ uri: import_coc4.Uri.file(item.file).toString(),
+ kind: SymbolKind2.fromProtocolScriptElementKind(item.kind),
+ range: Range2.fromTextSpan(item.span),
+ selectionRange: Range2.fromTextSpan(item.selectionSpan)
+ };
+ const kindModifiers = item.kindModifiers ? parseKindModifier2(item.kindModifiers) : void 0;
+ if (kindModifiers == null ? void 0 : kindModifiers.has(KindModifiers.deprecated)) {
+ result.tags = [import_vscode_languageserver_protocol5.SymbolTag.Deprecated];
+ }
+ return result;
}
-class TypeScriptQuickFixProvider {
- constructor(client) {
- this.client = client;
- coc_nvim_1.commands.register(new ApplyCodeActionCommand(client));
- coc_nvim_1.commands.register(new ApplyFixAllCodeAction(client));
- this.supportedCodeActionProvider = new SupportedCodeActionProvider(client);
- }
- provideCodeActions(document, _range, context, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.client.apiVersion.gte(api_1.default.v213)) {
- return [];
- }
- const file = this.client.toPath(document.uri);
- if (!file) {
- return [];
- }
- const fixableDiagnostics = yield this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context);
- if (!fixableDiagnostics.length) {
- return [];
- }
- if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
- return [];
- }
- const results = [];
- for (const diagnostic of fixableDiagnostics) {
- results.push(...(yield this.getFixesForDiagnostic(document, file, diagnostic, token)));
- }
- return results;
- });
- }
- getFixesForDiagnostic(document, file, diagnostic, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+diagnostic.code] });
- const codeFixesResponse = yield this.client.execute('getCodeFixes', args, token);
- if (codeFixesResponse.type != 'response') {
- return [];
- }
- if (codeFixesResponse.body) {
- const results = [];
- for (const tsCodeFix of codeFixesResponse.body) {
- results.push(...(yield this.getAllFixesForTsCodeAction(document, file, diagnostic, tsCodeFix)));
- }
- return results;
- }
- return [];
- });
- }
- getAllFixesForTsCodeAction(document, file, diagnostic, tsAction) {
- return __awaiter(this, void 0, void 0, function* () {
- const singleFix = this.getSingleFixForTsCodeAction(diagnostic, tsAction);
- const fixAll = yield this.getFixAllForTsCodeAction(document, file, diagnostic, tsAction);
- return fixAll ? [singleFix, fixAll] : [singleFix];
- });
- }
- getSingleFixForTsCodeAction(diagnostic, tsAction) {
- const codeAction = {
- title: tsAction.description,
- kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
- };
- codeAction.edit = codeAction_1.getEditForCodeAction(this.client, tsAction);
- codeAction.diagnostics = [diagnostic];
- codeAction.isPrefered = true;
- if (tsAction.commands) {
- codeAction.command = {
- command: ApplyCodeActionCommand.ID,
- arguments: [tsAction],
- title: tsAction.description
- };
- }
- return codeAction;
- }
- getFixAllForTsCodeAction(document, file, diagnostic, tsAction) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!tsAction.fixId || !this.client.apiVersion.gte(api_1.default.v270)) {
- return undefined;
- }
- // Make sure there are multiple diagnostics of the same type in the file
- if (!this.client.diagnosticsManager
- .getDiagnostics(document.uri)
- .some(x => x.code === diagnostic.code && x !== diagnostic)) {
- return;
- }
- const action = {
- title: tsAction.fixAllDescription || 'Fix all in file',
- kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
- };
- action.diagnostics = [diagnostic];
- action.command = {
- command: ApplyFixAllCodeAction.ID,
- arguments: [file, tsAction],
- title: ''
- };
- return action;
- });
- }
+function fromProtocolCallHierarchyIncomingCall(item) {
+ return {
+ from: fromProtocolCallHierarchyItem(item.from),
+ fromRanges: item.fromSpans.map(Range2.fromTextSpan)
+ };
+}
+function fromProtocolCallHierarchyOutgoingCall(item) {
+ return {
+ to: fromProtocolCallHierarchyItem(item.to),
+ fromRanges: item.fromSpans.map(Range2.fromTextSpan)
+ };
}
-exports.default = TypeScriptQuickFixProvider;
-
-
-/***/ }),
-/* 99 */
-/***/ (function(module, exports, __webpack_require__) {
-"use strict";
+// src/server/features/completionItemProvider.ts
+var import_coc8 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol9 = __toModule(require_main3());
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const coc_nvim_1 = __webpack_require__(1);
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const helper_1 = __webpack_require__(100);
-class ImportFixProvider {
- constructor(bufferSyncSupport) {
- this.bufferSyncSupport = bufferSyncSupport;
- }
- provideCodeActions(document, _range, context, _token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
- return [];
- }
- let diagnostics = context.diagnostics.filter(d => d.code == 2304);
- if (!diagnostics.length)
- return [];
- let edits = [];
- let names = [];
- let doc = coc_nvim_1.workspace.getDocument(document.uri);
- let command;
- for (const diagnostic of diagnostics) {
- let { range } = diagnostic;
- let line = doc.getline(range.start.line);
- let name = line.slice(range.start.character, range.end.character);
- if (names.indexOf(name) !== -1)
- continue;
- if (helper_1.nodeModules.indexOf(name) !== -1) {
- names.push(name);
- edits.push({
- range: vscode_languageserver_protocol_1.Range.create(0, 0, 0, 0),
- newText: `import ${name} from '${name}'\n`
- });
- command = 'tsserver.organizeImports';
- }
- }
- let edit = {
- changes: {
- [document.uri]: edits
- }
- };
- let cmd = null;
- if (command)
- cmd = {
- title: `fix import`,
- command: 'tsserver.organizeImports'
- };
- return [{
- title: `Add import ${names.join(', ')}`,
- edit,
- command: cmd
- }];
- });
+// src/server/utils/codeAction.ts
+var import_vscode_languageserver_protocol6 = __toModule(require_main3());
+var import_coc5 = __toModule(require("coc.nvim"));
+function getEditForCodeAction(client, action) {
+ return action.changes && action.changes.length ? WorkspaceEdit.fromFileCodeEdits(client, action.changes) : void 0;
+}
+async function applyCodeAction(client, action) {
+ const workspaceEdit = getEditForCodeAction(client, action);
+ if (workspaceEdit) {
+ if (!await import_coc5.workspace.applyEdit(workspaceEdit)) {
+ return false;
}
+ }
+ return applyCodeActionCommands(client, action);
+}
+async function applyCodeActionCommands(client, action) {
+ if (action.commands && action.commands.length) {
+ for (const command of action.commands) {
+ const response = await client.execute("applyCodeActionCommand", {command}, import_vscode_languageserver_protocol6.CancellationToken.None);
+ if (!response || response.type != "response" || !response.body) {
+ return false;
+ }
+ }
+ }
+ return true;
}
-exports.default = ImportFixProvider;
-
-
-/***/ }),
-/* 100 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.nodeModules = void 0;
-exports.nodeModules = [
- 'assert',
- 'cluster',
- 'crypto',
- 'dns',
- 'domain',
- 'events',
- 'fs',
- 'http',
- 'http2',
- 'https',
- 'inspector',
- 'net',
- 'os',
- 'path',
- 'punycode',
- 'querystring',
- 'readline',
- 'repl',
- 'stream',
- 'string_decoder',
- 'tls',
- 'tty',
- 'url',
- 'util',
- 'v8',
- 'vm',
- 'zlib',
- 'perf_hooks'
-];
-
-
-/***/ }),
-/* 101 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const coc_nvim_1 = __webpack_require__(1);
-const typeConverters = __importStar(__webpack_require__(37));
-class ApplyRefactoringCommand {
- constructor(client) {
- this.client = client;
- this.id = ApplyRefactoringCommand.ID;
- }
- execute(document, file, refactor, action, range) {
- return __awaiter(this, void 0, void 0, function* () {
- const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, range)), { refactor,
- action });
- const response = yield this.client.execute('getEditsForRefactor', args, vscode_languageserver_protocol_1.CancellationToken.None);
- const body = response && response.body;
- if (!body || !body.edits.length) {
- return false;
- }
- const workspaceEdit = yield this.toWorkspaceEdit(body);
- if (!(yield coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
- return false;
- }
- const renameLocation = body.renameLocation;
- if (renameLocation) {
- coc_nvim_1.commands.executeCommand('editor.action.rename', document.uri, typeConverters.Position.fromLocation(renameLocation));
- }
- return true;
- });
+// src/server/utils/completionItem.ts
+var import_coc6 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol7 = __toModule(require_main3());
+function convertCompletionEntry(tsEntry, uri, position, context) {
+ let label = tsEntry.name;
+ let sortText = tsEntry.sortText;
+ let preselect = false;
+ let detail;
+ if (tsEntry.isRecommended) {
+ preselect = true;
+ }
+ if (tsEntry.source && tsEntry.hasAction) {
+ sortText = "\uFFFF" + sortText;
+ } else {
+ sortText = tsEntry.sortText;
+ }
+ let kind = convertKind(tsEntry.kind);
+ let insertTextFormat = context.enableCallCompletions && (kind === import_coc6.CompletionItemKind.Function || kind === import_coc6.CompletionItemKind.Method) ? import_coc6.InsertTextFormat.Snippet : import_coc6.InsertTextFormat.PlainText;
+ let insertText = tsEntry.insertText;
+ let commitCharacters = getCommitCharacters(tsEntry, context);
+ let tags;
+ if (tsEntry.isImportStatementCompletion) {
+ insertText = label;
+ insertTextFormat = import_coc6.InsertTextFormat.Snippet;
+ }
+ let textEdit = null;
+ if (tsEntry.replacementSpan) {
+ let {start, end} = tsEntry.replacementSpan;
+ if (start.line == end.line) {
+ textEdit = {
+ range: import_coc6.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1),
+ newText: tsEntry.insertText || label
+ };
}
- toWorkspaceEdit(body) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const edit of body.edits) {
- yield coc_nvim_1.workspace.createFile(edit.fileName, { ignoreIfExists: true });
- }
- let workspaceEdit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.edits);
- return workspaceEdit;
- });
+ }
+ if (tsEntry.kindModifiers) {
+ const kindModifiers = new Set(tsEntry.kindModifiers.split(/,|\s+/g));
+ if (kindModifiers.has(KindModifiers.optional)) {
+ insertText = label;
+ label += "?";
+ }
+ if (kindModifiers.has(KindModifiers.deprecated)) {
+ tags = [import_vscode_languageserver_protocol7.CompletionItemTag.Deprecated];
+ }
+ if (kindModifiers.has(KindModifiers.color)) {
+ kind = import_coc6.CompletionItemKind.Color;
+ }
+ if (tsEntry.kind === Kind.script) {
+ for (const extModifier of KindModifiers.fileExtensionKindModifiers) {
+ if (kindModifiers.has(extModifier)) {
+ if (tsEntry.name.toLowerCase().endsWith(extModifier)) {
+ detail = tsEntry.name;
+ } else {
+ detail = tsEntry.name + extModifier;
+ }
+ break;
+ }
+ }
+ }
+ }
+ return {
+ label,
+ insertText,
+ textEdit,
+ kind,
+ tags,
+ preselect,
+ insertTextFormat,
+ sortText,
+ commitCharacters,
+ detail,
+ data: {
+ uri,
+ position,
+ name: tsEntry.name,
+ data: tsEntry.data,
+ source: tsEntry.source || ""
+ }
+ };
+}
+function convertKind(kind) {
+ switch (kind) {
+ case Kind.primitiveType:
+ case Kind.keyword:
+ return import_coc6.CompletionItemKind.Keyword;
+ case Kind.const:
+ return import_coc6.CompletionItemKind.Constant;
+ case Kind.let:
+ case Kind.variable:
+ case Kind.localVariable:
+ case Kind.alias:
+ return import_coc6.CompletionItemKind.Variable;
+ case Kind.memberVariable:
+ case Kind.memberGetAccessor:
+ case Kind.memberSetAccessor:
+ return import_coc6.CompletionItemKind.Field;
+ case Kind.function:
+ return import_coc6.CompletionItemKind.Function;
+ case Kind.method:
+ case Kind.constructSignature:
+ case Kind.callSignature:
+ case Kind.indexSignature:
+ return import_coc6.CompletionItemKind.Method;
+ case Kind.enum:
+ return import_coc6.CompletionItemKind.Enum;
+ case Kind.module:
+ case Kind.externalModuleName:
+ return import_coc6.CompletionItemKind.Module;
+ case Kind.class:
+ case Kind.type:
+ return import_coc6.CompletionItemKind.Class;
+ case Kind.interface:
+ return import_coc6.CompletionItemKind.Interface;
+ case Kind.warning:
+ case Kind.script:
+ return import_coc6.CompletionItemKind.File;
+ case Kind.directory:
+ return import_coc6.CompletionItemKind.Folder;
+ }
+ return import_coc6.CompletionItemKind.Variable;
+}
+function getCommitCharacters(tsEntry, context) {
+ if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
+ return void 0;
+ }
+ const commitCharacters = [];
+ switch (tsEntry.kind) {
+ case Kind.memberGetAccessor:
+ case Kind.memberSetAccessor:
+ case Kind.constructSignature:
+ case Kind.callSignature:
+ case Kind.indexSignature:
+ case Kind.enum:
+ case Kind.interface:
+ commitCharacters.push(".", ";");
+ break;
+ case Kind.module:
+ case Kind.alias:
+ case Kind.const:
+ case Kind.let:
+ case Kind.variable:
+ case Kind.localVariable:
+ case Kind.memberVariable:
+ case Kind.class:
+ case Kind.function:
+ case Kind.method:
+ case Kind.keyword:
+ case Kind.parameter:
+ commitCharacters.push(".", ",", ";");
+ if (context.enableCallCompletions) {
+ commitCharacters.push("(");
+ }
+ break;
+ }
+ return commitCharacters.length === 0 ? void 0 : commitCharacters;
+}
+function getParameterListParts(displayParts) {
+ const parts = [];
+ let isInMethod = false;
+ let hasOptionalParameters = false;
+ let parenCount = 0;
+ let braceCount = 0;
+ outer:
+ for (let i = 0; i < displayParts.length; ++i) {
+ const part = displayParts[i];
+ switch (part.kind) {
+ case DisplayPartKind.methodName:
+ case DisplayPartKind.functionName:
+ case DisplayPartKind.text:
+ case DisplayPartKind.propertyName:
+ if (parenCount === 0 && braceCount === 0) {
+ isInMethod = true;
+ }
+ break;
+ case DisplayPartKind.parameterName:
+ if (parenCount === 1 && braceCount === 0 && isInMethod) {
+ const next = displayParts[i + 1];
+ const nameIsFollowedByOptionalIndicator = next && next.text === "?";
+ const nameIsThis = part.text === "this";
+ if (!nameIsFollowedByOptionalIndicator && !nameIsThis) {
+ parts.push(part);
+ }
+ hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator;
+ }
+ break;
+ case DisplayPartKind.punctuation:
+ if (part.text === "(") {
+ ++parenCount;
+ } else if (part.text === ")") {
+ --parenCount;
+ if (parenCount <= 0 && isInMethod) {
+ break outer;
+ }
+ } else if (part.text === "..." && parenCount === 1) {
+ hasOptionalParameters = true;
+ break outer;
+ } else if (part.text === "{") {
+ ++braceCount;
+ } else if (part.text === "}") {
+ --braceCount;
+ }
+ break;
+ }
}
+ return {hasOptionalParameters, parts};
}
-ApplyRefactoringCommand.ID = '_typescript.applyRefactoring';
-class SelectRefactorCommand {
- constructor(doRefactoring) {
- this.doRefactoring = doRefactoring;
- this.id = SelectRefactorCommand.ID;
- }
- execute(document, file, info, range) {
- return __awaiter(this, void 0, void 0, function* () {
- let { actions } = info;
- const idx = actions.length == 1 ? 0 : yield coc_nvim_1.workspace.showQuickpick(actions.map(action => action.description || action.name));
- if (idx == -1)
- return false;
- let label = info.actions[idx].name;
- if (!label)
- return false;
- return this.doRefactoring.execute(document, file, info.name, label, range);
- });
+
+// src/server/utils/previewer.ts
+var import_vscode_languageserver_protocol8 = __toModule(require_main3());
+var import_coc7 = __toModule(require("coc.nvim"));
+function toResource(filepath) {
+ return import_coc7.Uri.file(filepath);
+}
+function replaceLinks(text) {
+ return text.replace(/\{@(link|linkplain|linkcode) (https?:\/\/[^ |}]+?)(?:[| ]([^{}\n]+?))?\}/gi, (_, tag, link, text2) => {
+ switch (tag) {
+ case "linkcode":
+ return `[\`${text2 ? text2.trim() : link}\`](${link})`;
+ default:
+ return `[${text2 ? text2.trim() : link}](${link})`;
}
+ });
}
-SelectRefactorCommand.ID = '_typescript.selectRefactoring';
-class TypeScriptRefactorProvider {
- constructor(client, formattingOptionsManager) {
- this.client = client;
- this.formattingOptionsManager = formattingOptionsManager;
- const doRefactoringCommand = coc_nvim_1.commands.register(new ApplyRefactoringCommand(this.client));
- coc_nvim_1.commands.register(new SelectRefactorCommand(doRefactoringCommand));
- }
- provideCodeActions(document, range, context, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.shouldTrigger(context)) {
- return undefined;
- }
- const file = this.client.toPath(document.uri);
- if (!file)
- return undefined;
- yield this.formattingOptionsManager.ensureConfigurationForDocument(document);
- const args = typeConverters.Range.toFileRangeRequestArgs(file, range);
- let response;
- try {
- response = yield this.client.interruptGetErr(() => {
- return this.client.execute('getApplicableRefactors', args, token);
- });
- if (!response || !response.body) {
- return undefined;
- }
- }
- catch (_a) {
- return undefined;
- }
- return this.convertApplicableRefactors(response.body, document, file, range);
- });
+function processInlineTags(text) {
+ return replaceLinks(text);
+}
+function getTagBodyText(tag) {
+ if (!tag.text) {
+ return void 0;
+ }
+ function makeCodeblock(text2) {
+ if (text2.match(/^\s*[~`]{3}/g)) {
+ return text2;
}
- convertApplicableRefactors(body, document, file, rangeOrSelection) {
- const actions = [];
- for (const info of body) {
- if (!info.inlineable) {
- const codeAction = {
- title: info.description,
- kind: vscode_languageserver_protocol_1.CodeActionKind.Refactor
- };
- codeAction.command = {
- title: info.description,
- command: SelectRefactorCommand.ID,
- arguments: [document, file, info, rangeOrSelection]
- };
- actions.push(codeAction);
- }
- else {
- for (const action of info.actions) {
- actions.push(this.refactorActionToCodeAction(action, document, file, info, rangeOrSelection));
+ return "```\n" + text2 + "\n```";
+ }
+ const text = convertLinkTags(tag.text);
+ switch (tag.name) {
+ case "example":
+ const captionTagMatches = text.match(/<caption>(.*?)<\/caption>\s*(\r\n|\n)/);
+ if (captionTagMatches && captionTagMatches.index === 0) {
+ return captionTagMatches[1] + "\n\n" + makeCodeblock(text.substr(captionTagMatches[0].length));
+ } else {
+ return makeCodeblock(text);
+ }
+ case "author":
+ const emailMatch = text.match(/(.+)\s<([-.\w]+@[-.\w]+)>/);
+ if (emailMatch === null) {
+ return text;
+ } else {
+ return `${emailMatch[1]} ${emailMatch[2]}`;
+ }
+ case "default":
+ return makeCodeblock(text);
+ }
+ return processInlineTags(text);
+}
+function getTagDocumentation(tag) {
+ switch (tag.name) {
+ case "augments":
+ case "extends":
+ case "param":
+ case "template":
+ const body = convertLinkTags(tag.text).split(/^(\S+)\s*-?\s*/);
+ if ((body == null ? void 0 : body.length) === 3) {
+ const param = body[1];
+ const doc = body[2];
+ const label2 = `*@${tag.name}* \`${param}\``;
+ if (!doc) {
+ return label2;
+ }
+ return label2 + (doc.match(/\r\n|\n/g) ? " \n" + processInlineTags(doc) : ` \u2014 ${processInlineTags(doc)}`);
+ }
+ }
+ const label = `*@${tag.name}*`;
+ const text = getTagBodyText(tag);
+ if (!text) {
+ return label;
+ }
+ return label + (text.match(/\r\n|\n/g) ? " \n" + text : ` \u2014 ${text}`);
+}
+function plain(parts) {
+ if (!parts || !parts.length)
+ return "";
+ return parts.map((part) => part.text).join("");
+}
+function tagsMarkdownPreview(tags) {
+ return (tags || []).map(getTagDocumentation).join(" \n\n");
+}
+function markdownDocumentation(documentation, tags) {
+ let out = plain(documentation);
+ const tagsPreview = tagsMarkdownPreview(tags);
+ if (tagsPreview) {
+ out = out + ("\n\n" + tagsPreview);
+ }
+ return {
+ kind: import_vscode_languageserver_protocol8.MarkupKind.Markdown,
+ value: out
+ };
+}
+function convertLinkTags(parts) {
+ var _a;
+ if (!parts) {
+ return "";
+ }
+ if (typeof parts === "string") {
+ return parts;
+ }
+ const out = [];
+ let currentLink;
+ for (const part of parts) {
+ switch (part.kind) {
+ case "link":
+ if (currentLink) {
+ const text = (_a = currentLink.text) != null ? _a : currentLink.name;
+ if (currentLink.target) {
+ const link = toResource(currentLink.target.file).with({
+ fragment: `L${currentLink.target.start.line},${currentLink.target.start.offset}`
+ });
+ out.push(`[${text}](${link.toString()})`);
+ } else {
+ if (text) {
+ if (/^https?:/.test(text)) {
+ const parts2 = text.split(" ");
+ if (parts2.length === 1) {
+ out.push(parts2[0]);
+ } else if (parts2.length > 1) {
+ out.push(`[${parts2.slice(1).join(" ")}](${parts2[0]})`);
}
+ } else {
+ out.push(text);
+ }
}
+ }
+ currentLink = void 0;
+ } else {
+ currentLink = {};
}
- return actions;
- }
- refactorActionToCodeAction(action, document, file, info, rangeOrSelection) {
- const codeAction = {
- title: action.description,
- kind: TypeScriptRefactorProvider.getKind(action)
- };
- codeAction.command = {
- title: action.description,
- command: ApplyRefactoringCommand.ID,
- arguments: [document, file, info.name, action.name, rangeOrSelection]
- };
- return codeAction;
- }
- shouldTrigger(context) {
- if (context.only &&
- context.only.indexOf(vscode_languageserver_protocol_1.CodeActionKind.Refactor) == -1) {
- return false;
- }
- return true;
- }
- static getKind(refactor) {
- if (refactor.name.startsWith('function_')) {
- return TypeScriptRefactorProvider.extractFunctionKind;
- }
- else if (refactor.name.startsWith('constant_')) {
- return TypeScriptRefactorProvider.extractConstantKind;
+ break;
+ case "linkName":
+ if (currentLink) {
+ currentLink.name = part.text;
+ currentLink.target = part.target;
}
- else if (refactor.name.startsWith('Move')) {
- return TypeScriptRefactorProvider.moveKind;
+ break;
+ case "linkText":
+ if (currentLink) {
+ currentLink.text = part.text;
}
- return vscode_languageserver_protocol_1.CodeActionKind.Refactor;
+ break;
+ default:
+ out.push(part.text);
+ break;
}
+ }
+ return processInlineTags(out.join(""));
}
-exports.default = TypeScriptRefactorProvider;
-TypeScriptRefactorProvider.extractFunctionKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.function';
-TypeScriptRefactorProvider.extractConstantKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.constant';
-TypeScriptRefactorProvider.moveKind = vscode_languageserver_protocol_1.CodeActionKind.Refactor + '.move';
-TypeScriptRefactorProvider.metadata = {
- providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.Refactor]
-};
-
-
-/***/ }),
-/* 102 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const typeConverters = __importStar(__webpack_require__(37));
-class TypeScriptReferences {
- constructor(client) {
- this.client = client;
- }
- provideReferences(document, position, context, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(document.uri);
- if (!filepath)
- return [];
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
- try {
- const msg = yield this.client.execute('references', args, token);
- if (!msg || msg.type != 'response' || !msg.body) {
- return [];
- }
- const result = [];
- for (const ref of msg.body.refs) {
- if (!context.includeDeclaration && ref.isDefinition) {
- continue;
- }
- const url = this.client.toResource(ref.file);
- const location = typeConverters.Location.fromTextSpan(url, ref);
- result.push(location);
- }
- return result;
- }
- catch (_a) {
- return [];
- }
- });
+// src/server/utils/SnippetString.ts
+var SnippetString = class {
+ constructor(value) {
+ this._tabstop = 1;
+ this.value = value || "";
+ }
+ static isSnippetString(thing) {
+ if (thing instanceof SnippetString) {
+ return true;
}
-}
-exports.default = TypeScriptReferences;
-
-
-/***/ }),
-/* 103 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
+ if (!thing) {
+ return false;
+ }
+ return typeof thing.value === "string";
+ }
+ static _escape(value) {
+ return value.replace(/\$|}|\\/g, "\\$&");
+ }
+ appendText(str) {
+ this.value += SnippetString._escape(str);
+ return this;
+ }
+ appendTabstop(n = this._tabstop++) {
+ this.value += "$";
+ this.value += n;
+ return this;
+ }
+ appendPlaceholder(value, n = this._tabstop++) {
+ if (typeof value === "function") {
+ const nested = new SnippetString();
+ nested._tabstop = this._tabstop;
+ value(nested);
+ this._tabstop = nested._tabstop;
+ value = nested.value;
+ } else {
+ value = SnippetString._escape(value);
+ }
+ this.value += "${";
+ this.value += n;
+ this.value += ":";
+ this.value += value;
+ this.value += "}";
+ return this;
+ }
+ appendVariable(name, defaultValue) {
+ if (typeof defaultValue === "function") {
+ const nested = new SnippetString();
+ nested._tabstop = this._tabstop;
+ defaultValue(nested);
+ this._tabstop = nested._tabstop;
+ defaultValue = nested.value;
+ } else if (typeof defaultValue === "string") {
+ defaultValue = defaultValue.replace(/\$|}/g, "\\$&");
+ }
+ this.value += "${";
+ this.value += name;
+ if (defaultValue) {
+ this.value += ":";
+ this.value += defaultValue;
+ }
+ this.value += "}";
+ return this;
+ }
+};
+var SnippetString_default = SnippetString;
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
+// src/server/features/completionItemProvider.ts
+var ApplyCompletionCodeActionCommand2 = class {
+ constructor(client) {
+ this.client = client;
+ this.id = ApplyCompletionCodeActionCommand2.ID;
+ }
+ async execute(codeActions) {
+ if (codeActions.length === 0) {
+ return;
+ }
+ if (codeActions.length === 1) {
+ await applyCodeAction(this.client, codeActions[0]);
+ return;
+ }
+ const idx = await import_coc8.window.showQuickpick(codeActions.map((o) => o.description), "Select code action to apply");
+ if (idx < 0)
+ return;
+ const action = codeActions[idx];
+ await applyCodeAction(this.client, action);
+ return;
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-const PConst = __importStar(__webpack_require__(39));
-const typeConverters = __importStar(__webpack_require__(37));
-const baseCodeLensProvider_1 = __webpack_require__(35);
-class TypeScriptReferencesCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
- resolveCodeLens(codeLens, token) {
- let { uri } = codeLens.data;
- let filepath = this.client.toPath(uri);
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
- return this.client
- .execute('references', args, token, true)
- .then(response => {
- if (!response || response.type != 'response' || !response.body) {
- throw codeLens;
- }
- const locations = response.body.refs
- .map(reference => typeConverters.Location.fromTextSpan(this.client.toResource(reference.file), reference))
- .filter(location =>
- // Exclude original definition from references
- !(location.uri.toString() === uri &&
- location.range.start.line === codeLens.range.start.line &&
- location.range.start.character ===
- codeLens.range.start.character));
- codeLens.command = {
- title: locations.length === 1 ? '1 reference' : `${locations.length} references`,
- command: locations.length ? 'editor.action.showReferences' : '',
- arguments: [uri, codeLens.range.start, locations]
- };
- return codeLens;
- })
- .catch(() => {
- codeLens.command = {
- title: '0 references',
- command: ''
- };
- return codeLens;
- });
- }
- extractSymbol(document, item, parent) {
- if (parent && parent.kind === PConst.Kind.enum) {
- return super.getSymbolRange(document, item);
- }
- switch (item.kind) {
- case PConst.Kind.const:
- case PConst.Kind.let:
- case PConst.Kind.variable:
- case PConst.Kind.function:
- // Only show references for exported variables
- if (!item.kindModifiers.match(/\bexport\b/)) {
- break;
- }
- // fallthrough
- case PConst.Kind.class:
- if (item.text === '<class>') {
- break;
- }
- // fallthrough
- case PConst.Kind.method:
- case PConst.Kind.memberVariable:
- case PConst.Kind.memberGetAccessor:
- case PConst.Kind.memberSetAccessor:
- case PConst.Kind.constructorImplementation:
- case PConst.Kind.interface:
- case PConst.Kind.type:
- case PConst.Kind.enum:
- return super.getSymbolRange(document, item);
+var ApplyCompletionCodeActionCommand = ApplyCompletionCodeActionCommand2;
+ApplyCompletionCodeActionCommand.ID = "_typescript.applyCompletionCodeAction";
+var TypeScriptCompletionItemProvider = class {
+ constructor(client, typingsStatus, fileConfigurationManager, languageId) {
+ this.client = client;
+ this.typingsStatus = typingsStatus;
+ this.fileConfigurationManager = fileConfigurationManager;
+ this.setCompleteOption(languageId);
+ import_coc8.commands.registerCommand(ApplyCompletionCodeActionCommand.ID, async (codeActions) => {
+ let cmd = new ApplyCompletionCodeActionCommand(this.client);
+ await cmd.execute(codeActions);
+ });
+ import_coc8.workspace.onDidChangeConfiguration((_e) => {
+ this.setCompleteOption(languageId);
+ });
+ }
+ setCompleteOption(languageId) {
+ this.completeOption = this.fileConfigurationManager.getCompleteOptions(languageId);
+ }
+ async provideCompletionItems(document, position, token, context) {
+ if (this.typingsStatus.isAcquiringTypings) {
+ return Promise.resolve({
+ isIncomplete: true,
+ items: [{
+ label: "Acquiring typings...",
+ detail: "Acquiring typings definitions for IntelliSense."
+ }]
+ });
+ }
+ let {uri} = document;
+ const file2 = this.client.toPath(document.uri);
+ if (!file2)
+ return null;
+ let preText = document.getText({
+ start: {line: position.line, character: 0},
+ end: position
+ });
+ let {triggerCharacter, option} = context;
+ if (!this.shouldTrigger(triggerCharacter, preText, option)) {
+ return null;
+ }
+ await this.client.interruptGetErr(() => this.fileConfigurationManager.ensureConfigurationForDocument(document, token));
+ const {completeOption} = this;
+ const args = {
+ ...Position.toFileLocationRequestArgs(file2, position),
+ includeExternalModuleExports: completeOption.autoImports,
+ includeInsertTextCompletions: true,
+ triggerCharacter: this.getTsTriggerCharacter(context),
+ includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions
+ };
+ let entries;
+ let dotAccessorContext;
+ let isNewIdentifierLocation = true;
+ let isMemberCompletion = false;
+ let isIncomplete = false;
+ const isInValidCommitCharacterContext = this.isInValidCommitCharacterContext(document, position);
+ if (this.client.apiVersion.gte(api_default.v300)) {
+ try {
+ const response = await this.client.interruptGetErr(() => this.client.execute("completionInfo", args, token));
+ if (response.type !== "response" || !response.body) {
+ return null;
+ }
+ isNewIdentifierLocation = response.body.isNewIdentifierLocation;
+ isMemberCompletion = response.body.isMemberCompletion;
+ if (isMemberCompletion) {
+ const dotMatch = preText.slice(0, position.character).match(/\??\.\s*$/) || void 0;
+ if (dotMatch) {
+ const range = import_vscode_languageserver_protocol9.Range.create({
+ line: position.line,
+ character: position.character - dotMatch.length
+ }, position);
+ const text = document.getText(range);
+ dotAccessorContext = {range, text};
+ }
+ }
+ isIncomplete = !!response.body.isIncomplete || response.metadata && response.metadata.isIncomplete;
+ entries = response.body.entries;
+ } catch (e) {
+ if (e.message == "No content available.") {
+ return null;
}
+ throw e;
+ }
+ } else {
+ const response = await this.client.interruptGetErr(() => this.client.execute("completions", args, token));
+ if (response.type !== "response" || !response.body) {
return null;
+ }
+ entries = response.body;
}
-}
-exports.default = TypeScriptReferencesCodeLensProvider;
-
-
-/***/ }),
-/* 104 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const coc_nvim_1 = __webpack_require__(1);
-const path_1 = __importDefault(__webpack_require__(13));
-const api_1 = __importDefault(__webpack_require__(40));
-const typeConverters = __importStar(__webpack_require__(37));
-class TypeScriptRenameProvider {
- constructor(client) {
- this.client = client;
- }
- prepareRename(document, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const response = yield this.execRename(document, position, token);
- if (!response || response.type !== 'response' || !response.body) {
- return null;
- }
- const renameInfo = response.body.info;
- if (!renameInfo.canRename) {
- return Promise.reject(new Error('Invalid location for rename.'));
- }
- if (this.client.apiVersion.gte(api_1.default.v310)) {
- const triggerSpan = renameInfo.triggerSpan;
- if (triggerSpan) {
- const range = typeConverters.Range.fromTextSpan(triggerSpan);
- return range;
- }
- }
- return null;
- });
+ const completionItems = [];
+ for (const element of entries) {
+ if (shouldExcludeCompletionEntry(element, completeOption)) {
+ continue;
+ }
+ const item = convertCompletionEntry(element, uri, position, {
+ isNewIdentifierLocation,
+ isMemberCompletion,
+ enableCallCompletions: completeOption.completeFunctionCalls,
+ isInValidCommitCharacterContext,
+ dotAccessorContext
+ });
+ completionItems.push(item);
+ }
+ return {isIncomplete, items: completionItems};
+ }
+ getTsTriggerCharacter(context) {
+ switch (context.triggerCharacter) {
+ case "@":
+ return this.client.apiVersion.gte(api_default.v310) && this.client.apiVersion.lt(api_default.v320) ? void 0 : "@";
+ case "#":
+ return this.client.apiVersion.lt(api_default.v381) ? void 0 : "#";
+ case " ":
+ return this.client.apiVersion.gte(api_default.v430) ? " " : void 0;
+ case ".":
+ case '"':
+ case "'":
+ case "`":
+ case "/":
+ case "<":
+ return context.triggerCharacter;
+ }
+ return void 0;
+ }
+ async resolveCompletionItem(item, token) {
+ if (item == null)
+ return void 0;
+ let {uri, position, source, name, data} = item.data;
+ const filepath = this.client.toPath(uri);
+ if (!filepath)
+ return void 0;
+ let document = import_coc8.workspace.getDocument(uri);
+ if (!document)
+ return void 0;
+ const args = {
+ ...Position.toFileLocationRequestArgs(filepath, position),
+ entryNames: [source ? {name, source, data} : name]
+ };
+ let response;
+ try {
+ response = await this.client.interruptGetErr(() => this.client.execute("completionEntryDetails", args, token));
+ } catch {
+ return item;
+ }
+ if (response.type !== "response" || !response.body || !response.body.length) {
+ return item;
+ }
+ const details = response.body;
+ if (!details || !details.length || !details[0]) {
+ return item;
+ }
+ const detail = details[0];
+ if (!item.detail && detail.displayParts.length) {
+ item.detail = plain(detail.displayParts);
+ }
+ item.documentation = this.getDocumentation(detail);
+ const {command, additionalTextEdits} = this.getCodeActions(detail, filepath);
+ if (command)
+ item.command = command;
+ item.additionalTextEdits = additionalTextEdits;
+ if (detail && item.insertTextFormat == import_vscode_languageserver_protocol9.InsertTextFormat.Snippet) {
+ const shouldCompleteFunction = await this.isValidFunctionCompletionContext(filepath, position, token);
+ if (shouldCompleteFunction) {
+ this.createSnippetOfFunctionCall(item, detail);
+ }
}
- provideRenameEdits(document, position, newName, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const response = yield this.execRename(document, position, token);
- if (!response || response.type !== 'response' || !response.body) {
- return null;
- }
- const renameInfo = response.body.info;
- if (!renameInfo.canRename) {
- return Promise.reject(new Error('Invalid location for rename.'));
- }
- if (this.client.apiVersion.gte(api_1.default.v310)) {
- if (renameInfo.fileToRename) {
- const edits = yield this.renameFile(renameInfo.fileToRename, newName, token);
- if (edits) {
- return edits;
- }
- else {
- return Promise.reject(new Error('An error occurred while renaming file'));
- }
- }
- }
- return this.toWorkspaceEdit(response.body.locs, newName);
- });
+ return item;
+ }
+ getCodeActions(detail, filepath) {
+ if (!detail.codeActions || !detail.codeActions.length) {
+ return {};
+ }
+ const additionalTextEdits = [];
+ let hasRemainingCommandsOrEdits = false;
+ for (const tsAction of detail.codeActions) {
+ if (tsAction.commands) {
+ hasRemainingCommandsOrEdits = true;
+ }
+ if (tsAction.changes) {
+ for (const change of tsAction.changes) {
+ if (change.fileName === filepath) {
+ additionalTextEdits.push(...change.textChanges.map(TextEdit.fromCodeEdit));
+ } else {
+ hasRemainingCommandsOrEdits = true;
+ }
+ }
+ }
}
- execRename(document, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const file = this.client.toPath(document.uri);
- if (!file)
- return undefined;
- const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { findInStrings: false, findInComments: false });
- return this.client.interruptGetErr(() => {
- return this.client.execute('rename', args, token);
- });
- });
+ let command = null;
+ if (hasRemainingCommandsOrEdits) {
+ command = {
+ title: "",
+ command: ApplyCompletionCodeActionCommand.ID,
+ arguments: [
+ detail.codeActions.map((x) => ({
+ commands: x.commands,
+ description: x.description,
+ changes: x.changes.filter((x2) => x2.fileName !== filepath)
+ }))
+ ]
+ };
}
- toWorkspaceEdit(locations, newName) {
- let changes = {};
- for (const spanGroup of locations) {
- const uri = this.client.toResource(spanGroup.file);
- if (uri) {
- changes[uri] = [];
- for (const textSpan of spanGroup.locs) {
- changes[uri].push({
- range: typeConverters.Range.fromTextSpan(textSpan),
- newText: (textSpan.prefixText || '') + newName + (textSpan.suffixText || '')
- });
- }
- }
+ return {
+ command,
+ additionalTextEdits: additionalTextEdits.length ? additionalTextEdits : void 0
+ };
+ }
+ shouldTrigger(triggerCharacter, pre, option) {
+ if (triggerCharacter && this.client.apiVersion.lt(api_default.v290)) {
+ if (triggerCharacter === "@") {
+ if (option.synname && /string/i.test(option.synname)) {
+ return true;
+ }
+ if (!pre.match(/^\s*\*[ ]?@/) && !pre.match(/\/\*\*+[ ]?@/)) {
+ return false;
}
- return { changes };
+ } else if (triggerCharacter === "<") {
+ return false;
+ }
}
- renameFile(fileToRename, newName, token) {
- return __awaiter(this, void 0, void 0, function* () {
- // Make sure we preserve file exension if none provided
- if (!path_1.default.extname(newName)) {
- newName += path_1.default.extname(fileToRename);
- }
- const dirname = path_1.default.dirname(fileToRename);
- const newFilePath = path_1.default.join(dirname, newName);
- const args = {
- file: fileToRename,
- oldFilePath: fileToRename,
- newFilePath
- };
- const response = yield this.client.execute('getEditsForFileRename', args, token);
- if (response.type !== 'response' || !response.body) {
- return undefined;
- }
- const edits = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, response.body);
- edits.documentChanges = edits.documentChanges || [];
- edits.documentChanges.push({
- kind: 'rename',
- oldUri: coc_nvim_1.Uri.file(fileToRename).toString(),
- newUri: coc_nvim_1.Uri.file(newFilePath).toString(),
- options: {
- overwrite: false,
- ignoreIfExists: true
- }
- });
- return edits;
- });
+ if (triggerCharacter === " ") {
+ if (!this.completeOption.importStatementSuggestions || !this.client.apiVersion.lt(api_default.v430)) {
+ return false;
+ }
+ return pre === "import ";
+ }
+ return true;
+ }
+ getDocumentation(detail) {
+ let documentation = "";
+ if (detail.source) {
+ const importPath = `'${plain(detail.source)}'`;
+ const autoImportLabel = `Auto import from ${importPath}`;
+ documentation += `${autoImportLabel}
+`;
+ }
+ let parts = [
+ plain(detail.documentation),
+ tagsMarkdownPreview(detail.tags)
+ ];
+ parts = parts.filter((s) => s && s.trim() != "");
+ documentation += parts.join("\n\n");
+ if (documentation.length) {
+ return {
+ kind: import_vscode_languageserver_protocol9.MarkupKind.Markdown,
+ value: documentation
+ };
+ }
+ return void 0;
+ }
+ createSnippetOfFunctionCall(item, detail) {
+ let {displayParts} = detail;
+ const parameterListParts = getParameterListParts(displayParts);
+ const snippet = new SnippetString_default();
+ snippet.appendText(`${item.insertText || item.label}(`);
+ appendJoinedPlaceholders(snippet, parameterListParts.parts, ", ");
+ if (parameterListParts.hasOptionalParameters) {
+ snippet.appendTabstop();
+ }
+ snippet.appendText(")");
+ snippet.appendTabstop(0);
+ item.insertText = snippet.value;
+ }
+ async isValidFunctionCompletionContext(filepath, position, token) {
+ try {
+ const args = Position.toFileLocationRequestArgs(filepath, position);
+ const response = await this.client.execute("quickinfo", args, token);
+ if (response.type !== "response") {
+ return true;
+ }
+ const {body} = response;
+ switch (body && body.kind) {
+ case "var":
+ case "let":
+ case "const":
+ case "alias":
+ return false;
+ default:
+ return true;
+ }
+ } catch (e) {
+ return true;
+ }
+ }
+ isInValidCommitCharacterContext(document, position) {
+ if (this.client.apiVersion.lt(api_default.v320)) {
+ if (position.character > 1) {
+ const preText = document.getText(import_vscode_languageserver_protocol9.Range.create(position.line, 0, position.line, position.character));
+ return preText.match(/(\s|^)\.$/ig) === null;
+ }
+ }
+ return true;
+ }
+};
+TypeScriptCompletionItemProvider.triggerCharacters = [".", '"', "'", "`", "/", "@", "<", "#", " "];
+var completionItemProvider_default = TypeScriptCompletionItemProvider;
+function shouldExcludeCompletionEntry(element, completionConfiguration) {
+ return !completionConfiguration.names && element.kind === Kind.warning || !completionConfiguration.paths && (element.kind === Kind.directory || element.kind === Kind.script || element.kind === Kind.externalModuleName) || !completionConfiguration.autoImports && element.hasAction;
+}
+function appendJoinedPlaceholders(snippet, parts, joiner) {
+ for (let i = 0; i < parts.length; ++i) {
+ const paramterPart = parts[i];
+ snippet.appendPlaceholder(paramterPart.text);
+ if (i !== parts.length - 1) {
+ snippet.appendText(joiner);
}
+ }
}
-exports.default = TypeScriptRenameProvider;
-
-
-/***/ }),
-/* 105 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const Previewer = __importStar(__webpack_require__(86));
-const typeConverters = __importStar(__webpack_require__(37));
-class TypeScriptSignatureHelpProvider {
- constructor(client) {
- this.client = client;
- }
- provideSignatureHelp(document, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(document.uri);
- if (!filepath) {
- return undefined;
- }
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
- let response;
- try {
- response = yield this.client.interruptGetErr(() => this.client.execute('signatureHelp', args, token));
- }
- catch (e) {
- return undefined;
- }
- if (response.type !== 'response' || !response.body) {
- return undefined;
- }
- let info = response.body;
- const result = {
- activeSignature: info.selectedItemIndex,
- activeParameter: this.getActiveParmeter(info),
- signatures: info.items.map(signature => {
- return this.convertSignature(signature);
- })
- };
- return result;
- });
+// src/server/features/definitionProvider.ts
+var TypeScriptDefinitionProvider = class {
+ constructor(client) {
+ this.client = client;
+ }
+ async getSymbolLocations(definitionType, document, position, token) {
+ const filepath = this.client.toPath(document.uri);
+ if (!filepath) {
+ return void 0;
+ }
+ const args = Position.toFileLocationRequestArgs(filepath, position);
+ try {
+ const response = await this.client.execute(definitionType, args, token);
+ const locations = response.type == "response" && response.body || [];
+ return locations.map((location) => Location2.fromTextSpan(this.client.toResource(location.file), location));
+ } catch {
+ return [];
}
- getActiveParmeter(info) {
- const activeSignature = info.items[info.selectedItemIndex];
- if (activeSignature && activeSignature.isVariadic) {
- return Math.min(info.argumentIndex, activeSignature.parameters.length - 1);
+ }
+ async provideDefinition(document, position, token) {
+ if (this.client.apiVersion.gte(api_default.v270)) {
+ const filepath = this.client.toOpenedFilePath(document.uri);
+ if (!filepath) {
+ return void 0;
+ }
+ const args = Position.toFileLocationRequestArgs(filepath, position);
+ const response = await this.client.execute("definitionAndBoundSpan", args, token);
+ if (response.type !== "response" || !response.body) {
+ return void 0;
+ }
+ const span = response.body.textSpan ? Range2.fromTextSpan(response.body.textSpan) : void 0;
+ return response.body.definitions.map((location) => {
+ const target = Location2.fromTextSpan(this.client.toResource(location.file), location);
+ if (location.contextStart && location.contextEnd) {
+ return {
+ originSelectionRange: span,
+ targetRange: Range2.fromLocations(location.contextStart, location.contextEnd),
+ targetUri: target.uri,
+ targetSelectionRange: target.range
+ };
}
- return info.argumentIndex;
- }
- convertSignature(item) {
- let parameters = item.parameters.map(p => {
- return {
- label: Previewer.plain(p.displayParts),
- documentation: Previewer.markdownDocumentation(p.documentation, [])
- };
- });
- let label = Previewer.plain(item.prefixDisplayParts);
- label += parameters.map(parameter => parameter.label).join(Previewer.plain(item.separatorDisplayParts));
- label += Previewer.plain(item.suffixDisplayParts);
return {
- label,
- documentation: Previewer.markdownDocumentation(item.documentation, item.tags.filter(x => x.name !== 'param')),
- parameters
+ originSelectionRange: span,
+ targetRange: target.range,
+ targetUri: target.uri,
+ targetSelectionRange: target.range
};
+ });
}
-}
-exports.default = TypeScriptSignatureHelpProvider;
-TypeScriptSignatureHelpProvider.triggerCharacters = ['(', ',', '<'];
-
-
-/***/ }),
-/* 106 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
+ return await this.getSymbolLocations("definition", document, position, token);
+ }
+ provideTypeDefinition(document, position, token) {
+ return this.getSymbolLocations("typeDefinition", document, position, token);
+ }
+ provideImplementation(document, position, token) {
+ return this.getSymbolLocations("implementation", document, position, token);
+ }
};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
+var definitionProvider_default = TypeScriptDefinitionProvider;
+
+// src/server/features/directiveCommentCompletions.ts
+var import_coc9 = __toModule(require("coc.nvim"));
+var import_coc10 = __toModule(require("coc.nvim"));
+var tsDirectives = [
+ {
+ value: "@ts-check",
+ description: "Enables semantic checking in a JavaScript file. Must be at the top of a file."
+ },
+ {
+ value: "@ts-nocheck",
+ description: "Disables semantic checking in a JavaScript file. Must be at the top of a file."
+ },
+ {
+ value: "@ts-ignore",
+ description: "Suppresses @ts-check errors on the next line of a file."
+ }
+];
+var tsDirectives390 = [
+ ...tsDirectives,
+ {
+ value: "@ts-expect-error",
+ description: "Suppresses @ts-check errors on the next line of a file, expecting at least one to exist."
+ }
+];
+var DirectiveCommentCompletionProvider = class {
+ constructor(client) {
+ this.client = client;
+ }
+ provideCompletionItems(document, position, _token, context) {
+ if (context.triggerCharacter != "@") {
+ return [];
+ }
+ const file2 = this.client.toPath(document.uri);
+ if (!file2) {
+ return [];
+ }
+ const doc = import_coc10.workspace.getDocument(document.uri);
+ const line = doc.getline(position.line);
+ const prefix = line.slice(0, position.character);
+ const match = prefix.match(/^\s*\/\/+\s?(@[a-zA-Z\-]*)?$/);
+ if (match) {
+ const directives = this.client.apiVersion.gte(api_default.v390) ? tsDirectives390 : tsDirectives;
+ let items = directives.map((directive) => {
+ const item = {label: directive.value};
+ item.kind = import_coc9.CompletionItemKind.Snippet;
+ item.detail = directive.description;
+ item.textEdit = {
+ range: import_coc9.Range.create(position.line, Math.max(0, position.character - (match[1] ? match[1].length : 0)), position.line, position.character),
+ newText: directive.value
+ };
+ return item;
+ });
+ let res = {
+ isIncomplete: false,
+ items
+ };
+ res.startcol = doc.fixStartcol(position, ["@"]);
+ return res;
+ }
+ return [];
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const coc_nvim_1 = __webpack_require__(1);
-const typeConverters = __importStar(__webpack_require__(37));
-const mutex_1 = __webpack_require__(107);
-function wait(ms) {
- return new Promise(resolve => {
- setTimeout(() => {
- resolve();
- }, ms);
- });
-}
-class UpdateImportsOnFileRenameHandler {
- constructor(client, fileConfigurationManager, languageId) {
- this.client = client;
- this.fileConfigurationManager = fileConfigurationManager;
- this.disposables = [];
- let glob = languageId == 'typescript' ? '**/*.{ts,tsx}' : '**/*.{js,jsx}';
- const watcher = coc_nvim_1.workspace.createFileSystemWatcher(glob);
- this.disposables.push(watcher);
- let mutex = new mutex_1.Mutex();
- watcher.onDidRename((e) => __awaiter(this, void 0, void 0, function* () {
- let release = yield mutex.acquire();
- try {
- yield this.doRename(e.oldUri, e.newUri);
- release();
- }
- catch (e) {
- this.client.logger.error('Error on rename:', e);
- release();
- }
- }), null, this.disposables);
- }
- dispose() {
- coc_nvim_1.disposeAll(this.disposables);
- }
- doRename(oldResource, newResource) {
- return __awaiter(this, void 0, void 0, function* () {
- if (oldResource.scheme !== 'file' || newResource.scheme !== 'file') {
- return;
- }
- const targetFile = newResource.fsPath;
- const oldFile = oldResource.fsPath;
- const newUri = newResource.toString();
- let oldDocument = coc_nvim_1.workspace.getDocument(oldResource.toString());
- if (oldDocument) {
- yield coc_nvim_1.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`);
- }
- let document = coc_nvim_1.workspace.getDocument(newUri);
- if (document) {
- yield coc_nvim_1.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`);
- yield wait(30);
- }
- document = yield coc_nvim_1.workspace.loadFile(newUri);
- if (!document)
- return;
- yield wait(50);
- const edits = yield this.getEditsForFileRename(document.textDocument, oldFile, targetFile);
- if (!edits)
- return;
- if (yield this.promptUser(newResource)) {
- yield coc_nvim_1.workspace.applyEdit(edits);
- }
- });
- }
- promptUser(newResource) {
- return __awaiter(this, void 0, void 0, function* () {
- return yield coc_nvim_1.workspace.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`);
- });
+var directiveCommentCompletions_default = DirectiveCommentCompletionProvider;
+
+// src/server/features/documentHighlight.ts
+var import_vscode_languageserver_protocol10 = __toModule(require_main3());
+var TypeScriptDocumentHighlightProvider = class {
+ constructor(client) {
+ this.client = client;
+ }
+ async provideDocumentHighlights(resource, position, token) {
+ const file2 = this.client.toPath(resource.uri);
+ if (!file2)
+ return [];
+ const args = {
+ ...Position.toFileLocationRequestArgs(file2, position),
+ filesToSearch: [file2]
+ };
+ try {
+ const response = await this.client.execute("documentHighlights", args, token);
+ if (response.type !== "response" || !response.body) {
+ return [];
+ }
+ return flatten(response.body.filter((highlight) => highlight.file === file2).map(convertDocumentHighlight));
+ } catch (_e) {
+ return [];
}
- getEditsForFileRename(document, oldFile, newFile) {
- return __awaiter(this, void 0, void 0, function* () {
- yield this.fileConfigurationManager.ensureConfigurationForDocument(document);
- const response = yield this.client.interruptGetErr(() => {
- const args = {
- oldFilePath: oldFile,
- newFilePath: newFile,
- };
- return this.client.execute('getEditsForFileRename', args, vscode_languageserver_protocol_1.CancellationToken.None);
- });
- if (!response || response.type != 'response' || !response.body) {
- return;
- }
- const edits = [];
- for (const edit of response.body) {
- // Workaround for https://github.com/Microsoft/vscode/issues/52675
- if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) {
- continue;
- }
- for (const change of edit.textChanges) {
- if (change.newText.match(/\/node_modules\//gi)) {
- continue;
- }
- }
- edits.push(edit);
- }
- return typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, edits);
- });
+ }
+};
+var documentHighlight_default = TypeScriptDocumentHighlightProvider;
+function convertDocumentHighlight(highlight) {
+ return highlight.highlightSpans.map((span) => {
+ return {
+ range: Range2.fromTextSpan(span),
+ kind: span.kind === "writtenReference" ? import_vscode_languageserver_protocol10.DocumentHighlightKind.Write : import_vscode_languageserver_protocol10.DocumentHighlightKind.Read
+ };
+ });
+}
+
+// src/server/features/documentSymbol.ts
+var import_vscode_languageserver_protocol11 = __toModule(require_main3());
+var getSymbolKind2 = (kind) => {
+ switch (kind) {
+ case Kind.module:
+ return import_vscode_languageserver_protocol11.SymbolKind.Module;
+ case Kind.class:
+ return import_vscode_languageserver_protocol11.SymbolKind.Class;
+ case Kind.enum:
+ return import_vscode_languageserver_protocol11.SymbolKind.Enum;
+ case Kind.interface:
+ return import_vscode_languageserver_protocol11.SymbolKind.Interface;
+ case Kind.method:
+ return import_vscode_languageserver_protocol11.SymbolKind.Method;
+ case Kind.memberVariable:
+ return import_vscode_languageserver_protocol11.SymbolKind.Property;
+ case Kind.memberGetAccessor:
+ return import_vscode_languageserver_protocol11.SymbolKind.Property;
+ case Kind.memberSetAccessor:
+ return import_vscode_languageserver_protocol11.SymbolKind.Property;
+ case Kind.variable:
+ return import_vscode_languageserver_protocol11.SymbolKind.Variable;
+ case Kind.const:
+ return import_vscode_languageserver_protocol11.SymbolKind.Variable;
+ case Kind.localVariable:
+ return import_vscode_languageserver_protocol11.SymbolKind.Variable;
+ case Kind.variable:
+ return import_vscode_languageserver_protocol11.SymbolKind.Variable;
+ case Kind.constructSignature:
+ case Kind.constructorImplementation:
+ case Kind.function:
+ case Kind.localFunction:
+ return import_vscode_languageserver_protocol11.SymbolKind.Function;
+ }
+ return import_vscode_languageserver_protocol11.SymbolKind.Variable;
+};
+var TypeScriptDocumentSymbolProvider = class {
+ constructor(client) {
+ this.client = client;
+ }
+ async provideDocumentSymbols(resource, token) {
+ const filepath = this.client.toPath(resource.uri);
+ if (!filepath)
+ return [];
+ const args = {
+ file: filepath
+ };
+ try {
+ const response = await this.client.execute("navtree", args, token);
+ if (response.type == "response" && response.body) {
+ const tree = response.body;
+ if (tree.childItems) {
+ const result = new Array();
+ tree.childItems.forEach((item) => TypeScriptDocumentSymbolProvider.convertNavTree(result, item));
+ return result;
+ }
+ }
+ return [];
+ } catch (e) {
+ return [];
}
-}
-exports.default = UpdateImportsOnFileRenameHandler;
-
-
-/***/ }),
-/* 107 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Mutex = void 0;
-class Mutex {
- constructor() {
- this.tasks = [];
- this.count = 1;
- }
- sched() {
- if (this.count > 0 && this.tasks.length > 0) {
- this.count--;
- let next = this.tasks.shift();
- next();
- }
- }
- get busy() {
- return this.count == 0;
- }
- // tslint:disable-next-line: typedef
- acquire() {
- return new Promise(res => {
- let task = () => {
- let released = false;
- res(() => {
- if (!released) {
- released = true;
- this.count++;
- this.sched();
- }
- });
- };
- this.tasks.push(task);
- process.nextTick(this.sched.bind(this));
- });
+ }
+ static convertNavTree(output, item) {
+ let shouldInclude = TypeScriptDocumentSymbolProvider.shouldInclueEntry(item);
+ const children = new Set(item.childItems || []);
+ for (const span of item.spans) {
+ const range = Range2.fromTextSpan(span);
+ const symbolInfo = TypeScriptDocumentSymbolProvider.convertSymbol(item, range);
+ if (children.size)
+ symbolInfo.children = [];
+ for (const child of children) {
+ if (child.spans.some((span2) => !!containsRange(range, Range2.fromTextSpan(span2)))) {
+ const includedChild = TypeScriptDocumentSymbolProvider.convertNavTree(symbolInfo.children, child);
+ shouldInclude = shouldInclude || includedChild;
+ children.delete(child);
+ }
+ }
+ if (shouldInclude) {
+ output.push(symbolInfo);
+ }
}
- use(f) {
- return this.acquire()
- .then(release => {
- return f()
- .then(res => {
- release();
- return res;
- })
- .catch(err => {
- release();
- throw err;
- });
- });
+ return shouldInclude;
+ }
+ static convertSymbol(item, range) {
+ const selectionRange = item.nameSpan ? Range2.fromTextSpan(item.nameSpan) : range;
+ let label = item.text;
+ switch (item.kind) {
+ case Kind.memberGetAccessor:
+ label = `(get) ${label}`;
+ break;
+ case Kind.memberSetAccessor:
+ label = `(set) ${label}`;
+ break;
+ }
+ const symbolInfo = import_vscode_languageserver_protocol11.DocumentSymbol.create(label, "", getSymbolKind2(item.kind), range, containsRange(range, selectionRange) ? selectionRange : range);
+ const kindModifiers = parseKindModifier3(item.kindModifiers);
+ if (kindModifiers.has(KindModifiers.deprecated)) {
+ symbolInfo.tags = [import_vscode_languageserver_protocol11.SymbolTag.Deprecated];
+ }
+ return symbolInfo;
+ }
+ static shouldInclueEntry(item) {
+ if (item.kind === Kind.alias) {
+ return false;
}
+ return !!(item.text && item.text !== "<function>" && item.text !== "<class>");
+ }
+};
+var documentSymbol_default = TypeScriptDocumentSymbolProvider;
+function containsRange(range, otherRange) {
+ if (otherRange.start.line < range.start.line || otherRange.end.line < range.start.line) {
+ return false;
+ }
+ if (otherRange.start.line > range.end.line || otherRange.end.line > range.end.line) {
+ return false;
+ }
+ if (otherRange.start.line === range.start.line && otherRange.start.character < range.start.character) {
+ return false;
+ }
+ if (otherRange.end.line === range.end.line && otherRange.end.character > range.end.character) {
+ return false;
+ }
+ return true;
+}
+function parseKindModifier3(kindModifiers) {
+ return new Set(kindModifiers.split(/,|\s+/g));
}
-exports.Mutex = Mutex;
-
-
-/***/ }),
-/* 108 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const coc_nvim_1 = __webpack_require__(1);
-const path_1 = __importDefault(__webpack_require__(13));
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const countRegex = /Found\s+(\d+)\s+error/;
-const errorRegex = /^(.+)\((\d+),(\d+)\):\s(\w+)\sTS(\d+):\s*(.+)$/;
-var TscStatus;
-(function (TscStatus) {
- TscStatus[TscStatus["INIT"] = 0] = "INIT";
- TscStatus[TscStatus["COMPILING"] = 1] = "COMPILING";
- TscStatus[TscStatus["RUNNING"] = 2] = "RUNNING";
- TscStatus[TscStatus["ERROR"] = 3] = "ERROR";
-})(TscStatus || (TscStatus = {}));
-class WatchProject {
- constructor(commandManager, client) {
- this.client = client;
- this.disposables = [];
- this.statusItem = coc_nvim_1.workspace.createStatusBarItem(1, { progress: true });
- let task = this.task = coc_nvim_1.workspace.createTask('TSC');
- this.disposables.push(commandManager.registerCommand(WatchProject.id, () => __awaiter(this, void 0, void 0, function* () {
- let opts = this.options = yield this.getOptions();
- yield this.start(opts);
- })));
- task.onExit(code => {
- if (code != 0) {
- coc_nvim_1.workspace.showMessage(`TSC exit with code ${code}`, 'warning');
- }
- this.onStop();
- });
- task.onStdout(lines => {
- for (let line of lines) {
- this.onLine(line);
- }
- });
- task.onStderr(lines => {
- coc_nvim_1.workspace.showMessage(`TSC error: ` + lines.join('\n'), 'error');
- });
- this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => {
- task.dispose();
- }));
- this.check().catch(_e => {
- // noop
- });
- }
- check() {
- return __awaiter(this, void 0, void 0, function* () {
- let running = yield this.task.running;
- if (running) {
- this.options = yield this.getOptions();
- this.statusItem.isProgress = false;
- this.statusItem.text = '?';
- this.statusItem.show();
- }
- else {
- this.onStop();
- }
- });
- }
- start(options) {
- return __awaiter(this, void 0, void 0, function* () {
- yield this.task.start(options);
- });
+// src/server/features/folding.ts
+var import_coc11 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_types = __toModule(require_main2());
+var TypeScriptFoldingProvider = class {
+ constructor(client) {
+ this.client = client;
+ }
+ async provideFoldingRanges(document, _context, token) {
+ const file2 = this.client.toPath(document.uri);
+ if (!file2) {
+ return;
}
- onStop() {
- this.statusItem.hide();
+ const args = {file: file2};
+ const res = await this.client.execute("getOutliningSpans", args, token);
+ if (res.type != "response") {
+ return;
}
- onStart() {
- this.statusItem.text = 'compiling';
- this.statusItem.isProgress = true;
- this.statusItem.show();
- coc_nvim_1.workspace.nvim.call('setqflist', [[]], true);
+ const {body} = res;
+ if (!body) {
+ return;
}
- onLine(line) {
- if (countRegex.test(line)) {
- let ms = line.match(countRegex);
- this.statusItem.text = ms[1] == '0' ? '✓' : '✗';
- this.statusItem.isProgress = false;
- }
- else if (WatchProject.startTexts.findIndex(s => line.indexOf(s) !== -1) != -1) {
- this.onStart();
- }
- else {
- let ms = line.match(errorRegex);
- if (!ms)
- return;
- let fullpath = path_1.default.join(this.options.cwd, ms[1]);
- let uri = coc_nvim_1.Uri.file(fullpath).toString();
- let doc = coc_nvim_1.workspace.getDocument(uri);
- let bufnr = doc ? doc.bufnr : null;
- let item = {
- filename: fullpath,
- lnum: Number(ms[2]),
- col: Number(ms[3]),
- text: `[tsc ${ms[5]}] ${ms[6]}`,
- type: /error/i.test(ms[4]) ? 'E' : 'W'
- };
- if (bufnr)
- item.bufnr = bufnr;
- coc_nvim_1.workspace.nvim.call('setqflist', [[item], 'a']);
- }
- }
- getOptions() {
- return __awaiter(this, void 0, void 0, function* () {
- let { tscPath } = this.client;
- if (!tscPath) {
- coc_nvim_1.workspace.showMessage(`Local & global tsc not found`, 'error');
- return;
- }
- let find = yield coc_nvim_1.workspace.findUp(['tsconfig.json']);
- if (!find) {
- coc_nvim_1.workspace.showMessage('tsconfig.json not found!', 'error');
- return;
- }
- let root = path_1.default.dirname(find);
- return {
- cmd: tscPath,
- args: ['-p', 'tsconfig.json', '--watch', 'true', '--pretty', 'false'],
- cwd: root
- };
- });
+ return body.map((span) => this.convertOutliningSpan(span, document)).filter((foldingRange) => !!foldingRange);
+ }
+ convertOutliningSpan(span, document) {
+ const range = Range2.fromTextSpan(span.textSpan);
+ const kind = TypeScriptFoldingProvider.getFoldingRangeKind(span);
+ if (span.kind === "comment") {
+ let doc = import_coc11.workspace.getDocument(document.uri);
+ const line = doc.getline(range.start.line);
+ if (line.match(/\/\/\s*#endregion/gi)) {
+ return void 0;
+ }
}
- dispose() {
- coc_nvim_1.disposeAll(this.disposables);
+ let {start, end} = range;
+ return import_vscode_languageserver_types.FoldingRange.create(start.line, end.line, start.character, end.character, kind);
+ }
+ static getFoldingRangeKind(span) {
+ switch (span.kind) {
+ case "comment":
+ case "region":
+ case "imports":
+ case "code":
+ return span.kind;
+ default:
+ return void 0;
}
-}
-exports.default = WatchProject;
-WatchProject.id = 'tsserver.watchBuild';
-WatchProject.startTexts = ['Starting compilation in watch mode', 'Starting incremental compilation'];
-
-
-/***/ }),
-/* 109 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const coc_nvim_1 = __webpack_require__(1);
-const typeConverters = __importStar(__webpack_require__(37));
-const api_1 = __importDefault(__webpack_require__(40));
-function getSymbolKind(item) {
- switch (item.kind) {
- case 'method':
- return vscode_languageserver_protocol_1.SymbolKind.Method;
- case 'enum':
- return vscode_languageserver_protocol_1.SymbolKind.Enum;
- case 'function':
- return vscode_languageserver_protocol_1.SymbolKind.Function;
- case 'class':
- return vscode_languageserver_protocol_1.SymbolKind.Class;
- case 'interface':
- return vscode_languageserver_protocol_1.SymbolKind.Interface;
- case 'var':
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- default:
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- }
-}
-class TypeScriptWorkspaceSymbolProvider {
- constructor(client, languageIds) {
- this.client = client;
- this.languageIds = languageIds;
- }
- provideWorkspaceSymbols(search, token) {
- return __awaiter(this, void 0, void 0, function* () {
- let filepath;
- if (this.searchAllOpenProjects) {
- filepath = undefined;
- }
- else {
- let uri = this.getUri();
- filepath = uri ? this.client.toPath(uri) : undefined;
- if (!filepath && this.client.apiVersion.lt(api_1.default.v390)) {
- return [];
- }
- }
- const args = {
- file: filepath,
- searchValue: search,
- maxResultCount: 256,
- };
- const response = yield this.client.execute('navto', args, token);
- if (response.type !== 'response' || response.body == null)
- return [];
- const result = [];
- for (const item of response.body) {
- if (!item.containerName && item.kind === 'alias') {
- continue;
- }
- const label = TypeScriptWorkspaceSymbolProvider.getLabel(item);
- const range = {
- start: typeConverters.Position.fromLocation(item.start),
- end: typeConverters.Position.fromLocation(item.end),
- };
- const symbolInfo = vscode_languageserver_protocol_1.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file));
- result.push(symbolInfo);
- }
- return result;
- });
+var folding_default = TypeScriptFoldingProvider;
+
+// src/server/features/formatting.ts
+var import_coc12 = __toModule(require("coc.nvim"));
+var TypeScriptFormattingProvider = class {
+ constructor(client, formattingOptionsManager) {
+ this.client = client;
+ this.formattingOptionsManager = formattingOptionsManager;
+ }
+ enabled(document) {
+ return this.formattingOptionsManager.formatEnabled(document);
+ }
+ async doFormat(document, options, args, token) {
+ if (!this.enabled(document))
+ return [];
+ await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
+ try {
+ const response = await this.client.execute("format", args, token);
+ if (response.type == "response" && response.body) {
+ let edits = response.body.map(TextEdit.fromCodeEdit);
+ return edits;
+ }
+ } catch {
}
- static getLabel(item) {
- let label = item.name;
- if (item.kind === 'method' || item.kind === 'function') {
- label += '()';
- }
- return label;
- }
- getUri() {
- // typescript wants to have a resource even when asking
- // general questions so we check the active editor. If this
- // doesn't match we take the first TS document.
- const documents = coc_nvim_1.workspace.textDocuments;
- for (const document of documents) {
- if (this.languageIds.indexOf(document.languageId) >= 0) {
- return document.uri;
- }
+ return [];
+ }
+ async provideDocumentRangeFormattingEdits(document, range, options, token) {
+ if (!this.enabled(document))
+ return [];
+ const filepath = this.client.toPath(document.uri);
+ if (!filepath)
+ return [];
+ const args = {
+ file: filepath,
+ line: range.start.line + 1,
+ offset: range.start.character + 1,
+ endLine: range.end.line + 1,
+ endOffset: range.end.character + 1
+ };
+ return this.doFormat(document, options, args, token);
+ }
+ async provideDocumentFormattingEdits(document, options, token) {
+ if (!this.enabled(document))
+ return [];
+ const filepath = this.client.toPath(document.uri);
+ if (!filepath)
+ return [];
+ const args = {
+ file: filepath,
+ line: 1,
+ offset: 1,
+ endLine: document.lineCount + 1,
+ endOffset: 1
+ };
+ return this.doFormat(document, options, args, token);
+ }
+ async provideOnTypeFormattingEdits(document, position, ch, options, token) {
+ if (!this.enabled(document))
+ return [];
+ if (!this.client.configuration.formatOnType)
+ return [];
+ const file2 = this.client.toPath(document.uri);
+ if (!file2)
+ return [];
+ await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
+ const doc = import_coc12.workspace.getDocument(document.uri);
+ const args = {
+ ...Position.toFileLocationRequestArgs(file2, position),
+ key: ch
+ };
+ try {
+ const res = await this.client.execute("formatonkey", args, token);
+ if (res.type != "response") {
+ return [];
+ }
+ const {body} = res;
+ const edits = body;
+ const result = [];
+ if (!edits) {
+ return result;
+ }
+ for (const edit of edits) {
+ const textEdit = TextEdit.fromCodeEdit(edit);
+ const range = textEdit.range;
+ if (range.start.character === 0 && range.start.line === range.end.line && textEdit.newText === "") {
+ const lText = doc.getline(range.start.line);
+ if (lText.trim().length > 0 || lText.length > range.end.character) {
+ result.push(textEdit);
+ }
+ } else {
+ result.push(textEdit);
}
- return undefined;
- }
- get searchAllOpenProjects() {
- return this.client.apiVersion.gte(api_1.default.v390)
- && coc_nvim_1.workspace.getConfiguration('typescript').get('workspaceSymbols.scope', 'allOpenProjects') === 'allOpenProjects';
+ }
+ return result;
+ } catch {
}
-}
-exports.default = TypeScriptWorkspaceSymbolProvider;
-
-
-/***/ }),
-/* 110 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
+ return [];
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-const typeConverters = __importStar(__webpack_require__(37));
-class SmartSelection {
- constructor(client) {
- this.client = client;
- }
- provideSelectionRanges(document, positions, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const file = this.client.toPath(document.uri);
- if (!file) {
- return undefined;
- }
- const args = {
- file,
- locations: positions.map(typeConverters.Position.toLocation)
- };
- const response = yield this.client.execute('selectionRange', args, token);
- if (response.type !== 'response' || !response.body) {
- return undefined;
- }
- return response.body.map(SmartSelection.convertSelectionRange);
- });
- }
- static convertSelectionRange(selectionRange) {
+var formatting_default = TypeScriptFormattingProvider;
+
+// src/server/features/hover.ts
+var TypeScriptHoverProvider = class {
+ constructor(client) {
+ this.client = client;
+ }
+ async provideHover(document, position, token) {
+ const filepath = this.client.toPath(document.uri);
+ if (!filepath) {
+ return void 0;
+ }
+ const args = Position.toFileLocationRequestArgs(filepath, position);
+ try {
+ const response = await this.client.interruptGetErr(() => this.client.execute("quickinfo", args, token));
+ if (response && response.type == "response" && response.body) {
+ const data = response.body;
return {
- range: typeConverters.Range.fromTextSpan(selectionRange.textSpan),
- parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : undefined,
+ contents: TypeScriptHoverProvider.getContents(data),
+ range: Range2.fromTextSpan(data)
};
+ }
+ } catch (e) {
}
-}
-exports.default = SmartSelection;
-
-
-/***/ }),
-/* 111 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const coc_nvim_1 = __webpack_require__(1);
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const modules_1 = __webpack_require__(112);
-class InstallModuleCommand {
- constructor() {
- this.id = InstallModuleCommand.ID;
+ return void 0;
+ }
+ static getContents(data) {
+ const parts = [];
+ if (data.displayString) {
+ parts.push({language: "typescript", value: data.displayString});
}
- execute(uri, name) {
- return __awaiter(this, void 0, void 0, function* () {
- yield modules_1.installModules(uri, [name]);
- });
+ const tags = tagsMarkdownPreview(data.tags);
+ parts.push(data.documentation + (tags ? "\n\n" + tags : ""));
+ return parts;
+ }
+};
+var hover_default = TypeScriptHoverProvider;
+
+// src/server/features/implementationsCodeLens.ts
+var TypeScriptImplementationsCodeLensProvider = class extends TypeScriptBaseCodeLensProvider {
+ async resolveCodeLens(codeLens, token) {
+ let {uri} = codeLens.data;
+ let filepath = this.client.toPath(uri);
+ const args = Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
+ try {
+ const response = await this.client.execute("implementation", args, token, {lowPriority: true});
+ if (response && response.type == "response" && response.body) {
+ const locations = response.body.map((reference) => {
+ return {
+ uri: this.client.toResource(reference.file),
+ range: {
+ start: Position.fromLocation(reference.start),
+ end: {
+ line: reference.start.line,
+ character: 0
+ }
+ }
+ };
+ }).filter((location) => !(location.uri.toString() === uri && location.range.start.line === codeLens.range.start.line && location.range.start.character === codeLens.range.start.character));
+ codeLens.command = this.getCommand(locations, codeLens);
+ return codeLens;
+ }
+ } catch {
}
-}
-InstallModuleCommand.ID = '_tsserver.installModule';
-class InstallModuleProvider {
- constructor(client) {
- this.client = client;
- coc_nvim_1.commands.register(new InstallModuleCommand(), true);
- }
- provideCodeActions(document, _range, context, _token) {
- return __awaiter(this, void 0, void 0, function* () {
- const uri = coc_nvim_1.Uri.parse(document.uri);
- if (uri.scheme != 'file')
- return null;
- let { diagnostics } = context;
- let diags = diagnostics.filter(s => s.code == 2307);
- let names = diags.map(o => {
- let ms = o.message.match(/module\s'(.+)'\./);
- return ms ? ms[1] : null;
- });
- names = names.filter(s => s != null);
- if (!names.length)
- return null;
- let actions = [];
- for (let name of names) {
- let title = `install ${name}`;
- let command = {
- title: `install ${name}`,
- command: InstallModuleCommand.ID,
- arguments: [document.uri, name]
- };
- let codeAction = vscode_languageserver_protocol_1.CodeAction.create(title, command);
- actions.push(codeAction);
- }
- return actions;
+ codeLens.command = {
+ title: "0 implementations",
+ command: ""
+ };
+ return codeLens;
+ }
+ getCommand(locations, codeLens) {
+ let {uri} = codeLens.data;
+ return {
+ title: this.getTitle(locations),
+ command: locations.length ? "editor.action.showReferences" : "",
+ arguments: [uri, codeLens.range.start, locations]
+ };
+ }
+ getTitle(locations) {
+ return locations.length === 1 ? "1 implementation" : `${locations.length} implementations`;
+ }
+ extractSymbol(document, item, _parent) {
+ switch (item.kind) {
+ case Kind.interface:
+ return super.getSymbolRange(document, item);
+ case Kind.class:
+ case Kind.method:
+ case Kind.memberVariable:
+ case Kind.memberGetAccessor:
+ case Kind.memberSetAccessor:
+ if (item.kindModifiers.match(/\babstract\b/g)) {
+ return super.getSymbolRange(document, item);
+ }
+ break;
+ }
+ return null;
+ }
+};
+var implementationsCodeLens_default = TypeScriptImplementationsCodeLensProvider;
+
+// src/server/features/importFix.ts
+var import_coc13 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol12 = __toModule(require_main3());
+
+// src/server/utils/helper.ts
+var nodeModules = [
+ "assert",
+ "cluster",
+ "crypto",
+ "dns",
+ "domain",
+ "events",
+ "fs",
+ "http",
+ "http2",
+ "https",
+ "inspector",
+ "net",
+ "os",
+ "path",
+ "punycode",
+ "querystring",
+ "readline",
+ "repl",
+ "stream",
+ "string_decoder",
+ "tls",
+ "tty",
+ "url",
+ "util",
+ "v8",
+ "vm",
+ "zlib",
+ "perf_hooks"
+];
+
+// src/server/features/importFix.ts
+var ImportFixProvider = class {
+ constructor(bufferSyncSupport) {
+ this.bufferSyncSupport = bufferSyncSupport;
+ }
+ async provideCodeActions(document, _range, context, _token) {
+ if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
+ return [];
+ }
+ let diagnostics = context.diagnostics.filter((d) => d.code == 2304);
+ if (!diagnostics.length)
+ return [];
+ let edits = [];
+ let names = [];
+ let doc = import_coc13.workspace.getDocument(document.uri);
+ let command;
+ for (const diagnostic of diagnostics) {
+ let {range} = diagnostic;
+ let line = doc.getline(range.start.line);
+ let name = line.slice(range.start.character, range.end.character);
+ if (names.indexOf(name) !== -1)
+ continue;
+ if (nodeModules.indexOf(name) !== -1) {
+ names.push(name);
+ edits.push({
+ range: import_vscode_languageserver_protocol12.Range.create(0, 0, 0, 0),
+ newText: `import ${name} from '${name}'
+`
});
+ command = "tsserver.organizeImports";
+ }
}
-}
-exports.default = InstallModuleProvider;
-
-
-/***/ }),
-/* 112 */
-/***/ (function(module, exports, __webpack_require__) {
+ let edit = {
+ changes: {
+ [document.uri]: edits
+ }
+ };
+ let cmd = null;
+ if (command)
+ cmd = {
+ title: `fix import`,
+ command: "tsserver.organizeImports"
+ };
+ return [{
+ title: `Add import ${names.join(", ")}`,
+ edit,
+ command: cmd
+ }];
+ }
+};
+var importFix_default = ImportFixProvider;
-"use strict";
+// src/server/features/moduleInstall.ts
+var import_coc15 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol13 = __toModule(require_main3());
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.installModules = exports.distinct = exports.moduleExists = exports.runCommand = void 0;
-const child_process_1 = __webpack_require__(113);
-const path_1 = __importDefault(__webpack_require__(13));
-const coc_nvim_1 = __webpack_require__(1);
+// src/server/utils/modules.ts
+var import_child_process = __toModule(require("child_process"));
+var import_coc14 = __toModule(require("coc.nvim"));
+var import_fs = __toModule(require("fs"));
+var import_path3 = __toModule(require("path"));
function runCommand(cmd, cwd, timeout) {
- return new Promise((resolve, reject) => {
- let timer;
- if (timeout) {
- timer = setTimeout(() => {
- reject(new Error(`timeout after ${timeout}s`));
- }, timeout * 1000);
- }
- child_process_1.exec(cmd, { cwd }, (err, stdout) => {
- if (timer)
- clearTimeout(timer);
- if (err) {
- reject(new Error(`exited with ${err.code}`));
- return;
- }
- resolve(stdout);
- });
- });
-}
-exports.runCommand = runCommand;
-function getManager() {
- return __awaiter(this, void 0, void 0, function* () {
- let res = yield coc_nvim_1.workspace.findUp(['yarn.lock', 'package-lock.json']);
- if (!res)
- return 'yarn';
- return res.endsWith('yarn.lock') ? 'yarn' : 'npm';
+ return new Promise((resolve, reject) => {
+ let timer;
+ if (timeout) {
+ timer = setTimeout(() => {
+ reject(new Error(`timeout after ${timeout}s`));
+ }, timeout * 1e3);
+ }
+ import_child_process.exec(cmd, {cwd}, (err, stdout) => {
+ if (timer)
+ clearTimeout(timer);
+ if (err) {
+ reject(new Error(`exited with ${err.code}`));
+ return;
+ }
+ resolve(stdout);
});
+ });
}
-function getRoot() {
- return __awaiter(this, void 0, void 0, function* () {
- let res = yield coc_nvim_1.workspace.findUp(['package.json']);
- if (!res)
- return null;
- return path_1.default.dirname(res);
- });
+async function getManager() {
+ let res = await import_coc14.workspace.findUp(["yarn.lock", "package-lock.json"]);
+ if (!res)
+ return "yarn";
+ return res.endsWith("yarn.lock") ? "yarn" : "npm";
}
-function moduleExists(name) {
- return __awaiter(this, void 0, void 0, function* () {
- try {
- let content = yield runCommand(`npm info ${name} --json`, process.cwd());
- if (!content)
- return false;
- let obj = JSON.parse(content);
- if (obj.error != null)
- return false;
- return true;
- }
- catch (e) {
- return false;
- }
- return false;
- });
+async function moduleExists(name) {
+ try {
+ let content = await runCommand(`npm info ${name} --json`, process.cwd());
+ if (!content)
+ return false;
+ let obj = JSON.parse(content);
+ if (obj.error != null)
+ return false;
+ return true;
+ } catch (e) {
+ return false;
+ }
+ return false;
}
-exports.moduleExists = moduleExists;
-/**
- * Removes duplicates from the given array. The optional keyFn allows to specify
- * how elements are checked for equalness by returning a unique string for each.
- */
function distinct(array, keyFn) {
- if (!keyFn) {
- return array.filter((element, position) => {
- return array.indexOf(element) === position;
- });
- }
- const seen = Object.create(null);
- return array.filter(elem => {
- const key = keyFn(elem);
- if (seen[key]) {
- return false;
- }
- seen[key] = true;
- return true;
+ if (!keyFn) {
+ return array.filter((element, position) => {
+ return array.indexOf(element) === position;
});
-}
-exports.distinct = distinct;
-function installModules(uri, names) {
- return __awaiter(this, void 0, void 0, function* () {
- names = distinct(names);
- let root = yield getRoot();
- if (!root) {
- coc_nvim_1.workspace.showMessage(`package.json not found from cwd: ${coc_nvim_1.workspace.cwd}`, 'error');
- return;
- }
- let arr = names.concat(names.map(s => `@types/${s}`));
- let statusItem = coc_nvim_1.workspace.createStatusBarItem(99, { progress: true });
- statusItem.text = `Checking module ${arr.join(' ')}`;
- statusItem.show();
- let exists = yield Promise.all(arr.map(name => {
- return moduleExists(name).then(exists => {
- return exists ? name : null;
- });
- }));
- let manager = yield getManager();
- exists = exists.filter(s => s != null);
- if (!exists.length)
- return;
- let devs = exists.filter(s => s.startsWith('@types'));
- let deps = exists.filter(s => devs.indexOf(s) == -1);
- statusItem.text = `Installing ${exists.join(' ')}`;
- try {
- yield Promise.all([deps, devs].map((names, i) => {
- let cmd = manager == 'npm' ? `npm i ${names.join(' ')}` : `yarn add ${names.join(' ')} --ignore-scripts --no-default-rc`;
- if (i == 1)
- cmd = cmd + ' --dev';
- return runCommand(cmd, root);
- }));
- }
- catch (e) {
- statusItem.dispose();
- coc_nvim_1.workspace.showMessage(`Install error ${e.message}`, 'error');
- return;
- }
- statusItem.dispose();
- coc_nvim_1.workspace.showMessage(`Installed: ${exists.join(' ')}`, 'more');
+ }
+ const seen = Object.create(null);
+ return array.filter((elem) => {
+ const key = keyFn(elem);
+ if (seen[key]) {
+ return false;
+ }
+ seen[key] = true;
+ return true;
+ });
+}
+async function installModules(uri, names) {
+ names = distinct(names);
+ let workspaceFolder = import_coc14.workspace.getWorkspaceFolder(uri);
+ let root = workspaceFolder ? import_coc14.Uri.parse(workspaceFolder.uri).fsPath : void 0;
+ if (!root || !import_fs.default.existsSync(import_path3.default.join(root, "package.json"))) {
+ import_coc14.window.showMessage(`package.json not found from workspaceFolder: ${root}`, "error");
+ return;
+ }
+ let arr = names.concat(names.map((s) => `@types/${s}`));
+ let statusItem = import_coc14.window.createStatusBarItem(99, {progress: true});
+ statusItem.text = `Checking module ${arr.join(" ")}`;
+ statusItem.show();
+ let exists = await Promise.all(arr.map((name) => {
+ return moduleExists(name).then((exists2) => {
+ return exists2 ? name : null;
});
+ }));
+ let manager = await getManager();
+ exists = exists.filter((s) => s != null);
+ if (!exists.length)
+ return;
+ let devs = exists.filter((s) => s.startsWith("@types"));
+ let deps = exists.filter((s) => devs.indexOf(s) == -1);
+ statusItem.text = `Installing ${exists.join(" ")}`;
+ try {
+ let cmd = manager == "npm" ? `npm i ${deps.join(" ")}` : `yarn add ${deps.join(" ")}`;
+ await runCommand(cmd, root);
+ cmd = manager == "npm" ? `npm i ${deps.join(" ")} --save-dev` : `yarn add ${deps.join(" ")} --save-dev`;
+ await runCommand(cmd, root);
+ } catch (e) {
+ statusItem.dispose();
+ import_coc14.window.showMessage(`Install error ${e.message}`, "error");
+ return;
+ }
+ statusItem.dispose();
+ import_coc14.window.showMessage(`Installed: ${exists.join(" ")}`, "more");
}
-exports.installModules = installModules;
-
-
-/***/ }),
-/* 113 */
-/***/ (function(module, exports) {
-
-module.exports = require("child_process");
-
-/***/ }),
-/* 114 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
+// src/server/features/moduleInstall.ts
+var InstallModuleProvider = class {
+ constructor(client) {
+ this.client = client;
+ import_coc15.commands.registerCommand("_tsserver.installModule", async (uri, name) => {
+ await installModules(uri, [name]);
});
+ }
+ async provideCodeActions(document, _range, context, _token) {
+ const uri = import_coc15.Uri.parse(document.uri);
+ if (uri.scheme != "file")
+ return null;
+ let {diagnostics} = context;
+ let diags = diagnostics.filter((s) => s.code == 2307);
+ let names = diags.map((o) => {
+ let ms = o.message.match(/module\s'(.+)'/);
+ return ms ? ms[1] : null;
+ });
+ names = names.filter((s) => s != null);
+ if (!names.length)
+ return null;
+ let actions = [];
+ for (let name of names) {
+ let title = `install ${name}`;
+ let command = {
+ title: `install ${name}`,
+ command: "_tsserver.installModule",
+ arguments: [document.uri, name]
+ };
+ let codeAction = import_vscode_languageserver_protocol13.CodeAction.create(title, command, import_vscode_languageserver_protocol13.CodeActionKind.QuickFix);
+ actions.push(codeAction);
+ }
+ return actions;
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.OrganizeImportsCodeActionProvider = exports.OrganizeImportsCommand = void 0;
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const coc_nvim_1 = __webpack_require__(1);
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const languageDescription_1 = __webpack_require__(115);
-const languageModeIds_1 = __webpack_require__(116);
-const typeconverts = __importStar(__webpack_require__(37));
-class OrganizeImportsCommand {
- constructor(client) {
- this.client = client;
- this.id = 'tsserver.organizeImports';
- }
- getTextEdits(document) {
- return __awaiter(this, void 0, void 0, function* () {
- let client = this.client;
- let file = client.toPath(document.uri);
- const args = {
- scope: {
- type: 'file',
- args: {
- file
- }
- }
- };
- const response = yield this.client.interruptGetErr(() => this.client.execute('organizeImports', args, vscode_languageserver_protocol_1.CancellationToken.None));
- if (!response || response.type != 'response' || !response.success) {
- return;
- }
- const edit = typeconverts.WorkspaceEdit.fromFileCodeEdits(client, response.body);
- let desc = languageDescription_1.standardLanguageDescriptions.find(o => o.modeIds.indexOf(document.languageId) !== -1);
- if (!desc)
- return null;
- return edit;
- });
- }
- execute(document) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!document) {
- let doc = yield coc_nvim_1.workspace.document;
- if (languageModeIds_1.languageIds.indexOf(doc.filetype) == -1)
- return;
- document = doc.textDocument;
- }
- let edit = yield this.getTextEdits(document);
- if (edit)
- yield coc_nvim_1.workspace.applyEdit(edit);
- return;
+var moduleInstall_default = InstallModuleProvider;
+
+// src/server/features/quickfix.ts
+var import_coc17 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol14 = __toModule(require_main3());
+
+// src/server/commands.ts
+var import_coc16 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_types2 = __toModule(require_main2());
+var ReloadProjectsCommand = class {
+ constructor(service) {
+ this.service = service;
+ this.id = "tsserver.reloadProjects";
+ }
+ async execute() {
+ let client = await this.service.getClientHost();
+ client.reloadProjects();
+ import_coc16.window.showMessage("projects reloaded");
+ }
+};
+var OpenTsServerLogCommand = class {
+ constructor(service) {
+ this.service = service;
+ this.id = "tsserver.openTsServerLog";
+ }
+ async execute() {
+ let client = await this.service.getClientHost();
+ client.serviceClient.openTsServerLogFile();
+ }
+};
+var TypeScriptGoToProjectConfigCommand = class {
+ constructor(service) {
+ this.service = service;
+ this.id = "tsserver.goToProjectConfig";
+ }
+ async execute() {
+ let client = await this.service.getClientHost();
+ let doc = await import_coc16.workspace.document;
+ let {languageId} = doc.textDocument;
+ if (client.serviceClient.modeIds.indexOf(languageId) == -1) {
+ throw new Error(`Could not determine TypeScript or JavaScript project. Unsupported file type: ${languageId}`);
+ return;
+ }
+ await goToProjectConfig(client, doc.uri);
+ }
+};
+async function goToProjectConfig(clientHost, uri) {
+ const client = clientHost.serviceClient;
+ const file2 = client.toPath(uri);
+ let res;
+ try {
+ res = await client.execute("projectInfo", {file: file2, needFileNameList: false}, import_coc16.CancellationToken.None);
+ } catch {
+ }
+ if (!res || !res.body) {
+ import_coc16.window.showMessage("Could not determine TypeScript or JavaScript project.", "warning");
+ return;
+ }
+ const {configFileName} = res.body;
+ if (configFileName && !isImplicitProjectConfigFile(configFileName)) {
+ await import_coc16.workspace.openResource(import_coc16.Uri.file(configFileName).toString());
+ return;
+ }
+ import_coc16.window.showMessage("Config file not found", "warning");
+}
+function isImplicitProjectConfigFile(configFileName) {
+ return configFileName.indexOf("/dev/null/") === 0;
+}
+var autoFixableDiagnosticCodes = new Set([
+ 2420,
+ 2552,
+ 2304
+]);
+var AutoFixCommand = class {
+ constructor(service) {
+ this.service = service;
+ this.id = "tsserver.executeAutofix";
+ }
+ async execute() {
+ if (this.service.state != import_coc16.ServiceStat.Running) {
+ throw new Error("service not running");
+ return;
+ }
+ let client = await this.service.getClientHost();
+ let document = await import_coc16.workspace.document;
+ let handles = await client.handles(document.textDocument);
+ if (!handles) {
+ throw new Error(`Document ${document.uri} is not handled by tsserver.`);
+ return;
+ }
+ let file2 = client.serviceClient.toPath(document.uri);
+ let diagnostics = client.serviceClient.diagnosticsManager.getDiagnostics(document.uri);
+ let missingDiagnostics = diagnostics.filter((o) => o.code == 2307);
+ if (missingDiagnostics.length) {
+ let names2 = missingDiagnostics.map((o) => {
+ let ms = o.message.match(/module\s'(.+)'\./);
+ return ms ? ms[1] : null;
+ });
+ names2 = names2.filter((s) => s != null);
+ if (names2.length) {
+ installModules(document.uri, names2).catch((e) => {
+ console.error(e.message);
});
+ }
}
-}
-exports.OrganizeImportsCommand = OrganizeImportsCommand;
-class OrganizeImportsCodeActionProvider {
- // public static readonly minVersion = API.v280
- constructor(client, fileConfigManager) {
- this.client = client;
- this.fileConfigManager = fileConfigManager;
- this.metadata = {
- providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]
- };
+ diagnostics = diagnostics.filter((x) => autoFixableDiagnosticCodes.has(x.code));
+ if (diagnostics.length == 0)
+ return;
+ diagnostics = diagnostics.reduce((arr, curr) => {
+ if (curr.code == 2304 && arr.findIndex((o) => o.message == curr.message) != -1)
+ return arr;
+ arr.push(curr);
+ return arr;
+ }, []);
+ let edits = [];
+ let command;
+ let names = [];
+ for (let diagnostic of diagnostics) {
+ const args = {
+ ...Range2.toFileRangeRequestArgs(file2, diagnostic.range),
+ errorCodes: [+diagnostic.code]
+ };
+ const response = await client.serviceClient.execute("getCodeFixes", args, import_coc16.CancellationToken.None);
+ if (response.type !== "response" || !response.body || response.body.length < 1) {
+ if (diagnostic.code == 2304) {
+ let {range} = diagnostic;
+ let line = document.getline(range.start.line);
+ let name = line.slice(range.start.character, range.end.character);
+ if (nodeModules.indexOf(name) !== -1 && names.indexOf(name) == -1) {
+ names.push(name);
+ edits.push({
+ range: import_vscode_languageserver_types2.Range.create(0, 0, 0, 0),
+ newText: `import ${name} from '${name}'
+`
+ });
+ command = "tsserver.organizeImports";
+ }
+ }
+ continue;
+ }
+ const fix = response.body[0];
+ for (let change of fix.changes) {
+ if (change.fileName != file2)
+ continue;
+ for (let ch of change.textChanges) {
+ edits.push({
+ range: Range2.fromTextSpan(ch),
+ newText: ch.newText
+ });
+ }
+ }
}
- provideCodeActions(document, _range, context, _token) {
- if (languageModeIds_1.languageIds.indexOf(document.languageId) == -1)
- return;
- if (!context.only || !context.only.includes(vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports)) {
- return [];
+ if (edits.length)
+ await document.applyEdits(edits);
+ if (command)
+ import_coc16.commands.executeCommand(command);
+ }
+};
+var ConfigurePluginCommand = class {
+ constructor(pluginManager) {
+ this.pluginManager = pluginManager;
+ this.id = "_typescript.configurePlugin";
+ }
+ execute(pluginId, configuration) {
+ this.pluginManager.setConfiguration(pluginId, configuration);
+ }
+};
+var FileReferencesCommand2 = class {
+ constructor(service) {
+ this.service = service;
+ this.id = "tsserver.findAllFileReferences";
+ }
+ async execute() {
+ const client = await this.service.getClientHost();
+ if (client.serviceClient.apiVersion.lt(FileReferencesCommand2.minVersion)) {
+ import_coc16.window.showMessage("Find file references failed. Requires TypeScript 4.2+.", "error");
+ return;
+ }
+ const doc = await import_coc16.workspace.document;
+ let {languageId} = doc.textDocument;
+ if (client.serviceClient.modeIds.indexOf(languageId) == -1)
+ return;
+ const openedFiledPath = client.serviceClient.toOpenedFilePath(doc.uri);
+ if (!openedFiledPath)
+ return;
+ const response = await client.serviceClient.execute("fileReferences", {file: openedFiledPath}, import_coc16.CancellationToken.None);
+ if (response.type !== "response" || !response.body)
+ return;
+ const locations = response.body.refs.map((r) => Location2.fromTextSpan(client.serviceClient.toResource(r.file), r));
+ await import_coc16.commands.executeCommand("editor.action.showReferences", doc.uri, import_vscode_languageserver_types2.Position.create(0, 0), locations);
+ }
+};
+var FileReferencesCommand = FileReferencesCommand2;
+FileReferencesCommand.minVersion = api_default.v420;
+function registCommand(cmd) {
+ let {id, execute} = cmd;
+ return import_coc16.commands.registerCommand(id, execute, cmd);
+}
+
+// src/server/features/quickfix.ts
+var ApplyCodeActionCommand2 = class {
+ constructor(client, formattingConfigurationManager) {
+ this.client = client;
+ this.formattingConfigurationManager = formattingConfigurationManager;
+ this.id = ApplyCodeActionCommand2.ID;
+ }
+ async execute(action) {
+ return applyCodeActionCommands(this.client, action);
+ }
+};
+var ApplyCodeActionCommand = ApplyCodeActionCommand2;
+ApplyCodeActionCommand.ID = "_typescript.applyCodeActionCommand";
+var ApplyFixAllCodeAction2 = class {
+ constructor(client, formattingConfigurationManager) {
+ this.client = client;
+ this.formattingConfigurationManager = formattingConfigurationManager;
+ this.id = ApplyFixAllCodeAction2.ID;
+ }
+ async execute(document, file2, tsAction) {
+ if (!tsAction.fixId) {
+ return;
+ }
+ await this.formattingConfigurationManager.ensureConfigurationForDocument(document, import_vscode_languageserver_protocol14.CancellationToken.None);
+ const args = {
+ scope: {
+ type: "file",
+ args: {file: file2}
+ },
+ fixId: tsAction.fixId
+ };
+ try {
+ const res = await this.client.execute("getCombinedCodeFix", args, import_vscode_languageserver_protocol14.CancellationToken.None);
+ if (res.type != "response") {
+ return;
+ }
+ let {body} = res;
+ const edit = WorkspaceEdit.fromFileCodeEdits(this.client, body.changes);
+ await import_coc17.workspace.applyEdit(edit);
+ const token = import_vscode_languageserver_protocol14.CancellationToken.None;
+ const {commands: commands7} = body;
+ if (commands7 && commands7.length) {
+ for (const command of commands7) {
+ await this.client.execute("applyCodeActionCommand", {command}, token);
}
- const action = vscode_languageserver_protocol_1.CodeAction.create('Organize Imports', {
- title: '',
- command: 'tsserver.organizeImports',
- arguments: [document]
- }, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports);
- return [action];
+ }
+ } catch {
}
-}
-exports.OrganizeImportsCodeActionProvider = OrganizeImportsCodeActionProvider;
-
-
-/***/ }),
-/* 115 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.standardLanguageDescriptions = void 0;
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const languageModeIds = __importStar(__webpack_require__(116));
-exports.standardLanguageDescriptions = [
- {
- id: 'typescript',
- diagnosticSource: 'ts',
- diagnosticOwner: 'typescript',
- modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact,
- languageModeIds.typescripttsx, languageModeIds.typescriptjsx],
- diagnosticLanguage: 1 /* TypeScript */,
- configFile: 'tsconfig.json'
- },
- {
- id: 'javascript',
- diagnosticSource: 'ts',
- diagnosticOwner: 'typescript',
- modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact],
- diagnosticLanguage: 0 /* JavaScript */,
- configFile: 'jsconfig.json'
+var ApplyFixAllCodeAction = ApplyFixAllCodeAction2;
+ApplyFixAllCodeAction.ID = "_typescript.applyFixAllCodeAction";
+var DiagnosticsSet = class {
+ constructor(_values) {
+ this._values = _values;
+ }
+ static from(diagnostics) {
+ const values = new Map();
+ for (const diagnostic of diagnostics) {
+ values.set(DiagnosticsSet.key(diagnostic), diagnostic);
}
-];
-
-
-/***/ }),
-/* 116 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"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.languageIds = exports.jsxTags = exports.javascriptjsx = exports.javascriptreact = exports.javascript = exports.typescriptjsx = exports.typescripttsx = exports.typescriptreact = exports.typescript = void 0;
-exports.typescript = 'typescript';
-exports.typescriptreact = 'typescriptreact';
-exports.typescripttsx = 'typescript.tsx';
-exports.typescriptjsx = 'typescript.jsx';
-exports.javascript = 'javascript';
-exports.javascriptreact = 'javascriptreact';
-exports.javascriptjsx = 'javascript.jsx';
-exports.jsxTags = 'jsx-tags';
-exports.languageIds = [exports.typescript, exports.typescriptreact, exports.javascript, exports.javascriptreact, exports.javascriptjsx, exports.typescripttsx, exports.jsxTags];
-
-
-/***/ }),
-/* 117 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
+ return new DiagnosticsSet(values);
+ }
+ static key(diagnostic) {
+ const {start, end} = diagnostic.range;
+ return `${diagnostic.code}-${start.line},${start.character}-${end.line},${end.character}`;
+ }
+ get values() {
+ return this._values.values();
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-const fs_1 = __importDefault(__webpack_require__(118));
-const os_1 = __importDefault(__webpack_require__(14));
-const path_1 = __importDefault(__webpack_require__(13));
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const which_1 = __importDefault(__webpack_require__(119));
-const coc_nvim_1 = __webpack_require__(1);
-const fileConfigurationManager_1 = __importDefault(__webpack_require__(93));
-const typescriptService_1 = __webpack_require__(123);
-const api_1 = __importDefault(__webpack_require__(40));
-const configuration_1 = __webpack_require__(124);
-const logger_1 = __importDefault(__webpack_require__(125));
-const process_1 = __webpack_require__(127);
-const tracer_1 = __importDefault(__webpack_require__(128));
-const tsconfig_1 = __webpack_require__(129);
-const versionProvider_1 = __webpack_require__(130);
-const versionStatus_1 = __importDefault(__webpack_require__(131));
-const wireProtocol_1 = __webpack_require__(132);
-const callbackMap_1 = __webpack_require__(133);
-const requestQueue_1 = __webpack_require__(134);
-const bufferSyncSupport_1 = __importDefault(__webpack_require__(135));
-const diagnostics_1 = __webpack_require__(137);
-class ForkedTsServerProcess {
- constructor(childProcess) {
- this.childProcess = childProcess;
- }
- onError(cb) {
- this.childProcess.on('error', cb);
- }
- onExit(cb) {
- this.childProcess.on('exit', cb);
- }
- write(serverRequest) {
- this.childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
- }
- createReader(callback, onError) {
- // tslint:disable-next-line:no-unused-expression
- new wireProtocol_1.Reader(this.childProcess.stdout, callback, onError);
- }
- kill() {
- this.childProcess.kill();
+var SupportedCodeActionProvider = class {
+ constructor(client) {
+ this.client = client;
+ }
+ async getFixableDiagnosticsForContext(context) {
+ const supportedActions = await this.supportedCodeActions;
+ const fixableDiagnostics = DiagnosticsSet.from(context.diagnostics.filter((diagnostic) => supportedActions.has(+diagnostic.code)));
+ return Array.from(fixableDiagnostics.values);
+ }
+ get supportedCodeActions() {
+ if (!this._supportedCodeActions) {
+ return new Promise((resolve, reject) => {
+ this.client.execute("getSupportedCodeFixes", null, import_vscode_languageserver_protocol14.CancellationToken.None).then((res) => {
+ if (res.type !== "response") {
+ resolve(new Set());
+ return;
+ }
+ let codes = res.body.map((code) => +code).filter((code) => !isNaN(code));
+ resolve(new Set(codes));
+ }, reject);
+ });
}
-}
-class TypeScriptServiceClient {
- constructor(pluginManager) {
- this.pluginManager = pluginManager;
- this.state = coc_nvim_1.ServiceStat.Initial;
- this.logger = new logger_1.default();
- this.tsServerLogFile = null;
- this.cancellationPipeName = null;
- this._callbacks = new callbackMap_1.CallbackMap();
- this._requestQueue = new requestQueue_1.RequestQueue();
- this._pendingResponses = new Set();
- this._onTsServerStarted = new vscode_languageserver_protocol_1.Emitter();
- this._onProjectLanguageServiceStateChanged = new vscode_languageserver_protocol_1.Emitter();
- this._onDidBeginInstallTypings = new vscode_languageserver_protocol_1.Emitter();
- this._onDidEndInstallTypings = new vscode_languageserver_protocol_1.Emitter();
- this._onTypesInstallerInitializationFailed = new vscode_languageserver_protocol_1.Emitter();
- this.disposables = [];
- this.isRestarting = false;
- this._onDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
- this._onConfigDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
- this._onResendModelsRequested = new vscode_languageserver_protocol_1.Emitter();
- this.pathSeparator = path_1.default.sep;
- this.lastStart = Date.now();
- this.servicePromise = null;
- this.lastError = null;
- this.numberRestarts = 0;
- this.fileConfigurationManager = new fileConfigurationManager_1.default(this);
- this._configuration = configuration_1.TypeScriptServiceConfiguration.loadFromWorkspace();
- this.versionProvider = new versionProvider_1.TypeScriptVersionProvider(this._configuration);
- this._apiVersion = api_1.default.defaultVersion;
- this.tracer = new tracer_1.default(this.logger);
- this.versionStatus = new versionStatus_1.default(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript());
- pluginManager.onDidUpdateConfig(update => {
- this.configurePlugin(update.pluginId, update.config);
- }, null, this.disposables);
- pluginManager.onDidChangePlugins(() => {
- this.restartTsServer();
- }, null, this.disposables);
- this.bufferSyncSupport = new bufferSyncSupport_1.default(this);
- this.onTsServerStarted(() => {
- this.bufferSyncSupport.listen();
- });
- this.diagnosticsManager = new diagnostics_1.DiagnosticsManager();
- this.bufferSyncSupport.onDelete(resource => {
- this.diagnosticsManager.delete(resource);
- }, null, this.disposables);
+ return Promise.resolve(this._supportedCodeActions);
+ }
+};
+var TypeScriptQuickFixProvider = class {
+ constructor(client, formattingConfigurationManager) {
+ this.client = client;
+ this.formattingConfigurationManager = formattingConfigurationManager;
+ registCommand(new ApplyCodeActionCommand(client, formattingConfigurationManager));
+ registCommand(new ApplyFixAllCodeAction(client, formattingConfigurationManager));
+ this.supportedCodeActionProvider = new SupportedCodeActionProvider(client);
+ }
+ async provideCodeActions(document, _range, context, token) {
+ const file2 = this.client.toPath(document.uri);
+ if (!file2) {
+ return [];
}
- get onDiagnosticsReceived() {
- return this._onDiagnosticsReceived.event;
+ await this.formattingConfigurationManager.ensureConfigurationForDocument(document, token);
+ const fixableDiagnostics = await this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context);
+ if (!fixableDiagnostics.length) {
+ return [];
}
- get onConfigDiagnosticsReceived() {
- return this._onConfigDiagnosticsReceived.event;
+ if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
+ return [];
}
- get onResendModelsRequested() {
- return this._onResendModelsRequested.event;
+ const results = [];
+ for (const diagnostic of fixableDiagnostics) {
+ results.push(...await this.getFixesForDiagnostic(document, file2, diagnostic, token));
}
- get configuration() {
- return this._configuration;
+ return results;
+ }
+ async getFixesForDiagnostic(document, file2, diagnostic, token) {
+ const args = {
+ ...Range2.toFileRangeRequestArgs(file2, diagnostic.range),
+ errorCodes: [+diagnostic.code]
+ };
+ const codeFixesResponse = await this.client.execute("getCodeFixes", args, token);
+ if (codeFixesResponse.type != "response") {
+ return [];
+ }
+ if (codeFixesResponse.body) {
+ const results = [];
+ for (const tsCodeFix of codeFixesResponse.body) {
+ results.push(...await this.getAllFixesForTsCodeAction(document, file2, diagnostic, tsCodeFix));
+ }
+ return results;
}
- dispose() {
- if (this.servicePromise) {
- this.servicePromise
- .then(childProcess => {
- childProcess.kill();
- })
- .then(undefined, () => void 0);
- }
- this.bufferSyncSupport.dispose();
- coc_nvim_1.disposeAll(this.disposables);
- this.logger.dispose();
- this._onTsServerStarted.dispose();
- this._onResendModelsRequested.dispose();
- this.versionStatus.dispose();
- }
- info(message, data) {
- this.logger.info(message, data);
- }
- error(message, data) {
- this.logger.error(message, data);
- }
- restartTsServer() {
- const start = () => {
- this.servicePromise = this.startService(true);
- return this.servicePromise;
- };
- if (this.servicePromise) {
- return Promise.resolve(this.servicePromise.then(childProcess => {
- this.state = coc_nvim_1.ServiceStat.Stopping;
- this.info('Killing TS Server');
- this.isRestarting = true;
- childProcess.kill();
- this.servicePromise = null;
- }).then(start));
- }
- else {
- return Promise.resolve(start());
- }
+ return [];
+ }
+ async getAllFixesForTsCodeAction(document, file2, diagnostic, tsAction) {
+ const singleFix = this.getSingleFixForTsCodeAction(diagnostic, tsAction);
+ const fixAll = await this.getFixAllForTsCodeAction(document, file2, diagnostic, tsAction);
+ return fixAll ? [singleFix, fixAll] : [singleFix];
+ }
+ getSingleFixForTsCodeAction(diagnostic, tsAction) {
+ const codeAction = {
+ title: tsAction.description,
+ kind: import_vscode_languageserver_protocol14.CodeActionKind.QuickFix
+ };
+ codeAction.edit = getEditForCodeAction(this.client, tsAction);
+ codeAction.diagnostics = [diagnostic];
+ codeAction.isPreferred = true;
+ if (tsAction.commands) {
+ codeAction.command = {
+ command: ApplyCodeActionCommand.ID,
+ arguments: [tsAction],
+ title: tsAction.description
+ };
+ }
+ return codeAction;
+ }
+ async getFixAllForTsCodeAction(document, file2, diagnostic, tsAction) {
+ if (!tsAction.fixId || !this.client.apiVersion.gte(api_default.v270)) {
+ return void 0;
}
- stop() {
- if (!this.servicePromise)
- return;
- return new Promise((resolve, reject) => {
- this.servicePromise.then(childProcess => {
- if (this.state == coc_nvim_1.ServiceStat.Running) {
- this.info('Killing TS Server');
- childProcess.onExit(() => {
- resolve();
- });
- childProcess.kill();
- this.servicePromise = null;
- }
- else {
- resolve();
- }
- }, reject);
- });
+ if (!this.client.diagnosticsManager.getDiagnostics(document.uri).some((x) => x.code === diagnostic.code && x !== diagnostic)) {
+ return;
}
- get onTsServerStarted() {
- return this._onTsServerStarted.event;
+ const action = {
+ title: tsAction.fixAllDescription || "Fix all in file",
+ kind: import_vscode_languageserver_protocol14.CodeActionKind.QuickFix
+ };
+ action.diagnostics = [diagnostic];
+ action.command = {
+ command: ApplyFixAllCodeAction.ID,
+ arguments: [document, file2, tsAction],
+ title: ""
+ };
+ return action;
+ }
+};
+var quickfix_default = TypeScriptQuickFixProvider;
+
+// src/server/features/refactor.ts
+var import_coc18 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol15 = __toModule(require_main3());
+var ApplyRefactoringCommand2 = class {
+ constructor(client) {
+ this.client = client;
+ this.id = ApplyRefactoringCommand2.ID;
+ }
+ async execute(document, file2, refactor, action, range) {
+ const args = {
+ ...Range2.toFileRangeRequestArgs(file2, range),
+ refactor,
+ action
+ };
+ const response = await this.client.execute("getEditsForRefactor", args, import_vscode_languageserver_protocol15.CancellationToken.None);
+ const body = response && response.body;
+ if (!body || !body.edits.length) {
+ return false;
}
- get onProjectLanguageServiceStateChanged() {
- return this._onProjectLanguageServiceStateChanged.event;
+ const workspaceEdit = await this.toWorkspaceEdit(body);
+ if (!await import_coc18.workspace.applyEdit(workspaceEdit)) {
+ return false;
}
- get onDidBeginInstallTypings() {
- return this._onDidBeginInstallTypings.event;
+ const renameLocation = body.renameLocation;
+ if (renameLocation) {
+ import_coc18.commands.executeCommand("editor.action.rename", document.uri, Position.fromLocation(renameLocation));
}
- get onDidEndInstallTypings() {
- return this._onDidEndInstallTypings.event;
+ return true;
+ }
+ async toWorkspaceEdit(body) {
+ for (const edit of body.edits) {
+ await import_coc18.workspace.createFile(edit.fileName, {ignoreIfExists: true});
}
- get onTypesInstallerInitializationFailed() {
- return this._onTypesInstallerInitializationFailed.event;
+ let workspaceEdit = WorkspaceEdit.fromFileCodeEdits(this.client, body.edits);
+ return workspaceEdit;
+ }
+};
+var ApplyRefactoringCommand = ApplyRefactoringCommand2;
+ApplyRefactoringCommand.ID = "_typescript.applyRefactoring";
+var SelectRefactorCommand2 = class {
+ constructor(doRefactoring) {
+ this.doRefactoring = doRefactoring;
+ this.id = SelectRefactorCommand2.ID;
+ }
+ async execute(document, file2, info, range) {
+ let {actions} = info;
+ const idx = actions.length == 1 ? 0 : await import_coc18.window.showQuickpick(actions.map((action) => action.description || action.name));
+ if (idx == -1)
+ return false;
+ let label = info.actions[idx].name;
+ if (!label)
+ return false;
+ return this.doRefactoring.execute(document, file2, info.name, label, range);
+ }
+};
+var SelectRefactorCommand = SelectRefactorCommand2;
+SelectRefactorCommand.ID = "_typescript.selectRefactoring";
+var TypeScriptRefactorProvider2 = class {
+ constructor(client, formattingOptionsManager) {
+ this.client = client;
+ this.formattingOptionsManager = formattingOptionsManager;
+ const doRefactoringCommand = new ApplyRefactoringCommand(this.client);
+ registCommand(doRefactoringCommand);
+ registCommand(new SelectRefactorCommand(doRefactoringCommand));
+ }
+ async provideCodeActions(document, range, context, token) {
+ if (!this.shouldTrigger(context)) {
+ return void 0;
+ }
+ const file2 = this.client.toPath(document.uri);
+ if (!file2)
+ return void 0;
+ await this.formattingOptionsManager.ensureConfigurationForDocument(document, token);
+ const args = Range2.toFileRangeRequestArgs(file2, range);
+ let response;
+ try {
+ response = await this.client.interruptGetErr(() => {
+ return this.client.execute("getApplicableRefactors", args, token);
+ });
+ if (!response || !response.body) {
+ return void 0;
+ }
+ } catch {
+ return void 0;
}
- get apiVersion() {
- return this._apiVersion;
+ return this.convertApplicableRefactors(response.body, document, file2, range, context.only && context.only.some((v) => v.includes(import_vscode_languageserver_protocol15.CodeActionKind.Refactor)));
+ }
+ convertApplicableRefactors(body, document, file2, rangeOrSelection, setPrefrred) {
+ const actions = [];
+ for (const info of body) {
+ if (info.notApplicableReason)
+ continue;
+ if (!info.inlineable) {
+ const codeAction = {
+ title: info.description,
+ kind: import_vscode_languageserver_protocol15.CodeActionKind.Refactor
+ };
+ codeAction.command = {
+ title: info.description,
+ command: SelectRefactorCommand.ID,
+ arguments: [document, file2, info, rangeOrSelection]
+ };
+ actions.push(codeAction);
+ } else {
+ for (const action of info.actions) {
+ let codeAction = this.refactorActionToCodeAction(action, document, file2, info, rangeOrSelection);
+ if (setPrefrred) {
+ codeAction.isPreferred = TypeScriptRefactorProvider2.isPreferred(action, info.actions);
+ }
+ actions.push(codeAction);
+ }
+ }
}
- get tscPath() {
- return this._tscPath;
+ return actions;
+ }
+ refactorActionToCodeAction(action, document, file2, info, rangeOrSelection) {
+ const codeAction = {
+ title: action.description,
+ kind: TypeScriptRefactorProvider2.getKind(action)
+ };
+ codeAction.command = {
+ title: action.description,
+ command: ApplyRefactoringCommand.ID,
+ arguments: [document, file2, info.name, action.name, rangeOrSelection]
+ };
+ return codeAction;
+ }
+ shouldTrigger(context) {
+ if (context.only && context.only.every((o) => !o.includes(import_vscode_languageserver_protocol15.CodeActionKind.Refactor))) {
+ return false;
}
- service() {
- if (this.servicePromise) {
- return this.servicePromise;
- }
- if (this.lastError) {
- return Promise.reject(this.lastError);
- }
- return this.startService().then(() => {
- if (this.servicePromise) {
- return this.servicePromise;
- }
- });
+ return true;
+ }
+ static getKind(refactor) {
+ if (refactor.name.startsWith("function_")) {
+ return TypeScriptRefactorProvider2.extractFunctionKind;
+ } else if (refactor.name.startsWith("constant_")) {
+ return TypeScriptRefactorProvider2.extractConstantKind;
+ } else if (refactor.name.startsWith("Move")) {
+ return TypeScriptRefactorProvider2.moveKind;
+ }
+ return import_vscode_languageserver_protocol15.CodeActionKind.Refactor;
+ }
+ static isPreferred(action, allActions) {
+ let kind = TypeScriptRefactorProvider2.getKind(action);
+ if (TypeScriptRefactorProvider2.extractConstantKind == kind) {
+ const getScope = (name2) => {
+ var _a;
+ const scope2 = (_a = name2.match(/scope_(\d)/)) == null ? void 0 : _a[1];
+ return scope2 ? +scope2 : void 0;
+ };
+ const scope = getScope(action.name);
+ if (typeof scope !== "number") {
+ return false;
+ }
+ return allActions.filter((otherAtion) => otherAtion !== action && otherAtion.name.startsWith("constant_")).every((otherAction) => {
+ const otherScope = getScope(otherAction.name);
+ return typeof otherScope === "number" ? scope < otherScope : true;
+ });
}
- ensureServiceStarted() {
- if (!this.servicePromise) {
- this.startService().catch(err => {
- coc_nvim_1.workspace.showMessage(`TSServer start failed: ${err.message}`, 'error');
- this.error(`Service start failed: ${err.stack}`);
- });
- }
+ let {name} = action;
+ if (name.startsWith("Extract to type alias") || name.startsWith("Extract to interface")) {
+ return true;
}
- startService(resendModels = false) {
- return __awaiter(this, void 0, void 0, function* () {
- const { ignoreLocalTsserver } = this.configuration;
- let currentVersion;
- if (!ignoreLocalTsserver)
- currentVersion = this.versionProvider.getLocalVersion();
- if (!currentVersion || !fs_1.default.existsSync(currentVersion.tsServerPath)) {
- currentVersion = this.versionProvider.getDefaultVersion();
- }
- if (!currentVersion || !currentVersion.isValid) {
- if (this.configuration.globalTsdk) {
- coc_nvim_1.workspace.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, 'error');
- }
- else {
- coc_nvim_1.workspace.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, 'error');
- }
- return;
- }
- this._apiVersion = currentVersion.version;
- this._tscPath = currentVersion.tscPath;
- this.versionStatus.onDidChangeTypeScriptVersion(currentVersion);
- this.lastError = null;
- const tsServerForkArgs = yield this.getTsServerArgs();
- const debugPort = this._configuration.debugPort;
- const maxTsServerMemory = this._configuration.maxTsServerMemory;
- const options = {
- execArgv: [
- ...(debugPort ? [`--inspect=${debugPort}`] : []),
- ...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []),
- ],
- cwd: coc_nvim_1.workspace.root
- };
- this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels);
- return this.servicePromise;
- });
+ return false;
+ }
+};
+var TypeScriptRefactorProvider = TypeScriptRefactorProvider2;
+TypeScriptRefactorProvider.extractFunctionKind = import_vscode_languageserver_protocol15.CodeActionKind.RefactorExtract + ".function";
+TypeScriptRefactorProvider.extractConstantKind = import_vscode_languageserver_protocol15.CodeActionKind.RefactorExtract + ".constant";
+TypeScriptRefactorProvider.moveKind = import_vscode_languageserver_protocol15.CodeActionKind.Refactor + ".move";
+TypeScriptRefactorProvider.metadata = {
+ providedCodeActionKinds: [import_vscode_languageserver_protocol15.CodeActionKind.Refactor]
+};
+var refactor_default = TypeScriptRefactorProvider;
+
+// src/server/features/references.ts
+var TypeScriptReferences = class {
+ constructor(client) {
+ this.client = client;
+ }
+ async provideReferences(document, position, context, token) {
+ const filepath = this.client.toPath(document.uri);
+ if (!filepath)
+ return [];
+ const args = Position.toFileLocationRequestArgs(filepath, position);
+ try {
+ const msg = await this.client.execute("references", args, token);
+ if (!msg || msg.type != "response" || !msg.body) {
+ return [];
+ }
+ const result = [];
+ for (const ref of msg.body.refs) {
+ if (!context.includeDeclaration && ref.isDefinition) {
+ continue;
+ }
+ const url = this.client.toResource(ref.file);
+ const location = Location2.fromTextSpan(url, ref);
+ result.push(location);
+ }
+ return result;
+ } catch {
+ return [];
}
- startProcess(currentVersion, args, options, resendModels) {
- this.state = coc_nvim_1.ServiceStat.Starting;
- return new Promise((resolve, reject) => {
- try {
- process_1.fork(currentVersion.tsServerPath, args, options, this.logger, (err, childProcess) => {
- if (err || !childProcess) {
- this.state = coc_nvim_1.ServiceStat.StartFailed;
- this.lastError = err;
- this.error('Starting TSServer failed with error.', err.stack);
- return;
- }
- this.state = coc_nvim_1.ServiceStat.Running;
- this.info('Started TSServer', JSON.stringify(currentVersion, null, 2));
- const handle = new ForkedTsServerProcess(childProcess);
- this.lastStart = Date.now();
- handle.onError((err) => {
- this.lastError = err;
- this.error('TSServer errored with error.', err);
- this.error(`TSServer log file: ${this.tsServerLogFile || ''}`);
- coc_nvim_1.workspace.showMessage(`TSServer errored with error. ${err.message}`, 'error');
- this.serviceExited(false);
- });
- handle.onExit((code) => {
- if (code == null) {
- this.info('TSServer normal exit');
- }
- else {
- this.error(`TSServer exited with code: ${code}`);
- }
- this.info(`TSServer log file: ${this.tsServerLogFile || ''}`);
- this.serviceExited(!this.isRestarting);
- this.isRestarting = false;
- });
- handle.createReader(msg => {
- this.dispatchMessage(msg);
- }, error => {
- this.error('ReaderError', error);
- });
- resolve(handle);
- this.serviceStarted(resendModels);
- this._onTsServerStarted.fire(currentVersion.version);
- });
- }
- catch (e) {
- reject(e);
- }
- });
+ }
+};
+var references_default = TypeScriptReferences;
+
+// src/server/features/referencesCodeLens.ts
+var TypeScriptReferencesCodeLensProvider = class extends TypeScriptBaseCodeLensProvider {
+ resolveCodeLens(codeLens, token) {
+ let {uri} = codeLens.data;
+ let filepath = this.client.toPath(uri);
+ const args = Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
+ return this.client.execute("references", args, token, {
+ lowPriority: true
+ }).then((response) => {
+ if (!response || response.type != "response" || !response.body) {
+ throw codeLens;
+ }
+ const locations = response.body.refs.map((reference) => Location2.fromTextSpan(this.client.toResource(reference.file), reference)).filter((location) => !(location.uri.toString() === uri && location.range.start.line === codeLens.range.start.line && location.range.start.character === codeLens.range.start.character));
+ codeLens.command = {
+ title: locations.length === 1 ? "1 reference" : `${locations.length} references`,
+ command: locations.length ? "editor.action.showReferences" : "",
+ arguments: [uri, codeLens.range.start, locations]
+ };
+ return codeLens;
+ }).catch(() => {
+ codeLens.command = {
+ title: "0 references",
+ command: ""
+ };
+ return codeLens;
+ });
+ }
+ extractSymbol(document, item, parent) {
+ if (parent && parent.kind === Kind.enum) {
+ return super.getSymbolRange(document, item);
}
- openTsServerLogFile() {
- return __awaiter(this, void 0, void 0, function* () {
- const isRoot = process.getuid && process.getuid() == 0;
- let echoErr = (msg) => {
- coc_nvim_1.workspace.showMessage(msg, 'error');
- };
- if (isRoot) {
- echoErr('Log disabled for root user.');
- return false;
- }
- if (!this.apiVersion.gte(api_1.default.v222)) {
- echoErr('TS Server logging requires TS 2.2.2+');
- return false;
- }
- if (this._configuration.tsServerLogLevel === configuration_1.TsServerLogLevel.Off) {
- echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`);
- return false;
- }
- if (!this.tsServerLogFile) {
- echoErr('TS Server has not started logging.');
- return false;
- }
- try {
- yield coc_nvim_1.workspace.nvim.command(`edit ${this.tsServerLogFile}`);
- return true;
- }
- catch (_a) {
- echoErr('Could not open TS Server log file');
- return false;
- }
- });
+ switch (item.kind) {
+ case Kind.const:
+ case Kind.let:
+ case Kind.variable:
+ case Kind.function:
+ if (!item.kindModifiers.match(/\bexport\b/)) {
+ break;
+ }
+ case Kind.class:
+ if (item.text === "<class>") {
+ break;
+ }
+ case Kind.method:
+ case Kind.memberVariable:
+ case Kind.memberGetAccessor:
+ case Kind.memberSetAccessor:
+ case Kind.constructorImplementation:
+ case Kind.interface:
+ case Kind.type:
+ case Kind.enum:
+ return super.getSymbolRange(document, item);
+ }
+ return null;
+ }
+};
+var referencesCodeLens_default = TypeScriptReferencesCodeLensProvider;
+
+// src/server/features/rename.ts
+var import_coc19 = __toModule(require("coc.nvim"));
+var import_path4 = __toModule(require("path"));
+var TypeScriptRenameProvider = class {
+ constructor(client, fileConfigurationManager) {
+ this.client = client;
+ this.fileConfigurationManager = fileConfigurationManager;
+ }
+ async prepareRename(document, position, token) {
+ const response = await this.execRename(document, position, token);
+ if (!response || response.type !== "response" || !response.body) {
+ return null;
+ }
+ const renameInfo = response.body.info;
+ if (!renameInfo.canRename) {
+ return Promise.reject(new Error("Invalid location for rename."));
+ }
+ if (this.client.apiVersion.gte(api_default.v310)) {
+ const triggerSpan = renameInfo.triggerSpan;
+ if (triggerSpan) {
+ const range = Range2.fromTextSpan(triggerSpan);
+ return range;
+ }
}
- serviceStarted(resendModels) {
- const watchOptions = this.apiVersion.gte(api_1.default.v380)
- ? this.configuration.watchOptions
- : undefined;
- const configureOptions = {
- hostInfo: 'coc-nvim',
- preferences: {
- providePrefixAndSuffixTextForRename: true,
- allowRenameOfImportPath: true,
- },
- watchOptions
- };
- this.executeWithoutWaitingForResponse('configure', configureOptions); // tslint:disable-line
- this.setCompilerOptionsForInferredProjects(this._configuration);
- if (resendModels) {
- this._onResendModelsRequested.fire(void 0);
- this.diagnosticsManager.reInitialize();
- this.bufferSyncSupport.reinitialize();
+ return null;
+ }
+ async provideRenameEdits(document, position, newName, token) {
+ const response = await this.execRename(document, position, token);
+ if (!response || response.type !== "response" || !response.body) {
+ return null;
+ }
+ const renameInfo = response.body.info;
+ if (!renameInfo.canRename) {
+ return Promise.reject(new Error("Invalid location for rename."));
+ }
+ if (this.client.apiVersion.gte(api_default.v310)) {
+ if (renameInfo.fileToRename) {
+ const edits = await this.renameFile(renameInfo.fileToRename, newName, token);
+ if (edits) {
+ return edits;
+ } else {
+ return Promise.reject(new Error("An error occurred while renaming file"));
}
- // Reconfigure any plugins
- for (const [config, pluginName] of this.pluginManager.configurations()) {
- this.configurePlugin(config, pluginName);
+ }
+ }
+ return this.toWorkspaceEdit(response.body.locs, newName);
+ }
+ async execRename(document, position, token) {
+ const file2 = this.client.toPath(document.uri);
+ if (!file2)
+ return void 0;
+ const args = {
+ ...Position.toFileLocationRequestArgs(file2, position),
+ findInStrings: false,
+ findInComments: false
+ };
+ await this.fileConfigurationManager.ensureConfigurationForDocument(document, token);
+ return this.client.interruptGetErr(() => {
+ return this.client.execute("rename", args, token);
+ });
+ }
+ toWorkspaceEdit(locations, newName) {
+ let changes = {};
+ for (const spanGroup of locations) {
+ const uri = this.client.toResource(spanGroup.file);
+ if (uri) {
+ changes[uri] = [];
+ for (const textSpan of spanGroup.locs) {
+ changes[uri].push({
+ range: Range2.fromTextSpan(textSpan),
+ newText: (textSpan.prefixText || "") + newName + (textSpan.suffixText || "")
+ });
}
+ }
}
- setCompilerOptionsForInferredProjects(configuration) {
- if (!this.apiVersion.gte(api_1.default.v206))
- return;
- const args = {
- options: this.getCompilerOptionsForInferredProjects(configuration)
- };
- this.executeWithoutWaitingForResponse('compilerOptionsForInferredProjects', args); // tslint:disable-line
+ return {changes};
+ }
+ async renameFile(fileToRename, newName, token) {
+ if (!import_path4.default.extname(newName)) {
+ newName += import_path4.default.extname(fileToRename);
+ }
+ const dirname = import_path4.default.dirname(fileToRename);
+ const newFilePath = import_path4.default.join(dirname, newName);
+ const args = {
+ file: fileToRename,
+ oldFilePath: fileToRename,
+ newFilePath
+ };
+ const response = await this.client.execute("getEditsForFileRename", args, token);
+ if (response.type !== "response" || !response.body) {
+ return void 0;
+ }
+ const edits = WorkspaceEdit.fromFileCodeEdits(this.client, response.body);
+ edits.documentChanges = edits.documentChanges || [];
+ edits.documentChanges.push({
+ kind: "rename",
+ oldUri: import_coc19.Uri.file(fileToRename).toString(),
+ newUri: import_coc19.Uri.file(newFilePath).toString(),
+ options: {
+ overwrite: false,
+ ignoreIfExists: true
+ }
+ });
+ return edits;
+ }
+};
+var rename_default = TypeScriptRenameProvider;
+
+// src/server/features/signatureHelp.ts
+var TypeScriptSignatureHelpProvider = class {
+ constructor(client) {
+ this.client = client;
+ }
+ async provideSignatureHelp(document, position, token) {
+ const filepath = this.client.toPath(document.uri);
+ if (!filepath) {
+ return void 0;
+ }
+ const args = Position.toFileLocationRequestArgs(filepath, position);
+ let response;
+ try {
+ response = await this.client.interruptGetErr(() => this.client.execute("signatureHelp", args, token));
+ } catch (e) {
+ return void 0;
+ }
+ if (response.type !== "response" || !response.body) {
+ return void 0;
+ }
+ let info = response.body;
+ const result = {
+ activeSignature: info.selectedItemIndex,
+ activeParameter: this.getActiveParmeter(info),
+ signatures: info.items.map((signature) => {
+ return this.convertSignature(signature);
+ })
+ };
+ return result;
+ }
+ getActiveParmeter(info) {
+ const activeSignature = info.items[info.selectedItemIndex];
+ if (activeSignature && activeSignature.isVariadic) {
+ return Math.min(info.argumentIndex, activeSignature.parameters.length - 1);
}
- getCompilerOptionsForInferredProjects(configuration) {
- return Object.assign(Object.assign({}, tsconfig_1.inferredProjectConfig(configuration)), { allowJs: true, allowSyntheticDefaultImports: true, allowNonTsExtensions: true });
+ return info.argumentIndex;
+ }
+ convertSignature(item) {
+ var _a;
+ let parameters = item.parameters.map((p) => {
+ return {
+ label: plain(p.displayParts),
+ documentation: markdownDocumentation(p.documentation, [])
+ };
+ });
+ let label = plain(item.prefixDisplayParts);
+ label += parameters.map((parameter) => parameter.label).join(plain(item.separatorDisplayParts));
+ label += plain(item.suffixDisplayParts);
+ return {
+ label,
+ documentation: markdownDocumentation(item.documentation, (_a = item.tags) == null ? void 0 : _a.filter((x) => x.name !== "param")),
+ parameters
+ };
+ }
+};
+TypeScriptSignatureHelpProvider.triggerCharacters = ["(", ",", "<"];
+var signatureHelp_default = TypeScriptSignatureHelpProvider;
+
+// src/server/features/smartSelect.ts
+var SmartSelection = class {
+ constructor(client) {
+ this.client = client;
+ }
+ async provideSelectionRanges(document, positions, token) {
+ const file2 = this.client.toPath(document.uri);
+ if (!file2) {
+ return void 0;
+ }
+ const args = {
+ file: file2,
+ locations: positions.map(Position.toLocation)
+ };
+ const response = await this.client.execute("selectionRange", args, token);
+ if (response.type !== "response" || !response.body) {
+ return void 0;
}
- serviceExited(restart) {
- this.state = coc_nvim_1.ServiceStat.Stopped;
- this.servicePromise = null;
- this.tsServerLogFile = null;
- this._callbacks.destroy('Service died.');
- this._callbacks = new callbackMap_1.CallbackMap();
- this._requestQueue = new requestQueue_1.RequestQueue();
- this._pendingResponses = new Set();
- if (restart) {
- const diff = Date.now() - this.lastStart;
- this.numberRestarts++;
- let startService = true;
- if (this.numberRestarts > 5) {
- this.numberRestarts = 0;
- if (diff < 10 * 1000 /* 10 seconds */) {
- this.lastStart = Date.now();
- startService = false;
- coc_nvim_1.workspace.showMessage('The TypeScript language service died 5 times right after it got started.', 'error'); // tslint:disable-line
- }
- else if (diff < 60 * 1000 /* 1 Minutes */) {
- this.lastStart = Date.now();
- coc_nvim_1.workspace.showMessage('The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.', 'error'); // tslint:disable-line
- }
- }
- if (startService) {
- this.startService(true); // tslint:disable-line
- }
- }
+ return response.body.map(SmartSelection.convertSelectionRange);
+ }
+ static convertSelectionRange(selectionRange) {
+ return {
+ range: Range2.fromTextSpan(selectionRange.textSpan),
+ parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : void 0
+ };
+ }
+};
+var smartSelect_default = SmartSelection;
+
+// src/server/features/tagClosing.ts
+var import_coc20 = __toModule(require("coc.nvim"));
+var TagClosing2 = class {
+ constructor(client, descriptionLanguageId) {
+ this.client = client;
+ this.descriptionLanguageId = descriptionLanguageId;
+ this._disposables = [];
+ this._disposed = false;
+ this._timeout = void 0;
+ this._cancel = void 0;
+ import_coc20.events.on("InsertCharPre", (character) => {
+ this.lastInsert = character;
+ }, null, this._disposables);
+ import_coc20.events.on("TextChangedI", this.onChange, this, this._disposables);
+ import_coc20.events.on("TextChangedP", this.onChange, this, this._disposables);
+ }
+ async onChange(bufnr, change) {
+ let doc = import_coc20.workspace.getDocument(bufnr);
+ if (!doc || !doc.attached)
+ return;
+ let enabled = this.isEnabled(doc.filetype, doc.uri);
+ if (!enabled)
+ return;
+ let {pre, changedtick, lnum} = change;
+ if (!pre.endsWith("/") && !pre.endsWith(">"))
+ return;
+ if (!pre.endsWith(this.lastInsert))
+ return;
+ if (pre.length > 1 && pre[pre.length - 2] == ">")
+ return;
+ const filepath = this.client.toOpenedFilePath(doc.uri);
+ if (!filepath)
+ return;
+ if (this._timeout) {
+ clearTimeout(this._timeout);
+ }
+ if (this._cancel) {
+ this._cancel.cancel();
+ this._cancel.dispose();
+ this._cancel = void 0;
+ }
+ await doc.patchChange();
+ this._timeout = setTimeout(async () => {
+ this._timeout = void 0;
+ if (this._disposed)
+ return;
+ if (doc.changedtick > changedtick)
+ return;
+ const position = import_coc20.Position.create(lnum - 1, pre.length);
+ const args = Position.toFileLocationRequestArgs(filepath, position);
+ this._cancel = new import_coc20.CancellationTokenSource();
+ const response = await this.client.execute("jsxClosingTag", args, this._cancel.token);
+ if (response.type !== "response" || !response.body) {
+ return;
+ }
+ if (this._disposed)
+ return;
+ const insertion = response.body;
+ if (doc.changedtick === changedtick) {
+ import_coc20.snippetManager.insertSnippet(this.getTagSnippet(insertion).value, false, import_coc20.Range.create(position, position));
+ }
+ }, 50);
+ }
+ isEnabled(languageId, uri) {
+ const configLang = TagClosing2._configurationLanguages[languageId];
+ if (!configLang || configLang !== this.descriptionLanguageId) {
+ return false;
}
- toPath(uri) {
- return this.normalizePath(coc_nvim_1.Uri.parse(uri));
+ if (!import_coc20.workspace.getConfiguration(void 0, uri).get(`${configLang}.autoClosingTags`)) {
+ return false;
}
- toResource(filepath) {
- if (this._apiVersion.gte(api_1.default.v213)) {
- if (filepath.startsWith('untitled:')) {
- let resource = coc_nvim_1.Uri.parse(filepath);
- if (this.inMemoryResourcePrefix) {
- const dirName = path_1.default.dirname(resource.path);
- const fileName = path_1.default.basename(resource.path);
- if (fileName.startsWith(this.inMemoryResourcePrefix)) {
- resource = resource.with({ path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) });
- }
- }
- return resource.toString();
- }
- }
- return coc_nvim_1.Uri.file(filepath).toString();
+ return true;
+ }
+ dispose() {
+ this._disposed = true;
+ if (this._timeout) {
+ clearTimeout(this._timeout);
+ this._timeout = void 0;
+ }
+ if (this._cancel) {
+ this._cancel.cancel();
+ this._cancel.dispose();
+ this._cancel = void 0;
+ }
+ import_coc20.disposeAll(this._disposables);
+ this._disposables = [];
+ }
+ getTagSnippet(closingTag) {
+ const snippet = new SnippetString_default();
+ snippet.appendPlaceholder("", 0);
+ snippet.appendText(closingTag.newText);
+ return snippet;
+ }
+};
+var TagClosing = TagClosing2;
+TagClosing.minVersion = api_default.v300;
+TagClosing._configurationLanguages = {
+ javascriptreact: "javascript",
+ typescriptreact: "typescript"
+};
+var tagClosing_default = TagClosing;
+
+// src/server/features/updatePathOnRename.ts
+var import_coc21 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol16 = __toModule(require_main3());
+
+// src/server/utils/mutex.ts
+var Mutex = class {
+ constructor() {
+ this.tasks = [];
+ this.count = 1;
+ }
+ sched() {
+ if (this.count > 0 && this.tasks.length > 0) {
+ this.count--;
+ let next = this.tasks.shift();
+ next();
}
- normalizePath(resource) {
- if (this._apiVersion.gte(api_1.default.v213)) {
- if (resource.scheme == 'untitled') {
- const dirName = path_1.default.dirname(resource.path);
- const fileName = this.inMemoryResourcePrefix + path_1.default.basename(resource.path);
- return resource
- .with({ path: path_1.default.posix.join(dirName, fileName) })
- .toString(true);
- }
+ }
+ get busy() {
+ return this.count == 0;
+ }
+ acquire() {
+ return new Promise((res) => {
+ let task = () => {
+ let released = false;
+ res(() => {
+ if (!released) {
+ released = true;
+ this.count++;
+ this.sched();
+ }
+ });
+ };
+ this.tasks.push(task);
+ process.nextTick(this.sched.bind(this));
+ });
+ }
+ use(f) {
+ return this.acquire().then((release) => {
+ return f().then((res) => {
+ release();
+ return res;
+ }).catch((err) => {
+ release();
+ throw err;
+ });
+ });
+ }
+};
+
+// src/server/features/updatePathOnRename.ts
+function wait(ms) {
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ resolve();
+ }, ms);
+ });
+}
+var UpdateImportsOnFileRenameHandler = class {
+ constructor(client, fileConfigurationManager, languageId) {
+ this.client = client;
+ this.fileConfigurationManager = fileConfigurationManager;
+ this.disposables = [];
+ let glob = languageId == "typescript" ? "**/*.{ts,tsx}" : "**/*.{js,jsx}";
+ const watcher = import_coc21.workspace.createFileSystemWatcher(glob);
+ this.disposables.push(watcher);
+ let mutex = new Mutex();
+ watcher.onDidRename(async (e) => {
+ let release = await mutex.acquire();
+ try {
+ await this.doRename(e.oldUri, e.newUri);
+ release();
+ } catch (e2) {
+ this.client.logger.error("Error on rename:", e2);
+ release();
+ }
+ }, null, this.disposables);
+ }
+ dispose() {
+ import_coc21.disposeAll(this.disposables);
+ }
+ async doRename(oldResource, newResource) {
+ if (oldResource.scheme !== "file" || newResource.scheme !== "file") {
+ return;
+ }
+ const targetFile = newResource.fsPath;
+ const oldFile = oldResource.fsPath;
+ const newUri = newResource.toString();
+ let oldDocument = import_coc21.workspace.getDocument(oldResource.toString());
+ if (oldDocument) {
+ await import_coc21.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`);
+ }
+ let document = import_coc21.workspace.getDocument(newUri);
+ if (document) {
+ await import_coc21.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`);
+ await wait(30);
+ }
+ document = await import_coc21.workspace.loadFile(newUri);
+ if (!document)
+ return;
+ await wait(50);
+ const edits = await this.getEditsForFileRename(document.textDocument, oldFile, targetFile);
+ if (!edits)
+ return;
+ if (await this.promptUser(newResource)) {
+ await import_coc21.workspace.applyEdit(edits);
+ }
+ }
+ async promptUser(newResource) {
+ return await import_coc21.window.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`);
+ }
+ async getEditsForFileRename(document, oldFile, newFile) {
+ await this.fileConfigurationManager.ensureConfigurationForDocument(document, import_vscode_languageserver_protocol16.CancellationToken.None);
+ const response = await this.client.interruptGetErr(() => {
+ const args = {
+ oldFilePath: oldFile,
+ newFilePath: newFile
+ };
+ return this.client.execute("getEditsForFileRename", args, import_vscode_languageserver_protocol16.CancellationToken.None);
+ });
+ if (!response || response.type != "response" || !response.body) {
+ return;
+ }
+ const edits = [];
+ for (const edit of response.body) {
+ if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) {
+ continue;
+ }
+ for (const change of edit.textChanges) {
+ if (change.newText.match(/\/node_modules\//gi)) {
+ continue;
}
- const result = resource.fsPath;
- if (!result)
- return null;
- // Both \ and / must be escaped in regular expressions
- return result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/');
- }
- get inMemoryResourcePrefix() {
- return this._apiVersion.gte(api_1.default.v270) ? '^' : '';
- }
- asUrl(filepath) {
- if (this._apiVersion.gte(api_1.default.v213)) {
- if (filepath.startsWith('untitled:')) {
- let resource = coc_nvim_1.Uri.parse(filepath);
- if (this.inMemoryResourcePrefix) {
- const dirName = path_1.default.dirname(resource.path);
- const fileName = path_1.default.basename(resource.path);
- if (fileName.startsWith(this.inMemoryResourcePrefix)) {
- resource = resource.with({
- path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length))
- });
- }
- }
- return resource;
- }
+ }
+ edits.push(edit);
+ }
+ return WorkspaceEdit.fromFileCodeEdits(this.client, edits);
+ }
+};
+var updatePathOnRename_default = UpdateImportsOnFileRenameHandler;
+
+// src/server/organizeImports.ts
+var import_coc22 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol17 = __toModule(require_main3());
+var OrganizeImportsCommand = class {
+ constructor(service) {
+ this.service = service;
+ this.id = "tsserver.organizeImports";
+ }
+ async _execute(client, document) {
+ let file2 = client.toPath(document.uri);
+ const args = {
+ scope: {
+ type: "file",
+ args: {
+ file: file2
}
- return coc_nvim_1.Uri.file(filepath);
+ }
+ };
+ const response = await client.interruptGetErr(() => client.execute("organizeImports", args, import_vscode_languageserver_protocol17.CancellationToken.None));
+ if (!response || response.type != "response" || !response.success) {
+ return;
+ }
+ const edit = WorkspaceEdit.fromFileCodeEdits(client, response.body);
+ let keys = Object.keys(edit.changes);
+ if (keys.length == 1) {
+ let doc = import_coc22.workspace.getDocument(keys[0]);
+ if (doc) {
+ await doc.applyEdits(edit.changes[keys[0]]);
+ return;
+ }
}
- execute(command, args, token, lowPriority) {
- return this.executeImpl(command, args, {
- isAsync: false,
- token,
- expectsResult: true,
- lowPriority
- });
+ if (edit)
+ await import_coc22.workspace.applyEdit(edit);
+ }
+ async execute(document) {
+ let client = await this.service.getClientHost();
+ if (!document) {
+ let doc = await import_coc22.workspace.document;
+ if (!doc.attached) {
+ throw new Error(`Document not attached.`);
+ }
+ if (client.serviceClient.modeIds.indexOf(doc.filetype) == -1) {
+ throw new Error(`filetype "${doc.filetype}" not supported by tsserver.`);
+ }
+ document = doc.textDocument;
}
- executeAsync(command, args, token) {
- return this.executeImpl(command, args, {
- isAsync: true,
- token,
- expectsResult: true
- });
+ await this._execute(client.serviceClient, document);
+ }
+};
+var OrganizeImportsCodeActionProvider = class {
+ constructor(client, fileConfigManager) {
+ this.client = client;
+ this.fileConfigManager = fileConfigManager;
+ this.metadata = {
+ providedCodeActionKinds: [import_vscode_languageserver_protocol17.CodeActionKind.SourceOrganizeImports]
+ };
+ }
+ async provideCodeActions(document, _range, context, token) {
+ if (this.client.modeIds.indexOf(document.languageId) == -1)
+ return;
+ if (!context.only || !context.only.includes(import_vscode_languageserver_protocol17.CodeActionKind.SourceOrganizeImports)) {
+ return [];
+ }
+ await this.fileConfigManager.ensureConfigurationForDocument(document, token);
+ const action = import_vscode_languageserver_protocol17.CodeAction.create("Organize Imports", {
+ title: "",
+ command: "tsserver.organizeImports",
+ arguments: [document]
+ }, import_vscode_languageserver_protocol17.CodeActionKind.SourceOrganizeImports);
+ return [action];
+ }
+};
+
+// src/server/languageProvider.ts
+var suggestionSetting = "suggestionActions.enabled";
+var LanguageProvider = class {
+ constructor(client, fileConfigurationManager, description, typingsStatus) {
+ this.client = client;
+ this.fileConfigurationManager = fileConfigurationManager;
+ this.description = description;
+ this.disposables = [];
+ import_coc23.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
+ this.configurationChanged();
+ let initialized = false;
+ client.onTsServerStarted(async () => {
+ if (!initialized) {
+ initialized = true;
+ this.registerProviders(client, typingsStatus);
+ }
+ });
+ }
+ configurationChanged() {
+ const config = import_coc23.workspace.getConfiguration(this.id, null);
+ this.client.diagnosticsManager.setEnableSuggestions(this.id, config.get(suggestionSetting, true));
+ }
+ dispose() {
+ import_coc23.disposeAll(this.disposables);
+ }
+ _register(disposable) {
+ this.disposables.push(disposable);
+ }
+ registerProviders(client, typingsStatus) {
+ let languageIds = this.description.modeIds;
+ let clientId = `tsserver-${this.description.id}`;
+ this._register(import_coc23.languages.registerCompletionItemProvider(clientId, "TSC", languageIds, new completionItemProvider_default(client, typingsStatus, this.fileConfigurationManager, this.description.id), completionItemProvider_default.triggerCharacters));
+ if (this.client.apiVersion.gte(api_default.v230)) {
+ this._register(import_coc23.languages.registerCompletionItemProvider(`${this.description.id}-directive`, "TSC", languageIds, new directiveCommentCompletions_default(client), ["@"]));
+ }
+ let definitionProvider = new definitionProvider_default(client);
+ this._register(import_coc23.languages.registerDefinitionProvider(languageIds, definitionProvider));
+ this._register(import_coc23.languages.registerTypeDefinitionProvider(languageIds, definitionProvider));
+ this._register(import_coc23.languages.registerImplementationProvider(languageIds, definitionProvider));
+ this._register(import_coc23.languages.registerReferencesProvider(languageIds, new references_default(client)));
+ this._register(import_coc23.languages.registerHoverProvider(languageIds, new hover_default(client)));
+ this._register(import_coc23.languages.registerDocumentHighlightProvider(languageIds, new documentHighlight_default(this.client)));
+ this._register(import_coc23.languages.registerSignatureHelpProvider(languageIds, new signatureHelp_default(client), ["(", ",", "<", ")"]));
+ this._register(import_coc23.languages.registerDocumentSymbolProvider(languageIds, new documentSymbol_default(client)));
+ this._register(import_coc23.languages.registerRenameProvider(languageIds, new rename_default(client, this.fileConfigurationManager)));
+ let formatProvider = new formatting_default(client, this.fileConfigurationManager);
+ this._register(import_coc23.languages.registerDocumentFormatProvider(languageIds, formatProvider));
+ this._register(import_coc23.languages.registerDocumentRangeFormatProvider(languageIds, formatProvider));
+ this._register(import_coc23.languages.registerOnTypeFormattingEditProvider(languageIds, formatProvider, [";", "}", "\n", String.fromCharCode(27)]));
+ this._register(import_coc23.languages.registerCodeActionProvider(languageIds, new moduleInstall_default(client), "tsserver"));
+ if (typeof import_coc23.languages["registerCallHierarchyProvider"] === "function") {
+ this._register(import_coc23.languages.registerCallHierarchyProvider(languageIds, new callHierarchy_default(client)));
+ }
+ let {fileConfigurationManager} = this;
+ let conf = fileConfigurationManager.getLanguageConfiguration(this.id);
+ if (["javascript", "typescript"].includes(this.id)) {
+ if (this.client.apiVersion.gte(api_default.v290) && conf.get("updateImportsOnFileMove.enable")) {
+ this._register(new updatePathOnRename_default(client, this.fileConfigurationManager, this.id));
+ }
}
- executeWithoutWaitingForResponse(command, args) {
- this.executeImpl(command, args, {
- isAsync: false,
- token: undefined,
- expectsResult: false
- });
+ if (this.client.apiVersion.gte(api_default.v280)) {
+ this._register(import_coc23.languages.registerFoldingRangeProvider(languageIds, new folding_default(this.client)));
+ this._register(import_coc23.languages.registerCodeActionProvider(languageIds, new OrganizeImportsCodeActionProvider(this.client, this.fileConfigurationManager), "tsserver", [import_vscode_languageserver_protocol18.CodeActionKind.SourceOrganizeImports]));
}
- executeImpl(command, args, executeInfo) {
- if (this.servicePromise == null) {
- return Promise.resolve(undefined);
- }
- this.bufferSyncSupport.beforeCommand(command);
- const request = this._requestQueue.createRequest(command, args);
- const requestInfo = {
- request,
- expectsResponse: executeInfo.expectsResult,
- isAsync: executeInfo.isAsync,
- queueingType: getQueueingType(command, executeInfo.lowPriority)
- };
- let result;
- if (executeInfo.expectsResult) {
- result = new Promise((resolve, reject) => {
- this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync);
- if (executeInfo.token) {
- executeInfo.token.onCancellationRequested(() => {
- this.tryCancelRequest(request.seq, command);
- });
- }
- }).catch((err) => {
- throw err;
- });
- }
- this._requestQueue.enqueue(requestInfo);
- this.sendNextRequests();
- return result;
+ if (this.client.apiVersion.gte(api_default.v240)) {
+ this._register(import_coc23.languages.registerCodeActionProvider(languageIds, new refactor_default(client, this.fileConfigurationManager), "tsserver", [import_vscode_languageserver_protocol18.CodeActionKind.Refactor]));
}
- sendNextRequests() {
- while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
- const item = this._requestQueue.dequeue();
- if (item) {
- this.sendRequest(item);
- }
- }
+ this._register(import_coc23.languages.registerCodeActionProvider(languageIds, new quickfix_default(client, this.fileConfigurationManager), "tsserver", [import_vscode_languageserver_protocol18.CodeActionKind.QuickFix]));
+ this._register(import_coc23.languages.registerCodeActionProvider(languageIds, new importFix_default(this.client.bufferSyncSupport), "tsserver", [import_vscode_languageserver_protocol18.CodeActionKind.QuickFix]));
+ let cachedResponse = new CachedNavTreeResponse();
+ if (this.client.apiVersion.gte(api_default.v206) && conf.get("referencesCodeLens.enable")) {
+ this._register(import_coc23.languages.registerCodeLensProvider(languageIds, new referencesCodeLens_default(client, cachedResponse)));
}
- sendRequest(requestItem) {
- const serverRequest = requestItem.request;
- this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
- if (requestItem.expectsResponse && !requestItem.isAsync) {
- this._pendingResponses.add(requestItem.request.seq);
- }
- this.service().then(childProcess => {
- try {
- childProcess.write(serverRequest);
- }
- catch (err) {
- const callback = this.fetchCallback(serverRequest.seq);
- if (callback) {
- callback.onError(err);
- }
- }
- });
+ if (this.client.apiVersion.gte(api_default.v220) && conf.get("implementationsCodeLens.enable")) {
+ this._register(import_coc23.languages.registerCodeLensProvider(languageIds, new implementationsCodeLens_default(client, cachedResponse)));
}
- tryCancelRequest(seq, command) {
- try {
- if (this._requestQueue.tryDeletePendingRequest(seq)) {
- this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
- return true;
- }
- if (this.cancellationPipeName) {
- this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
- try {
- fs_1.default.writeFileSync(this.cancellationPipeName + seq, '');
- }
- catch (_a) {
- // noop
- }
- return true;
- }
- this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
- return false;
- }
- finally {
- const callback = this.fetchCallback(seq);
- if (callback) {
- callback.onSuccess(new typescriptService_1.ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`));
- }
- }
+ if (this.client.apiVersion.gte(api_default.v350)) {
+ this._register(import_coc23.languages.registerSelectionRangeProvider(languageIds, new smartSelect_default(this.client)));
}
- fetchCallback(seq) {
- const callback = this._callbacks.fetch(seq);
- if (!callback) {
- return undefined;
- }
- this._pendingResponses.delete(seq);
- return callback;
+ if (this.client.apiVersion.gte(api_default.v300)) {
+ this._register(new tagClosing_default(this.client, this.description.id));
}
- dispatchMessage(message) {
- try {
- switch (message.type) {
- case 'response':
- this.dispatchResponse(message);
- break;
- case 'event':
- const event = message;
- if (event.event === 'requestCompleted') {
- const seq = event.body.request_seq;
- const p = this._callbacks.fetch(seq);
- if (p) {
- this.tracer.traceRequestCompleted('requestCompleted', seq, p.startTime);
- p.onSuccess(undefined);
- }
- }
- else {
- this.tracer.traceEvent(event);
- this.dispatchEvent(event);
- }
- break;
- default:
- throw new Error(`Unknown message type ${message.type} received`);
- }
- }
- finally {
- this.sendNextRequests();
- }
+ }
+ handles(resource, doc) {
+ if (doc && this.description.modeIds.indexOf(doc.languageId) >= 0) {
+ return true;
}
- dispatchResponse(response) {
- const callback = this.fetchCallback(response.request_seq);
- if (!callback) {
- return;
+ const base = import_path5.default.basename(import_coc23.Uri.parse(resource).fsPath);
+ return !!base && (!!this.description.configFilePattern && this.description.configFilePattern.test(base));
+ }
+ get id() {
+ return this.description.id;
+ }
+ get diagnosticSource() {
+ return this.description.diagnosticSource;
+ }
+ triggerAllDiagnostics() {
+ this.client.bufferSyncSupport.requestAllDiagnostics();
+ }
+ diagnosticsReceived(diagnosticsKind, file2, diagnostics) {
+ const config = import_coc23.workspace.getConfiguration(this.id, file2.toString());
+ const reportUnnecessary = config.get("showUnused", true);
+ const reportDeprecated = config.get("showDeprecated", true);
+ this.client.diagnosticsManager.diagnosticsReceived(diagnosticsKind, file2.toString(), diagnostics.filter((diag) => {
+ if (!reportUnnecessary) {
+ if (diag.reportUnnecessary && diag.severity === import_vscode_languageserver_protocol18.DiagnosticSeverity.Information) {
+ return false;
}
- this.tracer.traceResponse(response, callback.startTime);
- if (response.success) {
- callback.onSuccess(response);
- }
- else if (response.message === 'No content available.') {
- // Special case where response itself is successful but there is not any data to return.
- callback.onSuccess(typescriptService_1.ServerResponse.NoContent);
- }
- else {
- callback.onError(new Error(response.message));
- }
- }
- dispatchEvent(event) {
- switch (event.event) {
- case 'syntaxDiag':
- case 'semanticDiag':
- case 'suggestionDiag':
- const diagnosticEvent = event;
- if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) {
- this._onDiagnosticsReceived.fire({
- kind: getDiagnosticsKind(event),
- resource: this.asUrl(diagnosticEvent.body.file),
- diagnostics: diagnosticEvent.body.diagnostics
- });
- }
- break;
- case 'configFileDiag':
- this._onConfigDiagnosticsReceived.fire(event);
- break;
- case 'projectLanguageServiceState':
- if (event.body) {
- this._onProjectLanguageServiceStateChanged.fire(event.body);
- }
- break;
- case 'beginInstallTypes':
- if (event.body) {
- this._onDidBeginInstallTypings.fire(event.body);
- }
- break;
- case 'endInstallTypes':
- if (event.body) {
- this._onDidEndInstallTypings.fire(event.body);
- }
- break;
- case 'projectsUpdatedInBackground':
- const body = event.body;
- const resources = body.openFiles.map(coc_nvim_1.Uri.file);
- this.bufferSyncSupport.getErr(resources);
- break;
- case 'typesInstallerInitializationFailed':
- if (event.body) {
- this._onTypesInstallerInitializationFailed.fire(event.body);
- }
- break;
- case 'projectLoadingStart':
- this.versionStatus.loading = true;
- break;
- case 'projectLoadingFinish':
- this.versionStatus.loading = false;
- break;
- }
- }
- getTsServerArgs() {
- return __awaiter(this, void 0, void 0, function* () {
- const args = [];
- args.push('--allowLocalPluginLoads');
- if (this.apiVersion.gte(api_1.default.v250)) {
- args.push('--useInferredProjectPerProjectRoot');
- }
- else {
- args.push('--useSingleInferredProject');
- }
- if (this.apiVersion.gte(api_1.default.v206) && this._configuration.disableAutomaticTypeAcquisition) {
- args.push('--disableAutomaticTypingAcquisition');
- }
- if (this.apiVersion.gte(api_1.default.v222)) {
- this.cancellationPipeName = process_1.getTempFile(`tscancellation-${process_1.makeRandomHexString(20)}`);
- args.push('--cancellationPipeName', this.cancellationPipeName + '*');
- }
- if (this.apiVersion.gte(api_1.default.v222)) {
- const isRoot = process.getuid && process.getuid() == 0;
- if (this._configuration.tsServerLogLevel !== configuration_1.TsServerLogLevel.Off && !isRoot) {
- const logDir = process_1.getTempDirectory();
- if (logDir) {
- this.tsServerLogFile = path_1.default.join(logDir, `tsserver.log`);
- this.info('TSServer log file :', this.tsServerLogFile);
- }
- else {
- this.tsServerLogFile = null;
- this.error('Could not create TSServer log directory');
- }
- if (this.tsServerLogFile) {
- args.push('--logVerbosity', configuration_1.TsServerLogLevel.toString(this._configuration.tsServerLogLevel));
- args.push('--logFile', this.tsServerLogFile);
- }
- }
- }
- if (this.apiVersion.gte(api_1.default.v230)) {
- const pluginNames = this.pluginManager.plugins.map(x => x.name);
- const pluginRoot = this._configuration.tsServerPluginRoot;
- const pluginPaths = pluginRoot ? [pluginRoot] : [];
- if (pluginNames.length) {
- args.push('--globalPlugins', pluginNames.join(','));
- for (const plugin of this.pluginManager.plugins) {
- pluginPaths.push(plugin.path);
- }
- }
- if (pluginPaths.length) {
- args.push('--pluginProbeLocations', pluginPaths.join(','));
- }
- }
- if (this._configuration.typingsCacheLocation) {
- args.push('--globalTypingsCacheLocation', `"${this._configuration.typingsCacheLocation}"`);
- }
- if (this.apiVersion.gte(api_1.default.v234)) {
- if (this._configuration.npmLocation) {
- args.push('--npmLocation', `"${this._configuration.npmLocation}"`);
- }
- else {
- try {
- args.push('--npmLocation', `"${which_1.default.sync('npm')}"`);
- }
- catch (e) { } // tslint:disable-line
- }
- }
- if (this.apiVersion.gte(api_1.default.v291)) {
- args.push('--noGetErrOnBackgroundUpdate');
- }
- if (this.apiVersion.gte(api_1.default.v345)) {
- args.push('--validateDefaultNpmLocation');
- }
- return args;
- });
- }
- getProjectRootPath(uri) {
- let root = coc_nvim_1.workspace.cwd;
- let u = coc_nvim_1.Uri.parse(uri);
- if (u.scheme == 'file') {
- let folder = coc_nvim_1.workspace.getWorkspaceFolder(uri);
- if (folder) {
- root = coc_nvim_1.Uri.parse(folder.uri).fsPath;
- }
- else {
- let filepath = coc_nvim_1.Uri.parse(uri).fsPath;
- if (!filepath.startsWith(root)) {
- root = path_1.default.dirname(filepath);
- }
- }
+ }
+ if (!reportDeprecated) {
+ if (diag.reportDeprecated && diag.severity === import_vscode_languageserver_protocol18.DiagnosticSeverity.Hint) {
+ return false;
}
- if (root == os_1.default.homedir())
- return null;
- return root;
+ }
+ return true;
+ }));
+ }
+};
+var languageProvider_default = LanguageProvider;
+
+// src/server/typescriptServiceClient.ts
+var import_coc32 = __toModule(require("coc.nvim"));
+var import_fs4 = __toModule(require("fs"));
+var import_os2 = __toModule(require("os"));
+var import_path8 = __toModule(require("path"));
+var import_vscode_languageserver_protocol21 = __toModule(require_main3());
+
+// src/utils/fileSchemess.ts
+var file = "file";
+var git = "git";
+var vsls = "vsls";
+var disabledSchemes = new Set([
+ git,
+ vsls
+]);
+
+// src/server/typescriptService.ts
+var ServerResponse;
+(function(ServerResponse2) {
+ class Cancelled {
+ constructor(reason) {
+ this.reason = reason;
+ this.type = "cancelled";
}
- configurePlugin(pluginName, configuration) {
- if (this.apiVersion.gte(api_1.default.v314)) {
- if (!this.servicePromise)
- return;
- this.servicePromise.then(() => {
- // tslint:disable-next-line: no-floating-promises
- this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration });
- });
- }
+ }
+ ServerResponse2.Cancelled = Cancelled;
+ ServerResponse2.NoContent = new class {
+ constructor() {
+ this.type = "noContent";
+ }
+ }();
+})(ServerResponse || (ServerResponse = {}));
+var ExectuionTarget;
+(function(ExectuionTarget2) {
+ ExectuionTarget2[ExectuionTarget2["Semantic"] = 0] = "Semantic";
+ ExectuionTarget2[ExectuionTarget2["Syntax"] = 1] = "Syntax";
+})(ExectuionTarget || (ExectuionTarget = {}));
+
+// src/server/callbackMap.ts
+var CallbackMap = class {
+ constructor() {
+ this._callbacks = new Map();
+ this._asyncCallbacks = new Map();
+ }
+ destroy(cause) {
+ const cancellation = new ServerResponse.Cancelled(cause);
+ for (const callback of this._callbacks.values()) {
+ callback.onSuccess(cancellation);
}
- interruptGetErr(f) {
- return this.bufferSyncSupport.interuptGetErr(f);
+ this._callbacks.clear();
+ for (const callback of this._asyncCallbacks.values()) {
+ callback.onSuccess(cancellation);
}
-}
-exports.default = TypeScriptServiceClient;
-function getDiagnosticsKind(event) {
- switch (event.event) {
- case 'syntaxDiag':
- return diagnostics_1.DiagnosticKind.Syntax;
- case 'semanticDiag':
- return diagnostics_1.DiagnosticKind.Semantic;
- case 'suggestionDiag':
- return diagnostics_1.DiagnosticKind.Suggestion;
- }
- throw new Error('Unknown dignostics kind');
-}
-const fenceCommands = new Set(['change', 'close', 'open']);
-function getQueueingType(command, lowPriority) {
- if (fenceCommands.has(command)) {
- return requestQueue_1.RequestQueueingType.Fence;
+ this._asyncCallbacks.clear();
+ }
+ add(seq, callback, isAsync) {
+ if (isAsync) {
+ this._asyncCallbacks.set(seq, callback);
+ } else {
+ this._callbacks.set(seq, callback);
}
- return lowPriority ? requestQueue_1.RequestQueueingType.LowPriority : requestQueue_1.RequestQueueingType.Normal;
-}
-
-
-/***/ }),
-/* 118 */
-/***/ (function(module, exports) {
-
-module.exports = require("fs");
-
-/***/ }),
-/* 119 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const isWindows = process.platform === 'win32' ||
- process.env.OSTYPE === 'cygwin' ||
- process.env.OSTYPE === 'msys'
-
-const path = __webpack_require__(13)
-const COLON = isWindows ? ';' : ':'
-const isexe = __webpack_require__(120)
-
-const getNotFoundError = (cmd) =>
- Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })
-
-const getPathInfo = (cmd, opt) => {
- const colon = opt.colon || COLON
-
- // If it has a slash, then we don't bother searching the pathenv.
- // just check the file itself, and that's it.
- const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
- : (
- [
- // windows always checks the cwd first
- ...(isWindows ? [process.cwd()] : []),
- ...(opt.path || process.env.PATH ||
- /* istanbul ignore next: very unusual */ '').split(colon),
- ]
- )
- const pathExtExe = isWindows
- ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
- : ''
- const pathExt = isWindows ? pathExtExe.split(colon) : ['']
-
- if (isWindows) {
- if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
- pathExt.unshift('')
}
-
- return {
- pathEnv,
- pathExt,
- pathExtExe,
+ fetch(seq) {
+ const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
+ this.delete(seq);
+ return callback;
}
-}
-
-const which = (cmd, opt, cb) => {
- if (typeof opt === 'function') {
- cb = opt
- opt = {}
+ delete(seq) {
+ if (!this._callbacks.delete(seq)) {
+ this._asyncCallbacks.delete(seq);
+ }
}
- if (!opt)
- opt = {}
-
- const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
- const found = []
-
- const step = i => new Promise((resolve, reject) => {
- if (i === pathEnv.length)
- return opt.all && found.length ? resolve(found)
- : reject(getNotFoundError(cmd))
-
- const ppRaw = pathEnv[i]
- const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
-
- const pCmd = path.join(pathPart, cmd)
- const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
- : pCmd
-
- resolve(subStep(p, i, 0))
- })
-
- const subStep = (p, i, ii) => new Promise((resolve, reject) => {
- if (ii === pathExt.length)
- return resolve(step(i + 1))
- const ext = pathExt[ii]
- isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
- if (!er && is) {
- if (opt.all)
- found.push(p + ext)
- else
- return resolve(p + ext)
- }
- return resolve(subStep(p, i, ii + 1))
- })
- })
-
- return cb ? step(0).then(res => cb(null, res), cb) : step(0)
-}
-
-const whichSync = (cmd, opt) => {
- opt = opt || {}
-
- const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
- const found = []
-
- for (let i = 0; i < pathEnv.length; i ++) {
- const ppRaw = pathEnv[i]
- const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
-
- const pCmd = path.join(pathPart, cmd)
- const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
- : pCmd
+};
- for (let j = 0; j < pathExt.length; j ++) {
- const cur = p + pathExt[j]
- try {
- const is = isexe.sync(cur, { pathExt: pathExtExe })
- if (is) {
- if (opt.all)
- found.push(cur)
- else
- return cur
+// src/server/features/bufferSyncSupport.ts
+var import_coc25 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol19 = __toModule(require_main3());
+
+// src/server/utils/async.ts
+var Delayer = class {
+ constructor(defaultDelay) {
+ this.defaultDelay = defaultDelay;
+ this.timeout = null;
+ this.completionPromise = null;
+ this.onSuccess = null;
+ this.task = null;
+ }
+ 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 = null;
+ this.onSuccess = null;
+ let result = this.task && this.task();
+ this.task = null;
+ return result;
+ });
+ }
+ if (delay >= 0 || this.timeout === null) {
+ this.timeout = setTimeout(() => {
+ this.timeout = null;
+ if (this.onSuccess) {
+ this.onSuccess(void 0);
}
- } catch (ex) {}
+ }, delay >= 0 ? delay : this.defaultDelay);
}
+ return this.completionPromise;
}
+ cancelTimeout() {
+ if (this.timeout !== null) {
+ clearTimeout(this.timeout);
+ this.timeout = null;
+ }
+ }
+};
- if (opt.all && found.length)
- return found
-
- if (opt.nothrow)
- return null
-
- throw getNotFoundError(cmd)
+// src/server/utils/languageModeIds.ts
+var typescript = "typescript";
+var typescriptreact = "typescriptreact";
+var typescripttsx = "typescript.tsx";
+var typescriptjsx = "typescript.jsx";
+var javascript = "javascript";
+var javascriptreact = "javascriptreact";
+var javascriptjsx = "javascript.jsx";
+function mode2ScriptKind(mode) {
+ switch (mode) {
+ case typescript:
+ return "TS";
+ case typescripttsx:
+ return "TSX";
+ case typescriptjsx:
+ return "TSX";
+ case typescriptreact:
+ return "TSX";
+ case javascript:
+ return "JS";
+ case javascriptreact:
+ return "JSX";
+ }
+ return void 0;
}
-module.exports = which
-which.sync = whichSync
-
-
-/***/ }),
-/* 120 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var fs = __webpack_require__(118)
-var core
-if (process.platform === 'win32' || global.TESTING_WINDOWS) {
- core = __webpack_require__(121)
-} else {
- core = __webpack_require__(122)
+// src/server/features/resourceMap.ts
+var import_coc24 = __toModule(require("coc.nvim"));
+function defaultPathNormalizer(resource) {
+ let u = import_coc24.Uri.parse(resource);
+ if (u.scheme === "file") {
+ return u.fsPath;
+ }
+ return resource.toString();
}
-
-module.exports = isexe
-isexe.sync = sync
-
-function isexe (path, options, cb) {
- if (typeof options === 'function') {
- cb = options
- options = {}
+var ResourceMap = class {
+ constructor(_normalizePath = defaultPathNormalizer) {
+ this._normalizePath = _normalizePath;
+ this._map = new Map();
}
-
- if (!cb) {
- if (typeof Promise !== 'function') {
- throw new TypeError('callback not provided')
+ get size() {
+ return this._map.size;
+ }
+ get entries() {
+ return this._map.values();
+ }
+ has(uri) {
+ const file2 = this.toKey(uri);
+ return !!file2 && this._map.has(file2);
+ }
+ get(uri) {
+ const file2 = this.toKey(uri);
+ if (!file2)
+ return void 0;
+ let entry = this._map.get(file2);
+ return entry ? entry.value : void 0;
+ }
+ set(uri, value) {
+ const file2 = this.toKey(uri);
+ if (file2) {
+ this._map.set(file2, {uri, value});
}
-
- return new Promise(function (resolve, reject) {
- isexe(path, options || {}, function (er, is) {
- if (er) {
- reject(er)
- } else {
- resolve(is)
- }
- })
- })
}
-
- core(path, options || {}, function (er, is) {
- // ignore EACCES because that just means we aren't allowed to run it
- if (er) {
- if (er.code === 'EACCES' || options && options.ignoreErrors) {
- er = null
- is = false
+ delete(uri) {
+ const file2 = this.toKey(uri);
+ if (file2) {
+ this._map.delete(file2);
+ }
+ }
+ get values() {
+ return Array.from(this._map.values()).map((x) => x.value);
+ }
+ get uris() {
+ return Array.from(this._map.values()).map((x) => x.uri);
+ }
+ clear() {
+ this._map.clear();
+ }
+ toKey(uri) {
+ const key = this._normalizePath ? this._normalizePath(uri) : uri;
+ if (!key) {
+ return key;
+ }
+ return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
+ }
+ isCaseInsensitivePath(path9) {
+ if (isWindowsPath(path9)) {
+ return true;
+ }
+ return path9[0] === "/" && this.onIsCaseInsenitiveFileSystem;
+ }
+ get onIsCaseInsenitiveFileSystem() {
+ if (process.platform === "win32") {
+ return true;
+ }
+ if (process.platform === "darwin") {
+ return true;
+ }
+ return false;
+ }
+};
+function isWindowsPath(path9) {
+ return /^[a-zA-Z]:\\/.test(path9);
+}
+
+// src/server/features/bufferSyncSupport.ts
+var BufferKind;
+(function(BufferKind2) {
+ BufferKind2[BufferKind2["TypeScript"] = 1] = "TypeScript";
+ BufferKind2[BufferKind2["JavaScript"] = 2] = "JavaScript";
+})(BufferKind || (BufferKind = {}));
+var BufferState;
+(function(BufferState2) {
+ BufferState2[BufferState2["Initial"] = 1] = "Initial";
+ BufferState2[BufferState2["Open"] = 2] = "Open";
+ BufferState2[BufferState2["Closed"] = 2] = "Closed";
+})(BufferState || (BufferState = {}));
+var BufferOperationType;
+(function(BufferOperationType2) {
+ BufferOperationType2[BufferOperationType2["Close"] = 0] = "Close";
+ BufferOperationType2[BufferOperationType2["Open"] = 1] = "Open";
+ BufferOperationType2[BufferOperationType2["Change"] = 2] = "Change";
+})(BufferOperationType || (BufferOperationType = {}));
+var CloseOperation = class {
+ constructor(args) {
+ this.args = args;
+ this.type = 0;
+ }
+};
+var OpenOperation = class {
+ constructor(args) {
+ this.args = args;
+ this.type = 1;
+ }
+};
+var ChangeOperation = class {
+ constructor(args) {
+ this.args = args;
+ this.type = 2;
+ }
+};
+var SyncedBuffer = class {
+ constructor(document, filepath, client, synchronizer) {
+ this.document = document;
+ this.filepath = filepath;
+ this.client = client;
+ this.synchronizer = synchronizer;
+ this.state = 1;
+ }
+ open() {
+ const args = {
+ file: this.filepath,
+ fileContent: this.document.getText(),
+ projectRootPath: this.client.getProjectRootPath(this.document.uri)
+ };
+ const scriptKind = mode2ScriptKind(this.document.languageId);
+ if (scriptKind) {
+ args.scriptKindName = scriptKind;
+ }
+ if (this.client.apiVersion.gte(api_default.v240)) {
+ const tsPluginsForDocument = this.client.pluginManager.plugins.filter((x) => x.languages.indexOf(this.document.languageId) >= 0);
+ if (tsPluginsForDocument.length) {
+ args.plugins = tsPluginsForDocument.map((plugin) => plugin.name);
}
}
- cb(er, is)
- })
-}
-
-function sync (path, options) {
- // my kingdom for a filtered catch
- try {
- return core.sync(path, options || {})
- } catch (er) {
- if (options && options.ignoreErrors || er.code === 'EACCES') {
- return false
- } else {
- throw er
+ this.synchronizer.open(this.resource, args);
+ this.state = 2;
+ }
+ get resource() {
+ return this.document.uri;
+ }
+ get lineCount() {
+ return this.document.lineCount;
+ }
+ get kind() {
+ if (this.document.languageId.startsWith("javascript")) {
+ return 2;
}
+ return 1;
}
-}
-
-
-/***/ }),
-/* 121 */
-/***/ (function(module, exports, __webpack_require__) {
-
-module.exports = isexe
-isexe.sync = sync
-
-var fs = __webpack_require__(118)
-
-function checkPathExt (path, options) {
- var pathext = options.pathExt !== undefined ?
- options.pathExt : process.env.PATHEXT
-
- if (!pathext) {
- return true
+ close() {
+ if (this.state !== 2) {
+ this.state = 2;
+ return false;
+ }
+ this.state = 2;
+ return this.synchronizer.close(this.resource, this.filepath);
}
-
- pathext = pathext.split(';')
- if (pathext.indexOf('') !== -1) {
- return true
+ onContentChanged(events3) {
+ if (this.state !== 2) {
+ console.error(`Unexpected buffer state: ${this.state}`);
+ }
+ this.synchronizer.change(this.resource, this.filepath, events3);
}
- for (var i = 0; i < pathext.length; i++) {
- var p = pathext[i].toLowerCase()
- if (p && path.substr(-p.length).toLowerCase() === p) {
- return true
+};
+var SyncedBufferMap = class extends ResourceMap {
+ getForPath(filePath) {
+ return this.get(import_coc25.Uri.file(filePath).toString());
+ }
+ get allBuffers() {
+ return this.values;
+ }
+};
+var PendingDiagnostics = class extends ResourceMap {
+ getOrderedFileSet() {
+ const orderedResources = Array.from(this.entries).sort((a, b) => a.value - b.value).map((entry) => entry.uri);
+ const map = new ResourceMap(this._normalizePath);
+ for (const resource of orderedResources) {
+ map.set(resource, void 0);
+ }
+ return map;
+ }
+};
+var BufferSynchronizer = class {
+ constructor(client, pathNormalizer) {
+ this.client = client;
+ this._pending = new ResourceMap(pathNormalizer);
+ }
+ open(resource, args) {
+ if (this.supportsBatching) {
+ this.updatePending(resource, new OpenOperation(args));
+ } else {
+ this.client.executeWithoutWaitingForResponse("open", args);
}
}
- return false
-}
-
-function checkStat (stat, path, options) {
- if (!stat.isSymbolicLink() && !stat.isFile()) {
- return false
+ close(resource, filepath) {
+ if (this.supportsBatching) {
+ return this.updatePending(resource, new CloseOperation(filepath));
+ } else {
+ const args = {file: filepath};
+ this.client.executeWithoutWaitingForResponse("close", args);
+ return true;
+ }
}
- return checkPathExt(path, options)
-}
-
-function isexe (path, options, cb) {
- fs.stat(path, function (er, stat) {
- cb(er, er ? false : checkStat(stat, path, options))
- })
-}
-
-function sync (path, options) {
- return checkStat(fs.statSync(path), path, options)
-}
-
-
-/***/ }),
-/* 122 */
-/***/ (function(module, exports, __webpack_require__) {
-
-module.exports = isexe
-isexe.sync = sync
-
-var fs = __webpack_require__(118)
-
-function isexe (path, options, cb) {
- fs.stat(path, function (er, stat) {
- cb(er, er ? false : checkStat(stat, options))
- })
-}
-
-function sync (path, options) {
- return checkStat(fs.statSync(path), options)
-}
-
-function checkStat (stat, options) {
- return stat.isFile() && checkMode(stat, options)
-}
-
-function checkMode (stat, options) {
- var mod = stat.mode
- var uid = stat.uid
- var gid = stat.gid
-
- var myUid = options.uid !== undefined ?
- options.uid : process.getuid && process.getuid()
- var myGid = options.gid !== undefined ?
- options.gid : process.getgid && process.getgid()
-
- var u = parseInt('100', 8)
- var g = parseInt('010', 8)
- var o = parseInt('001', 8)
- var ug = u | g
-
- var ret = (mod & o) ||
- (mod & g) && gid === myGid ||
- (mod & u) && uid === myUid ||
- (mod & ug) && myUid === 0
-
- return ret
-}
-
-
-/***/ }),
-/* 123 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.ServerResponse = void 0;
-var ServerResponse;
-(function (ServerResponse) {
- class Cancelled {
- constructor(reason) {
- this.reason = reason;
- this.type = 'cancelled';
+ change(resource, filepath, events3) {
+ if (!events3.length) {
+ return;
+ }
+ if (this.supportsBatching) {
+ this.updatePending(resource, new ChangeOperation({
+ fileName: filepath,
+ textChanges: events3.map((change) => ({
+ newText: change.text,
+ start: Position.toLocation(change.range.start),
+ end: Position.toLocation(change.range.end)
+ })).reverse()
+ }));
+ } else {
+ for (const {range, text} of events3) {
+ const args = {
+ insertString: text,
+ ...Range2.toFormattingRequestArgs(filepath, range)
+ };
+ this.client.executeWithoutWaitingForResponse("change", args);
+ }
+ }
+ }
+ reset() {
+ this._pending.clear();
+ }
+ beforeCommand(command) {
+ if (command === "updateOpen") {
+ return;
+ }
+ this.flush();
+ }
+ flush() {
+ if (!this.supportsBatching) {
+ this._pending.clear();
+ return;
+ }
+ if (this._pending.size > 0) {
+ const closedFiles = [];
+ const openFiles = [];
+ const changedFiles = [];
+ for (const change of this._pending.values) {
+ switch (change.type) {
+ case 2:
+ changedFiles.push(change.args);
+ break;
+ case 1:
+ openFiles.push(change.args);
+ break;
+ case 0:
+ closedFiles.push(change.args);
+ break;
}
+ }
+ this.client.execute("updateOpen", {changedFiles, closedFiles, openFiles}, import_vscode_languageserver_protocol19.CancellationToken.None, {nonRecoverable: true});
+ this._pending.clear();
}
- ServerResponse.Cancelled = Cancelled;
- // tslint:disable-next-line: new-parens
- ServerResponse.NoContent = new class {
- constructor() {
- this.type = 'noContent';
+ }
+ get supportsBatching() {
+ return this.client.apiVersion.gte(api_default.v340);
+ }
+ updatePending(resource, op) {
+ switch (op.type) {
+ case 0:
+ const existing = this._pending.get(resource);
+ switch (existing == null ? void 0 : existing.type) {
+ case 1:
+ this._pending.delete(resource);
+ return false;
}
+ break;
+ }
+ if (this._pending.has(resource)) {
+ this.flush();
+ }
+ this._pending.set(resource, op);
+ return true;
+ }
+};
+var GetErrRequest = class {
+ constructor(client, uris, _token, onDone) {
+ this.uris = uris;
+ this._token = _token;
+ this._done = false;
+ let files = uris.map((uri) => client.normalizePath(uri));
+ const args = {
+ delay: 0,
+ files
};
-})(ServerResponse = exports.ServerResponse || (exports.ServerResponse = {}));
-
-
-/***/ }),
-/* 124 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
+ const done = () => {
+ if (this._done) {
+ return;
+ }
+ this._done = true;
+ onDone();
+ };
+ client.executeAsync("geterr", args, _token.token).then(done, done);
+ }
+ static executeGetErrRequest(client, uris, onDone) {
+ const token = new import_vscode_languageserver_protocol19.CancellationTokenSource();
+ return new GetErrRequest(client, uris, token, onDone);
+ }
+ cancel() {
+ if (!this._done) {
+ this._token.cancel();
+ }
+ this._token.dispose();
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.TypeScriptServiceConfiguration = exports.TsServerLogLevel = void 0;
-const coc_nvim_1 = __webpack_require__(1);
-const which_1 = __importDefault(__webpack_require__(119));
-var TsServerLogLevel;
-(function (TsServerLogLevel) {
- TsServerLogLevel[TsServerLogLevel["Off"] = 0] = "Off";
- TsServerLogLevel[TsServerLogLevel["Normal"] = 1] = "Normal";
- TsServerLogLevel[TsServerLogLevel["Terse"] = 2] = "Terse";
- TsServerLogLevel[TsServerLogLevel["Verbose"] = 3] = "Verbose";
-})(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
-(function (TsServerLogLevel) {
- function fromString(value) {
- switch (value && value.toLowerCase()) {
- case 'normal':
- return TsServerLogLevel.Normal;
- case 'terse':
- return TsServerLogLevel.Terse;
- case 'verbose':
- return TsServerLogLevel.Verbose;
- case 'off':
- default:
- return TsServerLogLevel.Off;
- }
- }
- TsServerLogLevel.fromString = fromString;
- function toString(value) {
- switch (value) {
- case TsServerLogLevel.Normal:
- return 'normal';
- case TsServerLogLevel.Terse:
- return 'terse';
- case TsServerLogLevel.Verbose:
- return 'verbose';
- case TsServerLogLevel.Off:
- default:
- return 'off';
- }
+var BufferSyncSupport = class {
+ constructor(client, modeIds) {
+ this.disposables = [];
+ this._validateJavaScript = true;
+ this._validateTypeScript = true;
+ this.listening = false;
+ this._onDelete = new import_vscode_languageserver_protocol19.Emitter();
+ this.onDelete = this._onDelete.event;
+ this._onWillChange = new import_vscode_languageserver_protocol19.Emitter();
+ this.onWillChange = this._onWillChange.event;
+ this.client = client;
+ this.modeIds = new Set(modeIds);
+ this.diagnosticDelayer = new Delayer(300);
+ const pathNormalizer = (path9) => this.client.toPath(path9);
+ this.syncedBuffers = new SyncedBufferMap(pathNormalizer);
+ this.pendingDiagnostics = new PendingDiagnostics(pathNormalizer);
+ this.synchronizer = new BufferSynchronizer(client, pathNormalizer);
+ this.updateConfiguration();
+ import_coc25.workspace.onDidChangeConfiguration(this.updateConfiguration, this, this.disposables);
+ }
+ listen() {
+ if (this.listening) {
+ return;
+ }
+ this.listening = true;
+ import_coc25.workspace.onDidOpenTextDocument(this.openTextDocument, this, this.disposables);
+ import_coc25.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, this.disposables);
+ import_coc25.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, this.disposables);
+ import_coc25.workspace.textDocuments.forEach(this.openTextDocument, this);
+ }
+ handles(resource) {
+ return this.syncedBuffers.has(resource);
+ }
+ dispose() {
+ this.pendingDiagnostics.clear();
+ import_coc25.disposeAll(this.disposables);
+ this._onWillChange.dispose();
+ this._onDelete.dispose();
+ }
+ ensureHasBuffer(resource) {
+ if (this.syncedBuffers.has(resource)) {
+ return true;
}
- TsServerLogLevel.toString = toString;
-})(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
-class TypeScriptServiceConfiguration {
- constructor() {
- this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
- coc_nvim_1.workspace.onDidChangeConfiguration(() => {
- this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
- });
+ const existingDocument = import_coc25.workspace.textDocuments.find((doc) => doc.uri.toString() === resource);
+ if (existingDocument) {
+ return this.openTextDocument(existingDocument);
+ }
+ return false;
+ }
+ toResource(filePath) {
+ const buffer = this.syncedBuffers.getForPath(filePath);
+ if (buffer)
+ return buffer.resource;
+ return import_coc25.Uri.file(filePath).toString();
+ }
+ reset() {
+ var _a;
+ (_a = this.pendingGetErr) == null ? void 0 : _a.cancel();
+ this.pendingDiagnostics.clear();
+ this.synchronizer.reset();
+ }
+ reinitialize() {
+ this.reset();
+ for (const buffer of this.syncedBuffers.allBuffers) {
+ buffer.open();
+ }
+ }
+ openTextDocument(document) {
+ if (!this.modeIds.has(document.languageId)) {
+ return false;
+ }
+ const resource = document.uri;
+ const filepath = this.client.normalizePath(import_coc25.Uri.parse(resource));
+ if (!filepath) {
+ return false;
+ }
+ if (this.syncedBuffers.has(resource)) {
+ return true;
+ }
+ const syncedBuffer = new SyncedBuffer(document, filepath, this.client, this.synchronizer);
+ this.syncedBuffers.set(resource, syncedBuffer);
+ syncedBuffer.open();
+ this.requestDiagnostic(syncedBuffer);
+ return true;
+ }
+ closeResource(resource) {
+ const syncedBuffer = this.syncedBuffers.get(resource);
+ if (!syncedBuffer) {
+ return;
+ }
+ this.pendingDiagnostics.delete(resource);
+ this.syncedBuffers.delete(resource);
+ const wasBufferOpen = syncedBuffer.close();
+ this._onDelete.fire(resource);
+ if (wasBufferOpen) {
+ this.requestAllDiagnostics();
+ }
+ }
+ onDidCloseTextDocument(document) {
+ this.closeResource(document.uri);
+ }
+ onDidChangeTextDocument(e) {
+ const syncedBuffer = this.syncedBuffers.get(e.textDocument.uri);
+ if (!syncedBuffer) {
+ return;
+ }
+ this._onWillChange.fire(syncedBuffer.resource);
+ syncedBuffer.onContentChanged(e.contentChanges);
+ const didTrigger = this.requestDiagnostic(syncedBuffer);
+ if (!didTrigger && this.pendingGetErr) {
+ this.pendingGetErr.cancel();
+ this.pendingGetErr = void 0;
+ this.triggerDiagnostics();
+ }
+ }
+ beforeCommand(command) {
+ this.synchronizer.beforeCommand(command);
+ }
+ interuptGetErr(f) {
+ if (!this.pendingGetErr) {
+ return f();
+ }
+ this.pendingGetErr.cancel();
+ this.pendingGetErr = void 0;
+ const result = f();
+ this.triggerDiagnostics();
+ return result;
+ }
+ getErr(resources) {
+ const handledResources = resources.filter((resource) => {
+ let syncedBuffer = this.syncedBuffers.get(resource.toString());
+ return syncedBuffer && this.shouldValidate(syncedBuffer);
+ });
+ if (!handledResources.length) {
+ return;
}
- get locale() {
- return this._configuration.get('locale', null);
+ for (const resource of handledResources) {
+ this.pendingDiagnostics.set(resource.toString(), Date.now());
}
- get globalTsdk() {
- return this._configuration.get('tsdk', null);
+ this.triggerDiagnostics();
+ }
+ triggerDiagnostics(delay = 200) {
+ this.diagnosticDelayer.trigger(() => {
+ this.sendPendingDiagnostics();
+ }, delay);
+ }
+ requestAllDiagnostics() {
+ for (const buffer of this.syncedBuffers.allBuffers) {
+ if (this.shouldValidate(buffer)) {
+ this.pendingDiagnostics.set(buffer.resource, Date.now());
+ }
}
- get ignoreLocalTsserver() {
- return this._configuration.get('ignoreLocalTsserver', false);
+ this.triggerDiagnostics();
+ }
+ requestDiagnostic(buffer) {
+ if (!this.shouldValidate(buffer)) {
+ return false;
}
- get tsServerLogLevel() {
- return TsServerLogLevel.fromString(this._configuration.get('log', null));
+ this.pendingDiagnostics.set(buffer.resource, Date.now());
+ const delay = Math.min(Math.max(Math.ceil(buffer.lineCount / 20), 300), 800);
+ this.triggerDiagnostics(delay);
+ return true;
+ }
+ hasPendingDiagnostics(uri) {
+ return this.pendingDiagnostics.has(uri);
+ }
+ sendPendingDiagnostics() {
+ const orderedFileSet = this.pendingDiagnostics.getOrderedFileSet();
+ if (this.pendingGetErr) {
+ this.pendingGetErr.cancel();
+ for (const uri of this.pendingGetErr.uris) {
+ let resource = uri.toString();
+ let syncedBuffer = this.syncedBuffers.get(resource);
+ if (syncedBuffer && this.shouldValidate(syncedBuffer)) {
+ orderedFileSet.set(resource, void 0);
+ } else {
+ orderedFileSet.delete(resource);
+ }
+ }
+ this.pendingGetErr = void 0;
}
- // public readonly watchOptions: protocol.WatchOptions | undefined;
- get watchOptions() {
- return this._configuration.get('watchOptions');
+ for (const buffer of this.syncedBuffers.values) {
+ if (this.shouldValidate(buffer)) {
+ orderedFileSet.set(buffer.resource, void 0);
+ }
}
- get typingsCacheLocation() {
- return this._configuration.get('typingsCacheLocation', '');
+ if (orderedFileSet.size) {
+ let uris = Array.from(orderedFileSet.uris).map((uri) => import_coc25.Uri.parse(uri));
+ const getErr = this.pendingGetErr = GetErrRequest.executeGetErrRequest(this.client, uris, () => {
+ if (this.pendingGetErr === getErr) {
+ this.pendingGetErr = void 0;
+ }
+ });
}
- get tsServerPluginRoot() {
- return this._configuration.get('tsServerPluginRoot', null);
+ this.pendingDiagnostics.clear();
+ }
+ updateConfiguration() {
+ const jsConfig = import_coc25.workspace.getConfiguration("javascript", null);
+ const tsConfig = import_coc25.workspace.getConfiguration("typescript", null);
+ this._validateJavaScript = jsConfig.get("validate.enable", true);
+ this._validateTypeScript = tsConfig.get("validate.enable", true);
+ }
+ shouldValidate(buffer) {
+ switch (buffer.kind) {
+ case 2:
+ return this._validateJavaScript;
+ case 1:
+ default:
+ return this._validateTypeScript;
}
- get checkJs() {
- return this._configuration.get('implicitProjectConfig.checkJs', false);
+ }
+};
+var bufferSyncSupport_default = BufferSyncSupport;
+
+// src/server/features/diagnostics.ts
+var import_coc26 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol20 = __toModule(require_main3());
+var DiagnosticSet = class {
+ constructor() {
+ this._map = new ResourceMap();
+ }
+ set(uri, diagnostics) {
+ this._map.set(uri, diagnostics);
+ }
+ get(uri) {
+ return this._map.get(uri) || [];
+ }
+ clear() {
+ this._map = new ResourceMap();
+ }
+};
+var DiagnosticKind;
+(function(DiagnosticKind2) {
+ DiagnosticKind2[DiagnosticKind2["Syntax"] = 0] = "Syntax";
+ DiagnosticKind2[DiagnosticKind2["Semantic"] = 1] = "Semantic";
+ DiagnosticKind2[DiagnosticKind2["Suggestion"] = 2] = "Suggestion";
+})(DiagnosticKind || (DiagnosticKind = {}));
+var allDiagnosticKinds = [
+ 0,
+ 1,
+ 2
+];
+var DiagnosticsManager = class {
+ constructor() {
+ this._diagnostics = new Map();
+ this._pendingUpdates = new ResourceMap();
+ this._enableJavascriptSuggestions = true;
+ this._enableTypescriptSuggestions = true;
+ this.updateDelay = 200;
+ for (const kind of allDiagnosticKinds) {
+ this._diagnostics.set(kind, new DiagnosticSet());
+ }
+ this._currentDiagnostics = import_coc26.languages.createDiagnosticCollection("tsserver");
+ }
+ dispose() {
+ this._currentDiagnostics.dispose();
+ for (const value of this._pendingUpdates.values) {
+ clearTimeout(value);
}
- get experimentalDecorators() {
- return this._configuration.get('implicitProjectConfig.experimentalDecorators', false);
+ this._pendingUpdates = new ResourceMap();
+ }
+ reInitialize() {
+ this._currentDiagnostics.clear();
+ for (const diagnosticSet of this._diagnostics.values()) {
+ diagnosticSet.clear();
}
- get disableAutomaticTypeAcquisition() {
- return this._configuration.get('disableAutomaticTypeAcquisition', false);
+ }
+ setEnableSuggestions(languageId, value) {
+ let curr = languageId == "javascript" ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions;
+ if (curr == value) {
+ return;
}
- get formatOnType() {
- return this._configuration.get('formatOnType', false);
+ if (languageId == "javascript") {
+ this._enableJavascriptSuggestions = value;
+ } else {
+ this._enableTypescriptSuggestions = value;
}
- get maxTsServerMemory() {
- return this._configuration.get('maxTsServerMemory', 0);
+ }
+ diagnosticsReceived(kind, uri, diagnostics) {
+ const collection = this._diagnostics.get(kind);
+ if (!collection)
+ return;
+ let doc = import_coc26.workspace.getDocument(uri);
+ if (doc)
+ uri = doc.uri;
+ if (diagnostics.length === 0) {
+ const existing = collection.get(uri);
+ if (existing.length === 0) {
+ return;
+ }
}
- get debugPort() {
- return this._configuration.get('debugPort', parseInt(process.env['TSS_DEBUG'], 10));
+ collection.set(uri, diagnostics);
+ this.scheduleDiagnosticsUpdate(uri);
+ }
+ configFileDiagnosticsReceived(uri, diagnostics) {
+ this._currentDiagnostics.set(uri, diagnostics);
+ }
+ delete(uri) {
+ this._currentDiagnostics.delete(uri);
+ }
+ getDiagnostics(uri) {
+ return this._currentDiagnostics.get(uri) || [];
+ return [];
+ }
+ scheduleDiagnosticsUpdate(uri) {
+ if (!this._pendingUpdates.has(uri)) {
+ this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay));
}
- get npmLocation() {
- let path = this._configuration.get('npm', '');
- if (path)
- return path;
- try {
- path = which_1.default.sync('npm');
- }
- catch (e) {
- return null;
- }
- return path;
+ }
+ updateCurrentDiagnostics(uri) {
+ if (this._pendingUpdates.has(uri)) {
+ clearTimeout(this._pendingUpdates.get(uri));
+ this._pendingUpdates.delete(uri);
+ }
+ const allDiagnostics = [
+ ...this._diagnostics.get(0).get(uri),
+ ...this._diagnostics.get(1).get(uri),
+ ...this.getSuggestionDiagnostics(uri)
+ ];
+ this._currentDiagnostics.set(uri, allDiagnostics);
+ }
+ getSuggestionDiagnostics(uri) {
+ const enabled = this.suggestionsEnabled(uri);
+ return this._diagnostics.get(2).get(uri).filter((x) => {
+ if (!enabled) {
+ return x.tags && (x.tags.includes(import_vscode_languageserver_protocol20.DiagnosticTag.Unnecessary) || x.tags.includes(import_vscode_languageserver_protocol20.DiagnosticTag.Deprecated));
+ }
+ return enabled;
+ });
+ }
+ suggestionsEnabled(uri) {
+ let doc = import_coc26.workspace.getDocument(uri);
+ if (!doc)
+ return false;
+ if (doc.filetype.startsWith("javascript")) {
+ return this._enableJavascriptSuggestions;
}
- static loadFromWorkspace() {
- return new TypeScriptServiceConfiguration();
+ if (doc.filetype.startsWith("typescript")) {
+ return this._enableTypescriptSuggestions;
}
-}
-exports.TypeScriptServiceConfiguration = TypeScriptServiceConfiguration;
-
-
-/***/ }),
-/* 125 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
+ return true;
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-const coc_nvim_1 = __webpack_require__(1);
-const is = __importStar(__webpack_require__(126));
-class Logger {
- get output() {
- if (this._channel) {
- return this._channel;
- }
- this._channel = coc_nvim_1.workspace.createOutputChannel('tsserver');
- return this._channel;
- }
- dispose() {
- if (this._channel) {
- this._channel.dispose();
- }
- }
- data2String(data) {
- if (data instanceof Error) {
- if (is.string(data.stack)) {
- return data.stack;
- }
- return data.message;
- }
- if (is.boolean(data.success) && !data.success && is.string(data.message)) {
- return data.message;
- }
- if (is.string(data)) {
- return data;
- }
- return data.toString();
- }
- info(message, data) {
- this.logLevel('Info', message, data);
+
+// src/server/requestQueue.ts
+var RequestQueueingType;
+(function(RequestQueueingType2) {
+ RequestQueueingType2[RequestQueueingType2["Normal"] = 1] = "Normal";
+ RequestQueueingType2[RequestQueueingType2["LowPriority"] = 2] = "LowPriority";
+ RequestQueueingType2[RequestQueueingType2["Fence"] = 3] = "Fence";
+})(RequestQueueingType || (RequestQueueingType = {}));
+var RequestQueue = class {
+ constructor() {
+ this.queue = [];
+ this.sequenceNumber = 0;
+ }
+ get length() {
+ return this.queue.length;
+ }
+ enqueue(item) {
+ if (item.queueingType === 1) {
+ let index = this.queue.length - 1;
+ while (index >= 0) {
+ if (this.queue[index].queueingType !== 2) {
+ break;
+ }
+ --index;
+ }
+ this.queue.splice(index + 1, 0, item);
+ } else {
+ this.queue.push(item);
}
- warn(message, data) {
- this.logLevel('Warn', message, data);
+ }
+ dequeue() {
+ return this.queue.shift();
+ }
+ tryDeletePendingRequest(seq) {
+ for (let i = 0; i < this.queue.length; i++) {
+ if (this.queue[i].request.seq === seq) {
+ this.queue.splice(i, 1);
+ return true;
+ }
}
- error(message, data) {
- // See https://github.com/Microsoft/TypeScript/issues/10496
- if (data && data.message === 'No content available.') {
- return;
- }
- this.logLevel('Error', message, data);
+ return false;
+ }
+ createRequest(command, args) {
+ return {
+ seq: this.sequenceNumber++,
+ type: "request",
+ command,
+ arguments: args
+ };
+ }
+};
+
+// src/server/utils/configuration.ts
+var import_coc27 = __toModule(require("coc.nvim"));
+var import_which = __toModule(require_which());
+var TsServerLogLevel;
+(function(TsServerLogLevel2) {
+ TsServerLogLevel2[TsServerLogLevel2["Off"] = 0] = "Off";
+ TsServerLogLevel2[TsServerLogLevel2["Normal"] = 1] = "Normal";
+ TsServerLogLevel2[TsServerLogLevel2["Terse"] = 2] = "Terse";
+ TsServerLogLevel2[TsServerLogLevel2["Verbose"] = 3] = "Verbose";
+})(TsServerLogLevel || (TsServerLogLevel = {}));
+(function(TsServerLogLevel2) {
+ function fromString(value) {
+ switch (value && value.toLowerCase()) {
+ case "normal":
+ return TsServerLogLevel2.Normal;
+ case "terse":
+ return TsServerLogLevel2.Terse;
+ case "verbose":
+ return TsServerLogLevel2.Verbose;
+ case "off":
+ default:
+ return TsServerLogLevel2.Off;
}
- logLevel(level, message, data) {
- this.output.appendLine(`[${level} - ${new Date().toLocaleTimeString()}] ${message}`);
- if (data) {
- this.output.appendLine(this.data2String(data));
- }
+ }
+ TsServerLogLevel2.fromString = fromString;
+ function toString2(value) {
+ switch (value) {
+ case TsServerLogLevel2.Normal:
+ return "normal";
+ case TsServerLogLevel2.Terse:
+ return "terse";
+ case TsServerLogLevel2.Verbose:
+ return "verbose";
+ case TsServerLogLevel2.Off:
+ default:
+ return "off";
}
-}
-exports.default = Logger;
-
-
-/***/ }),
-/* 126 */
-/***/ (function(module, exports, __webpack_require__) {
+ }
+ TsServerLogLevel2.toString = toString2;
+})(TsServerLogLevel || (TsServerLogLevel = {}));
+var TypeScriptServiceConfiguration = class {
+ constructor() {
+ this._configuration = import_coc27.workspace.getConfiguration("tsserver");
+ import_coc27.workspace.onDidChangeConfiguration(() => {
+ this._configuration = import_coc27.workspace.getConfiguration("tsserver");
+ });
+ }
+ get locale() {
+ return this._configuration.get("locale", null);
+ }
+ get globalTsdk() {
+ return this._configuration.get("tsdk", null);
+ }
+ get ignoreLocalTsserver() {
+ return this._configuration.get("ignoreLocalTsserver", false);
+ }
+ get tsServerLogLevel() {
+ return TsServerLogLevel.fromString(this._configuration.get("log", null));
+ }
+ get watchOptions() {
+ return this._configuration.get("watchOptions");
+ }
+ get typingsCacheLocation() {
+ return this._configuration.get("typingsCacheLocation", "");
+ }
+ get tsServerPluginPaths() {
+ return this._configuration.get("pluginPaths", []);
+ }
+ get checkJs() {
+ return this._configuration.get("implicitProjectConfig.checkJs", false);
+ }
+ get experimentalDecorators() {
+ return this._configuration.get("implicitProjectConfig.experimentalDecorators", false);
+ }
+ get disableAutomaticTypeAcquisition() {
+ return this._configuration.get("disableAutomaticTypeAcquisition", false);
+ }
+ get formatOnType() {
+ return this._configuration.get("formatOnType", false);
+ }
+ get maxTsServerMemory() {
+ return this._configuration.get("maxTsServerMemory", 0);
+ }
+ get debugPort() {
+ return this._configuration.get("debugPort", parseInt(process.env["TSS_DEBUG"], 10));
+ }
+ get npmLocation() {
+ let path9 = this._configuration.get("npm", "");
+ if (path9)
+ return import_coc27.workspace.expand(path9);
+ try {
+ path9 = import_which.default.sync("npm");
+ } catch (e) {
+ return null;
+ }
+ return path9;
+ }
+ static loadFromWorkspace() {
+ return new TypeScriptServiceConfiguration();
+ }
+};
-"use strict";
+// src/server/utils/logger.ts
+var import_coc28 = __toModule(require("coc.nvim"));
-/*---------------------------------------------------------------------------------------------
- * 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.string = exports.boolean = exports.defined = void 0;
-const toString = Object.prototype.toString;
-function defined(value) {
- return typeof value !== 'undefined';
-}
-exports.defined = defined;
+// src/server/utils/is.ts
+var toString = Object.prototype.toString;
function boolean(value) {
- return value === true || value === false;
+ return value === true || value === false;
}
-exports.boolean = boolean;
function string(value) {
- return toString.call(value) === '[object String]';
+ return toString.call(value) === "[object String]";
}
-exports.string = string;
-
-/***/ }),
-/* 127 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
+// src/server/utils/logger.ts
+var Logger = class {
+ get output() {
+ if (this._channel) {
+ return this._channel;
+ }
+ this._channel = import_coc28.window.createOutputChannel("tsserver");
+ return this._channel;
+ }
+ dispose() {
+ if (this._channel) {
+ this._channel.dispose();
+ }
+ }
+ data2String(data) {
+ if (data instanceof Error) {
+ if (string(data.stack)) {
+ return data.stack;
+ }
+ return data.message;
+ }
+ if (boolean(data.success) && !data.success && string(data.message)) {
+ return data.message;
+ }
+ if (string(data)) {
+ return data;
+ }
+ return data.toString();
+ }
+ info(message, data) {
+ this.logLevel("Info", message, data);
+ }
+ warn(message, data) {
+ this.logLevel("Warn", message, data);
+ }
+ error(message, data) {
+ if (data && data.message === "No content available.") {
+ return;
+ }
+ this.logLevel("Error", message, data);
+ }
+ logLevel(level, message, data) {
+ this.output.appendLine(`[${level} - ${new Date().toLocaleTimeString()}] ${message}`);
+ if (data) {
+ this.output.appendLine(this.data2String(data));
+ }
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.fork = exports.getTempFile = exports.getTempDirectory = exports.makeRandomHexString = void 0;
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const child_process_1 = __importDefault(__webpack_require__(113));
-const net_1 = __importDefault(__webpack_require__(16));
-const os_1 = __importDefault(__webpack_require__(14));
-const path_1 = __importDefault(__webpack_require__(13));
-const fs_1 = __importDefault(__webpack_require__(118));
+var logger_default = Logger;
+
+// src/server/utils/process.ts
+var import_child_process2 = __toModule(require("child_process"));
+var import_net = __toModule(require("net"));
+var import_os = __toModule(require("os"));
+var import_path6 = __toModule(require("path"));
+var import_fs2 = __toModule(require("fs"));
function makeRandomHexString(length) {
- let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
- let result = '';
- for (let i = 0; i < length; i++) {
- const idx = Math.floor(chars.length * Math.random());
- result += chars[idx];
- }
- return result;
+ let chars = ["0", "1", "2", "3", "4", "5", "6", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
+ let result = "";
+ for (let i = 0; i < length; i++) {
+ const idx = Math.floor(chars.length * Math.random());
+ result += chars[idx];
+ }
+ return result;
}
-exports.makeRandomHexString = makeRandomHexString;
function getTempDirectory() {
- let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`);
- if (!fs_1.default.existsSync(dir)) {
- fs_1.default.mkdirSync(dir);
- }
- return dir;
+ let dir = import_path6.default.join(import_os.default.tmpdir(), `coc.nvim-${process.pid}`);
+ if (!import_fs2.default.existsSync(dir)) {
+ import_fs2.default.mkdirSync(dir);
+ }
+ return dir;
}
-exports.getTempDirectory = getTempDirectory;
function generatePipeName() {
- return getPipeName(makeRandomHexString(40));
+ return getPipeName(makeRandomHexString(40));
}
function getPipeName(name) {
- const fullName = 'coc-tsc-' + name;
- if (process.platform === 'win32') {
- return '\\\\.\\pipe\\' + fullName + '-sock';
- }
- const tmpdir = getTempDirectory();
- // Mac/Unix: use socket file
- return path_1.default.join(tmpdir, fullName + '.sock');
+ const fullName = "coc-tsc-" + name;
+ if (process.platform === "win32") {
+ return "\\\\.\\pipe\\" + fullName + "-sock";
+ }
+ const tmpdir = getTempDirectory();
+ return import_path6.default.join(tmpdir, fullName + ".sock");
}
function getTempFile(name) {
- const fullName = 'coc-nvim-' + name;
- return path_1.default.join(getTempDirectory(), fullName + '.sock');
+ const fullName = "coc-nvim-" + name;
+ return import_path6.default.join(getTempDirectory(), fullName + ".sock");
}
-exports.getTempFile = getTempFile;
function generatePatchedEnv(env, stdInPipeName, stdOutPipeName, stdErrPipeName) {
- const newEnv = Object.assign({}, env);
- // Set the two unique pipe names and the electron flag as process env
- newEnv['STDIN_PIPE_NAME'] = stdInPipeName; // tslint:disable-line
- newEnv['STDOUT_PIPE_NAME'] = stdOutPipeName; // tslint:disable-line
- newEnv['STDERR_PIPE_NAME'] = stdErrPipeName; // tslint:disable-line
- newEnv['TSS_LOG'] = `-level verbose -file ${path_1.default.join(os_1.default.tmpdir(), 'coc-nvim-tsc.log')}`; // tslint:disable-line
- // Ensure we always have a PATH set
- newEnv['PATH'] = newEnv['PATH'] || process.env.PATH; // tslint:disable-line
- return newEnv;
+ const newEnv = Object.assign({}, env);
+ newEnv["STDIN_PIPE_NAME"] = stdInPipeName;
+ newEnv["STDOUT_PIPE_NAME"] = stdOutPipeName;
+ newEnv["STDERR_PIPE_NAME"] = stdErrPipeName;
+ newEnv["TSS_LOG"] = `-level verbose -file ${import_path6.default.join(import_os.default.tmpdir(), "coc-nvim-tsc.log")}`;
+ newEnv["PATH"] = newEnv["PATH"] || process.env.PATH;
+ return newEnv;
}
function fork(modulePath, args, options, logger, callback) {
- let callbackCalled = false;
- const resolve = (result) => {
- if (callbackCalled) {
- return;
- }
- callbackCalled = true;
- callback(null, result);
- };
- const reject = (err) => {
- if (callbackCalled) {
- return;
- }
- callbackCalled = true;
- callback(err, null);
- };
- // Generate three unique pipe names
- const stdInPipeName = generatePipeName();
- const stdOutPipeName = generatePipeName();
- const stdErrPipeName = generatePipeName();
- const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName);
- newEnv['NODE_PATH'] = path_1.default.join(modulePath, '..', '..', '..'); // tslint:disable-line
- let childProcess;
- // Begin listening to stderr pipe
- let stdErrServer = net_1.default.createServer(stdErrStream => {
- // From now on the childProcess.stderr is available for reading
- childProcess.stderr = stdErrStream;
- });
- stdErrServer.listen(stdErrPipeName);
- // Begin listening to stdout pipe
- let stdOutServer = net_1.default.createServer(stdOutStream => {
- // The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe
- stdOutStream.once('data', (_chunk) => {
- // The child process is sending me the `ready` chunk, time to connect to the stdin pipe
- childProcess.stdin = net_1.default.connect(stdInPipeName);
- // From now on the childProcess.stdout is available for reading
- childProcess.stdout = stdOutStream;
- resolve(childProcess);
- });
- });
- stdOutServer.listen(stdOutPipeName);
- let serverClosed = false;
- const closeServer = () => {
- if (serverClosed) {
- return;
- }
- serverClosed = true;
- stdOutServer.close();
- stdErrServer.close();
- };
- // Create the process
- logger.info('Forking TSServer', `PATH: ${newEnv['PATH']} `);
- const bootstrapperPath = path_1.default.resolve(__dirname, '../bin/tsserverForkStart');
- childProcess = child_process_1.default.fork(bootstrapperPath, [modulePath].concat(args), {
- silent: true,
- env: newEnv,
- execArgv: options.execArgv
- });
- childProcess.once('error', (err) => {
- closeServer();
- reject(err);
- });
- childProcess.once('exit', (err) => {
- closeServer();
- reject(err);
- });
-}
-exports.fork = fork;
-
-
-/***/ }),
-/* 128 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const coc_nvim_1 = __webpack_require__(1);
-var Trace;
-(function (Trace) {
- Trace[Trace["Off"] = 0] = "Off";
- Trace[Trace["Messages"] = 1] = "Messages";
- Trace[Trace["Verbose"] = 2] = "Verbose";
-})(Trace || (Trace = {}));
-(function (Trace) {
- function fromString(value) {
- value = value || '';
- value = value.toLowerCase();
- switch (value) {
- case 'off':
- return Trace.Off;
- case 'messages':
- return Trace.Messages;
- case 'verbose':
- return Trace.Verbose;
- default:
- return Trace.Off;
- }
- }
- Trace.fromString = fromString;
-})(Trace || (Trace = {}));
-class Tracer {
- constructor(logger) {
- this.logger = logger;
- this.trace = Tracer.readTrace();
- }
- static readTrace() {
- let result = Trace.fromString(coc_nvim_1.workspace.getConfiguration('tsserver').get('trace.server', 'off'));
- if (result === Trace.Off && !!process.env.TSS_TRACE) {
- result = Trace.Messages;
- }
- return result;
- }
- traceRequest(request, responseExpected, queueLength) {
- if (this.trace === Trace.Off)
- return;
- let data;
- if (this.trace === Trace.Verbose && request.arguments) {
- data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
- }
- this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${queueLength}`, data);
- }
- traceResponse(response, startTime) {
- if (this.trace === Trace.Off) {
- return;
- }
- let data;
- if (this.trace === Trace.Verbose && response.body) {
- data = `Result: ${JSON.stringify(response.body, null, 4)}`;
- }
- this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data);
- }
- traceEvent(event) {
- if (this.trace === Trace.Off) {
- return;
- }
- let data;
- if (this.trace === Trace.Verbose && event.body) {
- data = `Data: ${JSON.stringify(event.body, null, 4)}`;
- }
- this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
- }
- logTrace(message, data) {
- if (this.trace !== Trace.Off) {
- this.logger.logLevel('Trace', message, data);
- }
- }
- traceRequestCompleted(command, request_seq, startTime) {
- if (this.trace === Trace.Off) {
- return;
- }
- this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`);
- }
-}
-exports.default = Tracer;
-
-
-/***/ }),
-/* 129 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.inferredProjectConfig = void 0;
-function inferredProjectConfig(config) {
- const base = {
- module: 'commonjs',
- target: 'es2016',
- jsx: 'preserve'
- };
- if (config.checkJs) {
- base.checkJs = true;
- }
- if (config.experimentalDecorators) {
- base.experimentalDecorators = true;
- }
- return base;
-}
-exports.inferredProjectConfig = inferredProjectConfig;
-
-
-/***/ }),
-/* 130 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.TypeScriptVersionProvider = exports.TypeScriptVersion = void 0;
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const fs_1 = __importDefault(__webpack_require__(118));
-const path_1 = __importDefault(__webpack_require__(13));
-const coc_nvim_1 = __webpack_require__(1);
-const api_1 = __importDefault(__webpack_require__(40));
-const requireFunc = true ? require : undefined;
-class TypeScriptVersion {
- constructor(path, _pathLabel) {
- this.path = path;
- this._pathLabel = _pathLabel;
- this._api = null;
- }
- get tscPath() {
- return path_1.default.resolve(this.path, '../bin/tsc');
- }
- get tsServerPath() {
- return path_1.default.resolve(this.path, 'tsserver.js');
- }
- get pathLabel() {
- return typeof this._pathLabel === 'undefined' ? this.path : this._pathLabel;
- }
- get isValid() {
- return this.version != null;
- }
- get version() {
- if (this._api)
- return this._api;
- let api = this._api = this.getTypeScriptVersion(this.tsServerPath);
- return api;
- }
- get versionString() {
- const version = this.version;
- return version ? version.versionString : null;
- }
- getTypeScriptVersion(serverPath) {
- if (!fs_1.default.existsSync(serverPath)) {
- return undefined;
- }
- const p = serverPath.split(path_1.default.sep);
- if (p.length <= 2) {
- return undefined;
- }
- const p2 = p.slice(0, -2);
- const modulePath = p2.join(path_1.default.sep);
- let fileName = path_1.default.join(modulePath, 'package.json');
- if (!fs_1.default.existsSync(fileName)) {
- // Special case for ts dev versions
- if (path_1.default.basename(modulePath) === 'built') {
- fileName = path_1.default.join(modulePath, '..', 'package.json');
- }
- }
- if (!fs_1.default.existsSync(fileName)) {
- return undefined;
- }
- const contents = fs_1.default.readFileSync(fileName).toString();
- let desc = null;
- try {
- desc = JSON.parse(contents);
- }
- catch (err) {
- return undefined;
- }
- if (!desc || !desc.version) {
- return undefined;
- }
- return desc.version ? api_1.default.fromVersionString(desc.version) : undefined;
- }
-}
-exports.TypeScriptVersion = TypeScriptVersion;
-const MODULE_FOLDERS = ['node_modules/typescript/lib', '.vscode/pnpify/typescript/lib'];
-class TypeScriptVersionProvider {
- constructor(configuration) {
- this.configuration = configuration;
- }
- updateConfiguration(configuration) {
- this.configuration = configuration;
- }
- getDefaultVersion() {
- // tsdk from configuration
- let { globalTsdk } = this.configuration;
- if (globalTsdk)
- return new TypeScriptVersion(globalTsdk);
- return this.bundledVersion;
- }
- get globalVersion() {
- let { globalTsdk } = this.configuration;
- if (globalTsdk)
- return new TypeScriptVersion(globalTsdk);
- return undefined;
- }
- getLocalVersion() {
- let folders = coc_nvim_1.workspace.workspaceFolders.map(f => coc_nvim_1.Uri.parse(f.uri).fsPath);
- for (let p of folders) {
- for (let folder of MODULE_FOLDERS) {
- let libFolder = path_1.default.join(p, folder);
- if (fs_1.default.existsSync(libFolder)) {
- let version = new TypeScriptVersion(libFolder);
- if (version.isValid)
- return version;
- }
- }
- }
- return null;
- }
- get bundledVersion() {
- try {
- const file = requireFunc.resolve('typescript');
- const bundledVersion = new TypeScriptVersion(path_1.default.dirname(file), '');
- return bundledVersion;
- }
- catch (e) {
- coc_nvim_1.workspace.showMessage('Bundled typescript module not found', 'error');
- return null;
- }
- }
-}
-exports.TypeScriptVersionProvider = TypeScriptVersionProvider;
-
-
-/***/ }),
-/* 131 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const coc_nvim_1 = __webpack_require__(1);
-class VersionStatus {
- constructor(_normalizePath, enableJavascript) {
- this._normalizePath = _normalizePath;
- this.enableJavascript = enableJavascript;
- this._versionBarEntry = coc_nvim_1.workspace.createStatusBarItem(99);
- this._onChangeEditorSub = coc_nvim_1.events.on('BufEnter', this.onBufEnter, this);
- this._versionBarEntry.show();
- }
- dispose() {
- this._versionBarEntry.dispose();
- this._onChangeEditorSub.dispose();
- }
- onDidChangeTypeScriptVersion(_version) {
- this._versionBarEntry.text = `TSC`;
- }
- set loading(isLoading) {
- this._versionBarEntry.isProgress = isLoading;
- }
- checkFiletype(filetype) {
- if (filetype.startsWith('javascript') && this.enableJavascript) {
- return true;
- }
- return filetype.startsWith('typescript');
- }
- onBufEnter(bufnr) {
- return __awaiter(this, void 0, void 0, function* () {
- let filetype = yield coc_nvim_1.workspace.nvim.call('getbufvar', [bufnr, '&filetype', '']);
- if (this.checkFiletype(filetype)) {
- this._versionBarEntry.show();
- }
- else {
- this._versionBarEntry.hide();
- }
- });
- }
-}
-exports.default = VersionStatus;
-
-
-/***/ }),
-/* 132 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Reader = void 0;
-const DefaultSize = 8192;
-const ContentLength = 'Content-Length: ';
-const ContentLengthSize = Buffer.byteLength(ContentLength, 'utf8');
-const Blank = Buffer.from(' ', 'utf8')[0];
-const BackslashR = Buffer.from('\r', 'utf8')[0];
-const BackslashN = Buffer.from('\n', 'utf8')[0];
-class ProtocolBuffer {
- constructor() {
- this.index = 0;
- this.buffer = Buffer.allocUnsafe(DefaultSize);
- }
- append(data) {
- let toAppend = null;
- if (Buffer.isBuffer(data)) {
- toAppend = data;
- }
- else {
- toAppend = Buffer.from(data, 'utf8');
- }
- if (this.buffer.length - this.index >= toAppend.length) {
- toAppend.copy(this.buffer, this.index, 0, toAppend.length);
- }
- else {
- let newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) *
- DefaultSize;
- if (this.index === 0) {
- this.buffer = Buffer.allocUnsafe(newSize);
- toAppend.copy(this.buffer, 0, 0, toAppend.length);
- }
- else {
- this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
- }
- }
- this.index += toAppend.length;
- }
- tryReadContentLength() {
- let result = -1;
- let current = 0;
- // we are utf8 encoding...
- while (current < this.index &&
- (this.buffer[current] === Blank ||
- this.buffer[current] === BackslashR ||
- this.buffer[current] === BackslashN)) {
- current++;
- }
- if (this.index < current + ContentLengthSize) {
- return result;
- }
- current += ContentLengthSize;
- let start = current;
- while (current < this.index && this.buffer[current] !== BackslashR) {
- current++;
- }
- if (current + 3 >= this.index ||
- this.buffer[current + 1] !== BackslashN ||
- this.buffer[current + 2] !== BackslashR ||
- this.buffer[current + 3] !== BackslashN) {
- return result;
- }
- let data = this.buffer.toString('utf8', start, current);
- result = parseInt(data, 10);
- this.buffer = this.buffer.slice(current + 4);
- this.index = this.index - (current + 4);
- return result;
- }
- tryReadContent(length) {
- if (this.index < length) {
- return null;
- }
- let result = this.buffer.toString('utf8', 0, length);
- let sourceStart = length;
- while (sourceStart < this.index &&
- (this.buffer[sourceStart] === BackslashR ||
- this.buffer[sourceStart] === BackslashN)) {
- sourceStart++;
- }
- this.buffer.copy(this.buffer, 0, sourceStart);
- this.index = this.index - sourceStart;
- return result;
+ let callbackCalled = false;
+ const resolve = (result) => {
+ if (callbackCalled) {
+ return;
+ }
+ callbackCalled = true;
+ callback(null, result);
+ };
+ const reject = (err) => {
+ if (callbackCalled) {
+ return;
+ }
+ callbackCalled = true;
+ callback(err, null);
+ };
+ const stdInPipeName = generatePipeName();
+ const stdOutPipeName = generatePipeName();
+ const stdErrPipeName = generatePipeName();
+ const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName);
+ newEnv["NODE_PATH"] = import_path6.default.join(modulePath, "..", "..", "..");
+ let childProcess;
+ let stdErrServer = import_net.default.createServer((stdErrStream) => {
+ childProcess.stderr = stdErrStream;
+ });
+ stdErrServer.listen(stdErrPipeName);
+ let stdOutServer = import_net.default.createServer((stdOutStream) => {
+ stdOutStream.once("data", (_chunk) => {
+ childProcess.stdin = import_net.default.connect(stdInPipeName);
+ childProcess.stdout = stdOutStream;
+ resolve(childProcess);
+ });
+ });
+ stdOutServer.listen(stdOutPipeName);
+ let serverClosed = false;
+ const closeServer = () => {
+ if (serverClosed) {
+ return;
+ }
+ serverClosed = true;
+ stdOutServer.close();
+ stdErrServer.close();
+ };
+ logger.info("Forking TSServer", `PATH: ${newEnv["PATH"]} `);
+ const bootstrapperPath = import_path6.default.resolve(__dirname, "../bin/tsserverForkStart");
+ childProcess = import_child_process2.default.fork(bootstrapperPath, [modulePath].concat(args), {
+ silent: true,
+ env: newEnv,
+ execArgv: options.execArgv
+ });
+ childProcess.once("error", (err) => {
+ closeServer();
+ reject(err);
+ });
+ childProcess.once("exit", (err) => {
+ closeServer();
+ reject(err);
+ });
+}
+
+// src/server/utils/tracer.ts
+var import_coc29 = __toModule(require("coc.nvim"));
+var Trace;
+(function(Trace2) {
+ Trace2[Trace2["Off"] = 0] = "Off";
+ Trace2[Trace2["Messages"] = 1] = "Messages";
+ Trace2[Trace2["Verbose"] = 2] = "Verbose";
+})(Trace || (Trace = {}));
+(function(Trace2) {
+ function fromString(value) {
+ value = value || "";
+ value = value.toLowerCase();
+ switch (value) {
+ case "off":
+ return Trace2.Off;
+ case "messages":
+ return Trace2.Messages;
+ case "verbose":
+ return Trace2.Verbose;
+ default:
+ return Trace2.Off;
}
-}
-class Reader {
- constructor(readable, callback, onError) {
- this.readable = readable;
- this.callback = callback;
- this.onError = onError;
- this.buffer = new ProtocolBuffer();
- this.nextMessageLength = -1;
- this.readable.on('data', (data) => {
- this.onLengthData(data);
- });
+ }
+ Trace2.fromString = fromString;
+})(Trace || (Trace = {}));
+var Tracer = class {
+ constructor(logger) {
+ this.logger = logger;
+ this.trace = Tracer.readTrace();
+ }
+ static readTrace() {
+ let result = Trace.fromString(import_coc29.workspace.getConfiguration("tsserver").get("trace.server", "off"));
+ if (result === 0 && !!process.env.TSS_TRACE) {
+ result = 1;
}
- onLengthData(data) {
- try {
- this.buffer.append(data);
- while (true) {
- if (this.nextMessageLength === -1) {
- this.nextMessageLength = this.buffer.tryReadContentLength();
- if (this.nextMessageLength === -1) {
- return;
- }
- }
- const msg = this.buffer.tryReadContent(this.nextMessageLength);
- if (msg === null) {
- return;
- }
- this.nextMessageLength = -1;
- const json = JSON.parse(msg);
- this.callback(json);
- }
- }
- catch (e) {
- this.onError(e);
- }
+ return result;
+ }
+ traceRequest(request, responseExpected, queueLength) {
+ if (this.trace === 0)
+ return;
+ let data;
+ if (this.trace === 2 && request.arguments) {
+ data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
+ }
+ this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? "yes" : "no"}. Current queue length: ${queueLength}`, data);
+ }
+ traceResponse(response, startTime) {
+ if (this.trace === 0) {
+ return;
}
-}
-exports.Reader = Reader;
-
-
-/***/ }),
-/* 133 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"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.CallbackMap = void 0;
-const typescriptService_1 = __webpack_require__(123);
-class CallbackMap {
- constructor() {
- this._callbacks = new Map();
- this._asyncCallbacks = new Map();
+ let data;
+ if (this.trace === 2 && response.body) {
+ data = `Result: ${JSON.stringify(response.body, null, 4)}`;
}
- destroy(cause) {
- const cancellation = new typescriptService_1.ServerResponse.Cancelled(cause);
- for (const callback of this._callbacks.values()) {
- callback.onSuccess(cancellation);
- }
- this._callbacks.clear();
- for (const callback of this._asyncCallbacks.values()) {
- callback.onSuccess(cancellation);
- }
- this._asyncCallbacks.clear();
+ this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? ". Message: " + response.message : ""}`, data);
+ }
+ traceEvent(event) {
+ if (this.trace === 0) {
+ return;
}
- add(seq, callback, isAsync) {
- if (isAsync) {
- this._asyncCallbacks.set(seq, callback);
- }
- else {
- this._callbacks.set(seq, callback);
- }
+ let data;
+ if (this.trace === 2 && event.body) {
+ data = `Data: ${JSON.stringify(event.body, null, 4)}`;
}
- fetch(seq) {
- const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
- this.delete(seq);
- return callback;
+ this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
+ }
+ logTrace(message, data) {
+ if (this.trace !== 0) {
+ this.logger.logLevel("Trace", message, data);
}
- delete(seq) {
- if (!this._callbacks.delete(seq)) {
- this._asyncCallbacks.delete(seq);
- }
+ }
+ traceRequestCompleted(command, request_seq, startTime) {
+ if (this.trace === 0) {
+ return;
}
-}
-exports.CallbackMap = CallbackMap;
-
-
-/***/ }),
-/* 134 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
+ this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`);
+ }
+};
+var tracer_default = Tracer;
-/*---------------------------------------------------------------------------------------------
- * 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.RequestQueue = exports.RequestQueueingType = void 0;
-var RequestQueueingType;
-(function (RequestQueueingType) {
- /**
- * Normal request that is executed in order.
- */
- RequestQueueingType[RequestQueueingType["Normal"] = 1] = "Normal";
- /**
- * Request that normal requests jump in front of in the queue.
- */
- RequestQueueingType[RequestQueueingType["LowPriority"] = 2] = "LowPriority";
- /**
- * A fence that blocks request reordering.
- *
- * Fences are not reordered. Unlike a normal request, a fence will never jump in front of a low priority request
- * in the request queue.
- */
- RequestQueueingType[RequestQueueingType["Fence"] = 3] = "Fence";
-})(RequestQueueingType = exports.RequestQueueingType || (exports.RequestQueueingType = {}));
-class RequestQueue {
- constructor() {
- this.queue = [];
- this.sequenceNumber = 0;
- }
- get length() {
- return this.queue.length;
- }
- enqueue(item) {
- if (item.queueingType === RequestQueueingType.Normal) {
- let index = this.queue.length - 1;
- while (index >= 0) {
- if (this.queue[index].queueingType !== RequestQueueingType.LowPriority) {
- break;
- }
- --index;
- }
- this.queue.splice(index + 1, 0, item);
- }
- else {
- // Only normal priority requests can be reordered. All other requests just go to the end.
- this.queue.push(item);
- }
+// src/server/utils/tsconfig.ts
+function inferredProjectConfig(config) {
+ const base = {
+ module: "commonjs",
+ target: "es2016",
+ jsx: "preserve"
+ };
+ if (config.checkJs) {
+ base.checkJs = true;
+ }
+ if (config.experimentalDecorators) {
+ base.experimentalDecorators = true;
+ }
+ return base;
+}
+
+// src/server/utils/versionProvider.ts
+var import_coc30 = __toModule(require("coc.nvim"));
+var import_fs3 = __toModule(require("fs"));
+var import_path7 = __toModule(require("path"));
+var TypeScriptVersion = class {
+ constructor(path9, _pathLabel) {
+ this.path = path9;
+ this._pathLabel = _pathLabel;
+ this._api = null;
+ }
+ get tscPath() {
+ return import_path7.default.resolve(this.path, "../bin/tsc");
+ }
+ get tsServerPath() {
+ return import_path7.default.resolve(this.path, "tsserver.js");
+ }
+ get pathLabel() {
+ return typeof this._pathLabel === "undefined" ? this.path : this._pathLabel;
+ }
+ get isValid() {
+ return this.version != null;
+ }
+ get version() {
+ if (this._api)
+ return this._api;
+ let api = this._api = this.getTypeScriptVersion(this.tsServerPath);
+ return api;
+ }
+ get versionString() {
+ const version = this.version;
+ return version ? version.versionString : null;
+ }
+ getTypeScriptVersion(serverPath) {
+ if (!import_fs3.default.existsSync(serverPath)) {
+ return void 0;
+ }
+ const p = serverPath.split(import_path7.default.sep);
+ if (p.length <= 2) {
+ return void 0;
+ }
+ const p2 = p.slice(0, -2);
+ const modulePath = p2.join(import_path7.default.sep);
+ let fileName = import_path7.default.join(modulePath, "package.json");
+ if (!import_fs3.default.existsSync(fileName)) {
+ if (import_path7.default.basename(modulePath) === "built") {
+ fileName = import_path7.default.join(modulePath, "..", "package.json");
+ }
}
- dequeue() {
- return this.queue.shift();
+ if (!import_fs3.default.existsSync(fileName)) {
+ return void 0;
}
- tryDeletePendingRequest(seq) {
- for (let i = 0; i < this.queue.length; i++) {
- if (this.queue[i].request.seq === seq) {
- this.queue.splice(i, 1);
- return true;
- }
- }
- return false;
+ const contents = import_fs3.default.readFileSync(fileName).toString();
+ let desc = null;
+ try {
+ desc = JSON.parse(contents);
+ } catch (err) {
+ return void 0;
}
- createRequest(command, args) {
- return {
- seq: this.sequenceNumber++,
- type: 'request',
- command,
- arguments: args
- };
+ if (!desc || !desc.version) {
+ return void 0;
}
-}
-exports.RequestQueue = RequestQueue;
-
-
-/***/ }),
-/* 135 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
+ return desc.version ? api_default.fromVersionString(desc.version) : void 0;
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const coc_nvim_1 = __webpack_require__(1);
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const api_1 = __importDefault(__webpack_require__(40));
-const async_1 = __webpack_require__(136);
-const typeConverters = __importStar(__webpack_require__(37));
-const languageModeIds = __importStar(__webpack_require__(116));
-function mode2ScriptKind(mode) {
- switch (mode) {
- case languageModeIds.typescript:
- return 'TS';
- case languageModeIds.typescripttsx:
- return 'TSX';
- case languageModeIds.typescriptjsx:
- return 'TSX';
- case languageModeIds.typescriptreact:
- return 'TSX';
- case languageModeIds.javascript:
- return 'JS';
- case languageModeIds.javascriptreact:
- return 'JSX';
- }
- return undefined;
-}
-/**
- * Manages synchronization of buffers with the TS server.
- *
- * If supported, batches together file changes. This allows the TS server to more efficiently process changes.
- */
-class BufferSynchronizer {
- constructor(client) {
- this.client = client;
- this._pending = {};
- this._pendingFiles = new Set();
- }
- open(args) {
- this.client.executeWithoutWaitingForResponse('open', args);
- }
- close(filepath) {
- const args = { file: filepath };
- this.client.executeWithoutWaitingForResponse('close', args);
- }
- change(filepath, events) {
- if (!events.length) {
- return;
- }
- if (this.supportsBatching) {
- this.updatePending(filepath, pending => {
- if (!pending.changedFiles) {
- pending.changedFiles = [];
- }
- pending.changedFiles.push({
- fileName: filepath,
- textChanges: events.map((change) => ({
- newText: change.text,
- start: typeConverters.Position.toLocation(change.range.start),
- end: typeConverters.Position.toLocation(change.range.end),
- })).reverse(),
- });
- });
- }
- else {
- for (const event of events) {
- const args = Object.assign({ insertString: event.text }, typeConverters.Range.toFormattingRequestArgs(filepath, event.range));
- this.client.executeWithoutWaitingForResponse('change', args);
- }
- }
- }
- beforeCommand(command) {
- if (command === 'updateOpen') {
- return;
+var MODULE_FOLDERS = ["node_modules/typescript/lib", ".vscode/pnpify/typescript/lib", ".yarn/sdks/typescript/lib"];
+var TypeScriptVersionProvider = class {
+ constructor(configuration) {
+ this.configuration = configuration;
+ }
+ updateConfiguration(configuration) {
+ this.configuration = configuration;
+ }
+ getDefaultVersion() {
+ let {globalTsdk} = this.configuration;
+ if (globalTsdk)
+ return new TypeScriptVersion(globalTsdk);
+ return this.bundledVersion;
+ }
+ get globalVersion() {
+ let {globalTsdk} = this.configuration;
+ if (globalTsdk)
+ return new TypeScriptVersion(import_coc30.workspace.expand(globalTsdk));
+ return void 0;
+ }
+ getLocalVersion() {
+ let folders = import_coc30.workspace.workspaceFolders.map((f) => import_coc30.Uri.parse(f.uri).fsPath);
+ for (let p of folders) {
+ for (let folder of MODULE_FOLDERS) {
+ let libFolder = import_path7.default.join(p, folder);
+ if (import_fs3.default.existsSync(libFolder)) {
+ let version = new TypeScriptVersion(libFolder);
+ if (version.isValid)
+ return version;
}
- this.flush();
+ }
}
- flush() {
- if (!this.supportsBatching) {
- // We've already eagerly synchronized
- return;
- }
- if (this._pending.changedFiles) {
- this.client.executeWithoutWaitingForResponse('updateOpen', this._pending);
- this._pending = {};
- this._pendingFiles.clear();
- }
+ return null;
+ }
+ get bundledVersion() {
+ try {
+ const file2 = require.resolve("typescript");
+ const bundledVersion = new TypeScriptVersion(import_path7.default.dirname(file2), "");
+ return bundledVersion;
+ } catch (e) {
+ import_coc30.window.showMessage("Bundled typescript module not found", "error");
+ return null;
}
- get supportsBatching() {
- return this.client.apiVersion.gte(api_1.default.v340) && coc_nvim_1.workspace.getConfiguration('tsserver').get('useBatchedBufferSync', true);
+ }
+};
+
+// src/server/utils/versionStatus.ts
+var import_coc31 = __toModule(require("coc.nvim"));
+var VersionStatus = class {
+ constructor(_normalizePath, enableJavascript) {
+ this._normalizePath = _normalizePath;
+ this.enableJavascript = enableJavascript;
+ this._versionString = "";
+ this._versionBarEntry = import_coc31.window.createStatusBarItem(99);
+ this._onChangeEditorSub = import_coc31.events.on("BufEnter", this.onBufEnter, this);
+ this._versionBarEntry.show();
+ }
+ dispose() {
+ this._versionBarEntry.dispose();
+ this._onChangeEditorSub.dispose();
+ }
+ onDidChangeTypeScriptVersion(version) {
+ this._versionString = version.versionString;
+ }
+ set loading(isLoading) {
+ if (isLoading) {
+ this._versionBarEntry.text = `Initializing tsserver ${this._versionString}`;
+ } else {
+ this._versionBarEntry.text = `TSC ${this._versionString}`;
}
- updatePending(filepath, f) {
- if (this.supportsBatching && this._pendingFiles.has(filepath)) {
- this.flush();
- this._pendingFiles.clear();
- f(this._pending);
- this._pendingFiles.add(filepath);
- }
- else {
- f(this._pending);
- }
+ this._versionBarEntry.isProgress = isLoading;
+ }
+ checkFiletype(filetype) {
+ if (filetype.startsWith("javascript") && this.enableJavascript) {
+ return true;
}
- reset() {
- this._pending = {};
- this._pendingFiles.clear();
+ return filetype.startsWith("typescript");
+ }
+ async onBufEnter(bufnr) {
+ let filetype = await import_coc31.workspace.nvim.call("getbufvar", [bufnr, "&filetype", ""]);
+ if (this.checkFiletype(filetype)) {
+ this._versionBarEntry.show();
+ } else {
+ this._versionBarEntry.hide();
}
-}
-class BufferSyncSupport {
- constructor(client) {
- this.uris = new Set();
- this.disposables = [];
- this.pendingDiagnostics = new Map();
- this._validateJavaScript = true;
- this._validateTypeScript = true;
- this.listening = false;
- this._onDelete = new vscode_languageserver_protocol_1.Emitter();
- this.onDelete = this._onDelete.event;
- this.client = client;
- this.synchronizer = new BufferSynchronizer(client);
- this.modeIds = new Set(languageModeIds.languageIds);
- this.diagnosticDelayer = new async_1.Delayer(300);
- }
- listen() {
- if (this.listening) {
- return;
- }
- this.listening = true;
- coc_nvim_1.workspace.onDidOpenTextDocument(this.onDidOpenTextDocument, this, this.disposables);
- coc_nvim_1.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, this.disposables);
- coc_nvim_1.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, this.disposables);
- coc_nvim_1.workspace.textDocuments.forEach(this.onDidOpenTextDocument, this);
- this.updateConfiguration();
- coc_nvim_1.workspace.onDidChangeConfiguration(this.updateConfiguration, this, this.disposables);
+ }
+};
+var versionStatus_default = VersionStatus;
+
+// src/server/utils/wireProtocol.ts
+var DefaultSize = 8192;
+var ContentLength = "Content-Length: ";
+var ContentLengthSize = Buffer.byteLength(ContentLength, "utf8");
+var Blank = Buffer.from(" ", "utf8")[0];
+var BackslashR = Buffer.from("\r", "utf8")[0];
+var BackslashN = Buffer.from("\n", "utf8")[0];
+var ProtocolBuffer = class {
+ constructor() {
+ this.index = 0;
+ this.buffer = Buffer.allocUnsafe(DefaultSize);
+ }
+ append(data) {
+ let toAppend = null;
+ if (Buffer.isBuffer(data)) {
+ toAppend = data;
+ } else {
+ toAppend = Buffer.from(data, "utf8");
}
- dispose() {
- this.pendingDiagnostics.clear();
- coc_nvim_1.disposeAll(this.disposables);
+ if (this.buffer.length - this.index >= toAppend.length) {
+ toAppend.copy(this.buffer, this.index, 0, toAppend.length);
+ } else {
+ let newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
+ if (this.index === 0) {
+ this.buffer = Buffer.allocUnsafe(newSize);
+ toAppend.copy(this.buffer, 0, 0, toAppend.length);
+ } else {
+ this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
+ }
}
- onDidOpenTextDocument(document) {
- if (!this.modeIds.has(document.languageId))
- return;
- let { uri } = document;
- let filepath = this.client.toPath(uri);
- this.uris.add(uri);
- const args = {
- file: filepath,
- fileContent: document.getText()
- };
- if (this.client.apiVersion.gte(api_1.default.v203)) {
- const scriptKind = mode2ScriptKind(document.languageId);
- if (scriptKind) {
- args.scriptKindName = scriptKind;
- }
- }
- if (this.client.apiVersion.gte(api_1.default.v230)) {
- let root = this.client.getProjectRootPath(document.uri);
- if (root)
- args.projectRootPath = root;
- }
- this.synchronizer.open(args);
- // this.client.executeWithoutWaitingForResponse('open', args)
- this.requestDiagnostic(uri);
+ this.index += toAppend.length;
+ }
+ tryReadContentLength() {
+ let result = -1;
+ let current = 0;
+ while (current < this.index && (this.buffer[current] === Blank || this.buffer[current] === BackslashR || this.buffer[current] === BackslashN)) {
+ current++;
+ }
+ if (this.index < current + ContentLengthSize) {
+ return result;
+ }
+ current += ContentLengthSize;
+ let start = current;
+ while (current < this.index && this.buffer[current] !== BackslashR) {
+ current++;
+ }
+ if (current + 3 >= this.index || this.buffer[current + 1] !== BackslashN || this.buffer[current + 2] !== BackslashR || this.buffer[current + 3] !== BackslashN) {
+ return result;
+ }
+ let data = this.buffer.toString("utf8", start, current);
+ result = parseInt(data, 10);
+ this.buffer = this.buffer.slice(current + 4);
+ this.index = this.index - (current + 4);
+ return result;
+ }
+ tryReadContent(length) {
+ if (this.index < length) {
+ return null;
}
- onDidCloseTextDocument(document) {
- let { uri } = document;
- if (!this.uris.has(uri))
- return;
- let filepath = this.client.toPath(uri);
- this.uris.delete(uri);
- this.pendingDiagnostics.delete(uri);
- this.synchronizer.close(filepath);
- this._onDelete.fire(uri);
- this.requestAllDiagnostics();
- // this.client.executeWithoutWaitingForResponse('close', args)
- }
- onDidChangeTextDocument(e) {
- let { textDocument, contentChanges } = e;
- let { uri } = textDocument;
- if (!this.uris.has(uri))
- return;
- let filepath = this.client.toPath(uri);
- this.synchronizer.change(filepath, contentChanges);
- const didTrigger = this.requestDiagnostic(uri);
- if (!didTrigger && this.pendingGetErr) {
- // In this case we always want to re-trigger all diagnostics
- this.pendingGetErr.cancel();
- this.pendingGetErr = undefined;
- this.triggerDiagnostics();
- }
- }
- beforeCommand(command) {
- this.synchronizer.beforeCommand(command);
- }
- interuptGetErr(f) {
- if (!this.pendingGetErr) {
- return f();
- }
- this.pendingGetErr.cancel();
- this.pendingGetErr = undefined;
- const result = f();
- this.triggerDiagnostics();
- return result;
+ let result = this.buffer.toString("utf8", 0, length);
+ let sourceStart = length;
+ while (sourceStart < this.index && (this.buffer[sourceStart] === BackslashR || this.buffer[sourceStart] === BackslashN)) {
+ sourceStart++;
}
- getErr(resources) {
- const handledResources = resources.filter(resource => this.uris.has(resource.toString()));
- if (!handledResources.length) {
+ this.buffer.copy(this.buffer, 0, sourceStart);
+ this.index = this.index - sourceStart;
+ return result;
+ }
+};
+var Reader = class {
+ constructor(readable, callback, onError) {
+ this.readable = readable;
+ this.callback = callback;
+ this.onError = onError;
+ this.buffer = new ProtocolBuffer();
+ this.nextMessageLength = -1;
+ this.readable.on("data", (data) => {
+ this.onLengthData(data);
+ });
+ }
+ onLengthData(data) {
+ try {
+ this.buffer.append(data);
+ while (true) {
+ if (this.nextMessageLength === -1) {
+ this.nextMessageLength = this.buffer.tryReadContentLength();
+ if (this.nextMessageLength === -1) {
return;
+ }
}
- for (const resource of handledResources) {
- let uri = resource.toString();
- if (this.shouldValidate(uri)) {
- this.pendingDiagnostics.set(uri, Date.now());
- }
+ const msg = this.buffer.tryReadContent(this.nextMessageLength);
+ if (msg === null) {
+ return;
}
- this.triggerDiagnostics();
- }
- has(uri) {
- return this.uris.has(uri);
+ this.nextMessageLength = -1;
+ const json = JSON.parse(msg);
+ this.callback(json);
+ }
+ } catch (e) {
+ this.onError(e);
}
- triggerDiagnostics(delay = 200) {
- this.diagnosticDelayer.trigger(() => {
- this.sendPendingDiagnostics();
- }, delay);
+ }
+};
+
+// src/server/typescriptServiceClient.ts
+var ForkedTsServerProcess = class {
+ constructor(childProcess) {
+ this.childProcess = childProcess;
+ this.toCancelOnResourceChange = new Set();
+ }
+ onError(cb) {
+ this.childProcess.on("error", cb);
+ }
+ onExit(cb) {
+ this.childProcess.on("exit", cb);
+ }
+ write(serverRequest) {
+ this.childProcess.stdin.write(JSON.stringify(serverRequest) + "\r\n", "utf8");
+ }
+ createReader(callback, onError) {
+ new Reader(this.childProcess.stdout, callback, onError);
+ }
+ kill() {
+ this.childProcess.kill();
+ }
+};
+var TypeScriptServiceClient = class {
+ constructor(pluginManager, modeIds) {
+ this.pluginManager = pluginManager;
+ this.modeIds = modeIds;
+ this.state = import_coc32.ServiceStat.Initial;
+ this.logger = new logger_default();
+ this.tsServerLogFile = null;
+ this.cancellationPipeName = null;
+ this._callbacks = new CallbackMap();
+ this._requestQueue = new RequestQueue();
+ this._pendingResponses = new Set();
+ this._onTsServerStarted = new import_vscode_languageserver_protocol21.Emitter();
+ this._onProjectLanguageServiceStateChanged = new import_vscode_languageserver_protocol21.Emitter();
+ this._onDidBeginInstallTypings = new import_vscode_languageserver_protocol21.Emitter();
+ this._onDidEndInstallTypings = new import_vscode_languageserver_protocol21.Emitter();
+ this._onTypesInstallerInitializationFailed = new import_vscode_languageserver_protocol21.Emitter();
+ this.disposables = [];
+ this.isRestarting = false;
+ this._onDiagnosticsReceived = new import_vscode_languageserver_protocol21.Emitter();
+ this._onConfigDiagnosticsReceived = new import_vscode_languageserver_protocol21.Emitter();
+ this._onResendModelsRequested = new import_vscode_languageserver_protocol21.Emitter();
+ this.pathSeparator = import_path8.default.sep;
+ this.lastStart = Date.now();
+ this.servicePromise = null;
+ this.lastError = null;
+ this.numberRestarts = 0;
+ this.fileConfigurationManager = new fileConfigurationManager_default(this);
+ this._configuration = TypeScriptServiceConfiguration.loadFromWorkspace();
+ this.versionProvider = new TypeScriptVersionProvider(this._configuration);
+ this._apiVersion = api_default.defaultVersion;
+ this.tracer = new tracer_default(this.logger);
+ this.versionStatus = new versionStatus_default(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript());
+ pluginManager.onDidUpdateConfig((update) => {
+ this.configurePlugin(update.pluginId, update.config);
+ }, null, this.disposables);
+ pluginManager.onDidChangePlugins(() => {
+ this.restartTsServer();
+ }, null, this.disposables);
+ this.bufferSyncSupport = new bufferSyncSupport_default(this, modeIds);
+ this.onTsServerStarted(() => {
+ this.bufferSyncSupport.listen();
+ });
+ this.diagnosticsManager = new DiagnosticsManager();
+ this.bufferSyncSupport.onDelete((resource) => {
+ this.cancelInflightRequestsForResource(resource);
+ this.diagnosticsManager.delete(resource);
+ }, null, this.disposables);
+ this.bufferSyncSupport.onWillChange((resource) => {
+ this.cancelInflightRequestsForResource(resource);
+ });
+ }
+ get onDiagnosticsReceived() {
+ return this._onDiagnosticsReceived.event;
+ }
+ get onConfigDiagnosticsReceived() {
+ return this._onConfigDiagnosticsReceived.event;
+ }
+ get onResendModelsRequested() {
+ return this._onResendModelsRequested.event;
+ }
+ get configuration() {
+ return this._configuration;
+ }
+ dispose() {
+ if (this.servicePromise) {
+ this.servicePromise.then((childProcess) => {
+ childProcess.kill();
+ }).then(void 0, () => void 0);
+ }
+ this.bufferSyncSupport.dispose();
+ this.logger.dispose();
+ this._onTsServerStarted.dispose();
+ this._onResendModelsRequested.dispose();
+ this.versionStatus.dispose();
+ }
+ info(message, data) {
+ this.logger.info(message, data);
+ }
+ error(message, data) {
+ this.logger.error(message, data);
+ }
+ restartTsServer() {
+ const start = () => {
+ this.servicePromise = this.startService(true);
+ return this.servicePromise;
+ };
+ if (this.servicePromise) {
+ return Promise.resolve(this.servicePromise.then((childProcess) => {
+ this.state = import_coc32.ServiceStat.Stopping;
+ this.info("Killing TS Server");
+ this.isRestarting = true;
+ childProcess.kill();
+ this.servicePromise = null;
+ }).then(start));
+ } else {
+ return Promise.resolve(start());
}
- requestAllDiagnostics() {
- for (const uri of this.uris) {
- if (this.shouldValidate(uri)) {
- this.pendingDiagnostics.set(uri, Date.now());
- }
+ }
+ stop() {
+ if (!this.servicePromise)
+ return;
+ return new Promise((resolve, reject) => {
+ this.servicePromise.then((childProcess) => {
+ if (this.state == import_coc32.ServiceStat.Running) {
+ this.info("Killing TS Server");
+ childProcess.onExit(() => {
+ resolve();
+ });
+ childProcess.kill();
+ this.servicePromise = null;
+ } else {
+ resolve();
}
- this.diagnosticDelayer.trigger(() => {
- this.sendPendingDiagnostics();
- }, 200);
- }
- requestDiagnostic(uri) {
- let document = coc_nvim_1.workspace.getDocument(uri);
- if (!document || !this.shouldValidate(uri))
- return false;
- this.pendingDiagnostics.set(uri, Date.now());
- const lineCount = document.lineCount;
- const delay = Math.min(Math.max(Math.ceil(lineCount / 20), 300), 800);
- this.triggerDiagnostics(delay);
- return true;
+ }, reject);
+ });
+ }
+ get onTsServerStarted() {
+ return this._onTsServerStarted.event;
+ }
+ get onProjectLanguageServiceStateChanged() {
+ return this._onProjectLanguageServiceStateChanged.event;
+ }
+ get onDidBeginInstallTypings() {
+ return this._onDidBeginInstallTypings.event;
+ }
+ get onDidEndInstallTypings() {
+ return this._onDidEndInstallTypings.event;
+ }
+ get onTypesInstallerInitializationFailed() {
+ return this._onTypesInstallerInitializationFailed.event;
+ }
+ get apiVersion() {
+ return this._apiVersion;
+ }
+ get tscPath() {
+ return this._tscPath;
+ }
+ service() {
+ if (this.servicePromise) {
+ return this.servicePromise;
}
- hasPendingDiagnostics(uri) {
- return this.pendingDiagnostics.has(uri);
- }
- sendPendingDiagnostics() {
- const uris = Array.from(this.pendingDiagnostics.entries())
- .sort((a, b) => a[1] - b[1])
- .map(entry => entry[0]);
- // Add all open TS buffers to the geterr request. They might be visible
- for (const uri of this.uris) {
- if (uris.indexOf(uri) == -1) {
- uris.push(uri);
- }
- }
- let files = uris.map(uri => this.client.toPath(uri));
- if (files.length) {
- if (this.pendingGetErr)
- this.pendingGetErr.cancel();
- const getErr = this.pendingGetErr = GetErrRequest.executeGetErrRequest(this.client, files, () => {
- if (this.pendingGetErr === getErr) {
- this.pendingGetErr = undefined;
- }
- });
- }
- this.pendingDiagnostics.clear();
+ if (this.lastError) {
+ return Promise.reject(this.lastError);
}
- updateConfiguration() {
- const jsConfig = coc_nvim_1.workspace.getConfiguration('javascript', null);
- const tsConfig = coc_nvim_1.workspace.getConfiguration('typescript', null);
- this._validateJavaScript = jsConfig.get('validate.enable', true);
- this._validateTypeScript = tsConfig.get('validate.enable', true);
+ return this.startService().then(() => {
+ if (this.servicePromise) {
+ return this.servicePromise;
+ }
+ });
+ }
+ ensureServiceStarted() {
+ if (!this.servicePromise) {
+ this.startService().catch((err) => {
+ import_coc32.window.showMessage(`TSServer start failed: ${err.message}`, "error");
+ this.error(`Service start failed: ${err.stack}`);
+ });
}
- shouldValidate(uri) {
- let doc = coc_nvim_1.workspace.getDocument(uri);
- if (!doc)
- return false;
- if (languageModeIds.languageIds.indexOf(doc.filetype) == -1) {
- return false;
- }
- if (doc.filetype.startsWith('javascript')) {
- return this._validateJavaScript;
- }
- return this._validateTypeScript;
+ }
+ async startService(resendModels = false) {
+ const {ignoreLocalTsserver} = this.configuration;
+ let currentVersion;
+ if (!ignoreLocalTsserver)
+ currentVersion = this.versionProvider.getLocalVersion();
+ if (!currentVersion || !import_fs4.default.existsSync(currentVersion.tsServerPath)) {
+ currentVersion = this.versionProvider.getDefaultVersion();
+ }
+ if (!currentVersion || !currentVersion.isValid) {
+ if (this.configuration.globalTsdk) {
+ import_coc32.window.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, "error");
+ } else {
+ import_coc32.window.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, "error");
+ }
+ return;
+ }
+ this._apiVersion = currentVersion.version;
+ this._tscPath = currentVersion.tscPath;
+ this.versionStatus.onDidChangeTypeScriptVersion(currentVersion);
+ this.lastError = null;
+ const tsServerForkArgs = await this.getTsServerArgs(currentVersion);
+ const debugPort = this._configuration.debugPort;
+ const maxTsServerMemory = this._configuration.maxTsServerMemory;
+ const options = {
+ execArgv: [
+ ...debugPort ? [`--inspect=${debugPort}`] : [],
+ ...maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []
+ ],
+ cwd: import_coc32.workspace.root
+ };
+ this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels);
+ return this.servicePromise;
+ }
+ startProcess(currentVersion, args, options, resendModels) {
+ this.state = import_coc32.ServiceStat.Starting;
+ return new Promise((resolve, reject) => {
+ try {
+ fork(currentVersion.tsServerPath, args, options, this.logger, (err, childProcess) => {
+ if (err || !childProcess) {
+ this.state = import_coc32.ServiceStat.StartFailed;
+ this.lastError = err;
+ this.error("Starting TSServer failed with error.", err.stack);
+ return;
+ }
+ this.state = import_coc32.ServiceStat.Running;
+ this.info("Started TSServer", JSON.stringify(currentVersion, null, 2));
+ const handle = new ForkedTsServerProcess(childProcess);
+ this.tsServerProcess = handle;
+ this.lastStart = Date.now();
+ handle.onError((err2) => {
+ this.lastError = err2;
+ this.error("TSServer errored with error.", err2);
+ this.error(`TSServer log file: ${this.tsServerLogFile || ""}`);
+ import_coc32.window.showMessage(`TSServer errored with error. ${err2.message}`, "error");
+ this.serviceExited(false);
+ });
+ handle.onExit((code) => {
+ if (code == null) {
+ this.info("TSServer normal exit");
+ } else {
+ this.error(`TSServer exited with code: ${code}`);
+ }
+ this.info(`TSServer log file: ${this.tsServerLogFile || ""}`);
+ this.serviceExited(!this.isRestarting);
+ this.isRestarting = false;
+ });
+ handle.createReader((msg) => {
+ this.dispatchMessage(msg);
+ }, (error) => {
+ this.error("ReaderError", error);
+ });
+ resolve(handle);
+ this.serviceStarted(resendModels);
+ this._onTsServerStarted.fire(currentVersion.version);
+ });
+ } catch (e) {
+ reject(e);
+ }
+ });
+ }
+ async openTsServerLogFile() {
+ const isRoot = process.getuid && process.getuid() == 0;
+ let echoErr = (msg) => {
+ import_coc32.window.showMessage(msg, "error");
+ };
+ if (isRoot) {
+ echoErr("Log disabled for root user.");
+ return false;
}
- reinitialize() {
- var _a;
- this.pendingDiagnostics.clear();
- (_a = this.pendingGetErr) === null || _a === void 0 ? void 0 : _a.cancel();
- this.synchronizer.reset();
- for (let doc of coc_nvim_1.workspace.documents) {
- this.onDidOpenTextDocument(doc.textDocument);
- }
+ if (!this.apiVersion.gte(api_default.v222)) {
+ echoErr("TS Server logging requires TS 2.2.2+");
+ return false;
}
-}
-exports.default = BufferSyncSupport;
-class GetErrRequest {
- constructor(client, files, _token, onDone) {
- this.files = files;
- this._token = _token;
- this._done = false;
- const args = {
- delay: 0,
- files: this.files
- };
- const done = () => {
- if (this._done) {
- return;
- }
- this._done = true;
- onDone();
- };
- client.executeAsync('geterr', args, _token.token).then(done, done);
+ if (this._configuration.tsServerLogLevel === TsServerLogLevel.Off) {
+ echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`);
+ return false;
}
- static executeGetErrRequest(client, files, onDone) {
- const token = new vscode_languageserver_protocol_1.CancellationTokenSource();
- return new GetErrRequest(client, files, token, onDone);
+ if (!this.tsServerLogFile) {
+ echoErr("TS Server has not started logging.");
+ return false;
}
- cancel() {
- if (!this._done) {
- this._token.cancel();
- }
- this._token.dispose();
+ try {
+ await import_coc32.workspace.nvim.command(`edit ${this.tsServerLogFile}`);
+ return true;
+ } catch {
+ echoErr("Could not open TS Server log file");
+ return false;
}
-}
-
-
-/***/ }),
-/* 136 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Delayer = void 0;
-class Delayer {
- constructor(defaultDelay) {
- this.defaultDelay = defaultDelay;
- this.timeout = null;
- this.completionPromise = null;
- this.onSuccess = null;
- this.task = null;
+ }
+ serviceStarted(resendModels) {
+ this.bufferSyncSupport.reset();
+ const watchOptions = this.apiVersion.gte(api_default.v380) ? this.configuration.watchOptions : void 0;
+ const configureOptions = {
+ hostInfo: "coc-nvim",
+ preferences: {
+ providePrefixAndSuffixTextForRename: true,
+ allowRenameOfImportPath: true
+ },
+ watchOptions
+ };
+ this.executeWithoutWaitingForResponse("configure", configureOptions);
+ this.setCompilerOptionsForInferredProjects(this._configuration);
+ if (resendModels) {
+ this._onResendModelsRequested.fire(void 0);
+ this.fileConfigurationManager.reset();
+ this.diagnosticsManager.reInitialize();
+ this.bufferSyncSupport.reinitialize();
}
- 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 = null;
- this.onSuccess = null;
- let result = this.task && this.task();
- this.task = null;
- return result;
- });
- }
- if (delay >= 0 || this.timeout === null) {
- this.timeout = setTimeout(() => {
- this.timeout = null;
- if (this.onSuccess) {
- this.onSuccess(undefined);
- }
- }, delay >= 0 ? delay : this.defaultDelay);
- }
- return this.completionPromise;
+ for (const [config, pluginName] of this.pluginManager.configurations()) {
+ this.configurePlugin(config, pluginName);
}
- cancelTimeout() {
- if (this.timeout !== null) {
- clearTimeout(this.timeout);
- this.timeout = null;
+ }
+ setCompilerOptionsForInferredProjects(configuration) {
+ if (!this.apiVersion.gte(api_default.v206))
+ return;
+ const args = {
+ options: this.getCompilerOptionsForInferredProjects(configuration)
+ };
+ this.executeWithoutWaitingForResponse("compilerOptionsForInferredProjects", args);
+ }
+ getCompilerOptionsForInferredProjects(configuration) {
+ return {
+ ...inferredProjectConfig(configuration),
+ allowJs: true,
+ allowSyntheticDefaultImports: true,
+ allowNonTsExtensions: true
+ };
+ }
+ serviceExited(restart) {
+ this.state = import_coc32.ServiceStat.Stopped;
+ this.servicePromise = null;
+ this.tsServerLogFile = null;
+ this._callbacks.destroy("Service died.");
+ this._callbacks = new CallbackMap();
+ this._requestQueue = new RequestQueue();
+ this._pendingResponses = new Set();
+ if (restart) {
+ const diff = Date.now() - this.lastStart;
+ this.numberRestarts++;
+ let startService = true;
+ if (this.numberRestarts > 5) {
+ this.numberRestarts = 0;
+ if (diff < 10 * 1e3) {
+ this.lastStart = Date.now();
+ startService = false;
+ import_coc32.window.showMessage("The TypeScript language service died 5 times right after it got started.", "error");
+ } else if (diff < 60 * 1e3) {
+ this.lastStart = Date.now();
+ import_coc32.window.showMessage("The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.", "error");
}
+ }
+ if (startService) {
+ this.startService(true);
+ }
}
-}
-exports.Delayer = Delayer;
-
-
-/***/ }),
-/* 137 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.DiagnosticsManager = exports.DiagnosticKind = exports.DiagnosticSet = void 0;
-const coc_nvim_1 = __webpack_require__(1);
-const resourceMap_1 = __webpack_require__(138);
-class DiagnosticSet {
- constructor() {
- this._map = new resourceMap_1.ResourceMap();
- }
- set(uri, diagnostics) {
- this._map.set(uri, diagnostics);
- }
- get(uri) {
- return this._map.get(uri) || [];
- }
- clear() {
- this._map = new resourceMap_1.ResourceMap();
- }
-}
-exports.DiagnosticSet = DiagnosticSet;
-var DiagnosticKind;
-(function (DiagnosticKind) {
- DiagnosticKind[DiagnosticKind["Syntax"] = 0] = "Syntax";
- DiagnosticKind[DiagnosticKind["Semantic"] = 1] = "Semantic";
- DiagnosticKind[DiagnosticKind["Suggestion"] = 2] = "Suggestion";
-})(DiagnosticKind = exports.DiagnosticKind || (exports.DiagnosticKind = {}));
-const allDiagnosticKinds = [
- DiagnosticKind.Syntax,
- DiagnosticKind.Semantic,
- DiagnosticKind.Suggestion
-];
-class DiagnosticsManager {
- constructor() {
- this._diagnostics = new Map();
- this._pendingUpdates = new resourceMap_1.ResourceMap();
- this._enableJavascriptSuggestions = true;
- this._enableTypescriptSuggestions = true;
- this.updateDelay = 200;
- for (const kind of allDiagnosticKinds) {
- this._diagnostics.set(kind, new DiagnosticSet());
- }
- this._currentDiagnostics = coc_nvim_1.languages.createDiagnosticCollection('tsserver');
+ }
+ toPath(uri) {
+ return this.normalizePath(import_coc32.Uri.parse(uri));
+ }
+ toOpenedFilePath(uri, options = {}) {
+ if (!this.bufferSyncSupport.ensureHasBuffer(uri)) {
+ if (!options.suppressAlertOnFailure) {
+ console.error(`Unexpected resource ${uri}`);
+ }
+ return void 0;
}
- dispose() {
- this._currentDiagnostics.dispose();
- for (const value of this._pendingUpdates.values) {
- clearTimeout(value);
+ return this.toPath(uri);
+ }
+ toResource(filepath) {
+ if (this._apiVersion.gte(api_default.v213)) {
+ if (filepath.startsWith(this.inMemoryResourcePrefix + "untitled:")) {
+ let resource = import_coc32.Uri.parse(filepath);
+ if (this.inMemoryResourcePrefix) {
+ const dirName = import_path8.default.dirname(resource.path);
+ const fileName = import_path8.default.basename(resource.path);
+ if (fileName.startsWith(this.inMemoryResourcePrefix)) {
+ resource = resource.with({path: import_path8.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length))});
+ }
}
- this._pendingUpdates = new resourceMap_1.ResourceMap();
+ return resource.toString();
+ }
}
- reInitialize() {
- this._currentDiagnostics.clear();
- for (const diagnosticSet of this._diagnostics.values()) {
- diagnosticSet.clear();
- }
+ return import_coc32.Uri.file(filepath).toString();
+ }
+ normalizePath(resource) {
+ if (disabledSchemes.has(resource.scheme)) {
+ return void 0;
}
- setEnableSuggestions(languageId, value) {
- let curr = languageId == 'javascript' ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions;
- if (curr == value) {
- return;
- }
- if (languageId == 'javascript') {
- this._enableJavascriptSuggestions = value;
- }
- else {
- this._enableTypescriptSuggestions = value;
- }
+ switch (resource.scheme) {
+ case file: {
+ let result = resource.fsPath;
+ if (!result)
+ return void 0;
+ result = import_path8.default.normalize(result);
+ return result.replace(new RegExp("\\" + this.pathSeparator, "g"), "/");
+ }
+ default: {
+ return this.inMemoryResourcePrefix + resource.toString(true);
+ }
}
- diagnosticsReceived(kind, uri, diagnostics) {
- const collection = this._diagnostics.get(kind);
- if (!collection)
- return;
- if (diagnostics.length === 0) {
- const existing = collection.get(uri);
- if (existing.length === 0) {
- // No need to update
- return;
- }
+ }
+ getDocument(resource) {
+ if (resource.startsWith("untitled:")) {
+ let bufnr = parseInt(resource.split(":", 2)[1], 10);
+ return import_coc32.workspace.getDocument(bufnr);
+ }
+ return import_coc32.workspace.getDocument(resource);
+ }
+ get inMemoryResourcePrefix() {
+ return this._apiVersion.gte(api_default.v270) ? "^" : "";
+ }
+ asUrl(filepath) {
+ if (this._apiVersion.gte(api_default.v213)) {
+ if (filepath.startsWith(this.inMemoryResourcePrefix + "untitled:")) {
+ let resource = import_coc32.Uri.parse(filepath.slice(this.inMemoryResourcePrefix.length));
+ if (this.inMemoryResourcePrefix) {
+ const dirName = import_path8.default.dirname(resource.path);
+ const fileName = import_path8.default.basename(resource.path);
+ if (fileName.startsWith(this.inMemoryResourcePrefix)) {
+ resource = resource.with({
+ path: import_path8.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length))
+ });
+ }
}
- collection.set(uri, diagnostics);
- this.scheduleDiagnosticsUpdate(uri);
+ return resource;
+ }
}
- configFileDiagnosticsReceived(uri, diagnostics) {
- this._currentDiagnostics.set(uri, diagnostics);
+ return import_coc32.Uri.file(filepath);
+ }
+ execute(command, args, token, config) {
+ var _a;
+ let execution;
+ if (config == null ? void 0 : config.cancelOnResourceChange) {
+ const source = new import_vscode_languageserver_protocol21.CancellationTokenSource();
+ token.onCancellationRequested(() => source.cancel());
+ const inFlight = {
+ resource: config.cancelOnResourceChange,
+ cancel: () => source.cancel()
+ };
+ (_a = this.tsServerProcess) == null ? void 0 : _a.toCancelOnResourceChange.add(inFlight);
+ execution = this.executeImpl(command, args, {
+ isAsync: false,
+ token: source.token,
+ expectsResult: true,
+ ...config
+ }).finally(() => {
+ var _a2;
+ (_a2 = this.tsServerProcess) == null ? void 0 : _a2.toCancelOnResourceChange.delete(inFlight);
+ source.dispose();
+ });
+ } else {
+ execution = this.executeImpl(command, args, {
+ isAsync: false,
+ token,
+ expectsResult: true,
+ ...config
+ });
}
- delete(uri) {
- this._currentDiagnostics.delete(uri);
+ if (config == null ? void 0 : config.nonRecoverable) {
+ execution.catch((err) => this.fatalError(command, err));
}
- getDiagnostics(uri) {
- return this._currentDiagnostics.get(uri) || [];
- return [];
+ return execution;
+ }
+ fatalError(command, error) {
+ console.error(`A non-recoverable error occured while executing tsserver command: ${command}`);
+ if (this.state === import_coc32.ServiceStat.Running) {
+ this.info("Killing TS Server by fatal error:", error);
+ this.service().then((service) => {
+ service.kill();
+ });
}
- scheduleDiagnosticsUpdate(uri) {
- if (!this._pendingUpdates.has(uri)) {
- this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay));
- }
- }
- updateCurrentDiagnostics(uri) {
- if (this._pendingUpdates.has(uri)) {
- clearTimeout(this._pendingUpdates.get(uri));
- this._pendingUpdates.delete(uri);
- }
- const allDiagnostics = [
- ...this._diagnostics.get(DiagnosticKind.Syntax).get(uri),
- ...this._diagnostics.get(DiagnosticKind.Semantic).get(uri),
- ...this.getSuggestionDiagnostics(uri)
- ];
- this._currentDiagnostics.set(uri, allDiagnostics);
- }
- getSuggestionDiagnostics(uri) {
- const enabled = this.suggestionsEnabled(uri);
- return this._diagnostics
- .get(DiagnosticKind.Suggestion)
- .get(uri)
- .filter(x => {
- if (!enabled) {
- // Still show unused
- return x.code == 6133;
- }
- return enabled;
- });
+ }
+ executeAsync(command, args, token) {
+ return this.executeImpl(command, args, {
+ isAsync: true,
+ token,
+ expectsResult: true
+ });
+ }
+ executeWithoutWaitingForResponse(command, args) {
+ this.executeImpl(command, args, {
+ isAsync: false,
+ token: void 0,
+ expectsResult: false
+ });
+ }
+ executeImpl(command, args, executeInfo) {
+ if (this.servicePromise == null) {
+ return Promise.resolve(void 0);
+ }
+ this.bufferSyncSupport.beforeCommand(command);
+ const request = this._requestQueue.createRequest(command, args);
+ const requestInfo = {
+ request,
+ expectsResponse: executeInfo.expectsResult,
+ isAsync: executeInfo.isAsync,
+ queueingType: getQueueingType(command, executeInfo.lowPriority)
+ };
+ let result;
+ if (executeInfo.expectsResult) {
+ result = new Promise((resolve, reject) => {
+ this._callbacks.add(request.seq, {onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync}, executeInfo.isAsync);
+ if (executeInfo.token) {
+ executeInfo.token.onCancellationRequested(() => {
+ this.tryCancelRequest(request.seq, command);
+ });
+ }
+ }).catch((err) => {
+ throw err;
+ });
+ }
+ this._requestQueue.enqueue(requestInfo);
+ this.sendNextRequests();
+ return result;
+ }
+ sendNextRequests() {
+ while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
+ const item = this._requestQueue.dequeue();
+ if (item) {
+ this.sendRequest(item);
+ }
}
- suggestionsEnabled(uri) {
- let doc = coc_nvim_1.workspace.getDocument(uri);
- if (!doc)
- return false;
- if (doc.filetype.startsWith('javascript')) {
- return this._enableJavascriptSuggestions;
+ }
+ sendRequest(requestItem) {
+ const serverRequest = requestItem.request;
+ this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
+ if (requestItem.expectsResponse && !requestItem.isAsync) {
+ this._pendingResponses.add(requestItem.request.seq);
+ }
+ this.service().then((childProcess) => {
+ try {
+ childProcess.write(serverRequest);
+ } catch (err) {
+ const callback = this.fetchCallback(serverRequest.seq);
+ if (callback) {
+ callback.onError(err);
}
- if (doc.filetype.startsWith('typescript')) {
- return this._enableTypescriptSuggestions;
+ }
+ });
+ }
+ tryCancelRequest(seq, command) {
+ try {
+ if (this._requestQueue.tryDeletePendingRequest(seq)) {
+ this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
+ return true;
+ }
+ if (this.cancellationPipeName) {
+ this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
+ try {
+ import_fs4.default.writeFileSync(this.cancellationPipeName + seq, "");
+ } catch {
}
return true;
+ }
+ this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
+ return false;
+ } finally {
+ const callback = this.fetchCallback(seq);
+ if (callback) {
+ callback.onSuccess(new ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`));
+ }
}
-}
-exports.DiagnosticsManager = DiagnosticsManager;
-
-
-/***/ }),
-/* 138 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"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.isWindowsPath = exports.ResourceMap = void 0;
-/**
- * Maps of file resources
- *
- * Attempts to handle correct mapping on both case sensitive and case in-sensitive
- * file systems.
- */
-class ResourceMap {
- constructor(_normalizePath) {
- this._normalizePath = _normalizePath;
- this._map = new Map();
+ }
+ fetchCallback(seq) {
+ const callback = this._callbacks.fetch(seq);
+ if (!callback) {
+ return void 0;
}
- has(resource) {
- const file = this.toKey(resource);
- return !!file && this._map.has(file);
+ this._pendingResponses.delete(seq);
+ return callback;
+ }
+ dispatchMessage(message) {
+ try {
+ switch (message.type) {
+ case "response":
+ this.dispatchResponse(message);
+ break;
+ case "event":
+ const event = message;
+ if (event.event === "requestCompleted") {
+ const seq = event.body.request_seq;
+ const p = this._callbacks.fetch(seq);
+ if (p) {
+ this.tracer.traceRequestCompleted("requestCompleted", seq, p.startTime);
+ p.onSuccess(void 0);
+ }
+ } else {
+ this.tracer.traceEvent(event);
+ this.dispatchEvent(event);
+ }
+ break;
+ default:
+ throw new Error(`Unknown message type ${message.type} received`);
+ }
+ } finally {
+ this.sendNextRequests();
}
- get(resource) {
- const file = this.toKey(resource);
- return file ? this._map.get(file) : undefined;
+ }
+ dispatchResponse(response) {
+ const callback = this.fetchCallback(response.request_seq);
+ if (!callback) {
+ return;
+ }
+ this.tracer.traceResponse(response, callback.startTime);
+ if (response.success) {
+ callback.onSuccess(response);
+ } else if (response.message === "No content available.") {
+ callback.onSuccess(ServerResponse.NoContent);
+ } else {
+ callback.onError(new Error(response.message));
}
- set(resource, value) {
- const file = this.toKey(resource);
- if (file) {
- this._map.set(file, value);
- }
+ }
+ dispatchEvent(event) {
+ switch (event.event) {
+ case "syntaxDiag":
+ case "semanticDiag":
+ case "suggestionDiag":
+ const diagnosticEvent = event;
+ if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) {
+ this._onDiagnosticsReceived.fire({
+ kind: getDiagnosticsKind(event),
+ resource: this.asUrl(diagnosticEvent.body.file),
+ diagnostics: diagnosticEvent.body.diagnostics
+ });
+ }
+ break;
+ case "configFileDiag":
+ this._onConfigDiagnosticsReceived.fire(event);
+ break;
+ case "projectLanguageServiceState":
+ if (event.body) {
+ this._onProjectLanguageServiceStateChanged.fire(event.body);
+ }
+ break;
+ case "beginInstallTypes":
+ if (event.body) {
+ this._onDidBeginInstallTypings.fire(event.body);
+ }
+ break;
+ case "endInstallTypes":
+ if (event.body) {
+ this._onDidEndInstallTypings.fire(event.body);
+ }
+ break;
+ case "projectsUpdatedInBackground":
+ const body = event.body;
+ const resources = body.openFiles.map(import_coc32.Uri.file);
+ this.bufferSyncSupport.getErr(resources);
+ break;
+ case "typesInstallerInitializationFailed":
+ if (event.body) {
+ this._onTypesInstallerInitializationFailed.fire(event.body);
+ }
+ break;
+ case "projectLoadingStart":
+ this.versionStatus.loading = true;
+ break;
+ case "projectLoadingFinish":
+ this.versionStatus.loading = false;
+ break;
}
- delete(resource) {
- const file = this.toKey(resource);
- if (file) {
- this._map.delete(file);
+ }
+ async getTsServerArgs(currentVersion) {
+ const args = [];
+ args.push("--allowLocalPluginLoads");
+ if (this.apiVersion.gte(api_default.v250)) {
+ args.push("--useInferredProjectPerProjectRoot");
+ } else {
+ args.push("--useSingleInferredProject");
+ }
+ if (this.apiVersion.gte(api_default.v206) && this._configuration.disableAutomaticTypeAcquisition) {
+ args.push("--disableAutomaticTypingAcquisition");
+ }
+ if (this.apiVersion.gte(api_default.v222)) {
+ this.cancellationPipeName = getTempFile(`tscancellation-${makeRandomHexString(20)}`);
+ args.push("--cancellationPipeName", this.cancellationPipeName + "*");
+ }
+ if (this.apiVersion.gte(api_default.v222)) {
+ const isRoot = process.getuid && process.getuid() == 0;
+ if (this._configuration.tsServerLogLevel !== TsServerLogLevel.Off && !isRoot) {
+ const logDir = getTempDirectory();
+ if (logDir) {
+ this.tsServerLogFile = import_path8.default.join(logDir, `tsserver.log`);
+ this.info("TSServer log file :", this.tsServerLogFile);
+ } else {
+ this.tsServerLogFile = null;
+ this.error("Could not create TSServer log directory");
}
- }
- get values() {
- return this._map.values();
- }
- get keys() {
- return this._map.keys();
- }
- toKey(resource) {
- const key = this._normalizePath
- ? this._normalizePath(resource)
- : resource;
- if (!key) {
- return key;
+ if (this.tsServerLogFile) {
+ args.push("--logVerbosity", TsServerLogLevel.toString(this._configuration.tsServerLogLevel));
+ args.push("--logFile", this.tsServerLogFile);
}
- return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
+ }
}
- isCaseInsensitivePath(path) {
- if (isWindowsPath(path)) {
- return true;
+ if (this.apiVersion.gte(api_default.v230)) {
+ const pluginNames = this.pluginManager.plugins.map((x) => x.name);
+ let pluginPaths = this._configuration.tsServerPluginPaths;
+ pluginPaths = pluginPaths.reduce((p, c) => {
+ if (import_path8.default.isAbsolute(c)) {
+ p.push(c);
+ } else {
+ let roots = import_coc32.workspace.workspaceFolders.map((o) => import_coc32.Uri.parse(o.uri).fsPath);
+ p.push(...roots.map((r) => import_path8.default.join(r, c)));
+ }
+ return p;
+ }, []);
+ if (pluginNames.length) {
+ const isUsingBundledTypeScriptVersion = currentVersion.path == this.versionProvider.bundledVersion.path;
+ args.push("--globalPlugins", pluginNames.join(","));
+ for (const plugin of this.pluginManager.plugins) {
+ if (isUsingBundledTypeScriptVersion || plugin.enableForWorkspaceTypeScriptVersions) {
+ pluginPaths.push(plugin.path);
+ }
}
- return path[0] === '/' && this.onIsCaseInsenitiveFileSystem;
+ }
+ if (pluginPaths.length) {
+ args.push("--pluginProbeLocations", pluginPaths.join(","));
+ }
}
- get onIsCaseInsenitiveFileSystem() {
- if (process.platform === 'win32') {
- return true;
- }
- if (process.platform === 'darwin') {
- return true;
- }
- return false;
+ if (this._configuration.locale) {
+ args.push("--locale", this._configuration.locale);
}
-}
-exports.ResourceMap = ResourceMap;
-function isWindowsPath(path) {
- return /^[a-zA-Z]:\\/.test(path);
-}
-exports.isWindowsPath = isWindowsPath;
-
-
-/***/ }),
-/* 139 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.AtaProgressReporter = void 0;
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const coc_nvim_1 = __webpack_require__(1);
-const typingsInstallTimeout = 30 * 1000;
-class TypingsStatus {
- constructor(client) {
- this._acquiringTypings = Object.create({});
- this._subscriptions = [];
- this._client = client;
- this._subscriptions.push(this._client.onDidBeginInstallTypings(event => this.onBeginInstallTypings(event.eventId)));
- this._subscriptions.push(this._client.onDidEndInstallTypings(event => this.onEndInstallTypings(event.eventId)));
+ if (this._configuration.typingsCacheLocation) {
+ args.push("--globalTypingsCacheLocation", `"${this._configuration.typingsCacheLocation}"`);
}
- dispose() {
- this._subscriptions.forEach(x => x.dispose());
- for (const eventId of Object.keys(this._acquiringTypings)) {
- clearTimeout(this._acquiringTypings[eventId]);
- }
+ if (this.apiVersion.gte(api_default.v234)) {
+ let {npmLocation} = this._configuration;
+ if (npmLocation) {
+ this.logger.info(`using npm from ${npmLocation}`);
+ args.push("--npmLocation", `"${npmLocation}"`);
+ }
}
- get isAcquiringTypings() {
- return Object.keys(this._acquiringTypings).length > 0;
+ if (this.apiVersion.gte(api_default.v291)) {
+ args.push("--noGetErrOnBackgroundUpdate");
}
- onBeginInstallTypings(eventId) {
- if (this._acquiringTypings[eventId]) {
- return;
- }
- this._acquiringTypings[eventId] = setTimeout(() => {
- this.onEndInstallTypings(eventId);
- }, typingsInstallTimeout);
+ if (this.apiVersion.gte(api_default.v345)) {
+ args.push("--validateDefaultNpmLocation");
}
- onEndInstallTypings(eventId) {
- const timer = this._acquiringTypings[eventId];
- if (timer) {
- clearTimeout(timer);
- }
- delete this._acquiringTypings[eventId];
+ return args;
+ }
+ getProjectRootPath(uri) {
+ let root = import_coc32.workspace.cwd;
+ let u = import_coc32.Uri.parse(uri);
+ if (u.scheme !== "file")
+ return void 0;
+ let folder = import_coc32.workspace.getWorkspaceFolder(uri);
+ if (folder) {
+ root = import_coc32.Uri.parse(folder.uri).fsPath;
+ } else {
+ let filepath = import_coc32.Uri.parse(uri).fsPath;
+ if (!filepath.startsWith(root)) {
+ root = import_path8.default.dirname(filepath);
+ }
}
-}
-exports.default = TypingsStatus;
-class AtaProgressReporter {
- constructor(client) {
- this._promises = new Map();
- this._invalid = false;
- this.statusItem = coc_nvim_1.workspace.createStatusBarItem(10, { progress: true });
- const disposables = [];
- disposables.push(client.onDidBeginInstallTypings(e => this._onBegin(e.eventId)));
- disposables.push(client.onDidEndInstallTypings(e => this._onEndOrTimeout(e.eventId)));
- disposables.push(client.onTypesInstallerInitializationFailed(_ => this.onTypesInstallerInitializationFailed()));
- this._disposable = vscode_languageserver_protocol_1.Disposable.create(() => {
- disposables.forEach(disposable => {
- disposable.dispose();
- });
- });
+ if (root == import_os2.default.homedir())
+ return void 0;
+ return root;
+ }
+ configurePlugin(pluginName, configuration) {
+ if (this.apiVersion.gte(api_default.v314)) {
+ if (!this.servicePromise)
+ return;
+ this.servicePromise.then(() => {
+ this.executeWithoutWaitingForResponse("configurePlugin", {pluginName, configuration});
+ });
}
- dispose() {
- this._disposable.dispose();
- this._promises.forEach(value => value());
- }
- _onBegin(eventId) {
- const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout);
- new Promise(resolve => {
- this._promises.set(eventId, () => {
- clearTimeout(handle);
- resolve();
- });
- });
- this.statusItem.text = 'Fetching data for better TypeScript IntelliSense';
- this.statusItem.show();
- }
- _onEndOrTimeout(eventId) {
- this.statusItem.hide();
- const resolve = this._promises.get(eventId);
- if (resolve) {
- this._promises.delete(eventId);
- resolve();
- }
+ }
+ interruptGetErr(f) {
+ return this.bufferSyncSupport.interuptGetErr(f);
+ }
+ cancelInflightRequestsForResource(resource) {
+ if (this.state !== import_coc32.ServiceStat.Running || !this.tsServerProcess) {
+ return;
}
- onTypesInstallerInitializationFailed() {
- this.statusItem.hide();
- if (!this._invalid) {
- coc_nvim_1.workspace.showMessage('Could not install typings files for JavaScript language features. Please ensure that NPM is installed', 'error');
- }
- this._invalid = true;
+ for (const request of this.tsServerProcess.toCancelOnResourceChange) {
+ if (request.resource.toString() === resource.toString()) {
+ request.cancel();
+ }
}
+ }
+};
+var typescriptServiceClient_default = TypeScriptServiceClient;
+function getDiagnosticsKind(event) {
+ switch (event.event) {
+ case "syntaxDiag":
+ return DiagnosticKind.Syntax;
+ case "semanticDiag":
+ return DiagnosticKind.Semantic;
+ case "suggestionDiag":
+ return DiagnosticKind.Suggestion;
+ }
+ throw new Error("Unknown dignostics kind");
}
-exports.AtaProgressReporter = AtaProgressReporter;
-
-
-/***/ }),
-/* 140 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
+var fenceCommands = new Set(["change", "close", "open"]);
+function getQueueingType(command, lowPriority) {
+ if (fenceCommands.has(command)) {
+ return RequestQueueingType.Fence;
+ }
+ return lowPriority ? RequestQueueingType.LowPriority : RequestQueueingType.Normal;
+}
+
+// src/server/utils/languageDescription.ts
+var DiagnosticLanguage;
+(function(DiagnosticLanguage2) {
+ DiagnosticLanguage2[DiagnosticLanguage2["JavaScript"] = 0] = "JavaScript";
+ DiagnosticLanguage2[DiagnosticLanguage2["TypeScript"] = 1] = "TypeScript";
+})(DiagnosticLanguage || (DiagnosticLanguage = {}));
+var standardLanguageDescriptions = [
+ {
+ id: "typescript",
+ diagnosticSource: "ts",
+ diagnosticOwner: "typescript",
+ modeIds: [
+ typescript,
+ typescriptreact,
+ typescripttsx,
+ typescriptjsx
+ ],
+ diagnosticLanguage: 1,
+ configFile: "tsconfig.json",
+ configFilePattern: /^tsconfig(\..*)?\.json$/gi
+ },
+ {
+ id: "javascript",
+ diagnosticSource: "ts",
+ diagnosticOwner: "typescript",
+ modeIds: [javascript, javascriptreact, javascriptjsx],
+ diagnosticLanguage: 0,
+ configFile: "jsconfig.json",
+ configFilePattern: /^jsconfig(\..*)?\.json$/gi
+ }
+];
-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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.ConfigurePluginCommand = exports.AutoFixCommand = exports.TypeScriptGoToProjectConfigCommand = exports.OpenTsServerLogCommand = exports.ReloadProjectsCommand = void 0;
-const coc_nvim_1 = __webpack_require__(1);
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
-const typeConverters = __importStar(__webpack_require__(37));
-const vscode_languageserver_types_1 = __webpack_require__(18);
-const modules_1 = __webpack_require__(112);
-const helper_1 = __webpack_require__(100);
-const languageModeIds_1 = __webpack_require__(116);
-class ReloadProjectsCommand {
- constructor(client) {
- this.client = client;
- this.id = 'tsserver.reloadProjects';
- }
- execute() {
- this.client.reloadProjects();
- coc_nvim_1.workspace.showMessage('projects reloaded');
+// src/server/utils/typingsStatus.ts
+var import_coc33 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol22 = __toModule(require_main3());
+var typingsInstallTimeout = 30 * 1e3;
+var TypingsStatus = class {
+ constructor(client) {
+ this._acquiringTypings = Object.create({});
+ this._subscriptions = [];
+ this._client = client;
+ this._subscriptions.push(this._client.onDidBeginInstallTypings((event) => this.onBeginInstallTypings(event.eventId)));
+ this._subscriptions.push(this._client.onDidEndInstallTypings((event) => this.onEndInstallTypings(event.eventId)));
+ }
+ dispose() {
+ this._subscriptions.forEach((x) => x.dispose());
+ for (const eventId of Object.keys(this._acquiringTypings)) {
+ clearTimeout(this._acquiringTypings[eventId]);
}
-}
-exports.ReloadProjectsCommand = ReloadProjectsCommand;
-class OpenTsServerLogCommand {
- constructor(client) {
- this.client = client;
- this.id = 'tsserver.openTsServerLog';
+ }
+ get isAcquiringTypings() {
+ return Object.keys(this._acquiringTypings).length > 0;
+ }
+ onBeginInstallTypings(eventId) {
+ if (this._acquiringTypings[eventId]) {
+ return;
}
- execute() {
- this.client.serviceClient.openTsServerLogFile(); // tslint:disable-line
+ this._acquiringTypings[eventId] = setTimeout(() => {
+ this.onEndInstallTypings(eventId);
+ }, typingsInstallTimeout);
+ }
+ onEndInstallTypings(eventId) {
+ const timer = this._acquiringTypings[eventId];
+ if (timer) {
+ clearTimeout(timer);
}
-}
-exports.OpenTsServerLogCommand = OpenTsServerLogCommand;
-class TypeScriptGoToProjectConfigCommand {
- constructor(client) {
- this.client = client;
- this.id = 'tsserver.goToProjectConfig';
- }
- execute() {
- return __awaiter(this, void 0, void 0, function* () {
- let doc = yield coc_nvim_1.workspace.document;
- let { filetype } = doc;
- if (languageModeIds_1.languageIds.indexOf(filetype) == -1) {
- coc_nvim_1.workspace.showMessage(`Could not determine TypeScript or JavaScript project. Unsupported file type: ${filetype}`, 'warning');
- return;
- }
- // doc.filetype
- yield goToProjectConfig(this.client, doc.uri);
- });
+ delete this._acquiringTypings[eventId];
+ }
+};
+var typingsStatus_default = TypingsStatus;
+var AtaProgressReporter = class {
+ constructor(client) {
+ this._promises = new Map();
+ this._invalid = false;
+ this.statusItem = import_coc33.window.createStatusBarItem(10, {progress: true});
+ const disposables = [];
+ disposables.push(client.onDidBeginInstallTypings((e) => this._onBegin(e.eventId)));
+ disposables.push(client.onDidEndInstallTypings((e) => this._onEndOrTimeout(e.eventId)));
+ disposables.push(client.onTypesInstallerInitializationFailed((_) => this.onTypesInstallerInitializationFailed()));
+ this._disposable = import_vscode_languageserver_protocol22.Disposable.create(() => {
+ disposables.forEach((disposable) => {
+ disposable.dispose();
+ });
+ });
+ }
+ dispose() {
+ this._disposable.dispose();
+ this._promises.forEach((value) => value());
+ }
+ _onBegin(eventId) {
+ const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout);
+ new Promise((resolve) => {
+ this._promises.set(eventId, () => {
+ clearTimeout(handle);
+ resolve();
+ });
+ });
+ this.statusItem.text = "Fetching data for better TypeScript IntelliSense";
+ this.statusItem.show();
+ }
+ _onEndOrTimeout(eventId) {
+ this.statusItem.hide();
+ const resolve = this._promises.get(eventId);
+ if (resolve) {
+ this._promises.delete(eventId);
+ resolve();
}
-}
-exports.TypeScriptGoToProjectConfigCommand = TypeScriptGoToProjectConfigCommand;
-function goToProjectConfig(clientHost, uri) {
- return __awaiter(this, void 0, void 0, function* () {
- const client = clientHost.serviceClient;
- const file = client.toPath(uri);
- let res;
- try {
- res = yield client.execute('projectInfo', { file, needFileNameList: false }, vscode_languageserver_protocol_1.CancellationToken.None);
- }
- catch (_a) {
- // noop
- }
- if (!res || !res.body) {
- coc_nvim_1.workspace.showMessage('Could not determine TypeScript or JavaScript project.', 'warning');
- return;
+ }
+ onTypesInstallerInitializationFailed() {
+ this.statusItem.hide();
+ if (!this._invalid) {
+ import_coc33.window.showMessage("Could not install typings files for JavaScript language features. Please ensure that NPM is installed", "error");
+ }
+ this._invalid = true;
+ }
+};
+
+// src/server/typescriptServiceClientHost.ts
+var styleCheckDiagnostics = [
+ 6133,
+ 6138,
+ 7027,
+ 7028,
+ 7029,
+ 7030
+];
+var TypeScriptServiceClientHost = class {
+ constructor(descriptions, pluginManager) {
+ this.languagePerId = new Map();
+ this.disposables = [];
+ this.reportStyleCheckAsWarnings = true;
+ let timer;
+ const handleProjectChange = () => {
+ if (timer)
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ this.triggerAllDiagnostics();
+ }, 1500);
+ };
+ const configFileWatcher = import_coc34.workspace.createFileSystemWatcher("**/[tj]sconfig.json");
+ this.disposables.push(configFileWatcher);
+ configFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
+ configFileWatcher.onDidDelete(this.reloadProjects, this, this.disposables);
+ configFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
+ const packageFileWatcher = import_coc34.workspace.createFileSystemWatcher("**/package.json");
+ packageFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
+ packageFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
+ const allModeIds = this.getAllModeIds(descriptions, pluginManager);
+ this.client = new typescriptServiceClient_default(pluginManager, allModeIds);
+ this.disposables.push(this.client);
+ this.client.onDiagnosticsReceived(({kind, resource, diagnostics}) => {
+ this.diagnosticsReceived(kind, resource, diagnostics).catch((e) => {
+ console.error(e);
+ });
+ }, null, this.disposables);
+ this.disposables.push(new watchBuild_default(this.client));
+ this.disposables.push(import_coc34.languages.registerWorkspaceSymbolProvider(new workspaceSymbols_default(this.client, allModeIds)));
+ this.client.onConfigDiagnosticsReceived((diag) => {
+ let {body} = diag;
+ if (body) {
+ let {configFile, diagnostics} = body;
+ let uri = import_coc34.Uri.file(configFile);
+ if (diagnostics.length == 0) {
+ this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), []);
+ } else {
+ let diagnosticList = diagnostics.map((o) => {
+ let {text, code, category, start, end} = o;
+ let range;
+ if (!start || !end) {
+ range = import_vscode_languageserver_protocol23.Range.create(import_vscode_languageserver_protocol23.Position.create(0, 0), import_vscode_languageserver_protocol23.Position.create(0, 1));
+ } else {
+ range = import_vscode_languageserver_protocol23.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1);
+ }
+ let severity = category == "error" ? import_vscode_languageserver_protocol23.DiagnosticSeverity.Error : import_vscode_languageserver_protocol23.DiagnosticSeverity.Warning;
+ return import_vscode_languageserver_protocol23.Diagnostic.create(range, text, severity, code);
+ });
+ this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), diagnosticList);
}
- const { configFileName } = res.body;
- if (configFileName && !isImplicitProjectConfigFile(configFileName)) {
- yield coc_nvim_1.workspace.openResource(coc_nvim_1.Uri.file(configFileName).toString());
- return;
+ }
+ }, null, this.disposables);
+ this.typingsStatus = new typingsStatus_default(this.client);
+ this.ataProgressReporter = new AtaProgressReporter(this.client);
+ this.fileConfigurationManager = new fileConfigurationManager_default(this.client);
+ for (const description of descriptions) {
+ const manager = new languageProvider_default(this.client, this.fileConfigurationManager, description, this.typingsStatus);
+ this.languagePerId.set(description.id, manager);
+ }
+ const languageIds = new Set();
+ for (const plugin of pluginManager.plugins) {
+ if (plugin.configNamespace && plugin.languages.length) {
+ this.registerExtensionLanguageProvider({
+ id: plugin.configNamespace,
+ modeIds: Array.from(plugin.languages),
+ diagnosticSource: "ts-plugin",
+ diagnosticLanguage: DiagnosticLanguage.TypeScript,
+ diagnosticOwner: "typescript",
+ isExternal: true
+ });
+ } else {
+ for (const language2 of plugin.languages) {
+ languageIds.add(language2);
}
- coc_nvim_1.workspace.showMessage('Config file not found', 'warning');
+ }
+ }
+ if (languageIds.size) {
+ this.registerExtensionLanguageProvider({
+ id: "typescript-plugins",
+ modeIds: Array.from(languageIds.values()),
+ diagnosticSource: "ts-plugin",
+ diagnosticLanguage: DiagnosticLanguage.TypeScript,
+ diagnosticOwner: "typescript",
+ isExternal: true
+ });
+ }
+ this.client.ensureServiceStarted();
+ this.client.onTsServerStarted(() => {
+ this.triggerAllDiagnostics();
});
-}
-function isImplicitProjectConfigFile(configFileName) {
- return configFileName.indexOf('/dev/null/') === 0;
-}
-const autoFixableDiagnosticCodes = new Set([
- 2420,
- 2552,
- 2304,
-]);
-class AutoFixCommand {
- constructor(client) {
- this.client = client;
- this.id = 'tsserver.executeAutofix';
- }
- execute() {
- return __awaiter(this, void 0, void 0, function* () {
- let document = yield coc_nvim_1.workspace.document;
- let { uri } = document;
- if (!this.client.handles(uri)) {
- coc_nvim_1.workspace.showMessage(`Document ${uri} is not handled by tsserver.`, 'warning');
- return;
- }
- let file = this.client.serviceClient.toPath(document.uri);
- let diagnostics = coc_nvim_1.diagnosticManager.getDiagnostics(document.uri);
- let missingDiagnostics = diagnostics.filter(o => o.code == 2307);
- if (missingDiagnostics.length) {
- let names = missingDiagnostics.map(o => {
- let ms = o.message.match(/module\s'(.+)'\./);
- return ms ? ms[1] : null;
- });
- names = names.filter(s => s != null);
- if (names.length) {
- modules_1.installModules(document.uri, names).catch(e => {
- console.error(e.message); // tslint:disable-line
- });
- }
- }
- diagnostics = diagnostics.filter(x => autoFixableDiagnosticCodes.has(x.code));
- if (diagnostics.length == 0)
- return;
- diagnostics = diagnostics.reduce((arr, curr) => {
- if (curr.code == 2304 && arr.findIndex(o => o.message == curr.message) != -1)
- return arr;
- arr.push(curr);
- return arr;
- }, []);
- let client = this.client.serviceClient;
- let edits = [];
- let command;
- let names = [];
- for (let diagnostic of diagnostics) {
- const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+(diagnostic.code)] });
- const response = yield client.execute('getCodeFixes', args, vscode_languageserver_protocol_1.CancellationToken.None);
- if (response.type !== 'response' || !response.body || response.body.length < 1) {
- if (diagnostic.code == 2304) {
- let { range } = diagnostic;
- let line = document.getline(range.start.line);
- let name = line.slice(range.start.character, range.end.character);
- if (helper_1.nodeModules.indexOf(name) !== -1 && names.indexOf(name) == -1) {
- names.push(name);
- edits.push({
- range: vscode_languageserver_types_1.Range.create(0, 0, 0, 0),
- newText: `import ${name} from '${name}'\n`
- });
- command = 'tsserver.organizeImports';
- }
- }
- continue;
- }
- const fix = response.body[0];
- for (let change of fix.changes) {
- if (change.fileName != file)
- continue;
- // change.fileName
- for (let ch of change.textChanges) {
- edits.push({
- range: typeConverters.Range.fromTextSpan(ch),
- newText: ch.newText
- });
- }
- }
- }
- if (edits.length)
- yield document.applyEdits(coc_nvim_1.workspace.nvim, edits);
- if (command)
- coc_nvim_1.commands.executeCommand(command);
- });
+ import_coc34.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
+ this.configurationChanged();
+ }
+ registerExtensionLanguageProvider(description) {
+ const manager = new languageProvider_default(this.client, this.fileConfigurationManager, description, this.typingsStatus);
+ this.languagePerId.set(description.id, manager);
+ }
+ dispose() {
+ import_coc34.disposeAll(this.disposables);
+ for (let language2 of this.languagePerId.values()) {
+ language2.dispose();
+ }
+ this.languagePerId.clear();
+ this.fileConfigurationManager.dispose();
+ this.typingsStatus.dispose();
+ this.ataProgressReporter.dispose();
+ }
+ reset() {
+ this.fileConfigurationManager.reset();
+ }
+ get serviceClient() {
+ return this.client;
+ }
+ reloadProjects() {
+ this.client.diagnosticsManager.reInitialize();
+ this.client.execute("reloadProjects", null, import_vscode_languageserver_protocol23.CancellationToken.None);
+ this.triggerAllDiagnostics();
+ }
+ getProvider(languageId) {
+ return this.languagePerId.get(languageId);
+ }
+ configurationChanged() {
+ const config = import_coc34.workspace.getConfiguration("tsserver");
+ this.reportStyleCheckAsWarnings = config.get("reportStyleChecksAsWarnings", true);
+ }
+ async findLanguage(uri) {
+ try {
+ let doc = this.client.getDocument(uri);
+ if (!doc)
+ return void 0;
+ let languages4 = Array.from(this.languagePerId.values());
+ return languages4.find((language2) => language2.handles(uri, doc.textDocument));
+ } catch {
+ return void 0;
}
-}
-exports.AutoFixCommand = AutoFixCommand;
-class ConfigurePluginCommand {
- constructor(pluginManager) {
- this.pluginManager = pluginManager;
- this.id = '_typescript.configurePlugin';
+ }
+ async handles(doc) {
+ let languages4 = Array.from(this.languagePerId.values());
+ let idx = languages4.findIndex((language2) => language2.handles(doc.uri, doc));
+ if (idx != -1)
+ return true;
+ return this.client.bufferSyncSupport.handles(doc.uri);
+ }
+ triggerAllDiagnostics() {
+ for (const language2 of this.languagePerId.values()) {
+ language2.triggerAllDiagnostics();
}
- execute(pluginId, configuration) {
- this.pluginManager.setConfiguration(pluginId, configuration);
+ }
+ async diagnosticsReceived(kind, resource, diagnostics) {
+ const language2 = await this.findLanguage(resource.toString());
+ if (language2) {
+ language2.diagnosticsReceived(kind, resource, this.createMarkerDatas(diagnostics));
}
-}
-exports.ConfigurePluginCommand = ConfigurePluginCommand;
-
-
-/***/ }),
-/* 141 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
+ }
+ createMarkerDatas(diagnostics) {
+ return diagnostics.map((tsDiag) => this.tsDiagnosticToLspDiagnostic(tsDiag));
+ }
+ tsDiagnosticToLspDiagnostic(diagnostic) {
+ const {start, end, text} = diagnostic;
+ const range = {
+ start: Position.fromLocation(start),
+ end: Position.fromLocation(end)
+ };
+ let relatedInformation;
+ if (diagnostic.relatedInformation) {
+ relatedInformation = diagnostic.relatedInformation.map((o) => {
+ let {span, message} = o;
+ return {
+ location: Location2.fromTextSpan(this.client.toResource(span.file), span),
+ message
+ };
+ });
+ }
+ let tags = [];
+ if (diagnostic.reportsUnnecessary) {
+ tags.push(import_vscode_languageserver_protocol23.DiagnosticTag.Unnecessary);
+ }
+ if (diagnostic.reportsDeprecated) {
+ tags.push(import_vscode_languageserver_protocol23.DiagnosticTag.Deprecated);
+ }
+ tags = tags.length ? tags : void 0;
+ return {
+ range,
+ tags,
+ message: text,
+ code: diagnostic.code ? diagnostic.code : null,
+ severity: this.getDiagnosticSeverity(diagnostic),
+ reportDeprecated: diagnostic.reportsDeprecated,
+ reportUnnecessary: diagnostic.reportsUnnecessary,
+ source: diagnostic.source || "tsserver",
+ relatedInformation
+ };
+ }
+ getDiagnosticSeverity(diagnostic) {
+ if (this.reportStyleCheckAsWarnings && this.isStyleCheckDiagnostic(diagnostic.code) && diagnostic.category === DiagnosticCategory.error) {
+ return import_vscode_languageserver_protocol23.DiagnosticSeverity.Warning;
+ }
+ switch (diagnostic.category) {
+ case DiagnosticCategory.error:
+ return import_vscode_languageserver_protocol23.DiagnosticSeverity.Error;
+ case DiagnosticCategory.warning:
+ return import_vscode_languageserver_protocol23.DiagnosticSeverity.Warning;
+ case DiagnosticCategory.suggestion:
+ return import_vscode_languageserver_protocol23.DiagnosticSeverity.Information;
+ default:
+ return import_vscode_languageserver_protocol23.DiagnosticSeverity.Error;
+ }
+ }
+ isStyleCheckDiagnostic(code) {
+ return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false;
+ }
+ getAllModeIds(descriptions, pluginManager) {
+ const allModeIds = flatten([
+ ...descriptions.map((x) => x.modeIds),
+ ...pluginManager.plugins.map((x) => x.languages)
+ ]);
+ return allModeIds;
+ }
+};
+var typescriptServiceClientHost_default = TypeScriptServiceClientHost;
+
+// src/server/index.ts
+var TsserverService = class {
+ constructor(pluginManager) {
+ this.pluginManager = pluginManager;
+ this.id = "tsserver";
+ this.name = "tsserver";
+ this.state = import_coc35.ServiceStat.Initial;
+ this._onDidServiceReady = new import_vscode_languageserver_protocol24.Emitter();
+ this.onServiceReady = this._onDidServiceReady.event;
+ this.disposables = [];
+ this.descriptions = [];
+ const config = import_coc35.workspace.getConfiguration("tsserver");
+ const enableJavascript = !!config.get("enableJavascript");
+ this.enable = config.get("enable");
+ this.descriptions = standardLanguageDescriptions.filter((o) => {
+ return enableJavascript ? true : o.id != "javascript";
+ });
+ this.selector = this.descriptions.reduce((arr, c) => {
+ return arr.concat(c.modeIds);
+ }, []);
+ }
+ get config() {
+ return import_coc35.workspace.getConfiguration("tsserver");
+ }
+ getClientHost() {
+ if (this.state == import_coc35.ServiceStat.Running)
+ return Promise.resolve(this.clientHost);
+ this.start();
+ return new Promise((resolve, reject) => {
+ let timer = setTimeout(() => {
+ reject(new Error(`Server not started after 5s`));
+ }, 5e3);
+ let disposable = this.onServiceReady(() => {
+ clearTimeout(timer);
+ disposable.dispose();
+ resolve(this.clientHost);
+ });
+ });
+ }
+ start() {
+ if (this.clientHost)
+ return;
+ this.state = import_coc35.ServiceStat.Starting;
+ this.clientHost = new typescriptServiceClientHost_default(this.descriptions, this.pluginManager);
+ this.disposables.push(this.clientHost);
+ let client = this.clientHost.serviceClient;
+ return new Promise((resolve) => {
+ let started = false;
+ client.onTsServerStarted(() => {
+ Object.defineProperty(this, "state", {
+ get: () => {
+ return this.clientHost.serviceClient.state;
+ }
+ });
+ this._onDidServiceReady.fire(void 0);
+ if (!started) {
+ started = true;
+ resolve();
+ }
+ });
+ });
+ }
+ dispose() {
+ import_coc35.disposeAll(this.disposables);
+ }
+ async restart() {
+ if (!this.clientHost)
+ return;
+ let client = this.clientHost.serviceClient;
+ await client.restartTsServer();
+ }
+ async stop() {
+ if (!this.clientHost)
+ return;
+ this.clientHost.reset();
+ let client = this.clientHost.serviceClient;
+ await client.stop();
+ return;
+ }
};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.PluginManager = void 0;
-const coc_nvim_1 = __webpack_require__(1);
-const arrays = __importStar(__webpack_require__(91));
-const vscode_languageserver_protocol_1 = __webpack_require__(3);
+var server_default = TsserverService;
+
+// src/utils/plugins.ts
+var import_coc36 = __toModule(require("coc.nvim"));
+var import_vscode_languageserver_protocol25 = __toModule(require_main3());
var TypeScriptServerPlugin;
-(function (TypeScriptServerPlugin) {
- function equals(a, b) {
- return a.path === b.path
- && a.name === b.name
- && a.enableForWorkspaceTypeScriptVersions === b.enableForWorkspaceTypeScriptVersions
- && arrays.equals(a.languages, b.languages);
- }
- TypeScriptServerPlugin.equals = equals;
+(function(TypeScriptServerPlugin2) {
+ function equals2(a, b) {
+ return a.path === b.path && a.name === b.name && a.enableForWorkspaceTypeScriptVersions === b.enableForWorkspaceTypeScriptVersions && equals(a.languages, b.languages);
+ }
+ TypeScriptServerPlugin2.equals = equals2;
})(TypeScriptServerPlugin || (TypeScriptServerPlugin = {}));
-class PluginManager {
- constructor() {
- this._pluginConfigurations = new Map();
- this._disposables = [];
- this._onDidUpdatePlugins = this._register(new vscode_languageserver_protocol_1.Emitter());
- this.onDidChangePlugins = this._onDidUpdatePlugins.event;
- this._onDidUpdateConfig = this._register(new vscode_languageserver_protocol_1.Emitter());
- this.onDidUpdateConfig = this._onDidUpdateConfig.event;
- let loadPlugins = () => {
- if (!this._plugins) {
- return;
- }
- const newPlugins = this.readPlugins();
- if (!arrays.equals(arrays.flatten(Array.from(this._plugins.values())), arrays.flatten(Array.from(newPlugins.values())), TypeScriptServerPlugin.equals)) {
- this._plugins = newPlugins;
- this._onDidUpdatePlugins.fire(this);
- }
- };
- coc_nvim_1.extensions.onDidActiveExtension(loadPlugins, undefined, this._disposables);
- coc_nvim_1.extensions.onDidUnloadExtension(loadPlugins, undefined, this._disposables);
+var PluginManager = class {
+ constructor() {
+ this._pluginConfigurations = new Map();
+ this._disposables = [];
+ this._onDidUpdatePlugins = this._register(new import_vscode_languageserver_protocol25.Emitter());
+ this.onDidChangePlugins = this._onDidUpdatePlugins.event;
+ this._onDidUpdateConfig = this._register(new import_vscode_languageserver_protocol25.Emitter());
+ this.onDidUpdateConfig = this._onDidUpdateConfig.event;
+ let loadPlugins = () => {
+ if (!this._plugins) {
+ return;
+ }
+ const newPlugins = this.readPlugins();
+ if (!equals(flatten(Array.from(this._plugins.values())), flatten(Array.from(newPlugins.values())), TypeScriptServerPlugin.equals)) {
+ this._plugins = newPlugins;
+ this._onDidUpdatePlugins.fire(this);
+ }
+ };
+ import_coc36.extensions.onDidActiveExtension(loadPlugins, void 0, this._disposables);
+ import_coc36.extensions.onDidUnloadExtension(loadPlugins, void 0, this._disposables);
+ }
+ dispose() {
+ import_coc36.disposeAll(this._disposables);
+ }
+ get plugins() {
+ if (!this._plugins) {
+ this._plugins = this.readPlugins();
}
- dispose() {
- coc_nvim_1.disposeAll(this._disposables);
- }
- get plugins() {
- if (!this._plugins) {
- this._plugins = this.readPlugins();
- }
- return arrays.flatten(Array.from(this._plugins.values()));
- }
- _register(value) {
- this._disposables.push(value);
- return value;
- }
- setConfiguration(pluginId, config) {
- this._pluginConfigurations.set(pluginId, config);
- this._onDidUpdateConfig.fire({ pluginId, config });
- }
- configurations() {
- return this._pluginConfigurations.entries();
- }
- readPlugins() {
- const pluginMap = new Map();
- for (const extension of coc_nvim_1.extensions.all) {
- const pack = extension.packageJSON;
- if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
- const plugins = [];
- for (const plugin of pack.contributes.typescriptServerPlugins) {
- plugins.push({
- name: plugin.name,
- enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
- path: extension.extensionPath,
- languages: Array.isArray(plugin.languages) ? plugin.languages : [],
- });
- }
- if (plugins.length) {
- pluginMap.set(extension.id, plugins);
- }
- }
+ return flatten(Array.from(this._plugins.values()));
+ }
+ _register(value) {
+ this._disposables.push(value);
+ return value;
+ }
+ setConfiguration(pluginId, config) {
+ this._pluginConfigurations.set(pluginId, config);
+ this._onDidUpdateConfig.fire({pluginId, config});
+ }
+ configurations() {
+ return this._pluginConfigurations.entries();
+ }
+ readPlugins() {
+ const pluginMap = new Map();
+ for (const extension of import_coc36.extensions.all) {
+ const pack = extension.packageJSON;
+ if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
+ const plugins = [];
+ for (const plugin of pack.contributes.typescriptServerPlugins) {
+ plugins.push({
+ name: plugin.name,
+ enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
+ path: extension.extensionPath,
+ languages: Array.isArray(plugin.languages) ? plugin.languages : []
+ });
+ }
+ if (plugins.length) {
+ pluginMap.set(extension.id, plugins);
}
- return pluginMap;
+ }
}
-}
-exports.PluginManager = PluginManager;
-
+ return pluginMap;
+ }
+};
-/***/ })
-/******/ ])));
\ No newline at end of file
+// src/index.ts
+async function activate(context) {
+ let {subscriptions, logger} = context;
+ const config = import_coc37.workspace.getConfiguration().get("tsserver", {});
+ if (!config.enable)
+ return;
+ const pluginManager = new PluginManager();
+ const service = new server_default(pluginManager);
+ function registCommand2(cmd) {
+ let {id, execute} = cmd;
+ subscriptions.push(import_coc37.commands.registerCommand(id, execute, cmd));
+ }
+ registCommand2(new ConfigurePluginCommand(pluginManager));
+ registCommand2(new AutoFixCommand(service));
+ registCommand2(new ReloadProjectsCommand(service));
+ registCommand2(new FileReferencesCommand(service));
+ registCommand2(new OpenTsServerLogCommand(service));
+ registCommand2(new TypeScriptGoToProjectConfigCommand(service));
+ registCommand2(new OrganizeImportsCommand(service));
+ registCommand2({
+ id: "tsserver.restart",
+ execute: () => {
+ service.stop().then(() => {
+ setTimeout(() => {
+ service.restart();
+ }, 100);
+ });
+ }
+ });
+ service.start().then(() => {
+ subscriptions.push(import_coc37.services.regist(service));
+ }, (e) => {
+ logger.error(`Error on service start:`, e);
+ });
+ return {
+ configurePlugin: (pluginId, configuration) => {
+ pluginManager.setConfiguration(pluginId, configuration);
+ }
+ };
+}
+//# sourceMappingURL=index.js.map