1 (function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
2 /******/ // The module cache
3 /******/ var installedModules = {};
5 /******/ // The require function
6 /******/ function __webpack_require__(moduleId) {
8 /******/ // Check if module is in cache
9 /******/ if(installedModules[moduleId]) {
10 /******/ return installedModules[moduleId].exports;
12 /******/ // Create a new module (and put it into the cache)
13 /******/ var module = installedModules[moduleId] = {
19 /******/ // Execute the module function
20 /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
22 /******/ // Flag the module as loaded
23 /******/ module.l = true;
25 /******/ // Return the exports of the module
26 /******/ return module.exports;
30 /******/ // expose the modules object (__webpack_modules__)
31 /******/ __webpack_require__.m = modules;
33 /******/ // expose the module cache
34 /******/ __webpack_require__.c = installedModules;
36 /******/ // define getter function for harmony exports
37 /******/ __webpack_require__.d = function(exports, name, getter) {
38 /******/ if(!__webpack_require__.o(exports, name)) {
39 /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
43 /******/ // define __esModule on exports
44 /******/ __webpack_require__.r = function(exports) {
45 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
46 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
48 /******/ Object.defineProperty(exports, '__esModule', { value: true });
51 /******/ // create a fake namespace object
52 /******/ // mode & 1: value is a module id, require it
53 /******/ // mode & 2: merge all properties of value into the ns
54 /******/ // mode & 4: return value when already ns object
55 /******/ // mode & 8|1: behave like require
56 /******/ __webpack_require__.t = function(value, mode) {
57 /******/ if(mode & 1) value = __webpack_require__(value);
58 /******/ if(mode & 8) return value;
59 /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
60 /******/ var ns = Object.create(null);
61 /******/ __webpack_require__.r(ns);
62 /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
63 /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
67 /******/ // getDefaultExport function for compatibility with non-harmony modules
68 /******/ __webpack_require__.n = function(module) {
69 /******/ var getter = module && module.__esModule ?
70 /******/ function getDefault() { return module['default']; } :
71 /******/ function getModuleExports() { return module; };
72 /******/ __webpack_require__.d(getter, 'a', getter);
73 /******/ return getter;
76 /******/ // Object.prototype.hasOwnProperty.call
77 /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
79 /******/ // __webpack_public_path__
80 /******/ __webpack_require__.p = "";
83 /******/ // Load entry module and return exports
84 /******/ return __webpack_require__(__webpack_require__.s = 0);
86 /************************************************************************/
89 /***/ (function(module, exports, __webpack_require__) {
93 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
94 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
95 return new (P || (P = Promise))(function (resolve, reject) {
96 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
97 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
98 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
99 step((generator = generator.apply(thisArg, _arguments || [])).next());
102 var __importDefault = (this && this.__importDefault) || function (mod) {
103 return (mod && mod.__esModule) ? mod : { "default": mod };
105 Object.defineProperty(exports, "__esModule", { value: true });
106 exports.activate = void 0;
107 const coc_nvim_1 = __webpack_require__(1);
108 const server_1 = __importDefault(__webpack_require__(2));
109 const commands_1 = __webpack_require__(140);
110 const organizeImports_1 = __webpack_require__(114);
111 const plugins_1 = __webpack_require__(141);
112 function activate(context) {
113 return __awaiter(this, void 0, void 0, function* () {
114 let { subscriptions } = context;
115 const config = coc_nvim_1.workspace.getConfiguration().get('tsserver', {});
118 const pluginManager = new plugins_1.PluginManager();
119 const service = new server_1.default(pluginManager);
120 subscriptions.push(coc_nvim_1.services.regist(service));
121 yield service.start();
122 function registCommand(cmd) {
123 let { id, execute } = cmd;
124 subscriptions.push(coc_nvim_1.commands.registerCommand(id, execute, cmd));
126 registCommand(new commands_1.AutoFixCommand(service.clientHost));
127 registCommand(new commands_1.ReloadProjectsCommand(service.clientHost));
128 registCommand(new commands_1.OpenTsServerLogCommand(service.clientHost));
129 registCommand(new commands_1.TypeScriptGoToProjectConfigCommand(service.clientHost));
130 registCommand(new organizeImports_1.OrganizeImportsCommand(service.clientHost.serviceClient));
131 registCommand(new commands_1.ConfigurePluginCommand(pluginManager));
132 registCommand(coc_nvim_1.commands.register({
133 id: 'tsserver.restart',
135 // tslint:disable-next-line:no-floating-promises
136 service.stop().then(() => {
144 configurePlugin: (pluginId, configuration) => {
145 pluginManager.setConfiguration(pluginId, configuration);
150 exports.activate = activate;
155 /***/ (function(module, exports) {
157 module.exports = require("coc.nvim");
161 /***/ (function(module, exports, __webpack_require__) {
165 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
166 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
167 return new (P || (P = Promise))(function (resolve, reject) {
168 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
169 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
170 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
171 step((generator = generator.apply(thisArg, _arguments || [])).next());
174 var __importDefault = (this && this.__importDefault) || function (mod) {
175 return (mod && mod.__esModule) ? mod : { "default": mod };
177 Object.defineProperty(exports, "__esModule", { value: true });
178 const coc_nvim_1 = __webpack_require__(1);
179 const vscode_languageserver_protocol_1 = __webpack_require__(3);
180 const typescriptServiceClientHost_1 = __importDefault(__webpack_require__(33));
181 const languageDescription_1 = __webpack_require__(115);
182 class TsserverService {
183 constructor(pluginManager) {
184 this.pluginManager = pluginManager;
185 this.id = 'tsserver';
186 this.name = 'tsserver';
187 this.state = coc_nvim_1.ServiceStat.Initial;
188 this._onDidServiceReady = new vscode_languageserver_protocol_1.Emitter();
189 this.onServiceReady = this._onDidServiceReady.event;
190 this.disposables = [];
191 this.descriptions = [];
192 const config = coc_nvim_1.workspace.getConfiguration('tsserver');
193 const enableJavascript = !!config.get('enableJavascript');
194 this.enable = config.get('enable');
195 this.descriptions = languageDescription_1.standardLanguageDescriptions.filter(o => {
196 return enableJavascript ? true : o.id != 'javascript';
198 this.selector = this.descriptions.reduce((arr, c) => {
199 return arr.concat(c.modeIds);
201 coc_nvim_1.workspace.onDidOpenTextDocument(doc => {
202 this.ensureConfigurationForDocument(doc);
203 }, null, this.disposables);
206 return coc_nvim_1.workspace.getConfiguration('tsserver');
208 ensureConfigurationForDocument(document) {
209 let uri = coc_nvim_1.Uri.parse(document.uri);
210 let language = this.clientHost.findLanguage(uri);
213 language.fileConfigurationManager.ensureConfigurationForDocument(document).catch(_e => {
220 this.state = coc_nvim_1.ServiceStat.Starting;
221 this.clientHost = new typescriptServiceClientHost_1.default(this.descriptions, this.pluginManager);
222 this.disposables.push(this.clientHost);
223 let client = this.clientHost.serviceClient;
224 return new Promise(resolve => {
226 client.onTsServerStarted(() => {
227 Object.defineProperty(this, 'state', {
229 return this.clientHost.serviceClient.state;
232 this._onDidServiceReady.fire(void 0);
233 this.ensureConfiguration();
241 ensureConfiguration() {
242 if (!this.clientHost)
244 for (let doc of coc_nvim_1.workspace.documents) {
245 this.ensureConfigurationForDocument(doc.textDocument);
249 coc_nvim_1.disposeAll(this.disposables);
252 return __awaiter(this, void 0, void 0, function* () {
253 if (!this.clientHost)
255 let client = this.clientHost.serviceClient;
256 yield client.restartTsServer();
260 return __awaiter(this, void 0, void 0, function* () {
261 if (!this.clientHost)
263 this.clientHost.reset();
264 let client = this.clientHost.serviceClient;
270 exports.default = TsserverService;
275 /***/ (function(module, exports, __webpack_require__) {
278 /* --------------------------------------------------------------------------------------------
\r
279 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
280 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
281 * ------------------------------------------------------------------------------------------ */
\r
283 function __export(m) {
\r
284 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
\r
286 Object.defineProperty(exports, "__esModule", { value: true });
\r
287 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
288 exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
\r
289 exports.ResponseError = vscode_jsonrpc_1.ResponseError;
\r
290 exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
\r
291 exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
\r
292 exports.Disposable = vscode_jsonrpc_1.Disposable;
\r
293 exports.Event = vscode_jsonrpc_1.Event;
\r
294 exports.Emitter = vscode_jsonrpc_1.Emitter;
\r
295 exports.Trace = vscode_jsonrpc_1.Trace;
\r
296 exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
\r
297 exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
\r
298 exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
\r
299 exports.RequestType = vscode_jsonrpc_1.RequestType;
\r
300 exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
\r
301 exports.NotificationType = vscode_jsonrpc_1.NotificationType;
\r
302 exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
\r
303 exports.MessageReader = vscode_jsonrpc_1.MessageReader;
\r
304 exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
\r
305 exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
\r
306 exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
\r
307 exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
\r
308 exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
\r
309 exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
\r
310 exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
\r
311 exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
\r
312 exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
\r
313 exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
\r
314 exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
\r
315 exports.ProgressType = vscode_jsonrpc_1.ProgressType;
\r
316 __export(__webpack_require__(18));
\r
317 __export(__webpack_require__(19));
\r
318 const callHierarchy = __webpack_require__(31);
\r
319 const st = __webpack_require__(32);
\r
321 (function (Proposed) {
\r
322 let CallHierarchyPrepareRequest;
\r
323 (function (CallHierarchyPrepareRequest) {
\r
324 CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;
\r
325 CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;
\r
326 })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));
\r
327 let CallHierarchyIncomingCallsRequest;
\r
328 (function (CallHierarchyIncomingCallsRequest) {
\r
329 CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;
\r
330 CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;
\r
331 })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));
\r
332 let CallHierarchyOutgoingCallsRequest;
\r
333 (function (CallHierarchyOutgoingCallsRequest) {
\r
334 CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;
\r
335 CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;
\r
336 })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));
\r
337 Proposed.SemanticTokenTypes = st.SemanticTokenTypes;
\r
338 Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;
\r
339 Proposed.SemanticTokens = st.SemanticTokens;
\r
340 let SemanticTokensRequest;
\r
341 (function (SemanticTokensRequest) {
\r
342 SemanticTokensRequest.method = st.SemanticTokensRequest.method;
\r
343 SemanticTokensRequest.type = st.SemanticTokensRequest.type;
\r
344 })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));
\r
345 let SemanticTokensEditsRequest;
\r
346 (function (SemanticTokensEditsRequest) {
\r
347 SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;
\r
348 SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;
\r
349 })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));
\r
350 let SemanticTokensRangeRequest;
\r
351 (function (SemanticTokensRangeRequest) {
\r
352 SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;
\r
353 SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;
\r
354 })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));
\r
355 })(Proposed = exports.Proposed || (exports.Proposed = {}));
\r
356 function createProtocolConnection(reader, writer, logger, strategy) {
\r
357 return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
\r
359 exports.createProtocolConnection = createProtocolConnection;
\r
364 /***/ (function(module, exports, __webpack_require__) {
367 /* --------------------------------------------------------------------------------------------
\r
368 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
369 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
370 * ------------------------------------------------------------------------------------------ */
\r
371 /// <reference path="../typings/thenable.d.ts" />
\r
373 function __export(m) {
\r
374 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
\r
376 Object.defineProperty(exports, "__esModule", { value: true });
\r
377 const Is = __webpack_require__(5);
\r
378 const messages_1 = __webpack_require__(6);
\r
379 exports.RequestType = messages_1.RequestType;
\r
380 exports.RequestType0 = messages_1.RequestType0;
\r
381 exports.RequestType1 = messages_1.RequestType1;
\r
382 exports.RequestType2 = messages_1.RequestType2;
\r
383 exports.RequestType3 = messages_1.RequestType3;
\r
384 exports.RequestType4 = messages_1.RequestType4;
\r
385 exports.RequestType5 = messages_1.RequestType5;
\r
386 exports.RequestType6 = messages_1.RequestType6;
\r
387 exports.RequestType7 = messages_1.RequestType7;
\r
388 exports.RequestType8 = messages_1.RequestType8;
\r
389 exports.RequestType9 = messages_1.RequestType9;
\r
390 exports.ResponseError = messages_1.ResponseError;
\r
391 exports.ErrorCodes = messages_1.ErrorCodes;
\r
392 exports.NotificationType = messages_1.NotificationType;
\r
393 exports.NotificationType0 = messages_1.NotificationType0;
\r
394 exports.NotificationType1 = messages_1.NotificationType1;
\r
395 exports.NotificationType2 = messages_1.NotificationType2;
\r
396 exports.NotificationType3 = messages_1.NotificationType3;
\r
397 exports.NotificationType4 = messages_1.NotificationType4;
\r
398 exports.NotificationType5 = messages_1.NotificationType5;
\r
399 exports.NotificationType6 = messages_1.NotificationType6;
\r
400 exports.NotificationType7 = messages_1.NotificationType7;
\r
401 exports.NotificationType8 = messages_1.NotificationType8;
\r
402 exports.NotificationType9 = messages_1.NotificationType9;
\r
403 const messageReader_1 = __webpack_require__(7);
\r
404 exports.MessageReader = messageReader_1.MessageReader;
\r
405 exports.StreamMessageReader = messageReader_1.StreamMessageReader;
\r
406 exports.IPCMessageReader = messageReader_1.IPCMessageReader;
\r
407 exports.SocketMessageReader = messageReader_1.SocketMessageReader;
\r
408 const messageWriter_1 = __webpack_require__(9);
\r
409 exports.MessageWriter = messageWriter_1.MessageWriter;
\r
410 exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
\r
411 exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
\r
412 exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
\r
413 const events_1 = __webpack_require__(8);
\r
414 exports.Disposable = events_1.Disposable;
\r
415 exports.Event = events_1.Event;
\r
416 exports.Emitter = events_1.Emitter;
\r
417 const cancellation_1 = __webpack_require__(10);
\r
418 exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
\r
419 exports.CancellationToken = cancellation_1.CancellationToken;
\r
420 const linkedMap_1 = __webpack_require__(11);
\r
421 __export(__webpack_require__(12));
\r
422 __export(__webpack_require__(17));
\r
423 var CancelNotification;
\r
424 (function (CancelNotification) {
\r
425 CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
\r
426 })(CancelNotification || (CancelNotification = {}));
\r
427 var ProgressNotification;
\r
428 (function (ProgressNotification) {
\r
429 ProgressNotification.type = new messages_1.NotificationType('$/progress');
\r
430 })(ProgressNotification || (ProgressNotification = {}));
\r
431 class ProgressType {
\r
435 exports.ProgressType = ProgressType;
\r
436 exports.NullLogger = Object.freeze({
\r
443 (function (Trace) {
\r
444 Trace[Trace["Off"] = 0] = "Off";
\r
445 Trace[Trace["Messages"] = 1] = "Messages";
\r
446 Trace[Trace["Verbose"] = 2] = "Verbose";
\r
447 })(Trace = exports.Trace || (exports.Trace = {}));
\r
448 (function (Trace) {
\r
449 function fromString(value) {
\r
450 if (!Is.string(value)) {
\r
453 value = value.toLowerCase();
\r
458 return Trace.Messages;
\r
460 return Trace.Verbose;
\r
465 Trace.fromString = fromString;
\r
466 function toString(value) {
\r
470 case Trace.Messages:
\r
472 case Trace.Verbose:
\r
478 Trace.toString = toString;
\r
479 })(Trace = exports.Trace || (exports.Trace = {}));
\r
481 (function (TraceFormat) {
\r
482 TraceFormat["Text"] = "text";
\r
483 TraceFormat["JSON"] = "json";
\r
484 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
\r
485 (function (TraceFormat) {
\r
486 function fromString(value) {
\r
487 value = value.toLowerCase();
\r
488 if (value === 'json') {
\r
489 return TraceFormat.JSON;
\r
492 return TraceFormat.Text;
\r
495 TraceFormat.fromString = fromString;
\r
496 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
\r
497 var SetTraceNotification;
\r
498 (function (SetTraceNotification) {
\r
499 SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
\r
500 })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
\r
501 var LogTraceNotification;
\r
502 (function (LogTraceNotification) {
\r
503 LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
\r
504 })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
\r
505 var ConnectionErrors;
\r
506 (function (ConnectionErrors) {
\r
508 * The connection is closed.
\r
510 ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
\r
512 * The connection got disposed.
\r
514 ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
\r
516 * The connection is already in listening mode.
\r
518 ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
\r
519 })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
\r
520 class ConnectionError extends Error {
\r
521 constructor(code, message) {
\r
524 Object.setPrototypeOf(this, ConnectionError.prototype);
\r
527 exports.ConnectionError = ConnectionError;
\r
528 var ConnectionStrategy;
\r
529 (function (ConnectionStrategy) {
\r
530 function is(value) {
\r
531 let candidate = value;
\r
532 return candidate && Is.func(candidate.cancelUndispatched);
\r
534 ConnectionStrategy.is = is;
\r
535 })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
\r
536 var ConnectionState;
\r
537 (function (ConnectionState) {
\r
538 ConnectionState[ConnectionState["New"] = 1] = "New";
\r
539 ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
\r
540 ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
\r
541 ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
\r
542 })(ConnectionState || (ConnectionState = {}));
\r
543 function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
\r
544 let sequenceNumber = 0;
\r
545 let notificationSquenceNumber = 0;
\r
546 let unknownResponseSquenceNumber = 0;
\r
547 const version = '2.0';
\r
548 let starRequestHandler = undefined;
\r
549 let requestHandlers = Object.create(null);
\r
550 let starNotificationHandler = undefined;
\r
551 let notificationHandlers = Object.create(null);
\r
552 let progressHandlers = new Map();
\r
554 let messageQueue = new linkedMap_1.LinkedMap();
\r
555 let responsePromises = Object.create(null);
\r
556 let requestTokens = Object.create(null);
\r
557 let trace = Trace.Off;
\r
558 let traceFormat = TraceFormat.Text;
\r
560 let state = ConnectionState.New;
\r
561 let errorEmitter = new events_1.Emitter();
\r
562 let closeEmitter = new events_1.Emitter();
\r
563 let unhandledNotificationEmitter = new events_1.Emitter();
\r
564 let unhandledProgressEmitter = new events_1.Emitter();
\r
565 let disposeEmitter = new events_1.Emitter();
\r
566 function createRequestQueueKey(id) {
\r
567 return 'req-' + id.toString();
\r
569 function createResponseQueueKey(id) {
\r
571 return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
\r
574 return 'res-' + id.toString();
\r
577 function createNotificationQueueKey() {
\r
578 return 'not-' + (++notificationSquenceNumber).toString();
\r
580 function addMessageToQueue(queue, message) {
\r
581 if (messages_1.isRequestMessage(message)) {
\r
582 queue.set(createRequestQueueKey(message.id), message);
\r
584 else if (messages_1.isResponseMessage(message)) {
\r
585 queue.set(createResponseQueueKey(message.id), message);
\r
588 queue.set(createNotificationQueueKey(), message);
\r
591 function cancelUndispatched(_message) {
\r
594 function isListening() {
\r
595 return state === ConnectionState.Listening;
\r
597 function isClosed() {
\r
598 return state === ConnectionState.Closed;
\r
600 function isDisposed() {
\r
601 return state === ConnectionState.Disposed;
\r
603 function closeHandler() {
\r
604 if (state === ConnectionState.New || state === ConnectionState.Listening) {
\r
605 state = ConnectionState.Closed;
\r
606 closeEmitter.fire(undefined);
\r
608 // If the connection is disposed don't sent close events.
\r
610 function readErrorHandler(error) {
\r
611 errorEmitter.fire([error, undefined, undefined]);
\r
613 function writeErrorHandler(data) {
\r
614 errorEmitter.fire(data);
\r
616 messageReader.onClose(closeHandler);
\r
617 messageReader.onError(readErrorHandler);
\r
618 messageWriter.onClose(closeHandler);
\r
619 messageWriter.onError(writeErrorHandler);
\r
620 function triggerMessageQueue() {
\r
621 if (timer || messageQueue.size === 0) {
\r
624 timer = setImmediate(() => {
\r
626 processMessageQueue();
\r
629 function processMessageQueue() {
\r
630 if (messageQueue.size === 0) {
\r
633 let message = messageQueue.shift();
\r
635 if (messages_1.isRequestMessage(message)) {
\r
636 handleRequest(message);
\r
638 else if (messages_1.isNotificationMessage(message)) {
\r
639 handleNotification(message);
\r
641 else if (messages_1.isResponseMessage(message)) {
\r
642 handleResponse(message);
\r
645 handleInvalidMessage(message);
\r
649 triggerMessageQueue();
\r
652 let callback = (message) => {
\r
654 // We have received a cancellation message. Check if the message is still in the queue
\r
655 // and cancel it if allowed to do so.
\r
656 if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
\r
657 let key = createRequestQueueKey(message.params.id);
\r
658 let toCancel = messageQueue.get(key);
\r
659 if (messages_1.isRequestMessage(toCancel)) {
\r
660 let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
\r
661 if (response && (response.error !== void 0 || response.result !== void 0)) {
\r
662 messageQueue.delete(key);
\r
663 response.id = toCancel.id;
\r
664 traceSendingResponse(response, message.method, Date.now());
\r
665 messageWriter.write(response);
\r
670 addMessageToQueue(messageQueue, message);
\r
673 triggerMessageQueue();
\r
676 function handleRequest(requestMessage) {
\r
677 if (isDisposed()) {
\r
678 // we return here silently since we fired an event when the
\r
679 // connection got disposed.
\r
682 function reply(resultOrError, method, startTime) {
\r
685 id: requestMessage.id
\r
687 if (resultOrError instanceof messages_1.ResponseError) {
\r
688 message.error = resultOrError.toJson();
\r
691 message.result = resultOrError === void 0 ? null : resultOrError;
\r
693 traceSendingResponse(message, method, startTime);
\r
694 messageWriter.write(message);
\r
696 function replyError(error, method, startTime) {
\r
699 id: requestMessage.id,
\r
700 error: error.toJson()
\r
702 traceSendingResponse(message, method, startTime);
\r
703 messageWriter.write(message);
\r
705 function replySuccess(result, method, startTime) {
\r
706 // The JSON RPC defines that a response must either have a result or an error
\r
707 // So we can't treat undefined as a valid response result.
\r
708 if (result === void 0) {
\r
713 id: requestMessage.id,
\r
716 traceSendingResponse(message, method, startTime);
\r
717 messageWriter.write(message);
\r
719 traceReceivedRequest(requestMessage);
\r
720 let element = requestHandlers[requestMessage.method];
\r
722 let requestHandler;
\r
724 type = element.type;
\r
725 requestHandler = element.handler;
\r
727 let startTime = Date.now();
\r
728 if (requestHandler || starRequestHandler) {
\r
729 let cancellationSource = new cancellation_1.CancellationTokenSource();
\r
730 let tokenKey = String(requestMessage.id);
\r
731 requestTokens[tokenKey] = cancellationSource;
\r
734 if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
\r
735 handlerResult = requestHandler
\r
736 ? requestHandler(cancellationSource.token)
\r
737 : starRequestHandler(requestMessage.method, cancellationSource.token);
\r
739 else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
\r
740 handlerResult = requestHandler
\r
741 ? requestHandler(...requestMessage.params, cancellationSource.token)
\r
742 : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
\r
745 handlerResult = requestHandler
\r
746 ? requestHandler(requestMessage.params, cancellationSource.token)
\r
747 : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
\r
749 let promise = handlerResult;
\r
750 if (!handlerResult) {
\r
751 delete requestTokens[tokenKey];
\r
752 replySuccess(handlerResult, requestMessage.method, startTime);
\r
754 else if (promise.then) {
\r
755 promise.then((resultOrError) => {
\r
756 delete requestTokens[tokenKey];
\r
757 reply(resultOrError, requestMessage.method, startTime);
\r
759 delete requestTokens[tokenKey];
\r
760 if (error instanceof messages_1.ResponseError) {
\r
761 replyError(error, requestMessage.method, startTime);
\r
763 else if (error && Is.string(error.message)) {
\r
764 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
\r
767 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
\r
772 delete requestTokens[tokenKey];
\r
773 reply(handlerResult, requestMessage.method, startTime);
\r
777 delete requestTokens[tokenKey];
\r
778 if (error instanceof messages_1.ResponseError) {
\r
779 reply(error, requestMessage.method, startTime);
\r
781 else if (error && Is.string(error.message)) {
\r
782 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
\r
785 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
\r
790 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
\r
793 function handleResponse(responseMessage) {
\r
794 if (isDisposed()) {
\r
795 // See handle request.
\r
798 if (responseMessage.id === null) {
\r
799 if (responseMessage.error) {
\r
800 logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
\r
803 logger.error(`Received response message without id. No further error information provided.`);
\r
807 let key = String(responseMessage.id);
\r
808 let responsePromise = responsePromises[key];
\r
809 traceReceivedResponse(responseMessage, responsePromise);
\r
810 if (responsePromise) {
\r
811 delete responsePromises[key];
\r
813 if (responseMessage.error) {
\r
814 let error = responseMessage.error;
\r
815 responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
\r
817 else if (responseMessage.result !== void 0) {
\r
818 responsePromise.resolve(responseMessage.result);
\r
821 throw new Error('Should never happen.');
\r
825 if (error.message) {
\r
826 logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
\r
829 logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
\r
835 function handleNotification(message) {
\r
836 if (isDisposed()) {
\r
837 // See handle request.
\r
840 let type = undefined;
\r
841 let notificationHandler;
\r
842 if (message.method === CancelNotification.type.method) {
\r
843 notificationHandler = (params) => {
\r
844 let id = params.id;
\r
845 let source = requestTokens[String(id)];
\r
852 let element = notificationHandlers[message.method];
\r
854 notificationHandler = element.handler;
\r
855 type = element.type;
\r
858 if (notificationHandler || starNotificationHandler) {
\r
860 traceReceivedNotification(message);
\r
861 if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
\r
862 notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
\r
864 else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
\r
865 notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
\r
868 notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
\r
872 if (error.message) {
\r
873 logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
\r
876 logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
\r
881 unhandledNotificationEmitter.fire(message);
\r
884 function handleInvalidMessage(message) {
\r
886 logger.error('Received empty message.');
\r
889 logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
\r
890 // Test whether we find an id to reject the promise
\r
891 let responseMessage = message;
\r
892 if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
\r
893 let key = String(responseMessage.id);
\r
894 let responseHandler = responsePromises[key];
\r
895 if (responseHandler) {
\r
896 responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
\r
900 function traceSendingRequest(message) {
\r
901 if (trace === Trace.Off || !tracer) {
\r
904 if (traceFormat === TraceFormat.Text) {
\r
905 let data = undefined;
\r
906 if (trace === Trace.Verbose && message.params) {
\r
907 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
909 tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
\r
912 logLSPMessage('send-request', message);
\r
915 function traceSendingNotification(message) {
\r
916 if (trace === Trace.Off || !tracer) {
\r
919 if (traceFormat === TraceFormat.Text) {
\r
920 let data = undefined;
\r
921 if (trace === Trace.Verbose) {
\r
922 if (message.params) {
\r
923 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
926 data = 'No parameters provided.\n\n';
\r
929 tracer.log(`Sending notification '${message.method}'.`, data);
\r
932 logLSPMessage('send-notification', message);
\r
935 function traceSendingResponse(message, method, startTime) {
\r
936 if (trace === Trace.Off || !tracer) {
\r
939 if (traceFormat === TraceFormat.Text) {
\r
940 let data = undefined;
\r
941 if (trace === Trace.Verbose) {
\r
942 if (message.error && message.error.data) {
\r
943 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
\r
946 if (message.result) {
\r
947 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
\r
949 else if (message.error === void 0) {
\r
950 data = 'No result returned.\n\n';
\r
954 tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
\r
957 logLSPMessage('send-response', message);
\r
960 function traceReceivedRequest(message) {
\r
961 if (trace === Trace.Off || !tracer) {
\r
964 if (traceFormat === TraceFormat.Text) {
\r
965 let data = undefined;
\r
966 if (trace === Trace.Verbose && message.params) {
\r
967 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
969 tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
\r
972 logLSPMessage('receive-request', message);
\r
975 function traceReceivedNotification(message) {
\r
976 if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
\r
979 if (traceFormat === TraceFormat.Text) {
\r
980 let data = undefined;
\r
981 if (trace === Trace.Verbose) {
\r
982 if (message.params) {
\r
983 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
986 data = 'No parameters provided.\n\n';
\r
989 tracer.log(`Received notification '${message.method}'.`, data);
\r
992 logLSPMessage('receive-notification', message);
\r
995 function traceReceivedResponse(message, responsePromise) {
\r
996 if (trace === Trace.Off || !tracer) {
\r
999 if (traceFormat === TraceFormat.Text) {
\r
1000 let data = undefined;
\r
1001 if (trace === Trace.Verbose) {
\r
1002 if (message.error && message.error.data) {
\r
1003 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
\r
1006 if (message.result) {
\r
1007 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
\r
1009 else if (message.error === void 0) {
\r
1010 data = 'No result returned.\n\n';
\r
1014 if (responsePromise) {
\r
1015 let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
\r
1016 tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
\r
1019 tracer.log(`Received response ${message.id} without active response promise.`, data);
\r
1023 logLSPMessage('receive-response', message);
\r
1026 function logLSPMessage(type, message) {
\r
1027 if (!tracer || trace === Trace.Off) {
\r
1030 const lspMessage = {
\r
1031 isLSPMessage: true,
\r
1034 timestamp: Date.now()
\r
1036 tracer.log(lspMessage);
\r
1038 function throwIfClosedOrDisposed() {
\r
1040 throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
\r
1042 if (isDisposed()) {
\r
1043 throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
\r
1046 function throwIfListening() {
\r
1047 if (isListening()) {
\r
1048 throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
\r
1051 function throwIfNotListening() {
\r
1052 if (!isListening()) {
\r
1053 throw new Error('Call listen() first.');
\r
1056 function undefinedToNull(param) {
\r
1057 if (param === void 0) {
\r
1064 function computeMessageParams(type, params) {
\r
1066 let numberOfParams = type.numberOfParams;
\r
1067 switch (numberOfParams) {
\r
1072 result = undefinedToNull(params[0]);
\r
1076 for (let i = 0; i < params.length && i < numberOfParams; i++) {
\r
1077 result.push(undefinedToNull(params[i]));
\r
1079 if (params.length < numberOfParams) {
\r
1080 for (let i = params.length; i < numberOfParams; i++) {
\r
1081 result.push(null);
\r
1088 let connection = {
\r
1089 sendNotification: (type, ...params) => {
\r
1090 throwIfClosedOrDisposed();
\r
1092 let messageParams;
\r
1093 if (Is.string(type)) {
\r
1095 switch (params.length) {
\r
1097 messageParams = null;
\r
1100 messageParams = params[0];
\r
1103 messageParams = params;
\r
1108 method = type.method;
\r
1109 messageParams = computeMessageParams(type, params);
\r
1111 let notificationMessage = {
\r
1114 params: messageParams
\r
1116 traceSendingNotification(notificationMessage);
\r
1117 messageWriter.write(notificationMessage);
\r
1119 onNotification: (type, handler) => {
\r
1120 throwIfClosedOrDisposed();
\r
1121 if (Is.func(type)) {
\r
1122 starNotificationHandler = type;
\r
1124 else if (handler) {
\r
1125 if (Is.string(type)) {
\r
1126 notificationHandlers[type] = { type: undefined, handler };
\r
1129 notificationHandlers[type.method] = { type, handler };
\r
1133 onProgress: (_type, token, handler) => {
\r
1134 if (progressHandlers.has(token)) {
\r
1135 throw new Error(`Progress handler for token ${token} already registered`);
\r
1137 progressHandlers.set(token, handler);
\r
1140 progressHandlers.delete(token);
\r
1144 sendProgress: (_type, token, value) => {
\r
1145 connection.sendNotification(ProgressNotification.type, { token, value });
\r
1147 onUnhandledProgress: unhandledProgressEmitter.event,
\r
1148 sendRequest: (type, ...params) => {
\r
1149 throwIfClosedOrDisposed();
\r
1150 throwIfNotListening();
\r
1152 let messageParams;
\r
1153 let token = undefined;
\r
1154 if (Is.string(type)) {
\r
1156 switch (params.length) {
\r
1158 messageParams = null;
\r
1161 // The cancellation token is optional so it can also be undefined.
\r
1162 if (cancellation_1.CancellationToken.is(params[0])) {
\r
1163 messageParams = null;
\r
1164 token = params[0];
\r
1167 messageParams = undefinedToNull(params[0]);
\r
1171 const last = params.length - 1;
\r
1172 if (cancellation_1.CancellationToken.is(params[last])) {
\r
1173 token = params[last];
\r
1174 if (params.length === 2) {
\r
1175 messageParams = undefinedToNull(params[0]);
\r
1178 messageParams = params.slice(0, last).map(value => undefinedToNull(value));
\r
1182 messageParams = params.map(value => undefinedToNull(value));
\r
1188 method = type.method;
\r
1189 messageParams = computeMessageParams(type, params);
\r
1190 let numberOfParams = type.numberOfParams;
\r
1191 token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
\r
1193 let id = sequenceNumber++;
\r
1194 let result = new Promise((resolve, reject) => {
\r
1195 let requestMessage = {
\r
1199 params: messageParams
\r
1201 let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
\r
1202 traceSendingRequest(requestMessage);
\r
1204 messageWriter.write(requestMessage);
\r
1207 // Writing the message failed. So we need to reject the promise.
\r
1208 responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
\r
1209 responsePromise = null;
\r
1211 if (responsePromise) {
\r
1212 responsePromises[String(id)] = responsePromise;
\r
1216 token.onCancellationRequested(() => {
\r
1217 connection.sendNotification(CancelNotification.type, { id });
\r
1222 onRequest: (type, handler) => {
\r
1223 throwIfClosedOrDisposed();
\r
1224 if (Is.func(type)) {
\r
1225 starRequestHandler = type;
\r
1227 else if (handler) {
\r
1228 if (Is.string(type)) {
\r
1229 requestHandlers[type] = { type: undefined, handler };
\r
1232 requestHandlers[type.method] = { type, handler };
\r
1236 trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
\r
1237 let _sendNotification = false;
\r
1238 let _traceFormat = TraceFormat.Text;
\r
1239 if (sendNotificationOrTraceOptions !== void 0) {
\r
1240 if (Is.boolean(sendNotificationOrTraceOptions)) {
\r
1241 _sendNotification = sendNotificationOrTraceOptions;
\r
1244 _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
\r
1245 _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
\r
1249 traceFormat = _traceFormat;
\r
1250 if (trace === Trace.Off) {
\r
1251 tracer = undefined;
\r
1256 if (_sendNotification && !isClosed() && !isDisposed()) {
\r
1257 connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
\r
1260 onError: errorEmitter.event,
\r
1261 onClose: closeEmitter.event,
\r
1262 onUnhandledNotification: unhandledNotificationEmitter.event,
\r
1263 onDispose: disposeEmitter.event,
\r
1265 if (isDisposed()) {
\r
1268 state = ConnectionState.Disposed;
\r
1269 disposeEmitter.fire(undefined);
\r
1270 let error = new Error('Connection got disposed.');
\r
1271 Object.keys(responsePromises).forEach((key) => {
\r
1272 responsePromises[key].reject(error);
\r
1274 responsePromises = Object.create(null);
\r
1275 requestTokens = Object.create(null);
\r
1276 messageQueue = new linkedMap_1.LinkedMap();
\r
1277 // Test for backwards compatibility
\r
1278 if (Is.func(messageWriter.dispose)) {
\r
1279 messageWriter.dispose();
\r
1281 if (Is.func(messageReader.dispose)) {
\r
1282 messageReader.dispose();
\r
1286 throwIfClosedOrDisposed();
\r
1287 throwIfListening();
\r
1288 state = ConnectionState.Listening;
\r
1289 messageReader.listen(callback);
\r
1292 // eslint-disable-next-line no-console
\r
1293 console.log('inspect');
\r
1296 connection.onNotification(LogTraceNotification.type, (params) => {
\r
1297 if (trace === Trace.Off || !tracer) {
\r
1300 tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
\r
1302 connection.onNotification(ProgressNotification.type, (params) => {
\r
1303 const handler = progressHandlers.get(params.token);
\r
1305 handler(params.value);
\r
1308 unhandledProgressEmitter.fire(params);
\r
1311 return connection;
\r
1313 function isMessageReader(value) {
\r
1314 return value.listen !== void 0 && value.read === void 0;
\r
1316 function isMessageWriter(value) {
\r
1317 return value.write !== void 0 && value.end === void 0;
\r
1319 function createMessageConnection(input, output, logger, strategy) {
\r
1321 logger = exports.NullLogger;
\r
1323 let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
\r
1324 let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
\r
1325 return _createMessageConnection(reader, writer, logger, strategy);
\r
1327 exports.createMessageConnection = createMessageConnection;
\r
1332 /***/ (function(module, exports, __webpack_require__) {
1335 /* --------------------------------------------------------------------------------------------
\r
1336 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1337 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1338 * ------------------------------------------------------------------------------------------ */
\r
1340 Object.defineProperty(exports, "__esModule", { value: true });
\r
1341 function boolean(value) {
\r
1342 return value === true || value === false;
\r
1344 exports.boolean = boolean;
\r
1345 function string(value) {
\r
1346 return typeof value === 'string' || value instanceof String;
\r
1348 exports.string = string;
\r
1349 function number(value) {
\r
1350 return typeof value === 'number' || value instanceof Number;
\r
1352 exports.number = number;
\r
1353 function error(value) {
\r
1354 return value instanceof Error;
\r
1356 exports.error = error;
\r
1357 function func(value) {
\r
1358 return typeof value === 'function';
\r
1360 exports.func = func;
\r
1361 function array(value) {
\r
1362 return Array.isArray(value);
\r
1364 exports.array = array;
\r
1365 function stringArray(value) {
\r
1366 return array(value) && value.every(elem => string(elem));
\r
1368 exports.stringArray = stringArray;
\r
1373 /***/ (function(module, exports, __webpack_require__) {
1376 /* --------------------------------------------------------------------------------------------
\r
1377 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1378 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1379 * ------------------------------------------------------------------------------------------ */
\r
1381 Object.defineProperty(exports, "__esModule", { value: true });
\r
1382 const is = __webpack_require__(5);
\r
1384 * Predefined error codes.
\r
1387 (function (ErrorCodes) {
\r
1388 // Defined by JSON RPC
\r
1389 ErrorCodes.ParseError = -32700;
\r
1390 ErrorCodes.InvalidRequest = -32600;
\r
1391 ErrorCodes.MethodNotFound = -32601;
\r
1392 ErrorCodes.InvalidParams = -32602;
\r
1393 ErrorCodes.InternalError = -32603;
\r
1394 ErrorCodes.serverErrorStart = -32099;
\r
1395 ErrorCodes.serverErrorEnd = -32000;
\r
1396 ErrorCodes.ServerNotInitialized = -32002;
\r
1397 ErrorCodes.UnknownErrorCode = -32001;
\r
1398 // Defined by the protocol.
\r
1399 ErrorCodes.RequestCancelled = -32800;
\r
1400 ErrorCodes.ContentModified = -32801;
\r
1401 // Defined by VSCode library.
\r
1402 ErrorCodes.MessageWriteError = 1;
\r
1403 ErrorCodes.MessageReadError = 2;
\r
1404 })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
\r
1406 * An error object return in a response in case a request
\r
1409 class ResponseError extends Error {
\r
1410 constructor(code, message, data) {
\r
1412 this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
\r
1414 Object.setPrototypeOf(this, ResponseError.prototype);
\r
1419 message: this.message,
\r
1424 exports.ResponseError = ResponseError;
\r
1426 * An abstract implementation of a MessageType.
\r
1428 class AbstractMessageType {
\r
1429 constructor(_method, _numberOfParams) {
\r
1430 this._method = _method;
\r
1431 this._numberOfParams = _numberOfParams;
\r
1434 return this._method;
\r
1436 get numberOfParams() {
\r
1437 return this._numberOfParams;
\r
1440 exports.AbstractMessageType = AbstractMessageType;
\r
1442 * Classes to type request response pairs
\r
1444 * The type parameter RO will be removed in the next major version
\r
1445 * of the JSON RPC library since it is a LSP concept and doesn't
\r
1446 * belong here. For now it is tagged as default never.
\r
1448 class RequestType0 extends AbstractMessageType {
\r
1449 constructor(method) {
\r
1453 exports.RequestType0 = RequestType0;
\r
1454 class RequestType extends AbstractMessageType {
\r
1455 constructor(method) {
\r
1459 exports.RequestType = RequestType;
\r
1460 class RequestType1 extends AbstractMessageType {
\r
1461 constructor(method) {
\r
1465 exports.RequestType1 = RequestType1;
\r
1466 class RequestType2 extends AbstractMessageType {
\r
1467 constructor(method) {
\r
1471 exports.RequestType2 = RequestType2;
\r
1472 class RequestType3 extends AbstractMessageType {
\r
1473 constructor(method) {
\r
1477 exports.RequestType3 = RequestType3;
\r
1478 class RequestType4 extends AbstractMessageType {
\r
1479 constructor(method) {
\r
1483 exports.RequestType4 = RequestType4;
\r
1484 class RequestType5 extends AbstractMessageType {
\r
1485 constructor(method) {
\r
1489 exports.RequestType5 = RequestType5;
\r
1490 class RequestType6 extends AbstractMessageType {
\r
1491 constructor(method) {
\r
1495 exports.RequestType6 = RequestType6;
\r
1496 class RequestType7 extends AbstractMessageType {
\r
1497 constructor(method) {
\r
1501 exports.RequestType7 = RequestType7;
\r
1502 class RequestType8 extends AbstractMessageType {
\r
1503 constructor(method) {
\r
1507 exports.RequestType8 = RequestType8;
\r
1508 class RequestType9 extends AbstractMessageType {
\r
1509 constructor(method) {
\r
1513 exports.RequestType9 = RequestType9;
\r
1515 * The type parameter RO will be removed in the next major version
\r
1516 * of the JSON RPC library since it is a LSP concept and doesn't
\r
1517 * belong here. For now it is tagged as default never.
\r
1519 class NotificationType extends AbstractMessageType {
\r
1520 constructor(method) {
\r
1522 this._ = undefined;
\r
1525 exports.NotificationType = NotificationType;
\r
1526 class NotificationType0 extends AbstractMessageType {
\r
1527 constructor(method) {
\r
1531 exports.NotificationType0 = NotificationType0;
\r
1532 class NotificationType1 extends AbstractMessageType {
\r
1533 constructor(method) {
\r
1537 exports.NotificationType1 = NotificationType1;
\r
1538 class NotificationType2 extends AbstractMessageType {
\r
1539 constructor(method) {
\r
1543 exports.NotificationType2 = NotificationType2;
\r
1544 class NotificationType3 extends AbstractMessageType {
\r
1545 constructor(method) {
\r
1549 exports.NotificationType3 = NotificationType3;
\r
1550 class NotificationType4 extends AbstractMessageType {
\r
1551 constructor(method) {
\r
1555 exports.NotificationType4 = NotificationType4;
\r
1556 class NotificationType5 extends AbstractMessageType {
\r
1557 constructor(method) {
\r
1561 exports.NotificationType5 = NotificationType5;
\r
1562 class NotificationType6 extends AbstractMessageType {
\r
1563 constructor(method) {
\r
1567 exports.NotificationType6 = NotificationType6;
\r
1568 class NotificationType7 extends AbstractMessageType {
\r
1569 constructor(method) {
\r
1573 exports.NotificationType7 = NotificationType7;
\r
1574 class NotificationType8 extends AbstractMessageType {
\r
1575 constructor(method) {
\r
1579 exports.NotificationType8 = NotificationType8;
\r
1580 class NotificationType9 extends AbstractMessageType {
\r
1581 constructor(method) {
\r
1585 exports.NotificationType9 = NotificationType9;
\r
1587 * Tests if the given message is a request message
\r
1589 function isRequestMessage(message) {
\r
1590 let candidate = message;
\r
1591 return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
\r
1593 exports.isRequestMessage = isRequestMessage;
\r
1595 * Tests if the given message is a notification message
\r
1597 function isNotificationMessage(message) {
\r
1598 let candidate = message;
\r
1599 return candidate && is.string(candidate.method) && message.id === void 0;
\r
1601 exports.isNotificationMessage = isNotificationMessage;
\r
1603 * Tests if the given message is a response message
\r
1605 function isResponseMessage(message) {
\r
1606 let candidate = message;
\r
1607 return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
\r
1609 exports.isResponseMessage = isResponseMessage;
\r
1614 /***/ (function(module, exports, __webpack_require__) {
1617 /* --------------------------------------------------------------------------------------------
\r
1618 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1619 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1620 * ------------------------------------------------------------------------------------------ */
\r
1622 Object.defineProperty(exports, "__esModule", { value: true });
\r
1623 const events_1 = __webpack_require__(8);
\r
1624 const Is = __webpack_require__(5);
\r
1625 let DefaultSize = 8192;
\r
1626 let CR = Buffer.from('\r', 'ascii')[0];
\r
1627 let LF = Buffer.from('\n', 'ascii')[0];
\r
1628 let CRLF = '\r\n';
\r
1629 class MessageBuffer {
\r
1630 constructor(encoding = 'utf8') {
\r
1631 this.encoding = encoding;
\r
1633 this.buffer = Buffer.allocUnsafe(DefaultSize);
\r
1636 var toAppend = chunk;
\r
1637 if (typeof (chunk) === 'string') {
\r
1639 var bufferLen = Buffer.byteLength(str, this.encoding);
\r
1640 toAppend = Buffer.allocUnsafe(bufferLen);
\r
1641 toAppend.write(str, 0, bufferLen, this.encoding);
\r
1643 if (this.buffer.length - this.index >= toAppend.length) {
\r
1644 toAppend.copy(this.buffer, this.index, 0, toAppend.length);
\r
1647 var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
\r
1648 if (this.index === 0) {
\r
1649 this.buffer = Buffer.allocUnsafe(newSize);
\r
1650 toAppend.copy(this.buffer, 0, 0, toAppend.length);
\r
1653 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
\r
1656 this.index += toAppend.length;
\r
1658 tryReadHeaders() {
\r
1659 let result = undefined;
\r
1661 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
1664 // No header / body separator found (e.g CRLFCRLF)
\r
1665 if (current + 3 >= this.index) {
\r
1668 result = Object.create(null);
\r
1669 let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
\r
1670 headers.forEach((header) => {
\r
1671 let index = header.indexOf(':');
\r
1672 if (index === -1) {
\r
1673 throw new Error('Message header must separate key and value using :');
\r
1675 let key = header.substr(0, index);
\r
1676 let value = header.substr(index + 1).trim();
\r
1677 result[key] = value;
\r
1679 let nextStart = current + 4;
\r
1680 this.buffer = this.buffer.slice(nextStart);
\r
1681 this.index = this.index - nextStart;
\r
1684 tryReadContent(length) {
\r
1685 if (this.index < length) {
\r
1688 let result = this.buffer.toString(this.encoding, 0, length);
\r
1689 let nextStart = length;
\r
1690 this.buffer.copy(this.buffer, 0, nextStart);
\r
1691 this.index = this.index - nextStart;
\r
1694 get numberOfBytes() {
\r
1695 return this.index;
\r
1698 var MessageReader;
\r
1699 (function (MessageReader) {
\r
1700 function is(value) {
\r
1701 let candidate = value;
\r
1702 return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
\r
1703 Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
\r
1705 MessageReader.is = is;
\r
1706 })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
\r
1707 class AbstractMessageReader {
\r
1709 this.errorEmitter = new events_1.Emitter();
\r
1710 this.closeEmitter = new events_1.Emitter();
\r
1711 this.partialMessageEmitter = new events_1.Emitter();
\r
1714 this.errorEmitter.dispose();
\r
1715 this.closeEmitter.dispose();
\r
1718 return this.errorEmitter.event;
\r
1720 fireError(error) {
\r
1721 this.errorEmitter.fire(this.asError(error));
\r
1724 return this.closeEmitter.event;
\r
1727 this.closeEmitter.fire(undefined);
\r
1729 get onPartialMessage() {
\r
1730 return this.partialMessageEmitter.event;
\r
1732 firePartialMessage(info) {
\r
1733 this.partialMessageEmitter.fire(info);
\r
1736 if (error instanceof Error) {
\r
1740 return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
\r
1744 exports.AbstractMessageReader = AbstractMessageReader;
\r
1745 class StreamMessageReader extends AbstractMessageReader {
\r
1746 constructor(readable, encoding = 'utf8') {
\r
1748 this.readable = readable;
\r
1749 this.buffer = new MessageBuffer(encoding);
\r
1750 this._partialMessageTimeout = 10000;
\r
1752 set partialMessageTimeout(timeout) {
\r
1753 this._partialMessageTimeout = timeout;
\r
1755 get partialMessageTimeout() {
\r
1756 return this._partialMessageTimeout;
\r
1758 listen(callback) {
\r
1759 this.nextMessageLength = -1;
\r
1760 this.messageToken = 0;
\r
1761 this.partialMessageTimer = undefined;
\r
1762 this.callback = callback;
\r
1763 this.readable.on('data', (data) => {
\r
1764 this.onData(data);
\r
1766 this.readable.on('error', (error) => this.fireError(error));
\r
1767 this.readable.on('close', () => this.fireClose());
\r
1770 this.buffer.append(data);
\r
1772 if (this.nextMessageLength === -1) {
\r
1773 let headers = this.buffer.tryReadHeaders();
\r
1777 let contentLength = headers['Content-Length'];
\r
1778 if (!contentLength) {
\r
1779 throw new Error('Header must provide a Content-Length property.');
\r
1781 let length = parseInt(contentLength);
\r
1782 if (isNaN(length)) {
\r
1783 throw new Error('Content-Length value must be a number.');
\r
1785 this.nextMessageLength = length;
\r
1786 // Take the encoding form the header. For compatibility
\r
1787 // treat both utf-8 and utf8 as node utf8
\r
1789 var msg = this.buffer.tryReadContent(this.nextMessageLength);
\r
1790 if (msg === null) {
\r
1791 /** We haven't received the full message yet. */
\r
1792 this.setPartialMessageTimer();
\r
1795 this.clearPartialMessageTimer();
\r
1796 this.nextMessageLength = -1;
\r
1797 this.messageToken++;
\r
1798 var json = JSON.parse(msg);
\r
1799 this.callback(json);
\r
1802 clearPartialMessageTimer() {
\r
1803 if (this.partialMessageTimer) {
\r
1804 clearTimeout(this.partialMessageTimer);
\r
1805 this.partialMessageTimer = undefined;
\r
1808 setPartialMessageTimer() {
\r
1809 this.clearPartialMessageTimer();
\r
1810 if (this._partialMessageTimeout <= 0) {
\r
1813 this.partialMessageTimer = setTimeout((token, timeout) => {
\r
1814 this.partialMessageTimer = undefined;
\r
1815 if (token === this.messageToken) {
\r
1816 this.firePartialMessage({ messageToken: token, waitingTime: timeout });
\r
1817 this.setPartialMessageTimer();
\r
1819 }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
\r
1822 exports.StreamMessageReader = StreamMessageReader;
\r
1823 class IPCMessageReader extends AbstractMessageReader {
\r
1824 constructor(process) {
\r
1826 this.process = process;
\r
1827 let eventEmitter = this.process;
\r
1828 eventEmitter.on('error', (error) => this.fireError(error));
\r
1829 eventEmitter.on('close', () => this.fireClose());
\r
1831 listen(callback) {
\r
1832 this.process.on('message', callback);
\r
1835 exports.IPCMessageReader = IPCMessageReader;
\r
1836 class SocketMessageReader extends StreamMessageReader {
\r
1837 constructor(socket, encoding = 'utf-8') {
\r
1838 super(socket, encoding);
\r
1841 exports.SocketMessageReader = SocketMessageReader;
\r
1846 /***/ (function(module, exports, __webpack_require__) {
1849 /* --------------------------------------------------------------------------------------------
\r
1850 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1851 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1852 * ------------------------------------------------------------------------------------------ */
\r
1854 Object.defineProperty(exports, "__esModule", { value: true });
\r
1856 (function (Disposable) {
\r
1857 function create(func) {
\r
1862 Disposable.create = create;
\r
1863 })(Disposable = exports.Disposable || (exports.Disposable = {}));
\r
1865 (function (Event) {
\r
1866 const _disposable = { dispose() { } };
\r
1867 Event.None = function () { return _disposable; };
\r
1868 })(Event = exports.Event || (exports.Event = {}));
\r
1869 class CallbackList {
\r
1870 add(callback, context = null, bucket) {
\r
1871 if (!this._callbacks) {
\r
1872 this._callbacks = [];
\r
1873 this._contexts = [];
\r
1875 this._callbacks.push(callback);
\r
1876 this._contexts.push(context);
\r
1877 if (Array.isArray(bucket)) {
\r
1878 bucket.push({ dispose: () => this.remove(callback, context) });
\r
1881 remove(callback, context = null) {
\r
1882 if (!this._callbacks) {
\r
1885 var foundCallbackWithDifferentContext = false;
\r
1886 for (var i = 0, len = this._callbacks.length; i < len; i++) {
\r
1887 if (this._callbacks[i] === callback) {
\r
1888 if (this._contexts[i] === context) {
\r
1889 // callback & context match => remove it
\r
1890 this._callbacks.splice(i, 1);
\r
1891 this._contexts.splice(i, 1);
\r
1895 foundCallbackWithDifferentContext = true;
\r
1899 if (foundCallbackWithDifferentContext) {
\r
1900 throw new Error('When adding a listener with a context, you should remove it with the same context');
\r
1904 if (!this._callbacks) {
\r
1907 var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
\r
1908 for (var i = 0, len = callbacks.length; i < len; i++) {
\r
1910 ret.push(callbacks[i].apply(contexts[i], args));
\r
1913 // eslint-disable-next-line no-console
\r
1920 return !this._callbacks || this._callbacks.length === 0;
\r
1923 this._callbacks = undefined;
\r
1924 this._contexts = undefined;
\r
1928 constructor(_options) {
\r
1929 this._options = _options;
\r
1932 * For the public to allow to subscribe
\r
1933 * to events from this Emitter
\r
1936 if (!this._event) {
\r
1937 this._event = (listener, thisArgs, disposables) => {
\r
1938 if (!this._callbacks) {
\r
1939 this._callbacks = new CallbackList();
\r
1941 if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
\r
1942 this._options.onFirstListenerAdd(this);
\r
1944 this._callbacks.add(listener, thisArgs);
\r
1948 this._callbacks.remove(listener, thisArgs);
\r
1949 result.dispose = Emitter._noop;
\r
1950 if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
\r
1951 this._options.onLastListenerRemove(this);
\r
1955 if (Array.isArray(disposables)) {
\r
1956 disposables.push(result);
\r
1961 return this._event;
\r
1964 * To be kept private to fire an event to
\r
1968 if (this._callbacks) {
\r
1969 this._callbacks.invoke.call(this._callbacks, event);
\r
1973 if (this._callbacks) {
\r
1974 this._callbacks.dispose();
\r
1975 this._callbacks = undefined;
\r
1979 exports.Emitter = Emitter;
\r
1980 Emitter._noop = function () { };
\r
1985 /***/ (function(module, exports, __webpack_require__) {
1988 /* --------------------------------------------------------------------------------------------
\r
1989 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1990 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1991 * ------------------------------------------------------------------------------------------ */
\r
1993 Object.defineProperty(exports, "__esModule", { value: true });
\r
1994 const events_1 = __webpack_require__(8);
\r
1995 const Is = __webpack_require__(5);
\r
1996 let ContentLength = 'Content-Length: ';
\r
1997 let CRLF = '\r\n';
\r
1998 var MessageWriter;
\r
1999 (function (MessageWriter) {
\r
2000 function is(value) {
\r
2001 let candidate = value;
\r
2002 return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
\r
2003 Is.func(candidate.onError) && Is.func(candidate.write);
\r
2005 MessageWriter.is = is;
\r
2006 })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
\r
2007 class AbstractMessageWriter {
\r
2009 this.errorEmitter = new events_1.Emitter();
\r
2010 this.closeEmitter = new events_1.Emitter();
\r
2013 this.errorEmitter.dispose();
\r
2014 this.closeEmitter.dispose();
\r
2017 return this.errorEmitter.event;
\r
2019 fireError(error, message, count) {
\r
2020 this.errorEmitter.fire([this.asError(error), message, count]);
\r
2023 return this.closeEmitter.event;
\r
2026 this.closeEmitter.fire(undefined);
\r
2029 if (error instanceof Error) {
\r
2033 return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
\r
2037 exports.AbstractMessageWriter = AbstractMessageWriter;
\r
2038 class StreamMessageWriter extends AbstractMessageWriter {
\r
2039 constructor(writable, encoding = 'utf8') {
\r
2041 this.writable = writable;
\r
2042 this.encoding = encoding;
\r
2043 this.errorCount = 0;
\r
2044 this.writable.on('error', (error) => this.fireError(error));
\r
2045 this.writable.on('close', () => this.fireClose());
\r
2048 let json = JSON.stringify(msg);
\r
2049 let contentLength = Buffer.byteLength(json, this.encoding);
\r
2051 ContentLength, contentLength.toString(), CRLF,
\r
2055 // Header must be written in ASCII encoding
\r
2056 this.writable.write(headers.join(''), 'ascii');
\r
2057 // Now write the content. This can be written in any encoding
\r
2058 this.writable.write(json, this.encoding);
\r
2059 this.errorCount = 0;
\r
2062 this.errorCount++;
\r
2063 this.fireError(error, msg, this.errorCount);
\r
2067 exports.StreamMessageWriter = StreamMessageWriter;
\r
2068 class IPCMessageWriter extends AbstractMessageWriter {
\r
2069 constructor(process) {
\r
2071 this.process = process;
\r
2072 this.errorCount = 0;
\r
2074 this.sending = false;
\r
2075 let eventEmitter = this.process;
\r
2076 eventEmitter.on('error', (error) => this.fireError(error));
\r
2077 eventEmitter.on('close', () => this.fireClose);
\r
2080 if (!this.sending && this.queue.length === 0) {
\r
2081 // See https://github.com/nodejs/node/issues/7657
\r
2082 this.doWriteMessage(msg);
\r
2085 this.queue.push(msg);
\r
2088 doWriteMessage(msg) {
\r
2090 if (this.process.send) {
\r
2091 this.sending = true;
\r
2092 this.process.send(msg, undefined, undefined, (error) => {
\r
2093 this.sending = false;
\r
2095 this.errorCount++;
\r
2096 this.fireError(error, msg, this.errorCount);
\r
2099 this.errorCount = 0;
\r
2101 if (this.queue.length > 0) {
\r
2102 this.doWriteMessage(this.queue.shift());
\r
2108 this.errorCount++;
\r
2109 this.fireError(error, msg, this.errorCount);
\r
2113 exports.IPCMessageWriter = IPCMessageWriter;
\r
2114 class SocketMessageWriter extends AbstractMessageWriter {
\r
2115 constructor(socket, encoding = 'utf8') {
\r
2117 this.socket = socket;
\r
2119 this.sending = false;
\r
2120 this.encoding = encoding;
\r
2121 this.errorCount = 0;
\r
2122 this.socket.on('error', (error) => this.fireError(error));
\r
2123 this.socket.on('close', () => this.fireClose());
\r
2127 this.socket.destroy();
\r
2130 if (!this.sending && this.queue.length === 0) {
\r
2131 // See https://github.com/nodejs/node/issues/7657
\r
2132 this.doWriteMessage(msg);
\r
2135 this.queue.push(msg);
\r
2138 doWriteMessage(msg) {
\r
2139 let json = JSON.stringify(msg);
\r
2140 let contentLength = Buffer.byteLength(json, this.encoding);
\r
2142 ContentLength, contentLength.toString(), CRLF,
\r
2146 // Header must be written in ASCII encoding
\r
2147 this.sending = true;
\r
2148 this.socket.write(headers.join(''), 'ascii', (error) => {
\r
2150 this.handleError(error, msg);
\r
2153 // Now write the content. This can be written in any encoding
\r
2154 this.socket.write(json, this.encoding, (error) => {
\r
2155 this.sending = false;
\r
2157 this.handleError(error, msg);
\r
2160 this.errorCount = 0;
\r
2162 if (this.queue.length > 0) {
\r
2163 this.doWriteMessage(this.queue.shift());
\r
2168 this.handleError(error, msg);
\r
2173 this.handleError(error, msg);
\r
2176 handleError(error, msg) {
\r
2177 this.errorCount++;
\r
2178 this.fireError(error, msg, this.errorCount);
\r
2181 exports.SocketMessageWriter = SocketMessageWriter;
\r
2186 /***/ (function(module, exports, __webpack_require__) {
2189 /*---------------------------------------------------------------------------------------------
\r
2190 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2191 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2192 *--------------------------------------------------------------------------------------------*/
\r
2194 Object.defineProperty(exports, "__esModule", { value: true });
\r
2195 const events_1 = __webpack_require__(8);
\r
2196 const Is = __webpack_require__(5);
\r
2197 var CancellationToken;
\r
2198 (function (CancellationToken) {
\r
2199 CancellationToken.None = Object.freeze({
\r
2200 isCancellationRequested: false,
\r
2201 onCancellationRequested: events_1.Event.None
\r
2203 CancellationToken.Cancelled = Object.freeze({
\r
2204 isCancellationRequested: true,
\r
2205 onCancellationRequested: events_1.Event.None
\r
2207 function is(value) {
\r
2208 let candidate = value;
\r
2209 return candidate && (candidate === CancellationToken.None
\r
2210 || candidate === CancellationToken.Cancelled
\r
2211 || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
\r
2213 CancellationToken.is = is;
\r
2214 })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
\r
2215 const shortcutEvent = Object.freeze(function (callback, context) {
\r
2216 let handle = setTimeout(callback.bind(context), 0);
\r
2217 return { dispose() { clearTimeout(handle); } };
\r
2219 class MutableToken {
\r
2221 this._isCancelled = false;
\r
2224 if (!this._isCancelled) {
\r
2225 this._isCancelled = true;
\r
2226 if (this._emitter) {
\r
2227 this._emitter.fire(undefined);
\r
2232 get isCancellationRequested() {
\r
2233 return this._isCancelled;
\r
2235 get onCancellationRequested() {
\r
2236 if (this._isCancelled) {
\r
2237 return shortcutEvent;
\r
2239 if (!this._emitter) {
\r
2240 this._emitter = new events_1.Emitter();
\r
2242 return this._emitter.event;
\r
2245 if (this._emitter) {
\r
2246 this._emitter.dispose();
\r
2247 this._emitter = undefined;
\r
2251 class CancellationTokenSource {
\r
2253 if (!this._token) {
\r
2254 // be lazy and create the token only when
\r
2255 // actually needed
\r
2256 this._token = new MutableToken();
\r
2258 return this._token;
\r
2261 if (!this._token) {
\r
2262 // save an object by returning the default
\r
2263 // cancelled token when cancellation happens
\r
2264 // before someone asks for the token
\r
2265 this._token = CancellationToken.Cancelled;
\r
2268 this._token.cancel();
\r
2272 if (!this._token) {
\r
2273 // ensure to initialize with an empty token if we had none
\r
2274 this._token = CancellationToken.None;
\r
2276 else if (this._token instanceof MutableToken) {
\r
2277 // actually dispose
\r
2278 this._token.dispose();
\r
2282 exports.CancellationTokenSource = CancellationTokenSource;
\r
2287 /***/ (function(module, exports, __webpack_require__) {
2291 /*---------------------------------------------------------------------------------------------
\r
2292 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2293 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2294 *--------------------------------------------------------------------------------------------*/
\r
2295 Object.defineProperty(exports, "__esModule", { value: true });
\r
2297 (function (Touch) {
\r
2301 })(Touch = exports.Touch || (exports.Touch = {}));
\r
2304 this._map = new Map();
\r
2305 this._head = undefined;
\r
2306 this._tail = undefined;
\r
2310 this._map.clear();
\r
2311 this._head = undefined;
\r
2312 this._tail = undefined;
\r
2316 return !this._head && !this._tail;
\r
2319 return this._size;
\r
2322 return this._map.has(key);
\r
2325 const item = this._map.get(key);
\r
2329 return item.value;
\r
2331 set(key, value, touch = Touch.None) {
\r
2332 let item = this._map.get(key);
\r
2334 item.value = value;
\r
2335 if (touch !== Touch.None) {
\r
2336 this.touch(item, touch);
\r
2340 item = { key, value, next: undefined, previous: undefined };
\r
2343 this.addItemLast(item);
\r
2346 this.addItemFirst(item);
\r
2349 this.addItemLast(item);
\r
2352 this.addItemLast(item);
\r
2355 this._map.set(key, item);
\r
2360 const item = this._map.get(key);
\r
2364 this._map.delete(key);
\r
2365 this.removeItem(item);
\r
2370 if (!this._head && !this._tail) {
\r
2373 if (!this._head || !this._tail) {
\r
2374 throw new Error('Invalid list');
\r
2376 const item = this._head;
\r
2377 this._map.delete(item.key);
\r
2378 this.removeItem(item);
\r
2380 return item.value;
\r
2382 forEach(callbackfn, thisArg) {
\r
2383 let current = this._head;
\r
2386 callbackfn.bind(thisArg)(current.value, current.key, this);
\r
2389 callbackfn(current.value, current.key, this);
\r
2391 current = current.next;
\r
2394 forEachReverse(callbackfn, thisArg) {
\r
2395 let current = this._tail;
\r
2398 callbackfn.bind(thisArg)(current.value, current.key, this);
\r
2401 callbackfn(current.value, current.key, this);
\r
2403 current = current.previous;
\r
2408 let current = this._head;
\r
2410 result.push(current.value);
\r
2411 current = current.next;
\r
2417 let current = this._head;
\r
2419 result.push(current.key);
\r
2420 current = current.next;
\r
2424 /* JSON RPC run on es5 which has no Symbol.iterator
\r
2425 public keys(): IterableIterator<K> {
\r
2426 let current = this._head;
\r
2427 let iterator: IterableIterator<K> = {
\r
2428 [Symbol.iterator]() {
\r
2431 next():IteratorResult<K> {
\r
2433 let result = { value: current.key, done: false };
\r
2434 current = current.next;
\r
2437 return { value: undefined, done: true };
\r
2444 public values(): IterableIterator<V> {
\r
2445 let current = this._head;
\r
2446 let iterator: IterableIterator<V> = {
\r
2447 [Symbol.iterator]() {
\r
2450 next():IteratorResult<V> {
\r
2452 let result = { value: current.value, done: false };
\r
2453 current = current.next;
\r
2456 return { value: undefined, done: true };
\r
2463 addItemFirst(item) {
\r
2464 // First time Insert
\r
2465 if (!this._head && !this._tail) {
\r
2466 this._tail = item;
\r
2468 else if (!this._head) {
\r
2469 throw new Error('Invalid list');
\r
2472 item.next = this._head;
\r
2473 this._head.previous = item;
\r
2475 this._head = item;
\r
2477 addItemLast(item) {
\r
2478 // First time Insert
\r
2479 if (!this._head && !this._tail) {
\r
2480 this._head = item;
\r
2482 else if (!this._tail) {
\r
2483 throw new Error('Invalid list');
\r
2486 item.previous = this._tail;
\r
2487 this._tail.next = item;
\r
2489 this._tail = item;
\r
2491 removeItem(item) {
\r
2492 if (item === this._head && item === this._tail) {
\r
2493 this._head = undefined;
\r
2494 this._tail = undefined;
\r
2496 else if (item === this._head) {
\r
2497 this._head = item.next;
\r
2499 else if (item === this._tail) {
\r
2500 this._tail = item.previous;
\r
2503 const next = item.next;
\r
2504 const previous = item.previous;
\r
2505 if (!next || !previous) {
\r
2506 throw new Error('Invalid list');
\r
2508 next.previous = previous;
\r
2509 previous.next = next;
\r
2512 touch(item, touch) {
\r
2513 if (!this._head || !this._tail) {
\r
2514 throw new Error('Invalid list');
\r
2516 if ((touch !== Touch.First && touch !== Touch.Last)) {
\r
2519 if (touch === Touch.First) {
\r
2520 if (item === this._head) {
\r
2523 const next = item.next;
\r
2524 const previous = item.previous;
\r
2525 // Unlink the item
\r
2526 if (item === this._tail) {
\r
2527 // previous must be defined since item was not head but is tail
\r
2528 // So there are more than on item in the map
\r
2529 previous.next = undefined;
\r
2530 this._tail = previous;
\r
2533 // Both next and previous are not undefined since item was neither head nor tail.
\r
2534 next.previous = previous;
\r
2535 previous.next = next;
\r
2537 // Insert the node at head
\r
2538 item.previous = undefined;
\r
2539 item.next = this._head;
\r
2540 this._head.previous = item;
\r
2541 this._head = item;
\r
2543 else if (touch === Touch.Last) {
\r
2544 if (item === this._tail) {
\r
2547 const next = item.next;
\r
2548 const previous = item.previous;
\r
2549 // Unlink the item.
\r
2550 if (item === this._head) {
\r
2551 // next must be defined since item was not tail but is head
\r
2552 // So there are more than on item in the map
\r
2553 next.previous = undefined;
\r
2554 this._head = next;
\r
2557 // Both next and previous are not undefined since item was neither head nor tail.
\r
2558 next.previous = previous;
\r
2559 previous.next = next;
\r
2561 item.next = undefined;
\r
2562 item.previous = this._tail;
\r
2563 this._tail.next = item;
\r
2564 this._tail = item;
\r
2568 exports.LinkedMap = LinkedMap;
\r
2573 /***/ (function(module, exports, __webpack_require__) {
2576 /* --------------------------------------------------------------------------------------------
\r
2577 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2578 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2579 * ------------------------------------------------------------------------------------------ */
\r
2581 Object.defineProperty(exports, "__esModule", { value: true });
\r
2582 const path_1 = __webpack_require__(13);
\r
2583 const os_1 = __webpack_require__(14);
\r
2584 const crypto_1 = __webpack_require__(15);
\r
2585 const net_1 = __webpack_require__(16);
\r
2586 const messageReader_1 = __webpack_require__(7);
\r
2587 const messageWriter_1 = __webpack_require__(9);
\r
2588 function generateRandomPipeName() {
\r
2589 const randomSuffix = crypto_1.randomBytes(21).toString('hex');
\r
2590 if (process.platform === 'win32') {
\r
2591 return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
\r
2594 // Mac/Unix: use socket file
\r
2595 return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
\r
2598 exports.generateRandomPipeName = generateRandomPipeName;
\r
2599 function createClientPipeTransport(pipeName, encoding = 'utf-8') {
\r
2600 let connectResolve;
\r
2601 let connected = new Promise((resolve, _reject) => {
\r
2602 connectResolve = resolve;
\r
2604 return new Promise((resolve, reject) => {
\r
2605 let server = net_1.createServer((socket) => {
\r
2608 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2609 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2612 server.on('error', reject);
\r
2613 server.listen(pipeName, () => {
\r
2614 server.removeListener('error', reject);
\r
2616 onConnected: () => { return connected; }
\r
2621 exports.createClientPipeTransport = createClientPipeTransport;
\r
2622 function createServerPipeTransport(pipeName, encoding = 'utf-8') {
\r
2623 const socket = net_1.createConnection(pipeName);
\r
2625 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2626 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2629 exports.createServerPipeTransport = createServerPipeTransport;
\r
2634 /***/ (function(module, exports) {
2636 module.exports = require("path");
2640 /***/ (function(module, exports) {
2642 module.exports = require("os");
2646 /***/ (function(module, exports) {
2648 module.exports = require("crypto");
2652 /***/ (function(module, exports) {
2654 module.exports = require("net");
2658 /***/ (function(module, exports, __webpack_require__) {
2661 /* --------------------------------------------------------------------------------------------
\r
2662 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2663 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2664 * ------------------------------------------------------------------------------------------ */
\r
2666 Object.defineProperty(exports, "__esModule", { value: true });
\r
2667 const net_1 = __webpack_require__(16);
\r
2668 const messageReader_1 = __webpack_require__(7);
\r
2669 const messageWriter_1 = __webpack_require__(9);
\r
2670 function createClientSocketTransport(port, encoding = 'utf-8') {
\r
2671 let connectResolve;
\r
2672 let connected = new Promise((resolve, _reject) => {
\r
2673 connectResolve = resolve;
\r
2675 return new Promise((resolve, reject) => {
\r
2676 let server = net_1.createServer((socket) => {
\r
2679 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2680 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2683 server.on('error', reject);
\r
2684 server.listen(port, '127.0.0.1', () => {
\r
2685 server.removeListener('error', reject);
\r
2687 onConnected: () => { return connected; }
\r
2692 exports.createClientSocketTransport = createClientSocketTransport;
\r
2693 function createServerSocketTransport(port, encoding = 'utf-8') {
\r
2694 const socket = net_1.createConnection(port, '127.0.0.1');
\r
2696 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2697 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2700 exports.createServerSocketTransport = createServerSocketTransport;
\r
2705 /***/ (function(module, __webpack_exports__, __webpack_require__) {
2708 __webpack_require__.r(__webpack_exports__);
2709 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
2710 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
2711 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
2712 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
2713 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
2714 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
2715 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
2716 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
2717 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
2718 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
2719 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
2720 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
2721 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
2722 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
2723 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
2724 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
2725 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
2726 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
2727 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
2728 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
2729 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
2730 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
2731 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
2732 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
2733 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
2734 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
2735 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
2736 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
2737 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
2738 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
2739 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
2740 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
2741 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
2742 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
2743 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
2744 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
2745 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
2746 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
2747 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
2748 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
2749 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
2750 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
2751 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
2752 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
2753 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
2754 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
2755 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
2756 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
2757 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
2758 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
2759 /* --------------------------------------------------------------------------------------------
\r
2760 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2761 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2762 * ------------------------------------------------------------------------------------------ */
\r
2765 * The Position namespace provides helper functions to work with
\r
2766 * [Position](#Position) literals.
\r
2769 (function (Position) {
\r
2771 * Creates a new Position literal from the given line and character.
\r
2772 * @param line The position's line.
\r
2773 * @param character The position's character.
\r
2775 function create(line, character) {
\r
2776 return { line: line, character: character };
\r
2778 Position.create = create;
\r
2780 * Checks whether the given liternal conforms to the [Position](#Position) interface.
\r
2782 function is(value) {
\r
2783 var candidate = value;
\r
2784 return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
\r
2787 })(Position || (Position = {}));
\r
2789 * The Range namespace provides helper functions to work with
\r
2790 * [Range](#Range) literals.
\r
2793 (function (Range) {
\r
2794 function create(one, two, three, four) {
\r
2795 if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
\r
2796 return { start: Position.create(one, two), end: Position.create(three, four) };
\r
2798 else if (Position.is(one) && Position.is(two)) {
\r
2799 return { start: one, end: two };
\r
2802 throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
\r
2805 Range.create = create;
\r
2807 * Checks whether the given literal conforms to the [Range](#Range) interface.
\r
2809 function is(value) {
\r
2810 var candidate = value;
\r
2811 return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
\r
2814 })(Range || (Range = {}));
\r
2816 * The Location namespace provides helper functions to work with
\r
2817 * [Location](#Location) literals.
\r
2820 (function (Location) {
\r
2822 * Creates a Location literal.
\r
2823 * @param uri The location's uri.
\r
2824 * @param range The location's range.
\r
2826 function create(uri, range) {
\r
2827 return { uri: uri, range: range };
\r
2829 Location.create = create;
\r
2831 * Checks whether the given literal conforms to the [Location](#Location) interface.
\r
2833 function is(value) {
\r
2834 var candidate = value;
\r
2835 return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
\r
2838 })(Location || (Location = {}));
\r
2840 * The LocationLink namespace provides helper functions to work with
\r
2841 * [LocationLink](#LocationLink) literals.
\r
2844 (function (LocationLink) {
\r
2846 * Creates a LocationLink literal.
\r
2847 * @param targetUri The definition's uri.
\r
2848 * @param targetRange The full range of the definition.
\r
2849 * @param targetSelectionRange The span of the symbol definition at the target.
\r
2850 * @param originSelectionRange The span of the symbol being defined in the originating source file.
\r
2852 function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
\r
2853 return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
\r
2855 LocationLink.create = create;
\r
2857 * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
\r
2859 function is(value) {
\r
2860 var candidate = value;
\r
2861 return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
\r
2862 && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
\r
2863 && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
\r
2865 LocationLink.is = is;
\r
2866 })(LocationLink || (LocationLink = {}));
\r
2868 * The Color namespace provides helper functions to work with
\r
2869 * [Color](#Color) literals.
\r
2872 (function (Color) {
\r
2874 * Creates a new Color literal.
\r
2876 function create(red, green, blue, alpha) {
\r
2884 Color.create = create;
\r
2886 * Checks whether the given literal conforms to the [Color](#Color) interface.
\r
2888 function is(value) {
\r
2889 var candidate = value;
\r
2890 return Is.number(candidate.red)
\r
2891 && Is.number(candidate.green)
\r
2892 && Is.number(candidate.blue)
\r
2893 && Is.number(candidate.alpha);
\r
2896 })(Color || (Color = {}));
\r
2898 * The ColorInformation namespace provides helper functions to work with
\r
2899 * [ColorInformation](#ColorInformation) literals.
\r
2901 var ColorInformation;
\r
2902 (function (ColorInformation) {
\r
2904 * Creates a new ColorInformation literal.
\r
2906 function create(range, color) {
\r
2912 ColorInformation.create = create;
\r
2914 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
2916 function is(value) {
\r
2917 var candidate = value;
\r
2918 return Range.is(candidate.range) && Color.is(candidate.color);
\r
2920 ColorInformation.is = is;
\r
2921 })(ColorInformation || (ColorInformation = {}));
\r
2923 * The Color namespace provides helper functions to work with
\r
2924 * [ColorPresentation](#ColorPresentation) literals.
\r
2926 var ColorPresentation;
\r
2927 (function (ColorPresentation) {
\r
2929 * Creates a new ColorInformation literal.
\r
2931 function create(label, textEdit, additionalTextEdits) {
\r
2934 textEdit: textEdit,
\r
2935 additionalTextEdits: additionalTextEdits,
\r
2938 ColorPresentation.create = create;
\r
2940 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
2942 function is(value) {
\r
2943 var candidate = value;
\r
2944 return Is.string(candidate.label)
\r
2945 && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
\r
2946 && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
\r
2948 ColorPresentation.is = is;
\r
2949 })(ColorPresentation || (ColorPresentation = {}));
\r
2951 * Enum of known range kinds
\r
2953 var FoldingRangeKind;
\r
2954 (function (FoldingRangeKind) {
\r
2956 * Folding range for a comment
\r
2958 FoldingRangeKind["Comment"] = "comment";
\r
2960 * Folding range for a imports or includes
\r
2962 FoldingRangeKind["Imports"] = "imports";
\r
2964 * Folding range for a region (e.g. `#region`)
\r
2966 FoldingRangeKind["Region"] = "region";
\r
2967 })(FoldingRangeKind || (FoldingRangeKind = {}));
\r
2969 * The folding range namespace provides helper functions to work with
\r
2970 * [FoldingRange](#FoldingRange) literals.
\r
2973 (function (FoldingRange) {
\r
2975 * Creates a new FoldingRange literal.
\r
2977 function create(startLine, endLine, startCharacter, endCharacter, kind) {
\r
2979 startLine: startLine,
\r
2982 if (Is.defined(startCharacter)) {
\r
2983 result.startCharacter = startCharacter;
\r
2985 if (Is.defined(endCharacter)) {
\r
2986 result.endCharacter = endCharacter;
\r
2988 if (Is.defined(kind)) {
\r
2989 result.kind = kind;
\r
2993 FoldingRange.create = create;
\r
2995 * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
\r
2997 function is(value) {
\r
2998 var candidate = value;
\r
2999 return Is.number(candidate.startLine) && Is.number(candidate.startLine)
\r
3000 && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
\r
3001 && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
\r
3002 && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
\r
3004 FoldingRange.is = is;
\r
3005 })(FoldingRange || (FoldingRange = {}));
\r
3007 * The DiagnosticRelatedInformation namespace provides helper functions to work with
\r
3008 * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
\r
3010 var DiagnosticRelatedInformation;
\r
3011 (function (DiagnosticRelatedInformation) {
\r
3013 * Creates a new DiagnosticRelatedInformation literal.
\r
3015 function create(location, message) {
\r
3017 location: location,
\r
3021 DiagnosticRelatedInformation.create = create;
\r
3023 * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
\r
3025 function is(value) {
\r
3026 var candidate = value;
\r
3027 return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
\r
3029 DiagnosticRelatedInformation.is = is;
\r
3030 })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
\r
3032 * The diagnostic's severity.
\r
3034 var DiagnosticSeverity;
\r
3035 (function (DiagnosticSeverity) {
\r
3037 * Reports an error.
\r
3039 DiagnosticSeverity.Error = 1;
\r
3041 * Reports a warning.
\r
3043 DiagnosticSeverity.Warning = 2;
\r
3045 * Reports an information.
\r
3047 DiagnosticSeverity.Information = 3;
\r
3051 DiagnosticSeverity.Hint = 4;
\r
3052 })(DiagnosticSeverity || (DiagnosticSeverity = {}));
\r
3054 * The diagnostic tags.
\r
3058 var DiagnosticTag;
\r
3059 (function (DiagnosticTag) {
\r
3061 * Unused or unnecessary code.
\r
3063 * Clients are allowed to render diagnostics with this tag faded out instead of having
\r
3064 * an error squiggle.
\r
3066 DiagnosticTag.Unnecessary = 1;
\r
3068 * Deprecated or obsolete code.
\r
3070 * Clients are allowed to rendered diagnostics with this tag strike through.
\r
3072 DiagnosticTag.Deprecated = 2;
\r
3073 })(DiagnosticTag || (DiagnosticTag = {}));
\r
3075 * The Diagnostic namespace provides helper functions to work with
\r
3076 * [Diagnostic](#Diagnostic) literals.
\r
3079 (function (Diagnostic) {
\r
3081 * Creates a new Diagnostic literal.
\r
3083 function create(range, message, severity, code, source, relatedInformation) {
\r
3084 var result = { range: range, message: message };
\r
3085 if (Is.defined(severity)) {
\r
3086 result.severity = severity;
\r
3088 if (Is.defined(code)) {
\r
3089 result.code = code;
\r
3091 if (Is.defined(source)) {
\r
3092 result.source = source;
\r
3094 if (Is.defined(relatedInformation)) {
\r
3095 result.relatedInformation = relatedInformation;
\r
3099 Diagnostic.create = create;
\r
3101 * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
\r
3103 function is(value) {
\r
3104 var candidate = value;
\r
3105 return Is.defined(candidate)
\r
3106 && Range.is(candidate.range)
\r
3107 && Is.string(candidate.message)
\r
3108 && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
\r
3109 && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
\r
3110 && (Is.string(candidate.source) || Is.undefined(candidate.source))
\r
3111 && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
\r
3113 Diagnostic.is = is;
\r
3114 })(Diagnostic || (Diagnostic = {}));
\r
3116 * The Command namespace provides helper functions to work with
\r
3117 * [Command](#Command) literals.
\r
3120 (function (Command) {
\r
3122 * Creates a new Command literal.
\r
3124 function create(title, command) {
\r
3126 for (var _i = 2; _i < arguments.length; _i++) {
\r
3127 args[_i - 2] = arguments[_i];
\r
3129 var result = { title: title, command: command };
\r
3130 if (Is.defined(args) && args.length > 0) {
\r
3131 result.arguments = args;
\r
3135 Command.create = create;
\r
3137 * Checks whether the given literal conforms to the [Command](#Command) interface.
\r
3139 function is(value) {
\r
3140 var candidate = value;
\r
3141 return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
\r
3144 })(Command || (Command = {}));
\r
3146 * The TextEdit namespace provides helper function to create replace,
\r
3147 * insert and delete edits more easily.
\r
3150 (function (TextEdit) {
\r
3152 * Creates a replace text edit.
\r
3153 * @param range The range of text to be replaced.
\r
3154 * @param newText The new text.
\r
3156 function replace(range, newText) {
\r
3157 return { range: range, newText: newText };
\r
3159 TextEdit.replace = replace;
\r
3161 * Creates a insert text edit.
\r
3162 * @param position The position to insert the text at.
\r
3163 * @param newText The text to be inserted.
\r
3165 function insert(position, newText) {
\r
3166 return { range: { start: position, end: position }, newText: newText };
\r
3168 TextEdit.insert = insert;
\r
3170 * Creates a delete text edit.
\r
3171 * @param range The range of text to be deleted.
\r
3173 function del(range) {
\r
3174 return { range: range, newText: '' };
\r
3176 TextEdit.del = del;
\r
3177 function is(value) {
\r
3178 var candidate = value;
\r
3179 return Is.objectLiteral(candidate)
\r
3180 && Is.string(candidate.newText)
\r
3181 && Range.is(candidate.range);
\r
3184 })(TextEdit || (TextEdit = {}));
\r
3186 * The TextDocumentEdit namespace provides helper function to create
\r
3187 * an edit that manipulates a text document.
\r
3189 var TextDocumentEdit;
\r
3190 (function (TextDocumentEdit) {
\r
3192 * Creates a new `TextDocumentEdit`
\r
3194 function create(textDocument, edits) {
\r
3195 return { textDocument: textDocument, edits: edits };
\r
3197 TextDocumentEdit.create = create;
\r
3198 function is(value) {
\r
3199 var candidate = value;
\r
3200 return Is.defined(candidate)
\r
3201 && VersionedTextDocumentIdentifier.is(candidate.textDocument)
\r
3202 && Array.isArray(candidate.edits);
\r
3204 TextDocumentEdit.is = is;
\r
3205 })(TextDocumentEdit || (TextDocumentEdit = {}));
\r
3207 (function (CreateFile) {
\r
3208 function create(uri, options) {
\r
3213 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
3214 result.options = options;
\r
3218 CreateFile.create = create;
\r
3219 function is(value) {
\r
3220 var candidate = value;
\r
3221 return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
\r
3222 (candidate.options === void 0 ||
\r
3223 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
3225 CreateFile.is = is;
\r
3226 })(CreateFile || (CreateFile = {}));
\r
3228 (function (RenameFile) {
\r
3229 function create(oldUri, newUri, options) {
\r
3235 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
3236 result.options = options;
\r
3240 RenameFile.create = create;
\r
3241 function is(value) {
\r
3242 var candidate = value;
\r
3243 return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
\r
3244 (candidate.options === void 0 ||
\r
3245 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
3247 RenameFile.is = is;
\r
3248 })(RenameFile || (RenameFile = {}));
\r
3250 (function (DeleteFile) {
\r
3251 function create(uri, options) {
\r
3256 if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
\r
3257 result.options = options;
\r
3261 DeleteFile.create = create;
\r
3262 function is(value) {
\r
3263 var candidate = value;
\r
3264 return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
\r
3265 (candidate.options === void 0 ||
\r
3266 ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
\r
3268 DeleteFile.is = is;
\r
3269 })(DeleteFile || (DeleteFile = {}));
\r
3270 var WorkspaceEdit;
\r
3271 (function (WorkspaceEdit) {
\r
3272 function is(value) {
\r
3273 var candidate = value;
\r
3274 return candidate &&
\r
3275 (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
\r
3276 (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
\r
3277 if (Is.string(change.kind)) {
\r
3278 return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
\r
3281 return TextDocumentEdit.is(change);
\r
3285 WorkspaceEdit.is = is;
\r
3286 })(WorkspaceEdit || (WorkspaceEdit = {}));
\r
3287 var TextEditChangeImpl = /** @class */ (function () {
\r
3288 function TextEditChangeImpl(edits) {
\r
3289 this.edits = edits;
\r
3291 TextEditChangeImpl.prototype.insert = function (position, newText) {
\r
3292 this.edits.push(TextEdit.insert(position, newText));
\r
3294 TextEditChangeImpl.prototype.replace = function (range, newText) {
\r
3295 this.edits.push(TextEdit.replace(range, newText));
\r
3297 TextEditChangeImpl.prototype.delete = function (range) {
\r
3298 this.edits.push(TextEdit.del(range));
\r
3300 TextEditChangeImpl.prototype.add = function (edit) {
\r
3301 this.edits.push(edit);
\r
3303 TextEditChangeImpl.prototype.all = function () {
\r
3304 return this.edits;
\r
3306 TextEditChangeImpl.prototype.clear = function () {
\r
3307 this.edits.splice(0, this.edits.length);
\r
3309 return TextEditChangeImpl;
\r
3312 * A workspace change helps constructing changes to a workspace.
\r
3314 var WorkspaceChange = /** @class */ (function () {
\r
3315 function WorkspaceChange(workspaceEdit) {
\r
3317 this._textEditChanges = Object.create(null);
\r
3318 if (workspaceEdit) {
\r
3319 this._workspaceEdit = workspaceEdit;
\r
3320 if (workspaceEdit.documentChanges) {
\r
3321 workspaceEdit.documentChanges.forEach(function (change) {
\r
3322 if (TextDocumentEdit.is(change)) {
\r
3323 var textEditChange = new TextEditChangeImpl(change.edits);
\r
3324 _this._textEditChanges[change.textDocument.uri] = textEditChange;
\r
3328 else if (workspaceEdit.changes) {
\r
3329 Object.keys(workspaceEdit.changes).forEach(function (key) {
\r
3330 var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
\r
3331 _this._textEditChanges[key] = textEditChange;
\r
3336 Object.defineProperty(WorkspaceChange.prototype, "edit", {
\r
3338 * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
\r
3339 * use to be returned from a workspace edit operation like rename.
\r
3341 get: function () {
\r
3342 return this._workspaceEdit;
\r
3345 configurable: true
\r
3347 WorkspaceChange.prototype.getTextEditChange = function (key) {
\r
3348 if (VersionedTextDocumentIdentifier.is(key)) {
\r
3349 if (!this._workspaceEdit) {
\r
3350 this._workspaceEdit = {
\r
3351 documentChanges: []
\r
3354 if (!this._workspaceEdit.documentChanges) {
\r
3355 throw new Error('Workspace edit is not configured for document changes.');
\r
3357 var textDocument = key;
\r
3358 var result = this._textEditChanges[textDocument.uri];
\r
3361 var textDocumentEdit = {
\r
3362 textDocument: textDocument,
\r
3365 this._workspaceEdit.documentChanges.push(textDocumentEdit);
\r
3366 result = new TextEditChangeImpl(edits);
\r
3367 this._textEditChanges[textDocument.uri] = result;
\r
3372 if (!this._workspaceEdit) {
\r
3373 this._workspaceEdit = {
\r
3374 changes: Object.create(null)
\r
3377 if (!this._workspaceEdit.changes) {
\r
3378 throw new Error('Workspace edit is not configured for normal text edit changes.');
\r
3380 var result = this._textEditChanges[key];
\r
3383 this._workspaceEdit.changes[key] = edits;
\r
3384 result = new TextEditChangeImpl(edits);
\r
3385 this._textEditChanges[key] = result;
\r
3390 WorkspaceChange.prototype.createFile = function (uri, options) {
\r
3391 this.checkDocumentChanges();
\r
3392 this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
\r
3394 WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
\r
3395 this.checkDocumentChanges();
\r
3396 this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
\r
3398 WorkspaceChange.prototype.deleteFile = function (uri, options) {
\r
3399 this.checkDocumentChanges();
\r
3400 this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
\r
3402 WorkspaceChange.prototype.checkDocumentChanges = function () {
\r
3403 if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
\r
3404 throw new Error('Workspace edit is not configured for document changes.');
\r
3407 return WorkspaceChange;
\r
3411 * The TextDocumentIdentifier namespace provides helper functions to work with
\r
3412 * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
\r
3414 var TextDocumentIdentifier;
\r
3415 (function (TextDocumentIdentifier) {
\r
3417 * Creates a new TextDocumentIdentifier literal.
\r
3418 * @param uri The document's uri.
\r
3420 function create(uri) {
\r
3421 return { uri: uri };
\r
3423 TextDocumentIdentifier.create = create;
\r
3425 * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
\r
3427 function is(value) {
\r
3428 var candidate = value;
\r
3429 return Is.defined(candidate) && Is.string(candidate.uri);
\r
3431 TextDocumentIdentifier.is = is;
\r
3432 })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
\r
3434 * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
\r
3435 * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
\r
3437 var VersionedTextDocumentIdentifier;
\r
3438 (function (VersionedTextDocumentIdentifier) {
\r
3440 * Creates a new VersionedTextDocumentIdentifier literal.
\r
3441 * @param uri The document's uri.
\r
3442 * @param uri The document's text.
\r
3444 function create(uri, version) {
\r
3445 return { uri: uri, version: version };
\r
3447 VersionedTextDocumentIdentifier.create = create;
\r
3449 * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
\r
3451 function is(value) {
\r
3452 var candidate = value;
\r
3453 return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
\r
3455 VersionedTextDocumentIdentifier.is = is;
\r
3456 })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
\r
3458 * The TextDocumentItem namespace provides helper functions to work with
\r
3459 * [TextDocumentItem](#TextDocumentItem) literals.
\r
3461 var TextDocumentItem;
\r
3462 (function (TextDocumentItem) {
\r
3464 * Creates a new TextDocumentItem literal.
\r
3465 * @param uri The document's uri.
\r
3466 * @param languageId The document's language identifier.
\r
3467 * @param version The document's version number.
\r
3468 * @param text The document's text.
\r
3470 function create(uri, languageId, version, text) {
\r
3471 return { uri: uri, languageId: languageId, version: version, text: text };
\r
3473 TextDocumentItem.create = create;
\r
3475 * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
\r
3477 function is(value) {
\r
3478 var candidate = value;
\r
3479 return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
\r
3481 TextDocumentItem.is = is;
\r
3482 })(TextDocumentItem || (TextDocumentItem = {}));
\r
3484 * Describes the content type that a client supports in various
\r
3485 * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
\r
3487 * Please note that `MarkupKinds` must not start with a `$`. This kinds
\r
3488 * are reserved for internal usage.
\r
3491 (function (MarkupKind) {
\r
3493 * Plain text is supported as a content format
\r
3495 MarkupKind.PlainText = 'plaintext';
\r
3497 * Markdown is supported as a content format
\r
3499 MarkupKind.Markdown = 'markdown';
\r
3500 })(MarkupKind || (MarkupKind = {}));
\r
3501 (function (MarkupKind) {
\r
3503 * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
\r
3505 function is(value) {
\r
3506 var candidate = value;
\r
3507 return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
\r
3509 MarkupKind.is = is;
\r
3510 })(MarkupKind || (MarkupKind = {}));
\r
3511 var MarkupContent;
\r
3512 (function (MarkupContent) {
\r
3514 * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
\r
3516 function is(value) {
\r
3517 var candidate = value;
\r
3518 return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
\r
3520 MarkupContent.is = is;
\r
3521 })(MarkupContent || (MarkupContent = {}));
\r
3523 * The kind of a completion entry.
\r
3525 var CompletionItemKind;
\r
3526 (function (CompletionItemKind) {
\r
3527 CompletionItemKind.Text = 1;
\r
3528 CompletionItemKind.Method = 2;
\r
3529 CompletionItemKind.Function = 3;
\r
3530 CompletionItemKind.Constructor = 4;
\r
3531 CompletionItemKind.Field = 5;
\r
3532 CompletionItemKind.Variable = 6;
\r
3533 CompletionItemKind.Class = 7;
\r
3534 CompletionItemKind.Interface = 8;
\r
3535 CompletionItemKind.Module = 9;
\r
3536 CompletionItemKind.Property = 10;
\r
3537 CompletionItemKind.Unit = 11;
\r
3538 CompletionItemKind.Value = 12;
\r
3539 CompletionItemKind.Enum = 13;
\r
3540 CompletionItemKind.Keyword = 14;
\r
3541 CompletionItemKind.Snippet = 15;
\r
3542 CompletionItemKind.Color = 16;
\r
3543 CompletionItemKind.File = 17;
\r
3544 CompletionItemKind.Reference = 18;
\r
3545 CompletionItemKind.Folder = 19;
\r
3546 CompletionItemKind.EnumMember = 20;
\r
3547 CompletionItemKind.Constant = 21;
\r
3548 CompletionItemKind.Struct = 22;
\r
3549 CompletionItemKind.Event = 23;
\r
3550 CompletionItemKind.Operator = 24;
\r
3551 CompletionItemKind.TypeParameter = 25;
\r
3552 })(CompletionItemKind || (CompletionItemKind = {}));
\r
3554 * Defines whether the insert text in a completion item should be interpreted as
\r
3555 * plain text or a snippet.
\r
3557 var InsertTextFormat;
\r
3558 (function (InsertTextFormat) {
\r
3560 * The primary text to be inserted is treated as a plain string.
\r
3562 InsertTextFormat.PlainText = 1;
\r
3564 * The primary text to be inserted is treated as a snippet.
\r
3566 * A snippet can define tab stops and placeholders with `$1`, `$2`
\r
3567 * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
\r
3568 * the end of the snippet. Placeholders with equal identifiers are linked,
\r
3569 * that is typing in one will update others too.
\r
3571 * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
\r
3573 InsertTextFormat.Snippet = 2;
\r
3574 })(InsertTextFormat || (InsertTextFormat = {}));
\r
3576 * Completion item tags are extra annotations that tweak the rendering of a completion
\r
3581 var CompletionItemTag;
\r
3582 (function (CompletionItemTag) {
\r
3584 * Render a completion as obsolete, usually using a strike-out.
\r
3586 CompletionItemTag.Deprecated = 1;
\r
3587 })(CompletionItemTag || (CompletionItemTag = {}));
\r
3589 * The CompletionItem namespace provides functions to deal with
\r
3590 * completion items.
\r
3592 var CompletionItem;
\r
3593 (function (CompletionItem) {
\r
3595 * Create a completion item and seed it with a label.
\r
3596 * @param label The completion item's label
\r
3598 function create(label) {
\r
3599 return { label: label };
\r
3601 CompletionItem.create = create;
\r
3602 })(CompletionItem || (CompletionItem = {}));
\r
3604 * The CompletionList namespace provides functions to deal with
\r
3605 * completion lists.
\r
3607 var CompletionList;
\r
3608 (function (CompletionList) {
\r
3610 * Creates a new completion list.
\r
3612 * @param items The completion items.
\r
3613 * @param isIncomplete The list is not complete.
\r
3615 function create(items, isIncomplete) {
\r
3616 return { items: items ? items : [], isIncomplete: !!isIncomplete };
\r
3618 CompletionList.create = create;
\r
3619 })(CompletionList || (CompletionList = {}));
\r
3621 (function (MarkedString) {
\r
3623 * Creates a marked string from plain text.
\r
3625 * @param plainText The plain text.
\r
3627 function fromPlainText(plainText) {
\r
3628 return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
\r
3630 MarkedString.fromPlainText = fromPlainText;
\r
3632 * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
\r
3634 function is(value) {
\r
3635 var candidate = value;
\r
3636 return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
\r
3638 MarkedString.is = is;
\r
3639 })(MarkedString || (MarkedString = {}));
\r
3641 (function (Hover) {
\r
3643 * Checks whether the given value conforms to the [Hover](#Hover) interface.
\r
3645 function is(value) {
\r
3646 var candidate = value;
\r
3647 return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
\r
3648 MarkedString.is(candidate.contents) ||
\r
3649 Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
\r
3652 })(Hover || (Hover = {}));
\r
3654 * The ParameterInformation namespace provides helper functions to work with
\r
3655 * [ParameterInformation](#ParameterInformation) literals.
\r
3657 var ParameterInformation;
\r
3658 (function (ParameterInformation) {
\r
3660 * Creates a new parameter information literal.
\r
3662 * @param label A label string.
\r
3663 * @param documentation A doc string.
\r
3665 function create(label, documentation) {
\r
3666 return documentation ? { label: label, documentation: documentation } : { label: label };
\r
3668 ParameterInformation.create = create;
\r
3669 })(ParameterInformation || (ParameterInformation = {}));
\r
3671 * The SignatureInformation namespace provides helper functions to work with
\r
3672 * [SignatureInformation](#SignatureInformation) literals.
\r
3674 var SignatureInformation;
\r
3675 (function (SignatureInformation) {
\r
3676 function create(label, documentation) {
\r
3677 var parameters = [];
\r
3678 for (var _i = 2; _i < arguments.length; _i++) {
\r
3679 parameters[_i - 2] = arguments[_i];
\r
3681 var result = { label: label };
\r
3682 if (Is.defined(documentation)) {
\r
3683 result.documentation = documentation;
\r
3685 if (Is.defined(parameters)) {
\r
3686 result.parameters = parameters;
\r
3689 result.parameters = [];
\r
3693 SignatureInformation.create = create;
\r
3694 })(SignatureInformation || (SignatureInformation = {}));
\r
3696 * A document highlight kind.
\r
3698 var DocumentHighlightKind;
\r
3699 (function (DocumentHighlightKind) {
\r
3701 * A textual occurrence.
\r
3703 DocumentHighlightKind.Text = 1;
\r
3705 * Read-access of a symbol, like reading a variable.
\r
3707 DocumentHighlightKind.Read = 2;
\r
3709 * Write-access of a symbol, like writing to a variable.
\r
3711 DocumentHighlightKind.Write = 3;
\r
3712 })(DocumentHighlightKind || (DocumentHighlightKind = {}));
\r
3714 * DocumentHighlight namespace to provide helper functions to work with
\r
3715 * [DocumentHighlight](#DocumentHighlight) literals.
\r
3717 var DocumentHighlight;
\r
3718 (function (DocumentHighlight) {
\r
3720 * Create a DocumentHighlight object.
\r
3721 * @param range The range the highlight applies to.
\r
3723 function create(range, kind) {
\r
3724 var result = { range: range };
\r
3725 if (Is.number(kind)) {
\r
3726 result.kind = kind;
\r
3730 DocumentHighlight.create = create;
\r
3731 })(DocumentHighlight || (DocumentHighlight = {}));
\r
3736 (function (SymbolKind) {
\r
3737 SymbolKind.File = 1;
\r
3738 SymbolKind.Module = 2;
\r
3739 SymbolKind.Namespace = 3;
\r
3740 SymbolKind.Package = 4;
\r
3741 SymbolKind.Class = 5;
\r
3742 SymbolKind.Method = 6;
\r
3743 SymbolKind.Property = 7;
\r
3744 SymbolKind.Field = 8;
\r
3745 SymbolKind.Constructor = 9;
\r
3746 SymbolKind.Enum = 10;
\r
3747 SymbolKind.Interface = 11;
\r
3748 SymbolKind.Function = 12;
\r
3749 SymbolKind.Variable = 13;
\r
3750 SymbolKind.Constant = 14;
\r
3751 SymbolKind.String = 15;
\r
3752 SymbolKind.Number = 16;
\r
3753 SymbolKind.Boolean = 17;
\r
3754 SymbolKind.Array = 18;
\r
3755 SymbolKind.Object = 19;
\r
3756 SymbolKind.Key = 20;
\r
3757 SymbolKind.Null = 21;
\r
3758 SymbolKind.EnumMember = 22;
\r
3759 SymbolKind.Struct = 23;
\r
3760 SymbolKind.Event = 24;
\r
3761 SymbolKind.Operator = 25;
\r
3762 SymbolKind.TypeParameter = 26;
\r
3763 })(SymbolKind || (SymbolKind = {}));
\r
3765 * Symbol tags are extra annotations that tweak the rendering of a symbol.
\r
3769 (function (SymbolTag) {
\r
3771 * Render a symbol as obsolete, usually using a strike-out.
\r
3773 SymbolTag.Deprecated = 1;
\r
3774 })(SymbolTag || (SymbolTag = {}));
\r
3775 var SymbolInformation;
\r
3776 (function (SymbolInformation) {
\r
3778 * Creates a new symbol information literal.
\r
3780 * @param name The name of the symbol.
\r
3781 * @param kind The kind of the symbol.
\r
3782 * @param range The range of the location of the symbol.
\r
3783 * @param uri The resource of the location of symbol, defaults to the current document.
\r
3784 * @param containerName The name of the symbol containing the symbol.
\r
3786 function create(name, kind, range, uri, containerName) {
\r
3790 location: { uri: uri, range: range }
\r
3792 if (containerName) {
\r
3793 result.containerName = containerName;
\r
3797 SymbolInformation.create = create;
\r
3798 })(SymbolInformation || (SymbolInformation = {}));
\r
3799 var DocumentSymbol;
\r
3800 (function (DocumentSymbol) {
\r
3802 * Creates a new symbol information literal.
\r
3804 * @param name The name of the symbol.
\r
3805 * @param detail The detail of the symbol.
\r
3806 * @param kind The kind of the symbol.
\r
3807 * @param range The range of the symbol.
\r
3808 * @param selectionRange The selectionRange of the symbol.
\r
3809 * @param children Children of the symbol.
\r
3811 function create(name, detail, kind, range, selectionRange, children) {
\r
3817 selectionRange: selectionRange
\r
3819 if (children !== void 0) {
\r
3820 result.children = children;
\r
3824 DocumentSymbol.create = create;
\r
3826 * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
\r
3828 function is(value) {
\r
3829 var candidate = value;
\r
3830 return candidate &&
\r
3831 Is.string(candidate.name) && Is.number(candidate.kind) &&
\r
3832 Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
\r
3833 (candidate.detail === void 0 || Is.string(candidate.detail)) &&
\r
3834 (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
\r
3835 (candidate.children === void 0 || Array.isArray(candidate.children));
\r
3837 DocumentSymbol.is = is;
\r
3838 })(DocumentSymbol || (DocumentSymbol = {}));
\r
3840 * A set of predefined code action kinds
\r
3842 var CodeActionKind;
\r
3843 (function (CodeActionKind) {
\r
3847 CodeActionKind.Empty = '';
\r
3849 * Base kind for quickfix actions: 'quickfix'
\r
3851 CodeActionKind.QuickFix = 'quickfix';
\r
3853 * Base kind for refactoring actions: 'refactor'
\r
3855 CodeActionKind.Refactor = 'refactor';
\r
3857 * Base kind for refactoring extraction actions: 'refactor.extract'
\r
3859 * Example extract actions:
\r
3861 * - Extract method
\r
3862 * - Extract function
\r
3863 * - Extract variable
\r
3864 * - Extract interface from class
\r
3867 CodeActionKind.RefactorExtract = 'refactor.extract';
\r
3869 * Base kind for refactoring inline actions: 'refactor.inline'
\r
3871 * Example inline actions:
\r
3873 * - Inline function
\r
3874 * - Inline variable
\r
3875 * - Inline constant
\r
3878 CodeActionKind.RefactorInline = 'refactor.inline';
\r
3880 * Base kind for refactoring rewrite actions: 'refactor.rewrite'
\r
3882 * Example rewrite actions:
\r
3884 * - Convert JavaScript function to class
\r
3885 * - Add or remove parameter
\r
3886 * - Encapsulate field
\r
3887 * - Make method static
\r
3888 * - Move method to base class
\r
3891 CodeActionKind.RefactorRewrite = 'refactor.rewrite';
\r
3893 * Base kind for source actions: `source`
\r
3895 * Source code actions apply to the entire file.
\r
3897 CodeActionKind.Source = 'source';
\r
3899 * Base kind for an organize imports source action: `source.organizeImports`
\r
3901 CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
\r
3903 * Base kind for auto-fix source actions: `source.fixAll`.
\r
3905 * Fix all actions automatically fix errors that have a clear fix that do not require user input.
\r
3906 * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
\r
3910 CodeActionKind.SourceFixAll = 'source.fixAll';
\r
3911 })(CodeActionKind || (CodeActionKind = {}));
\r
3913 * The CodeActionContext namespace provides helper functions to work with
\r
3914 * [CodeActionContext](#CodeActionContext) literals.
\r
3916 var CodeActionContext;
\r
3917 (function (CodeActionContext) {
\r
3919 * Creates a new CodeActionContext literal.
\r
3921 function create(diagnostics, only) {
\r
3922 var result = { diagnostics: diagnostics };
\r
3923 if (only !== void 0 && only !== null) {
\r
3924 result.only = only;
\r
3928 CodeActionContext.create = create;
\r
3930 * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
\r
3932 function is(value) {
\r
3933 var candidate = value;
\r
3934 return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
\r
3936 CodeActionContext.is = is;
\r
3937 })(CodeActionContext || (CodeActionContext = {}));
\r
3939 (function (CodeAction) {
\r
3940 function create(title, commandOrEdit, kind) {
\r
3941 var result = { title: title };
\r
3942 if (Command.is(commandOrEdit)) {
\r
3943 result.command = commandOrEdit;
\r
3946 result.edit = commandOrEdit;
\r
3948 if (kind !== void 0) {
\r
3949 result.kind = kind;
\r
3953 CodeAction.create = create;
\r
3954 function is(value) {
\r
3955 var candidate = value;
\r
3956 return candidate && Is.string(candidate.title) &&
\r
3957 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
\r
3958 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
\r
3959 (candidate.edit !== void 0 || candidate.command !== void 0) &&
\r
3960 (candidate.command === void 0 || Command.is(candidate.command)) &&
\r
3961 (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
\r
3962 (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
\r
3964 CodeAction.is = is;
\r
3965 })(CodeAction || (CodeAction = {}));
\r
3967 * The CodeLens namespace provides helper functions to work with
\r
3968 * [CodeLens](#CodeLens) literals.
\r
3971 (function (CodeLens) {
\r
3973 * Creates a new CodeLens literal.
\r
3975 function create(range, data) {
\r
3976 var result = { range: range };
\r
3977 if (Is.defined(data)) {
\r
3978 result.data = data;
\r
3982 CodeLens.create = create;
\r
3984 * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
\r
3986 function is(value) {
\r
3987 var candidate = value;
\r
3988 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
\r
3991 })(CodeLens || (CodeLens = {}));
\r
3993 * The FormattingOptions namespace provides helper functions to work with
\r
3994 * [FormattingOptions](#FormattingOptions) literals.
\r
3996 var FormattingOptions;
\r
3997 (function (FormattingOptions) {
\r
3999 * Creates a new FormattingOptions literal.
\r
4001 function create(tabSize, insertSpaces) {
\r
4002 return { tabSize: tabSize, insertSpaces: insertSpaces };
\r
4004 FormattingOptions.create = create;
\r
4006 * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
\r
4008 function is(value) {
\r
4009 var candidate = value;
\r
4010 return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
\r
4012 FormattingOptions.is = is;
\r
4013 })(FormattingOptions || (FormattingOptions = {}));
\r
4015 * The DocumentLink namespace provides helper functions to work with
\r
4016 * [DocumentLink](#DocumentLink) literals.
\r
4019 (function (DocumentLink) {
\r
4021 * Creates a new DocumentLink literal.
\r
4023 function create(range, target, data) {
\r
4024 return { range: range, target: target, data: data };
\r
4026 DocumentLink.create = create;
\r
4028 * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
\r
4030 function is(value) {
\r
4031 var candidate = value;
\r
4032 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
\r
4034 DocumentLink.is = is;
\r
4035 })(DocumentLink || (DocumentLink = {}));
\r
4037 * The SelectionRange namespace provides helper function to work with
\r
4038 * SelectionRange literals.
\r
4040 var SelectionRange;
\r
4041 (function (SelectionRange) {
\r
4043 * Creates a new SelectionRange
\r
4044 * @param range the range.
\r
4045 * @param parent an optional parent.
\r
4047 function create(range, parent) {
\r
4048 return { range: range, parent: parent };
\r
4050 SelectionRange.create = create;
\r
4051 function is(value) {
\r
4052 var candidate = value;
\r
4053 return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
\r
4055 SelectionRange.is = is;
\r
4056 })(SelectionRange || (SelectionRange = {}));
\r
4057 var EOL = ['\n', '\r\n', '\r'];
\r
4059 * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
\r
4062 (function (TextDocument) {
\r
4064 * Creates a new ITextDocument literal from the given uri and content.
\r
4065 * @param uri The document's uri.
\r
4066 * @param languageId The document's language Id.
\r
4067 * @param content The document's content.
\r
4069 function create(uri, languageId, version, content) {
\r
4070 return new FullTextDocument(uri, languageId, version, content);
\r
4072 TextDocument.create = create;
\r
4074 * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
\r
4076 function is(value) {
\r
4077 var candidate = value;
\r
4078 return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
\r
4079 && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
\r
4081 TextDocument.is = is;
\r
4082 function applyEdits(document, edits) {
\r
4083 var text = document.getText();
\r
4084 var sortedEdits = mergeSort(edits, function (a, b) {
\r
4085 var diff = a.range.start.line - b.range.start.line;
\r
4087 return a.range.start.character - b.range.start.character;
\r
4091 var lastModifiedOffset = text.length;
\r
4092 for (var i = sortedEdits.length - 1; i >= 0; i--) {
\r
4093 var e = sortedEdits[i];
\r
4094 var startOffset = document.offsetAt(e.range.start);
\r
4095 var endOffset = document.offsetAt(e.range.end);
\r
4096 if (endOffset <= lastModifiedOffset) {
\r
4097 text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
\r
4100 throw new Error('Overlapping edit');
\r
4102 lastModifiedOffset = startOffset;
\r
4106 TextDocument.applyEdits = applyEdits;
\r
4107 function mergeSort(data, compare) {
\r
4108 if (data.length <= 1) {
\r
4112 var p = (data.length / 2) | 0;
\r
4113 var left = data.slice(0, p);
\r
4114 var right = data.slice(p);
\r
4115 mergeSort(left, compare);
\r
4116 mergeSort(right, compare);
\r
4120 while (leftIdx < left.length && rightIdx < right.length) {
\r
4121 var ret = compare(left[leftIdx], right[rightIdx]);
\r
4123 // smaller_equal -> take left to preserve order
\r
4124 data[i++] = left[leftIdx++];
\r
4127 // greater -> take right
\r
4128 data[i++] = right[rightIdx++];
\r
4131 while (leftIdx < left.length) {
\r
4132 data[i++] = left[leftIdx++];
\r
4134 while (rightIdx < right.length) {
\r
4135 data[i++] = right[rightIdx++];
\r
4139 })(TextDocument || (TextDocument = {}));
\r
4140 var FullTextDocument = /** @class */ (function () {
\r
4141 function FullTextDocument(uri, languageId, version, content) {
\r
4143 this._languageId = languageId;
\r
4144 this._version = version;
\r
4145 this._content = content;
\r
4146 this._lineOffsets = undefined;
\r
4148 Object.defineProperty(FullTextDocument.prototype, "uri", {
\r
4149 get: function () {
\r
4153 configurable: true
\r
4155 Object.defineProperty(FullTextDocument.prototype, "languageId", {
\r
4156 get: function () {
\r
4157 return this._languageId;
\r
4160 configurable: true
\r
4162 Object.defineProperty(FullTextDocument.prototype, "version", {
\r
4163 get: function () {
\r
4164 return this._version;
\r
4167 configurable: true
\r
4169 FullTextDocument.prototype.getText = function (range) {
\r
4171 var start = this.offsetAt(range.start);
\r
4172 var end = this.offsetAt(range.end);
\r
4173 return this._content.substring(start, end);
\r
4175 return this._content;
\r
4177 FullTextDocument.prototype.update = function (event, version) {
\r
4178 this._content = event.text;
\r
4179 this._version = version;
\r
4180 this._lineOffsets = undefined;
\r
4182 FullTextDocument.prototype.getLineOffsets = function () {
\r
4183 if (this._lineOffsets === undefined) {
\r
4184 var lineOffsets = [];
\r
4185 var text = this._content;
\r
4186 var isLineStart = true;
\r
4187 for (var i = 0; i < text.length; i++) {
\r
4188 if (isLineStart) {
\r
4189 lineOffsets.push(i);
\r
4190 isLineStart = false;
\r
4192 var ch = text.charAt(i);
\r
4193 isLineStart = (ch === '\r' || ch === '\n');
\r
4194 if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
\r
4198 if (isLineStart && text.length > 0) {
\r
4199 lineOffsets.push(text.length);
\r
4201 this._lineOffsets = lineOffsets;
\r
4203 return this._lineOffsets;
\r
4205 FullTextDocument.prototype.positionAt = function (offset) {
\r
4206 offset = Math.max(Math.min(offset, this._content.length), 0);
\r
4207 var lineOffsets = this.getLineOffsets();
\r
4208 var low = 0, high = lineOffsets.length;
\r
4210 return Position.create(0, offset);
\r
4212 while (low < high) {
\r
4213 var mid = Math.floor((low + high) / 2);
\r
4214 if (lineOffsets[mid] > offset) {
\r
4221 // low is the least x for which the line offset is larger than the current offset
\r
4222 // or array.length if no line offset is larger than the current offset
\r
4223 var line = low - 1;
\r
4224 return Position.create(line, offset - lineOffsets[line]);
\r
4226 FullTextDocument.prototype.offsetAt = function (position) {
\r
4227 var lineOffsets = this.getLineOffsets();
\r
4228 if (position.line >= lineOffsets.length) {
\r
4229 return this._content.length;
\r
4231 else if (position.line < 0) {
\r
4234 var lineOffset = lineOffsets[position.line];
\r
4235 var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
\r
4236 return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
\r
4238 Object.defineProperty(FullTextDocument.prototype, "lineCount", {
\r
4239 get: function () {
\r
4240 return this.getLineOffsets().length;
\r
4243 configurable: true
\r
4245 return FullTextDocument;
\r
4249 var toString = Object.prototype.toString;
\r
4250 function defined(value) {
\r
4251 return typeof value !== 'undefined';
\r
4253 Is.defined = defined;
\r
4254 function undefined(value) {
\r
4255 return typeof value === 'undefined';
\r
4257 Is.undefined = undefined;
\r
4258 function boolean(value) {
\r
4259 return value === true || value === false;
\r
4261 Is.boolean = boolean;
\r
4262 function string(value) {
\r
4263 return toString.call(value) === '[object String]';
\r
4265 Is.string = string;
\r
4266 function number(value) {
\r
4267 return toString.call(value) === '[object Number]';
\r
4269 Is.number = number;
\r
4270 function func(value) {
\r
4271 return toString.call(value) === '[object Function]';
\r
4274 function objectLiteral(value) {
\r
4275 // Strictly speaking class instances pass this check as well. Since the LSP
\r
4276 // doesn't use classes we ignore this for now. If we do we need to add something
\r
4277 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
\r
4278 return value !== null && typeof value === 'object';
\r
4280 Is.objectLiteral = objectLiteral;
\r
4281 function typedArray(value, check) {
\r
4282 return Array.isArray(value) && value.every(check);
\r
4284 Is.typedArray = typedArray;
\r
4285 })(Is || (Is = {}));
\r
4290 /***/ (function(module, exports, __webpack_require__) {
4293 /* --------------------------------------------------------------------------------------------
\r
4294 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4295 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4296 * ------------------------------------------------------------------------------------------ */
\r
4298 Object.defineProperty(exports, "__esModule", { value: true });
\r
4299 const Is = __webpack_require__(20);
\r
4300 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4301 const messages_1 = __webpack_require__(21);
\r
4302 const protocol_implementation_1 = __webpack_require__(22);
\r
4303 exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
\r
4304 const protocol_typeDefinition_1 = __webpack_require__(23);
\r
4305 exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
\r
4306 const protocol_workspaceFolders_1 = __webpack_require__(24);
\r
4307 exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
\r
4308 exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
\r
4309 const protocol_configuration_1 = __webpack_require__(25);
\r
4310 exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
\r
4311 const protocol_colorProvider_1 = __webpack_require__(26);
\r
4312 exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
\r
4313 exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
\r
4314 const protocol_foldingRange_1 = __webpack_require__(27);
\r
4315 exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
\r
4316 const protocol_declaration_1 = __webpack_require__(28);
\r
4317 exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
\r
4318 const protocol_selectionRange_1 = __webpack_require__(29);
\r
4319 exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
\r
4320 const protocol_progress_1 = __webpack_require__(30);
\r
4321 exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
\r
4322 exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
\r
4323 exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
\r
4324 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
4325 let __noDynamicImport;
\r
4327 * The DocumentFilter namespace provides helper functions to work with
\r
4328 * [DocumentFilter](#DocumentFilter) literals.
\r
4330 var DocumentFilter;
\r
4331 (function (DocumentFilter) {
\r
4332 function is(value) {
\r
4333 const candidate = value;
\r
4334 return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
\r
4336 DocumentFilter.is = is;
\r
4337 })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
\r
4339 * The DocumentSelector namespace provides helper functions to work with
\r
4340 * [DocumentSelector](#DocumentSelector)s.
\r
4342 var DocumentSelector;
\r
4343 (function (DocumentSelector) {
\r
4344 function is(value) {
\r
4345 if (!Array.isArray(value)) {
\r
4348 for (let elem of value) {
\r
4349 if (!Is.string(elem) && !DocumentFilter.is(elem)) {
\r
4355 DocumentSelector.is = is;
\r
4356 })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));
\r
4358 * The `client/registerCapability` request is sent from the server to the client to register a new capability
\r
4359 * handler on the client side.
\r
4361 var RegistrationRequest;
\r
4362 (function (RegistrationRequest) {
\r
4363 RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');
\r
4364 })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
\r
4366 * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
\r
4367 * handler on the client side.
\r
4369 var UnregistrationRequest;
\r
4370 (function (UnregistrationRequest) {
\r
4371 UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');
\r
4372 })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
\r
4373 var ResourceOperationKind;
\r
4374 (function (ResourceOperationKind) {
\r
4376 * Supports creating new files and folders.
\r
4378 ResourceOperationKind.Create = 'create';
\r
4380 * Supports renaming existing files and folders.
\r
4382 ResourceOperationKind.Rename = 'rename';
\r
4384 * Supports deleting existing files and folders.
\r
4386 ResourceOperationKind.Delete = 'delete';
\r
4387 })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
\r
4388 var FailureHandlingKind;
\r
4389 (function (FailureHandlingKind) {
\r
4391 * Applying the workspace change is simply aborted if one of the changes provided
\r
4392 * fails. All operations executed before the failing operation stay executed.
\r
4394 FailureHandlingKind.Abort = 'abort';
\r
4396 * All operations are executed transactional. That means they either all
\r
4397 * succeed or no changes at all are applied to the workspace.
\r
4399 FailureHandlingKind.Transactional = 'transactional';
\r
4401 * If the workspace edit contains only textual file changes they are executed transactional.
\r
4402 * If resource changes (create, rename or delete file) are part of the change the failure
\r
4403 * handling startegy is abort.
\r
4405 FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
\r
4407 * The client tries to undo the operations already executed. But there is no
\r
4408 * guarantee that this is succeeding.
\r
4410 FailureHandlingKind.Undo = 'undo';
\r
4411 })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
\r
4413 * The StaticRegistrationOptions namespace provides helper functions to work with
\r
4414 * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.
\r
4416 var StaticRegistrationOptions;
\r
4417 (function (StaticRegistrationOptions) {
\r
4418 function hasId(value) {
\r
4419 const candidate = value;
\r
4420 return candidate && Is.string(candidate.id) && candidate.id.length > 0;
\r
4422 StaticRegistrationOptions.hasId = hasId;
\r
4423 })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));
\r
4425 * The TextDocumentRegistrationOptions namespace provides helper functions to work with
\r
4426 * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.
\r
4428 var TextDocumentRegistrationOptions;
\r
4429 (function (TextDocumentRegistrationOptions) {
\r
4430 function is(value) {
\r
4431 const candidate = value;
\r
4432 return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
\r
4434 TextDocumentRegistrationOptions.is = is;
\r
4435 })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));
\r
4437 * The WorkDoneProgressOptions namespace provides helper functions to work with
\r
4438 * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.
\r
4440 var WorkDoneProgressOptions;
\r
4441 (function (WorkDoneProgressOptions) {
\r
4442 function is(value) {
\r
4443 const candidate = value;
\r
4444 return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
\r
4446 WorkDoneProgressOptions.is = is;
\r
4447 function hasWorkDoneProgress(value) {
\r
4448 const candidate = value;
\r
4449 return candidate && Is.boolean(candidate.workDoneProgress);
\r
4451 WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
\r
4452 })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));
\r
4454 * The initialize request is sent from the client to the server.
\r
4455 * It is sent once as the request after starting up the server.
\r
4456 * The requests parameter is of type [InitializeParams](#InitializeParams)
\r
4457 * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
\r
4458 * resolves to such.
\r
4460 var InitializeRequest;
\r
4461 (function (InitializeRequest) {
\r
4462 InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');
\r
4463 })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
\r
4465 * Known error codes for an `InitializeError`;
\r
4467 var InitializeError;
\r
4468 (function (InitializeError) {
\r
4470 * If the protocol version provided by the client can't be handled by the server.
\r
4471 * @deprecated This initialize error got replaced by client capabilities. There is
\r
4472 * no version handshake in version 3.0x
\r
4474 InitializeError.unknownProtocolVersion = 1;
\r
4475 })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
\r
4477 * The intialized notification is sent from the client to the
\r
4478 * server after the client is fully initialized and the server
\r
4479 * is allowed to send requests from the server to the client.
\r
4481 var InitializedNotification;
\r
4482 (function (InitializedNotification) {
\r
4483 InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');
\r
4484 })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
\r
4485 //---- Shutdown Method ----
\r
4487 * A shutdown request is sent from the client to the server.
\r
4488 * It is sent once when the client decides to shutdown the
\r
4489 * server. The only notification that is sent after a shutdown request
\r
4490 * is the exit event.
\r
4492 var ShutdownRequest;
\r
4493 (function (ShutdownRequest) {
\r
4494 ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');
\r
4495 })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
\r
4496 //---- Exit Notification ----
\r
4498 * The exit event is sent from the client to the server to
\r
4499 * ask the server to exit its process.
\r
4501 var ExitNotification;
\r
4502 (function (ExitNotification) {
\r
4503 ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');
\r
4504 })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
\r
4506 * The configuration change notification is sent from the client to the server
\r
4507 * when the client's configuration has changed. The notification contains
\r
4508 * the changed configuration as defined by the language client.
\r
4510 var DidChangeConfigurationNotification;
\r
4511 (function (DidChangeConfigurationNotification) {
\r
4512 DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');
\r
4513 })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
\r
4514 //---- Message show and log notifications ----
\r
4516 * The message type
\r
4519 (function (MessageType) {
\r
4521 * An error message.
\r
4523 MessageType.Error = 1;
\r
4525 * A warning message.
\r
4527 MessageType.Warning = 2;
\r
4529 * An information message.
\r
4531 MessageType.Info = 3;
\r
4535 MessageType.Log = 4;
\r
4536 })(MessageType = exports.MessageType || (exports.MessageType = {}));
\r
4538 * The show message notification is sent from a server to a client to ask
\r
4539 * the client to display a particular message in the user interface.
\r
4541 var ShowMessageNotification;
\r
4542 (function (ShowMessageNotification) {
\r
4543 ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');
\r
4544 })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
\r
4546 * The show message request is sent from the server to the client to show a message
\r
4547 * and a set of options actions to the user.
\r
4549 var ShowMessageRequest;
\r
4550 (function (ShowMessageRequest) {
\r
4551 ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');
\r
4552 })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
\r
4554 * The log message notification is sent from the server to the client to ask
\r
4555 * the client to log a particular message.
\r
4557 var LogMessageNotification;
\r
4558 (function (LogMessageNotification) {
\r
4559 LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');
\r
4560 })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
\r
4561 //---- Telemetry notification
\r
4563 * The telemetry event notification is sent from the server to the client to ask
\r
4564 * the client to log telemetry data.
\r
4566 var TelemetryEventNotification;
\r
4567 (function (TelemetryEventNotification) {
\r
4568 TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');
\r
4569 })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
\r
4571 * Defines how the host (editor) should sync
\r
4572 * document changes to the language server.
\r
4574 var TextDocumentSyncKind;
\r
4575 (function (TextDocumentSyncKind) {
\r
4577 * Documents should not be synced at all.
\r
4579 TextDocumentSyncKind.None = 0;
\r
4581 * Documents are synced by always sending the full content
\r
4582 * of the document.
\r
4584 TextDocumentSyncKind.Full = 1;
\r
4586 * Documents are synced by sending the full content on open.
\r
4587 * After that only incremental updates to the document are
\r
4590 TextDocumentSyncKind.Incremental = 2;
\r
4591 })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
\r
4593 * The document open notification is sent from the client to the server to signal
\r
4594 * newly opened text documents. The document's truth is now managed by the client
\r
4595 * and the server must not try to read the document's truth using the document's
\r
4596 * uri. Open in this sense means it is managed by the client. It doesn't necessarily
\r
4597 * mean that its content is presented in an editor. An open notification must not
\r
4598 * be sent more than once without a corresponding close notification send before.
\r
4599 * This means open and close notification must be balanced and the max open count
\r
4602 var DidOpenTextDocumentNotification;
\r
4603 (function (DidOpenTextDocumentNotification) {
\r
4604 DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
\r
4605 DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
\r
4606 })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
\r
4608 * The document change notification is sent from the client to the server to signal
\r
4609 * changes to a text document.
\r
4611 var DidChangeTextDocumentNotification;
\r
4612 (function (DidChangeTextDocumentNotification) {
\r
4613 DidChangeTextDocumentNotification.method = 'textDocument/didChange';
\r
4614 DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
\r
4615 })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
\r
4617 * The document close notification is sent from the client to the server when
\r
4618 * the document got closed in the client. The document's truth now exists where
\r
4619 * the document's uri points to (e.g. if the document's uri is a file uri the
\r
4620 * truth now exists on disk). As with the open notification the close notification
\r
4621 * is about managing the document's content. Receiving a close notification
\r
4622 * doesn't mean that the document was open in an editor before. A close
\r
4623 * notification requires a previous open notification to be sent.
\r
4625 var DidCloseTextDocumentNotification;
\r
4626 (function (DidCloseTextDocumentNotification) {
\r
4627 DidCloseTextDocumentNotification.method = 'textDocument/didClose';
\r
4628 DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
\r
4629 })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
\r
4631 * The document save notification is sent from the client to the server when
\r
4632 * the document got saved in the client.
\r
4634 var DidSaveTextDocumentNotification;
\r
4635 (function (DidSaveTextDocumentNotification) {
\r
4636 DidSaveTextDocumentNotification.method = 'textDocument/didSave';
\r
4637 DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
\r
4638 })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
\r
4640 * Represents reasons why a text document is saved.
\r
4642 var TextDocumentSaveReason;
\r
4643 (function (TextDocumentSaveReason) {
\r
4645 * Manually triggered, e.g. by the user pressing save, by starting debugging,
\r
4646 * or by an API call.
\r
4648 TextDocumentSaveReason.Manual = 1;
\r
4650 * Automatic after a delay.
\r
4652 TextDocumentSaveReason.AfterDelay = 2;
\r
4654 * When the editor lost focus.
\r
4656 TextDocumentSaveReason.FocusOut = 3;
\r
4657 })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));
\r
4659 * A document will save notification is sent from the client to the server before
\r
4660 * the document is actually saved.
\r
4662 var WillSaveTextDocumentNotification;
\r
4663 (function (WillSaveTextDocumentNotification) {
\r
4664 WillSaveTextDocumentNotification.method = 'textDocument/willSave';
\r
4665 WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
\r
4666 })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
\r
4668 * A document will save request is sent from the client to the server before
\r
4669 * the document is actually saved. The request can return an array of TextEdits
\r
4670 * which will be applied to the text document before it is saved. Please note that
\r
4671 * clients might drop results if computing the text edits took too long or if a
\r
4672 * server constantly fails on this request. This is done to keep the save fast and
\r
4675 var WillSaveTextDocumentWaitUntilRequest;
\r
4676 (function (WillSaveTextDocumentWaitUntilRequest) {
\r
4677 WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
\r
4678 WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
\r
4679 })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
\r
4681 * The watched files notification is sent from the client to the server when
\r
4682 * the client detects changes to file watched by the language client.
\r
4684 var DidChangeWatchedFilesNotification;
\r
4685 (function (DidChangeWatchedFilesNotification) {
\r
4686 DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');
\r
4687 })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
\r
4689 * The file event type
\r
4691 var FileChangeType;
\r
4692 (function (FileChangeType) {
\r
4694 * The file got created.
\r
4696 FileChangeType.Created = 1;
\r
4698 * The file got changed.
\r
4700 FileChangeType.Changed = 2;
\r
4702 * The file got deleted.
\r
4704 FileChangeType.Deleted = 3;
\r
4705 })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
\r
4707 (function (WatchKind) {
\r
4709 * Interested in create events.
\r
4711 WatchKind.Create = 1;
\r
4713 * Interested in change events
\r
4715 WatchKind.Change = 2;
\r
4717 * Interested in delete events
\r
4719 WatchKind.Delete = 4;
\r
4720 })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
\r
4722 * Diagnostics notification are sent from the server to the client to signal
\r
4723 * results of validation runs.
\r
4725 var PublishDiagnosticsNotification;
\r
4726 (function (PublishDiagnosticsNotification) {
\r
4727 PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');
\r
4728 })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
\r
4730 * How a completion was triggered
\r
4732 var CompletionTriggerKind;
\r
4733 (function (CompletionTriggerKind) {
\r
4735 * Completion was triggered by typing an identifier (24x7 code
\r
4736 * complete), manual invocation (e.g Ctrl+Space) or via API.
\r
4738 CompletionTriggerKind.Invoked = 1;
\r
4740 * Completion was triggered by a trigger character specified by
\r
4741 * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
\r
4743 CompletionTriggerKind.TriggerCharacter = 2;
\r
4745 * Completion was re-triggered as current completion list is incomplete
\r
4747 CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
\r
4748 })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
\r
4750 * Request to request completion at a given text document position. The request's
\r
4751 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
\r
4752 * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
\r
4753 * or a Thenable that resolves to such.
\r
4755 * The request can delay the computation of the [`detail`](#CompletionItem.detail)
\r
4756 * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
\r
4757 * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
\r
4758 * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
\r
4760 var CompletionRequest;
\r
4761 (function (CompletionRequest) {
\r
4762 CompletionRequest.method = 'textDocument/completion';
\r
4763 CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
\r
4764 /** @deprecated Use CompletionRequest.type */
\r
4765 CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4766 })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
\r
4768 * Request to resolve additional information for a given completion item.The request's
\r
4769 * parameter is of type [CompletionItem](#CompletionItem) the response
\r
4770 * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
\r
4772 var CompletionResolveRequest;
\r
4773 (function (CompletionResolveRequest) {
\r
4774 CompletionResolveRequest.method = 'completionItem/resolve';
\r
4775 CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
\r
4776 })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
\r
4778 * Request to request hover information at a given text document position. The request's
\r
4779 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
\r
4780 * type [Hover](#Hover) or a Thenable that resolves to such.
\r
4783 (function (HoverRequest) {
\r
4784 HoverRequest.method = 'textDocument/hover';
\r
4785 HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
\r
4786 })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
\r
4788 * How a signature help was triggered.
\r
4792 var SignatureHelpTriggerKind;
\r
4793 (function (SignatureHelpTriggerKind) {
\r
4795 * Signature help was invoked manually by the user or by a command.
\r
4797 SignatureHelpTriggerKind.Invoked = 1;
\r
4799 * Signature help was triggered by a trigger character.
\r
4801 SignatureHelpTriggerKind.TriggerCharacter = 2;
\r
4803 * Signature help was triggered by the cursor moving or by the document content changing.
\r
4805 SignatureHelpTriggerKind.ContentChange = 3;
\r
4806 })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
\r
4807 var SignatureHelpRequest;
\r
4808 (function (SignatureHelpRequest) {
\r
4809 SignatureHelpRequest.method = 'textDocument/signatureHelp';
\r
4810 SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
\r
4811 })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
\r
4813 * A request to resolve the definition location of a symbol at a given text
\r
4814 * document position. The request's parameter is of type [TextDocumentPosition]
\r
4815 * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
\r
4816 * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
\r
4819 var DefinitionRequest;
\r
4820 (function (DefinitionRequest) {
\r
4821 DefinitionRequest.method = 'textDocument/definition';
\r
4822 DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
\r
4823 /** @deprecated Use DefinitionRequest.type */
\r
4824 DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4825 })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
\r
4827 * A request to resolve project-wide references for the symbol denoted
\r
4828 * by the given text document position. The request's parameter is of
\r
4829 * type [ReferenceParams](#ReferenceParams) the response is of type
\r
4830 * [Location[]](#Location) or a Thenable that resolves to such.
\r
4832 var ReferencesRequest;
\r
4833 (function (ReferencesRequest) {
\r
4834 ReferencesRequest.method = 'textDocument/references';
\r
4835 ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
\r
4836 /** @deprecated Use ReferencesRequest.type */
\r
4837 ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4838 })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
\r
4840 * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
\r
4841 * text document position. The request's parameter is of type [TextDocumentPosition]
\r
4842 * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
\r
4843 * (#DocumentHighlight) or a Thenable that resolves to such.
\r
4845 var DocumentHighlightRequest;
\r
4846 (function (DocumentHighlightRequest) {
\r
4847 DocumentHighlightRequest.method = 'textDocument/documentHighlight';
\r
4848 DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
\r
4849 /** @deprecated Use DocumentHighlightRequest.type */
\r
4850 DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4851 })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
\r
4853 * A request to list all symbols found in a given text document. The request's
\r
4854 * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
\r
4855 * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
\r
4856 * that resolves to such.
\r
4858 var DocumentSymbolRequest;
\r
4859 (function (DocumentSymbolRequest) {
\r
4860 DocumentSymbolRequest.method = 'textDocument/documentSymbol';
\r
4861 DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
\r
4862 /** @deprecated Use DocumentSymbolRequest.type */
\r
4863 DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4864 })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
\r
4866 * A request to provide commands for the given text document and range.
\r
4868 var CodeActionRequest;
\r
4869 (function (CodeActionRequest) {
\r
4870 CodeActionRequest.method = 'textDocument/codeAction';
\r
4871 CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
\r
4872 /** @deprecated Use CodeActionRequest.type */
\r
4873 CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4874 })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
\r
4876 * A request to list project-wide symbols matching the query string given
\r
4877 * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
\r
4878 * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
\r
4879 * resolves to such.
\r
4881 var WorkspaceSymbolRequest;
\r
4882 (function (WorkspaceSymbolRequest) {
\r
4883 WorkspaceSymbolRequest.method = 'workspace/symbol';
\r
4884 WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
\r
4885 /** @deprecated Use WorkspaceSymbolRequest.type */
\r
4886 WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4887 })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
\r
4889 * A request to provide code lens for the given text document.
\r
4891 var CodeLensRequest;
\r
4892 (function (CodeLensRequest) {
\r
4893 CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');
\r
4894 /** @deprecated Use CodeLensRequest.type */
\r
4895 CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4896 })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
\r
4898 * A request to resolve a command for a given code lens.
\r
4900 var CodeLensResolveRequest;
\r
4901 (function (CodeLensResolveRequest) {
\r
4902 CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');
\r
4903 })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
\r
4905 * A request to provide document links
\r
4907 var DocumentLinkRequest;
\r
4908 (function (DocumentLinkRequest) {
\r
4909 DocumentLinkRequest.method = 'textDocument/documentLink';
\r
4910 DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
\r
4911 /** @deprecated Use DocumentLinkRequest.type */
\r
4912 DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4913 })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
\r
4915 * Request to resolve additional information for a given document link. The request's
\r
4916 * parameter is of type [DocumentLink](#DocumentLink) the response
\r
4917 * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
\r
4919 var DocumentLinkResolveRequest;
\r
4920 (function (DocumentLinkResolveRequest) {
\r
4921 DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');
\r
4922 })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
\r
4924 * A request to to format a whole document.
\r
4926 var DocumentFormattingRequest;
\r
4927 (function (DocumentFormattingRequest) {
\r
4928 DocumentFormattingRequest.method = 'textDocument/formatting';
\r
4929 DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
\r
4930 })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
\r
4932 * A request to to format a range in a document.
\r
4934 var DocumentRangeFormattingRequest;
\r
4935 (function (DocumentRangeFormattingRequest) {
\r
4936 DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
\r
4937 DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
\r
4938 })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
\r
4940 * A request to format a document on type.
\r
4942 var DocumentOnTypeFormattingRequest;
\r
4943 (function (DocumentOnTypeFormattingRequest) {
\r
4944 DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
\r
4945 DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
\r
4946 })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
\r
4948 * A request to rename a symbol.
\r
4950 var RenameRequest;
\r
4951 (function (RenameRequest) {
\r
4952 RenameRequest.method = 'textDocument/rename';
\r
4953 RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
\r
4954 })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
\r
4956 * A request to test and perform the setup necessary for a rename.
\r
4958 var PrepareRenameRequest;
\r
4959 (function (PrepareRenameRequest) {
\r
4960 PrepareRenameRequest.method = 'textDocument/prepareRename';
\r
4961 PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
\r
4962 })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
\r
4964 * A request send from the client to the server to execute a command. The request might return
\r
4965 * a workspace edit which the client will apply to the workspace.
\r
4967 var ExecuteCommandRequest;
\r
4968 (function (ExecuteCommandRequest) {
\r
4969 ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');
\r
4970 })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
\r
4972 * A request sent from the server to the client to modified certain resources.
\r
4974 var ApplyWorkspaceEditRequest;
\r
4975 (function (ApplyWorkspaceEditRequest) {
\r
4976 ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
\r
4977 })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
\r
4982 /***/ (function(module, exports, __webpack_require__) {
4985 /* --------------------------------------------------------------------------------------------
\r
4986 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4987 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4988 * ------------------------------------------------------------------------------------------ */
\r
4990 Object.defineProperty(exports, "__esModule", { value: true });
\r
4991 function boolean(value) {
\r
4992 return value === true || value === false;
\r
4994 exports.boolean = boolean;
\r
4995 function string(value) {
\r
4996 return typeof value === 'string' || value instanceof String;
\r
4998 exports.string = string;
\r
4999 function number(value) {
\r
5000 return typeof value === 'number' || value instanceof Number;
\r
5002 exports.number = number;
\r
5003 function error(value) {
\r
5004 return value instanceof Error;
\r
5006 exports.error = error;
\r
5007 function func(value) {
\r
5008 return typeof value === 'function';
\r
5010 exports.func = func;
\r
5011 function array(value) {
\r
5012 return Array.isArray(value);
\r
5014 exports.array = array;
\r
5015 function stringArray(value) {
\r
5016 return array(value) && value.every(elem => string(elem));
\r
5018 exports.stringArray = stringArray;
\r
5019 function typedArray(value, check) {
\r
5020 return Array.isArray(value) && value.every(check);
\r
5022 exports.typedArray = typedArray;
\r
5023 function objectLiteral(value) {
\r
5024 // Strictly speaking class instances pass this check as well. Since the LSP
\r
5025 // doesn't use classes we ignore this for now. If we do we need to add something
\r
5026 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
\r
5027 return value !== null && typeof value === 'object';
\r
5029 exports.objectLiteral = objectLiteral;
\r
5034 /***/ (function(module, exports, __webpack_require__) {
5037 /* --------------------------------------------------------------------------------------------
\r
5038 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5039 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5040 * ------------------------------------------------------------------------------------------ */
\r
5042 Object.defineProperty(exports, "__esModule", { value: true });
\r
5043 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5044 class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
\r
5045 constructor(method) {
\r
5049 exports.ProtocolRequestType0 = ProtocolRequestType0;
\r
5050 class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
\r
5051 constructor(method) {
\r
5055 exports.ProtocolRequestType = ProtocolRequestType;
\r
5056 class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
\r
5057 constructor(method) {
\r
5061 exports.ProtocolNotificationType = ProtocolNotificationType;
\r
5062 class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
\r
5063 constructor(method) {
\r
5067 exports.ProtocolNotificationType0 = ProtocolNotificationType0;
\r
5072 /***/ (function(module, exports, __webpack_require__) {
5075 /* --------------------------------------------------------------------------------------------
\r
5076 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5077 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5078 * ------------------------------------------------------------------------------------------ */
\r
5080 Object.defineProperty(exports, "__esModule", { value: true });
\r
5081 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5082 const messages_1 = __webpack_require__(21);
\r
5083 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5084 let __noDynamicImport;
\r
5086 * A request to resolve the implementation locations of a symbol at a given text
\r
5087 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5088 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
\r
5089 * Thenable that resolves to such.
\r
5091 var ImplementationRequest;
\r
5092 (function (ImplementationRequest) {
\r
5093 ImplementationRequest.method = 'textDocument/implementation';
\r
5094 ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);
\r
5095 /** @deprecated Use ImplementationRequest.type */
\r
5096 ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5097 })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
\r
5102 /***/ (function(module, exports, __webpack_require__) {
5105 /* --------------------------------------------------------------------------------------------
\r
5106 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5107 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5108 * ------------------------------------------------------------------------------------------ */
\r
5110 Object.defineProperty(exports, "__esModule", { value: true });
\r
5111 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5112 const messages_1 = __webpack_require__(21);
\r
5113 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5114 let __noDynamicImport;
\r
5116 * A request to resolve the type definition locations of a symbol at a given text
\r
5117 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5118 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
\r
5119 * Thenable that resolves to such.
\r
5121 var TypeDefinitionRequest;
\r
5122 (function (TypeDefinitionRequest) {
\r
5123 TypeDefinitionRequest.method = 'textDocument/typeDefinition';
\r
5124 TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);
\r
5125 /** @deprecated Use TypeDefinitionRequest.type */
\r
5126 TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5127 })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
\r
5132 /***/ (function(module, exports, __webpack_require__) {
5135 /* --------------------------------------------------------------------------------------------
\r
5136 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5137 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5138 * ------------------------------------------------------------------------------------------ */
\r
5140 Object.defineProperty(exports, "__esModule", { value: true });
\r
5141 const messages_1 = __webpack_require__(21);
\r
5143 * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
\r
5145 var WorkspaceFoldersRequest;
\r
5146 (function (WorkspaceFoldersRequest) {
\r
5147 WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');
\r
5148 })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
\r
5150 * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
\r
5151 * folder configuration changes.
\r
5153 var DidChangeWorkspaceFoldersNotification;
\r
5154 (function (DidChangeWorkspaceFoldersNotification) {
\r
5155 DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');
\r
5156 })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
\r
5161 /***/ (function(module, exports, __webpack_require__) {
5164 /* --------------------------------------------------------------------------------------------
\r
5165 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5166 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5167 * ------------------------------------------------------------------------------------------ */
\r
5169 Object.defineProperty(exports, "__esModule", { value: true });
\r
5170 const messages_1 = __webpack_require__(21);
\r
5172 * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
\r
5173 * configuration setting.
\r
5175 * This pull model replaces the old push model were the client signaled configuration change via an
\r
5176 * event. If the server still needs to react to configuration changes (since the server caches the
\r
5177 * result of `workspace/configuration` requests) the server should register for an empty configuration
\r
5178 * change event and empty the cache if such an event is received.
\r
5180 var ConfigurationRequest;
\r
5181 (function (ConfigurationRequest) {
\r
5182 ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');
\r
5183 })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
\r
5188 /***/ (function(module, exports, __webpack_require__) {
5191 /* --------------------------------------------------------------------------------------------
\r
5192 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5193 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5194 * ------------------------------------------------------------------------------------------ */
\r
5196 Object.defineProperty(exports, "__esModule", { value: true });
\r
5197 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5198 const messages_1 = __webpack_require__(21);
\r
5200 * A request to list all color symbols found in a given text document. The request's
\r
5201 * parameter is of type [DocumentColorParams](#DocumentColorParams) the
\r
5202 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
\r
5203 * that resolves to such.
\r
5205 var DocumentColorRequest;
\r
5206 (function (DocumentColorRequest) {
\r
5207 DocumentColorRequest.method = 'textDocument/documentColor';
\r
5208 DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);
\r
5209 /** @deprecated Use DocumentColorRequest.type */
\r
5210 DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5211 })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
\r
5213 * A request to list all presentation for a color. The request's
\r
5214 * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
\r
5215 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
\r
5216 * that resolves to such.
\r
5218 var ColorPresentationRequest;
\r
5219 (function (ColorPresentationRequest) {
\r
5220 ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');
\r
5221 })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
\r
5226 /***/ (function(module, exports, __webpack_require__) {
5230 /*---------------------------------------------------------------------------------------------
\r
5231 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5232 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5233 *--------------------------------------------------------------------------------------------*/
\r
5234 Object.defineProperty(exports, "__esModule", { value: true });
\r
5235 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5236 const messages_1 = __webpack_require__(21);
\r
5238 * Enum of known range kinds
\r
5240 var FoldingRangeKind;
\r
5241 (function (FoldingRangeKind) {
\r
5243 * Folding range for a comment
\r
5245 FoldingRangeKind["Comment"] = "comment";
\r
5247 * Folding range for a imports or includes
\r
5249 FoldingRangeKind["Imports"] = "imports";
\r
5251 * Folding range for a region (e.g. `#region`)
\r
5253 FoldingRangeKind["Region"] = "region";
\r
5254 })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
\r
5256 * A request to provide folding ranges in a document. The request's
\r
5257 * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
\r
5258 * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
\r
5259 * that resolves to such.
\r
5261 var FoldingRangeRequest;
\r
5262 (function (FoldingRangeRequest) {
\r
5263 FoldingRangeRequest.method = 'textDocument/foldingRange';
\r
5264 FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);
\r
5265 /** @deprecated Use FoldingRangeRequest.type */
\r
5266 FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5267 })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
\r
5272 /***/ (function(module, exports, __webpack_require__) {
5275 /* --------------------------------------------------------------------------------------------
\r
5276 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5277 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5278 * ------------------------------------------------------------------------------------------ */
\r
5280 Object.defineProperty(exports, "__esModule", { value: true });
\r
5281 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5282 const messages_1 = __webpack_require__(21);
\r
5283 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5284 let __noDynamicImport;
\r
5286 * A request to resolve the type definition locations of a symbol at a given text
\r
5287 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5288 * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
\r
5289 * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
\r
5292 var DeclarationRequest;
\r
5293 (function (DeclarationRequest) {
\r
5294 DeclarationRequest.method = 'textDocument/declaration';
\r
5295 DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);
\r
5296 /** @deprecated Use DeclarationRequest.type */
\r
5297 DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5298 })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
\r
5303 /***/ (function(module, exports, __webpack_require__) {
5307 /*---------------------------------------------------------------------------------------------
\r
5308 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5309 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5310 *--------------------------------------------------------------------------------------------*/
\r
5311 Object.defineProperty(exports, "__esModule", { value: true });
\r
5312 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5313 const messages_1 = __webpack_require__(21);
\r
5315 * A request to provide selection ranges in a document. The request's
\r
5316 * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
\r
5317 * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
\r
5318 * that resolves to such.
\r
5320 var SelectionRangeRequest;
\r
5321 (function (SelectionRangeRequest) {
\r
5322 SelectionRangeRequest.method = 'textDocument/selectionRange';
\r
5323 SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);
\r
5324 /** @deprecated Use SelectionRangeRequest.type */
\r
5325 SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5326 })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
\r
5331 /***/ (function(module, exports, __webpack_require__) {
5334 /* --------------------------------------------------------------------------------------------
\r
5335 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5336 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5337 * ------------------------------------------------------------------------------------------ */
\r
5339 Object.defineProperty(exports, "__esModule", { value: true });
\r
5340 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
5341 const messages_1 = __webpack_require__(21);
\r
5342 var WorkDoneProgress;
\r
5343 (function (WorkDoneProgress) {
\r
5344 WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();
\r
5345 })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));
\r
5347 * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
\r
5348 * reporting from the server.
\r
5350 var WorkDoneProgressCreateRequest;
\r
5351 (function (WorkDoneProgressCreateRequest) {
\r
5352 WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');
\r
5353 })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));
\r
5355 * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
\r
5356 * initiated on the server side.
\r
5358 var WorkDoneProgressCancelNotification;
\r
5359 (function (WorkDoneProgressCancelNotification) {
\r
5360 WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');
\r
5361 })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));
\r
5366 /***/ (function(module, exports, __webpack_require__) {
5369 /* --------------------------------------------------------------------------------------------
\r
5370 * Copyright (c) TypeFox and others. All rights reserved.
\r
5371 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5372 * ------------------------------------------------------------------------------------------ */
\r
5374 Object.defineProperty(exports, "__esModule", { value: true });
\r
5375 const messages_1 = __webpack_require__(21);
\r
5377 * A request to result a `CallHierarchyItem` in a document at a given position.
\r
5378 * Can be used as an input to a incoming or outgoing call hierarchy.
\r
5380 * @since 3.16.0 - Proposed state
\r
5382 var CallHierarchyPrepareRequest;
\r
5383 (function (CallHierarchyPrepareRequest) {
\r
5384 CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
\r
5385 CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);
\r
5386 })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));
\r
5388 * A request to resolve the incoming calls for a given `CallHierarchyItem`.
\r
5390 * @since 3.16.0 - Proposed state
\r
5392 var CallHierarchyIncomingCallsRequest;
\r
5393 (function (CallHierarchyIncomingCallsRequest) {
\r
5394 CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
\r
5395 CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
\r
5396 })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));
\r
5398 * A request to resolve the outgoing calls for a given `CallHierarchyItem`.
\r
5400 * @since 3.16.0 - Proposed state
\r
5402 var CallHierarchyOutgoingCallsRequest;
\r
5403 (function (CallHierarchyOutgoingCallsRequest) {
\r
5404 CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
\r
5405 CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
\r
5406 })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));
\r
5411 /***/ (function(module, exports, __webpack_require__) {
5414 /* --------------------------------------------------------------------------------------------
\r
5415 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5416 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5417 * ------------------------------------------------------------------------------------------ */
\r
5419 Object.defineProperty(exports, "__esModule", { value: true });
\r
5420 const messages_1 = __webpack_require__(21);
\r
5422 * A set of predefined token types. This set is not fixed
\r
5423 * an clients can specify additional token types via the
\r
5424 * corresponding client capabilities.
\r
5426 * @since 3.16.0 - Proposed state
\r
5428 var SemanticTokenTypes;
\r
5429 (function (SemanticTokenTypes) {
\r
5430 SemanticTokenTypes["comment"] = "comment";
\r
5431 SemanticTokenTypes["keyword"] = "keyword";
\r
5432 SemanticTokenTypes["string"] = "string";
\r
5433 SemanticTokenTypes["number"] = "number";
\r
5434 SemanticTokenTypes["regexp"] = "regexp";
\r
5435 SemanticTokenTypes["operator"] = "operator";
\r
5436 SemanticTokenTypes["namespace"] = "namespace";
\r
5437 SemanticTokenTypes["type"] = "type";
\r
5438 SemanticTokenTypes["struct"] = "struct";
\r
5439 SemanticTokenTypes["class"] = "class";
\r
5440 SemanticTokenTypes["interface"] = "interface";
\r
5441 SemanticTokenTypes["enum"] = "enum";
\r
5442 SemanticTokenTypes["typeParameter"] = "typeParameter";
\r
5443 SemanticTokenTypes["function"] = "function";
\r
5444 SemanticTokenTypes["member"] = "member";
\r
5445 SemanticTokenTypes["property"] = "property";
\r
5446 SemanticTokenTypes["macro"] = "macro";
\r
5447 SemanticTokenTypes["variable"] = "variable";
\r
5448 SemanticTokenTypes["parameter"] = "parameter";
\r
5449 SemanticTokenTypes["label"] = "label";
\r
5450 })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));
\r
5452 * A set of predefined token modifiers. This set is not fixed
\r
5453 * an clients can specify additional token types via the
\r
5454 * corresponding client capabilities.
\r
5456 * @since 3.16.0 - Proposed state
\r
5458 var SemanticTokenModifiers;
\r
5459 (function (SemanticTokenModifiers) {
\r
5460 SemanticTokenModifiers["documentation"] = "documentation";
\r
5461 SemanticTokenModifiers["declaration"] = "declaration";
\r
5462 SemanticTokenModifiers["definition"] = "definition";
\r
5463 SemanticTokenModifiers["reference"] = "reference";
\r
5464 SemanticTokenModifiers["static"] = "static";
\r
5465 SemanticTokenModifiers["abstract"] = "abstract";
\r
5466 SemanticTokenModifiers["deprecated"] = "deprecated";
\r
5467 SemanticTokenModifiers["async"] = "async";
\r
5468 SemanticTokenModifiers["volatile"] = "volatile";
\r
5469 SemanticTokenModifiers["readonly"] = "readonly";
\r
5470 })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));
\r
5472 * @since 3.16.0 - Proposed state
\r
5474 var SemanticTokens;
\r
5475 (function (SemanticTokens) {
\r
5476 function is(value) {
\r
5477 const candidate = value;
\r
5478 return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
\r
5479 Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
\r
5481 SemanticTokens.is = is;
\r
5482 })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));
\r
5484 * @since 3.16.0 - Proposed state
\r
5486 var SemanticTokensRequest;
\r
5487 (function (SemanticTokensRequest) {
\r
5488 SemanticTokensRequest.method = 'textDocument/semanticTokens';
\r
5489 SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);
\r
5490 })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));
\r
5492 * @since 3.16.0 - Proposed state
\r
5494 var SemanticTokensEditsRequest;
\r
5495 (function (SemanticTokensEditsRequest) {
\r
5496 SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';
\r
5497 SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);
\r
5498 })(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));
\r
5500 * @since 3.16.0 - Proposed state
\r
5502 var SemanticTokensRangeRequest;
\r
5503 (function (SemanticTokensRangeRequest) {
\r
5504 SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
\r
5505 SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);
\r
5506 })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));
\r
5511 /***/ (function(module, exports, __webpack_require__) {
5515 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5516 if (k2 === undefined) k2 = k;
5517 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5518 }) : (function(o, m, k, k2) {
5519 if (k2 === undefined) k2 = k;
5522 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
5523 Object.defineProperty(o, "default", { enumerable: true, value: v });
5524 }) : function(o, v) {
5527 var __importStar = (this && this.__importStar) || function (mod) {
5528 if (mod && mod.__esModule) return mod;
5530 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
5531 __setModuleDefault(result, mod);
5534 var __importDefault = (this && this.__importDefault) || function (mod) {
5535 return (mod && mod.__esModule) ? mod : { "default": mod };
5537 Object.defineProperty(exports, "__esModule", { value: true });
5538 /*---------------------------------------------------------------------------------------------
5539 * Copyright (c) Microsoft Corporation. All rights reserved.
5540 * Licensed under the MIT License. See License.txt in the project root for license information.
5541 *--------------------------------------------------------------------------------------------*/
5542 const coc_nvim_1 = __webpack_require__(1);
5543 const vscode_languageserver_protocol_1 = __webpack_require__(3);
5544 const languageProvider_1 = __importDefault(__webpack_require__(34));
5545 const PConst = __importStar(__webpack_require__(39));
5546 const typescriptServiceClient_1 = __importDefault(__webpack_require__(117));
5547 const typeConverters = __importStar(__webpack_require__(37));
5548 const typingsStatus_1 = __importStar(__webpack_require__(139));
5549 // Style check diagnostics that can be reported as warnings
5550 const styleCheckDiagnostics = [
5556 7030 // not all code paths return a value
5558 class TypeScriptServiceClientHost {
5559 constructor(descriptions, pluginManager) {
5560 this.languages = [];
5561 this.languagePerId = new Map();
5562 this.disposables = [];
5563 this.reportStyleCheckAsWarnings = true;
5565 const handleProjectChange = () => {
5567 clearTimeout(timer);
5568 timer = setTimeout(() => {
5569 this.triggerAllDiagnostics();
5572 const configFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/[tj]sconfig.json');
5573 this.disposables.push(configFileWatcher);
5574 configFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
5575 configFileWatcher.onDidDelete(this.reloadProjects, this, this.disposables);
5576 configFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
5577 const packageFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/package.json');
5578 packageFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
5579 packageFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
5580 this.client = new typescriptServiceClient_1.default(pluginManager);
5581 this.disposables.push(this.client);
5582 this.client.onDiagnosticsReceived(({ kind, resource, diagnostics }) => {
5583 this.diagnosticsReceived(kind, resource, diagnostics);
5584 }, null, this.disposables);
5585 this.client.onConfigDiagnosticsReceived(diag => {
5586 let { body } = diag;
5588 let { configFile, diagnostics } = body;
5589 let uri = coc_nvim_1.Uri.file(configFile);
5590 if (diagnostics.length == 0) {
5591 this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), []);
5594 let diagnosticList = diagnostics.map(o => {
5595 let { text, code, category, start, end } = o;
5597 if (!start || !end) {
5598 range = vscode_languageserver_protocol_1.Range.create(vscode_languageserver_protocol_1.Position.create(0, 0), vscode_languageserver_protocol_1.Position.create(0, 1));
5601 range = vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1);
5603 let severity = category == 'error' ? vscode_languageserver_protocol_1.DiagnosticSeverity.Error : vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
5604 return vscode_languageserver_protocol_1.Diagnostic.create(range, text, severity, code);
5606 this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), diagnosticList);
5609 }, null, this.disposables);
5610 this.typingsStatus = new typingsStatus_1.default(this.client);
5611 this.ataProgressReporter = new typingsStatus_1.AtaProgressReporter(this.client);
5612 for (const description of descriptions) { // tslint:disable-line
5613 const manager = new languageProvider_1.default(this.client, description, this.typingsStatus);
5614 this.languages.push(manager);
5615 this.disposables.push(manager);
5616 this.languagePerId.set(description.id, manager);
5618 this.client.ensureServiceStarted();
5619 this.client.onTsServerStarted(() => {
5620 this.triggerAllDiagnostics();
5622 coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
5623 this.configurationChanged();
5626 coc_nvim_1.disposeAll(this.disposables);
5627 this.typingsStatus.dispose();
5628 this.ataProgressReporter.dispose();
5631 for (let lang of this.languages) {
5632 lang.fileConfigurationManager.reset();
5635 get serviceClient() {
5639 this.client.execute('reloadProjects', null, vscode_languageserver_protocol_1.CancellationToken.None);
5640 this.triggerAllDiagnostics();
5642 // typescript or javascript
5643 getProvider(languageId) {
5644 return this.languagePerId.get(languageId);
5646 configurationChanged() {
5647 const config = coc_nvim_1.workspace.getConfiguration('tsserver');
5648 this.reportStyleCheckAsWarnings = config.get('reportStyleChecksAsWarnings', true);
5650 findLanguage(resource) {
5652 return this.languages.find(language => language.handles(resource));
5659 return this.findLanguage(coc_nvim_1.Uri.parse(uri)) != null;
5661 triggerAllDiagnostics() {
5662 for (const language of this.languagePerId.values()) {
5663 language.triggerAllDiagnostics();
5666 diagnosticsReceived(kind, resource, diagnostics) {
5667 const language = this.findLanguage(resource);
5669 language.diagnosticsReceived(kind, resource, this.createMarkerDatas(diagnostics));
5672 createMarkerDatas(diagnostics) {
5673 return diagnostics.map(tsDiag => this.tsDiagnosticToLspDiagnostic(tsDiag));
5675 tsDiagnosticToLspDiagnostic(diagnostic) {
5676 const { start, end, text } = diagnostic;
5678 start: typeConverters.Position.fromLocation(start),
5679 end: typeConverters.Position.fromLocation(end)
5681 let relatedInformation;
5682 if (diagnostic.relatedInformation) {
5683 relatedInformation = diagnostic.relatedInformation.map(o => {
5684 let { span, message } = o;
5686 location: typeConverters.Location.fromTextSpan(this.client.toResource(span.file), span),
5694 code: diagnostic.code ? diagnostic.code : null,
5695 severity: this.getDiagnosticSeverity(diagnostic),
5696 reportUnnecessary: diagnostic.reportsUnnecessary,
5697 source: diagnostic.source || 'tsserver',
5701 getDiagnosticSeverity(diagnostic) {
5702 if (this.reportStyleCheckAsWarnings &&
5703 this.isStyleCheckDiagnostic(diagnostic.code) &&
5704 diagnostic.category === PConst.DiagnosticCategory.error) {
5705 return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
5707 switch (diagnostic.category) {
5708 case PConst.DiagnosticCategory.error:
5709 return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
5710 case PConst.DiagnosticCategory.warning:
5711 return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
5712 case PConst.DiagnosticCategory.suggestion:
5713 return vscode_languageserver_protocol_1.DiagnosticSeverity.Information;
5715 return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
5718 isStyleCheckDiagnostic(code) {
5719 return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false;
5722 exports.default = TypeScriptServiceClientHost;
5727 /***/ (function(module, exports, __webpack_require__) {
5731 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5732 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5733 return new (P || (P = Promise))(function (resolve, reject) {
5734 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5735 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
5736 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
5737 step((generator = generator.apply(thisArg, _arguments || [])).next());
5740 var __importDefault = (this && this.__importDefault) || function (mod) {
5741 return (mod && mod.__esModule) ? mod : { "default": mod };
5743 Object.defineProperty(exports, "__esModule", { value: true });
5744 /*---------------------------------------------------------------------------------------------
5745 * Copyright (c) Microsoft Corporation. All rights reserved.
5746 * Licensed under the MIT License. See License.txt in the project root for license information.
5747 *--------------------------------------------------------------------------------------------*/
5748 const vscode_languageserver_protocol_1 = __webpack_require__(3);
5749 const coc_nvim_1 = __webpack_require__(1);
5750 const baseCodeLensProvider_1 = __webpack_require__(35);
5751 const completionItemProvider_1 = __importDefault(__webpack_require__(38));
5752 const definitionProvider_1 = __importDefault(__webpack_require__(88));
5753 const directiveCommentCompletions_1 = __importDefault(__webpack_require__(89));
5754 const documentHighlight_1 = __importDefault(__webpack_require__(90));
5755 const documentSymbol_1 = __importDefault(__webpack_require__(92));
5756 const fileConfigurationManager_1 = __importDefault(__webpack_require__(93));
5757 const folding_1 = __importDefault(__webpack_require__(94));
5758 const formatting_1 = __importDefault(__webpack_require__(95));
5759 const hover_1 = __importDefault(__webpack_require__(96));
5760 const implementationsCodeLens_1 = __importDefault(__webpack_require__(97));
5761 // import TagCompletionProvider from './features/tagCompletion'
5762 const quickfix_1 = __importDefault(__webpack_require__(98));
5763 const importFix_1 = __importDefault(__webpack_require__(99));
5764 const refactor_1 = __importDefault(__webpack_require__(101));
5765 const references_1 = __importDefault(__webpack_require__(102));
5766 const referencesCodeLens_1 = __importDefault(__webpack_require__(103));
5767 const rename_1 = __importDefault(__webpack_require__(104));
5768 const signatureHelp_1 = __importDefault(__webpack_require__(105));
5769 const updatePathOnRename_1 = __importDefault(__webpack_require__(106));
5770 const watchBuild_1 = __importDefault(__webpack_require__(108));
5771 const workspaceSymbols_1 = __importDefault(__webpack_require__(109));
5772 const smartSelect_1 = __importDefault(__webpack_require__(110));
5773 const moduleInstall_1 = __importDefault(__webpack_require__(111));
5774 const api_1 = __importDefault(__webpack_require__(40));
5775 const organizeImports_1 = __webpack_require__(114);
5776 const suggestionSetting = 'suggestionActions.enabled';
5777 class LanguageProvider {
5778 constructor(client, description, typingsStatus) {
5779 this.client = client;
5780 this.description = description;
5781 this.disposables = [];
5782 this.fileConfigurationManager = new fileConfigurationManager_1.default(client);
5783 coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
5784 this.configurationChanged();
5785 let initialized = false;
5786 client.onTsServerStarted(() => __awaiter(this, void 0, void 0, function* () {
5789 this.registerProviders(client, typingsStatus);
5792 this.client.diagnosticsManager.reInitialize();
5796 configurationChanged() {
5797 const config = coc_nvim_1.workspace.getConfiguration(this.id, null);
5798 this.client.diagnosticsManager.setEnableSuggestions(this.id, config.get(suggestionSetting, true));
5801 coc_nvim_1.disposeAll(this.disposables);
5803 registerProviders(client, typingsStatus) {
5804 let languageIds = this.description.modeIds;
5805 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));
5806 if (this.client.apiVersion.gte(api_1.default.v230)) {
5807 this.disposables.push(coc_nvim_1.languages.registerCompletionItemProvider(`${this.description.id}-directive`, 'TSC', languageIds, new directiveCommentCompletions_1.default(client), ['@']));
5809 let definitionProvider = new definitionProvider_1.default(client);
5810 this.disposables.push(coc_nvim_1.languages.registerDefinitionProvider(languageIds, definitionProvider));
5811 this.disposables.push(coc_nvim_1.languages.registerTypeDefinitionProvider(languageIds, definitionProvider));
5812 this.disposables.push(coc_nvim_1.languages.registerImplementationProvider(languageIds, definitionProvider));
5813 this.disposables.push(coc_nvim_1.languages.registerReferencesProvider(languageIds, new references_1.default(client)));
5814 this.disposables.push(coc_nvim_1.languages.registerHoverProvider(languageIds, new hover_1.default(client)));
5815 this.disposables.push(coc_nvim_1.languages.registerDocumentHighlightProvider(languageIds, new documentHighlight_1.default(this.client)));
5816 this.disposables.push(coc_nvim_1.languages.registerSignatureHelpProvider(languageIds, new signatureHelp_1.default(client), ['(', ',', '<', ')']));
5817 this.disposables.push(coc_nvim_1.languages.registerDocumentSymbolProvider(languageIds, new documentSymbol_1.default(client)));
5818 this.disposables.push(coc_nvim_1.languages.registerWorkspaceSymbolProvider(languageIds, new workspaceSymbols_1.default(client, languageIds)));
5819 this.disposables.push(coc_nvim_1.languages.registerRenameProvider(languageIds, new rename_1.default(client)));
5820 let formatProvider = new formatting_1.default(client, this.fileConfigurationManager);
5821 this.disposables.push(coc_nvim_1.languages.registerDocumentFormatProvider(languageIds, formatProvider));
5822 this.disposables.push(coc_nvim_1.languages.registerDocumentRangeFormatProvider(languageIds, formatProvider));
5823 this.disposables.push(coc_nvim_1.languages.registerOnTypeFormattingEditProvider(languageIds, formatProvider, [';', '}', '\n', String.fromCharCode(27)]));
5824 // this.disposables.push(
5825 // new ProjectError(client, commandManager)
5827 if (this.client.apiVersion.gte(api_1.default.v280)) {
5828 this.disposables.push(coc_nvim_1.languages.registerFoldingRangeProvider(languageIds, new folding_1.default(this.client)));
5829 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]));
5831 let { fileConfigurationManager } = this;
5832 let conf = fileConfigurationManager.getLanguageConfiguration(this.id);
5833 if (this.client.apiVersion.gte(api_1.default.v290)
5834 && conf.get('updateImportsOnFileMove.enable')) {
5835 this.disposables.push(new updatePathOnRename_1.default(client, this.fileConfigurationManager, this.id));
5837 if (this.client.apiVersion.gte(api_1.default.v240)) {
5838 this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new refactor_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.Refactor]));
5840 this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new moduleInstall_1.default(client), 'tsserver'));
5841 this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new quickfix_1.default(client), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
5842 this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new importFix_1.default(this.client.bufferSyncSupport), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
5843 let cachedResponse = new baseCodeLensProvider_1.CachedNavTreeResponse();
5844 if (this.client.apiVersion.gte(api_1.default.v206)
5845 && conf.get('referencesCodeLens.enable')) {
5846 this.disposables.push(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new referencesCodeLens_1.default(client, cachedResponse)));
5848 if (this.client.apiVersion.gte(api_1.default.v220)
5849 && conf.get('implementationsCodeLens.enable')) {
5850 this.disposables.push(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new implementationsCodeLens_1.default(client, cachedResponse)));
5852 if (this.client.apiVersion.gte(api_1.default.v350)) {
5853 this.disposables.push(coc_nvim_1.languages.registerSelectionRangeProvider(languageIds, new smartSelect_1.default(this.client)));
5855 if (this.description.id == 'typescript') {
5856 // this.client.apiVersion
5857 this.disposables.push(new watchBuild_1.default(coc_nvim_1.commands, this.client));
5859 // if (this.client.apiVersion.gte(API.v300)) {
5860 // this.disposables.push(
5861 // languages.registerCompletionItemProvider(
5862 // `tsserver-${this.description.id}-tag`,
5865 // new TagCompletionProvider(client),
5872 let { modeIds, configFile } = this.description;
5873 if (resource.toString().endsWith(configFile)) {
5876 let doc = coc_nvim_1.workspace.getDocument(resource.toString());
5877 if (doc && modeIds.indexOf(doc.filetype) !== -1) {
5880 let str = resource.toString();
5881 if (this.id === 'typescript' && /\.ts(x)?$/.test(str)) {
5884 if (this.id === 'javascript' && /\.js(x)?$/.test(str)) {
5890 return this.description.id;
5892 get diagnosticSource() {
5893 return this.description.diagnosticSource;
5895 triggerAllDiagnostics() {
5896 this.client.bufferSyncSupport.requestAllDiagnostics();
5898 diagnosticsReceived(diagnosticsKind, file, diagnostics) {
5899 if (!this.client.bufferSyncSupport.shouldValidate(file.toString())) {
5902 const config = coc_nvim_1.workspace.getConfiguration(this.id, file.toString());
5903 const reportUnnecessary = config.get('showUnused', true);
5904 this.client.diagnosticsManager.diagnosticsReceived(diagnosticsKind, file.toString(), diagnostics.filter(diag => {
5905 if (!reportUnnecessary) {
5906 diag.tags = undefined;
5907 if (diag.reportUnnecessary && diag.severity === vscode_languageserver_protocol_1.DiagnosticSeverity.Information) {
5915 exports.default = LanguageProvider;
5920 /***/ (function(module, exports, __webpack_require__) {
5924 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5925 if (k2 === undefined) k2 = k;
5926 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5927 }) : (function(o, m, k, k2) {
5928 if (k2 === undefined) k2 = k;
5931 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
5932 Object.defineProperty(o, "default", { enumerable: true, value: v });
5933 }) : function(o, v) {
5936 var __importStar = (this && this.__importStar) || function (mod) {
5937 if (mod && mod.__esModule) return mod;
5939 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
5940 __setModuleDefault(result, mod);
5943 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5944 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5945 return new (P || (P = Promise))(function (resolve, reject) {
5946 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5947 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
5948 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
5949 step((generator = generator.apply(thisArg, _arguments || [])).next());
5952 Object.defineProperty(exports, "__esModule", { value: true });
5953 exports.TypeScriptBaseCodeLensProvider = exports.CachedNavTreeResponse = void 0;
5954 /*---------------------------------------------------------------------------------------------
5955 * Copyright (c) Microsoft Corporation. All rights reserved.
5956 * Licensed under the MIT License. See License.txt in the project root for license information.
5957 *--------------------------------------------------------------------------------------------*/
5958 const vscode_languageserver_protocol_1 = __webpack_require__(3);
5959 const regexp_1 = __webpack_require__(36);
5960 const typeConverters = __importStar(__webpack_require__(37));
5961 class CachedNavTreeResponse {
5966 execute(document, f) {
5967 if (this.matches(document)) {
5968 return this.response;
5970 return this.update(document, f());
5973 return (this.version === document.version &&
5974 this.document === document.uri.toString());
5976 update(document, response) {
5977 this.response = response;
5978 this.version = document.version;
5979 this.document = document.uri.toString();
5983 exports.CachedNavTreeResponse = CachedNavTreeResponse;
5984 class TypeScriptBaseCodeLensProvider {
5985 constructor(client, cachedResponse) {
5986 this.client = client;
5987 this.cachedResponse = cachedResponse;
5988 this.onDidChangeCodeLensesEmitter = new vscode_languageserver_protocol_1.Emitter();
5990 get onDidChangeCodeLenses() {
5991 return this.onDidChangeCodeLensesEmitter.event;
5993 provideCodeLenses(document, token) {
5994 return __awaiter(this, void 0, void 0, function* () {
5995 const filepath = this.client.toPath(document.uri);
6000 const response = yield this.cachedResponse.execute(document, () => this.client.execute('navtree', { file: filepath }, token));
6004 const tree = response.body;
6005 const referenceableSpans = [];
6006 if (tree && tree.childItems) {
6007 tree.childItems.forEach(item => this.walkNavTree(document, item, null, referenceableSpans));
6009 return referenceableSpans.map(range => {
6012 data: { uri: document.uri }
6021 walkNavTree(document, item, parent, results) {
6025 const range = this.extractSymbol(document, item, parent);
6027 results.push(range);
6029 if (item.childItems) {
6030 item.childItems.forEach(child => this.walkNavTree(document, child, item, results));
6033 getSymbolRange(document, item) {
6037 // TS 3.0+ provides a span for just the symbol
6038 if (item.nameSpan) {
6039 return typeConverters.Range.fromTextSpan(item.nameSpan);
6041 // In older versions, we have to calculate this manually. See #23924
6042 const span = item.spans && item.spans[0];
6046 const range = typeConverters.Range.fromTextSpan(span);
6047 const text = document.getText(range);
6048 const identifierMatch = new RegExp(`^(.*?(\\b|\\W))${regexp_1.escapeRegExp(item.text || '')}(\\b|\\W)`, 'gm');
6049 const match = identifierMatch.exec(text);
6050 const prefixLength = match ? match.index + match[1].length : 0;
6051 const startOffset = document.offsetAt(range.start) + prefixLength;
6053 start: document.positionAt(startOffset),
6054 end: document.positionAt(startOffset + item.text.length)
6058 exports.TypeScriptBaseCodeLensProvider = TypeScriptBaseCodeLensProvider;
6063 /***/ (function(module, exports, __webpack_require__) {
6067 /*---------------------------------------------------------------------------------------------
6068 * Copyright (c) Microsoft Corporation. All rights reserved.
6069 * Licensed under the MIT License. See License.txt in the project root for license information.
6070 *--------------------------------------------------------------------------------------------*/
6071 Object.defineProperty(exports, "__esModule", { value: true });
6072 exports.escapeRegExp = void 0;
6073 function escapeRegExp(text) {
6074 return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
6076 exports.escapeRegExp = escapeRegExp;
6081 /***/ (function(module, exports, __webpack_require__) {
6085 Object.defineProperty(exports, "__esModule", { value: true });
6086 exports.WorkspaceEdit = exports.TextEdit = exports.Location = exports.Position = exports.Range = void 0;
6089 Range.fromTextSpan = (span) => {
6092 line: span.start.line - 1,
6093 character: span.start.offset - 1
6096 line: span.end.line - 1,
6097 character: span.end.offset - 1
6101 Range.toFormattingRequestArgs = (file, range) => ({
6103 line: range.start.line + 1,
6104 offset: range.start.character + 1,
6105 endLine: range.end.line + 1,
6106 endOffset: range.end.character + 1
6108 Range.toFileRangeRequestArgs = (file, range) => ({
6110 startLine: range.start.line + 1,
6111 startOffset: range.start.character + 1,
6112 endLine: range.end.line + 1,
6113 endOffset: range.end.character + 1
6115 })(Range = exports.Range || (exports.Range = {}));
6117 (function (Position) {
6118 Position.fromLocation = (tslocation) => {
6120 line: tslocation.line - 1,
6121 character: tslocation.offset - 1
6124 Position.toLocation = (position) => ({
6125 line: position.line + 1,
6126 offset: position.character + 1,
6128 Position.toFileLocationRequestArgs = (file, position) => ({
6130 line: position.line + 1,
6131 offset: position.character + 1
6133 })(Position = exports.Position || (exports.Position = {}));
6135 (function (Location) {
6136 Location.fromTextSpan = (uri, tsTextSpan) => {
6139 range: Range.fromTextSpan(tsTextSpan)
6142 })(Location = exports.Location || (exports.Location = {}));
6144 (function (TextEdit) {
6145 TextEdit.fromCodeEdit = (edit) => {
6147 range: Range.fromTextSpan(edit),
6148 newText: edit.newText
6151 })(TextEdit = exports.TextEdit || (exports.TextEdit = {}));
6153 (function (WorkspaceEdit) {
6154 function fromFileCodeEdits(client, edits) {
6156 for (const edit of edits) {
6157 let uri = client.toResource(edit.fileName);
6158 changes[uri] = edit.textChanges.map(change => {
6159 return TextEdit.fromCodeEdit(change);
6164 WorkspaceEdit.fromFileCodeEdits = fromFileCodeEdits;
6165 })(WorkspaceEdit = exports.WorkspaceEdit || (exports.WorkspaceEdit = {}));
6170 /***/ (function(module, exports, __webpack_require__) {
6174 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6175 if (k2 === undefined) k2 = k;
6176 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
6177 }) : (function(o, m, k, k2) {
6178 if (k2 === undefined) k2 = k;
6181 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
6182 Object.defineProperty(o, "default", { enumerable: true, value: v });
6183 }) : function(o, v) {
6186 var __importStar = (this && this.__importStar) || function (mod) {
6187 if (mod && mod.__esModule) return mod;
6189 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
6190 __setModuleDefault(result, mod);
6193 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
6194 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6195 return new (P || (P = Promise))(function (resolve, reject) {
6196 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6197 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6198 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
6199 step((generator = generator.apply(thisArg, _arguments || [])).next());
6202 var __importDefault = (this && this.__importDefault) || function (mod) {
6203 return (mod && mod.__esModule) ? mod : { "default": mod };
6205 Object.defineProperty(exports, "__esModule", { value: true });
6206 /*---------------------------------------------------------------------------------------------
6207 * Copyright (c) Microsoft Corporation. All rights reserved.
6208 * Licensed under the MIT License. See License.txt in the project root for license information.
6209 *--------------------------------------------------------------------------------------------*/
6210 const vscode_languageserver_protocol_1 = __webpack_require__(3);
6211 const coc_nvim_1 = __webpack_require__(1);
6212 const PConst = __importStar(__webpack_require__(39));
6213 const api_1 = __importDefault(__webpack_require__(40));
6214 const codeAction_1 = __webpack_require__(84);
6215 const completionItem_1 = __webpack_require__(85);
6216 const Previewer = __importStar(__webpack_require__(86));
6217 const typeConverters = __importStar(__webpack_require__(37));
6218 const SnippetString_1 = __importDefault(__webpack_require__(87));
6219 class ApplyCompletionCodeActionCommand {
6220 constructor(client) {
6221 this.client = client;
6222 this.id = ApplyCompletionCodeActionCommand.ID;
6224 // apply code action on complete
6225 execute(codeActions) {
6226 return __awaiter(this, void 0, void 0, function* () {
6227 if (codeActions.length === 0) {
6230 if (codeActions.length === 1) {
6231 yield codeAction_1.applyCodeAction(this.client, codeActions[0]);
6234 const idx = yield coc_nvim_1.workspace.showQuickpick(codeActions.map(o => o.description), 'Select code action to apply');
6237 const action = codeActions[idx];
6238 yield codeAction_1.applyCodeAction(this.client, action);
6243 ApplyCompletionCodeActionCommand.ID = '_typescript.applyCompletionCodeAction';
6244 class TypeScriptCompletionItemProvider {
6245 constructor(client, typingsStatus, fileConfigurationManager, languageId) {
6246 this.client = client;
6247 this.typingsStatus = typingsStatus;
6248 this.fileConfigurationManager = fileConfigurationManager;
6249 this.setCompleteOption(languageId);
6250 coc_nvim_1.commands.register(new ApplyCompletionCodeActionCommand(this.client));
6251 coc_nvim_1.workspace.onDidChangeConfiguration(_e => {
6252 this.setCompleteOption(languageId);
6255 setCompleteOption(languageId) {
6256 this.completeOption = this.fileConfigurationManager.getCompleteOptions(languageId);
6259 * Get completionItems
6262 * @param {TextDocument} document
6263 * @param {Position} position
6264 * @param {CancellationToken} token
6265 * @param {string} triggerCharacter
6266 * @returns {Promise<CompletionItem[]>}
6268 provideCompletionItems(document, position, token, context) {
6269 return __awaiter(this, void 0, void 0, function* () {
6270 if (this.typingsStatus.isAcquiringTypings) {
6271 return Promise.resolve({
6274 label: 'Acquiring typings...',
6275 detail: 'Acquiring typings definitions for IntelliSense.'
6279 let { uri } = document;
6280 const file = this.client.toPath(document.uri);
6283 let preText = document.getText({
6284 start: { line: position.line, character: 0 },
6287 let { triggerCharacter, option } = context;
6288 if (!this.shouldTrigger(triggerCharacter, preText, option)) {
6291 const { completeOption } = this;
6292 const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { includeExternalModuleExports: completeOption.autoImports, includeInsertTextCompletions: true, triggerCharacter: this.getTsTriggerCharacter(context), includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions });
6294 let dotAccessorContext;
6295 let isNewIdentifierLocation = true;
6296 let isMemberCompletion = false;
6297 let isIncomplete = false;
6298 const isInValidCommitCharacterContext = this.isInValidCommitCharacterContext(document, position);
6299 if (this.client.apiVersion.gte(api_1.default.v300)) {
6301 const response = yield this.client.interruptGetErr(() => this.client.execute('completionInfo', args, token));
6302 if (response.type !== 'response' || !response.body) {
6305 isNewIdentifierLocation = response.body.isNewIdentifierLocation;
6306 isMemberCompletion = response.body.isMemberCompletion;
6307 if (isMemberCompletion) {
6308 const dotMatch = preText.slice(0, position.character).match(/\??\.\s*$/) || undefined;
6310 const range = vscode_languageserver_protocol_1.Range.create({
6311 line: position.line,
6312 character: position.character - dotMatch.length
6314 const text = document.getText(range);
6315 dotAccessorContext = { range, text };
6318 isIncomplete = response.metadata && response.metadata.isIncomplete;
6319 entries = response.body.entries;
6322 if (e.message == 'No content available.') {
6329 const response = yield this.client.interruptGetErr(() => this.client.execute('completions', args, token));
6330 if (response.type !== 'response' || !response.body) {
6333 entries = response.body;
6335 const completionItems = [];
6336 for (const element of entries) {
6337 if (shouldExcludeCompletionEntry(element, completeOption)) {
6340 const item = completionItem_1.convertCompletionEntry(element, uri, position, {
6341 isNewIdentifierLocation,
6343 enableCallCompletions: completeOption.completeFunctionCalls,
6344 isInValidCommitCharacterContext,
6347 completionItems.push(item);
6349 return { isIncomplete, items: completionItems };
6352 getTsTriggerCharacter(context) {
6353 // return context.triggerCharacter as Proto.CompletionsTriggerCharacter
6354 switch (context.triggerCharacter) {
6355 case '@': // Workaround for https://github.com/Microsoft/TypeScript/issues/27321
6356 return this.client.apiVersion.gte(api_1.default.v310) && this.client.apiVersion.lt(api_1.default.v320) ? undefined : '@';
6357 case '#': // Workaround for https://github.com/microsoft/TypeScript/issues/36367
6358 return this.client.apiVersion.lt(api_1.default.v381) ? undefined : '#';
6365 return context.triggerCharacter;
6370 * Resolve complete item, could have documentation added
6373 * @param {CompletionItem} item
6374 * @param {CancellationToken} token
6375 * @returns {Promise<CompletionItem>}
6377 resolveCompletionItem(item, token) {
6378 return __awaiter(this, void 0, void 0, function* () {
6381 let { uri, position, source } = item.data;
6382 const filepath = this.client.toPath(uri);
6385 let document = coc_nvim_1.workspace.getDocument(uri);
6388 const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(filepath, position)), { entryNames: [
6390 ? { name: item.label, source }
6395 response = yield this.client.interruptGetErr(() => this.client.execute('completionEntryDetails', args, token));
6400 if (response.type !== 'response' || !response.body) {
6403 const details = response.body;
6404 if (!details || !details.length || !details[0]) {
6407 const detail = details[0];
6408 if (!item.detail && detail.displayParts.length) {
6409 item.detail = Previewer.plain(detail.displayParts);
6411 item.documentation = this.getDocumentation(detail);
6412 const { command, additionalTextEdits } = this.getCodeActions(detail, filepath);
6414 item.command = command;
6415 item.additionalTextEdits = additionalTextEdits;
6416 if (detail && item.insertTextFormat == vscode_languageserver_protocol_1.InsertTextFormat.Snippet) {
6417 const shouldCompleteFunction = yield this.isValidFunctionCompletionContext(filepath, position, token);
6418 if (shouldCompleteFunction) {
6419 this.createSnippetOfFunctionCall(item, detail);
6425 getCodeActions(detail, filepath) {
6426 if (!detail.codeActions || !detail.codeActions.length) {
6429 // Try to extract out the additionalTextEdits for the current file.
6430 // Also check if we still have to apply other workspace edits
6431 const additionalTextEdits = [];
6432 let hasRemainingCommandsOrEdits = false;
6433 for (const tsAction of detail.codeActions) {
6434 if (tsAction.commands) {
6435 hasRemainingCommandsOrEdits = true;
6437 // Convert all edits in the current file using `additionalTextEdits`
6438 if (tsAction.changes) {
6439 for (const change of tsAction.changes) {
6440 if (change.fileName === filepath) {
6441 additionalTextEdits.push(...change.textChanges.map(typeConverters.TextEdit.fromCodeEdit));
6444 hasRemainingCommandsOrEdits = true;
6450 if (hasRemainingCommandsOrEdits) {
6451 // Create command that applies all edits not in the current file.
6454 command: ApplyCompletionCodeActionCommand.ID,
6456 detail.codeActions.map((x) => ({
6457 commands: x.commands,
6458 description: x.description,
6459 changes: x.changes.filter(x => x.fileName !== filepath)
6466 additionalTextEdits: additionalTextEdits.length
6467 ? additionalTextEdits
6471 shouldTrigger(triggerCharacter, pre, option) {
6472 if (triggerCharacter && this.client.apiVersion.lt(api_1.default.v290)) {
6473 if (triggerCharacter === '@') {
6474 // trigger in string
6475 if (option.synname && /string/i.test(option.synname)) {
6478 // make sure we are in something that looks like the start of a jsdoc comment
6479 if (!pre.match(/^\s*\*[ ]?@/) && !pre.match(/\/\*\*+[ ]?@/)) {
6483 else if (triggerCharacter === '<') {
6489 // complete item documentation
6490 getDocumentation(detail) {
6491 let documentation = '';
6492 if (detail.source) {
6493 const importPath = `'${Previewer.plain(detail.source)}'`;
6494 const autoImportLabel = `Auto import from ${importPath}`;
6495 documentation += `${autoImportLabel}\n`;
6498 Previewer.plain(detail.documentation),
6499 Previewer.tagsMarkdownPreview(detail.tags)
6501 parts = parts.filter(s => s && s.trim() != '');
6502 documentation += parts.join('\n\n');
6503 if (documentation.length) {
6505 kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
6506 value: documentation
6511 createSnippetOfFunctionCall(item, detail) {
6512 let { displayParts } = detail;
6513 const parameterListParts = completionItem_1.getParameterListParts(displayParts);
6514 const snippet = new SnippetString_1.default();
6515 snippet.appendText(`${item.insertText || item.label}(`);
6516 appendJoinedPlaceholders(snippet, parameterListParts.parts, ', ');
6517 if (parameterListParts.hasOptionalParameters) {
6518 snippet.appendTabstop();
6520 snippet.appendText(')');
6521 snippet.appendTabstop(0);
6522 item.insertText = snippet.value;
6524 isValidFunctionCompletionContext(filepath, position, token) {
6525 return __awaiter(this, void 0, void 0, function* () {
6526 // Workaround for https://github.com/Microsoft/TypeScript/issues/12677
6527 // Don't complete function calls inside of destructive assigments or imports
6529 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
6530 const response = yield this.client.execute('quickinfo', args, token);
6531 if (response.type !== 'response') {
6534 const { body } = response;
6535 switch (body && body.kind) {
6550 isInValidCommitCharacterContext(document, position) {
6551 if (this.client.apiVersion.lt(api_1.default.v320)) {
6552 // Workaround for https://github.com/Microsoft/TypeScript/issues/27742
6553 // Only enable dot completions when previous character not a dot preceded by whitespace.
6554 // Prevents incorrectly completing while typing spread operators.
6555 if (position.character > 1) {
6556 const preText = document.getText(vscode_languageserver_protocol_1.Range.create(position.line, 0, position.line, position.character));
6557 return preText.match(/(\s|^)\.$/ig) === null;
6563 exports.default = TypeScriptCompletionItemProvider;
6564 TypeScriptCompletionItemProvider.triggerCharacters = ['.', '"', '\'', '`', '/', '@', '<', '#'];
6565 function shouldExcludeCompletionEntry(element, completionConfiguration) {
6566 return ((!completionConfiguration.names && element.kind === PConst.Kind.warning)
6567 || (!completionConfiguration.paths &&
6568 (element.kind === PConst.Kind.directory || element.kind === PConst.Kind.script || element.kind === PConst.Kind.externalModuleName))
6569 || (!completionConfiguration.autoImports && element.hasAction));
6571 function appendJoinedPlaceholders(snippet, parts, joiner) {
6572 for (let i = 0; i < parts.length; ++i) {
6573 const paramterPart = parts[i];
6574 snippet.appendPlaceholder(paramterPart.text);
6575 if (i !== parts.length - 1) {
6576 snippet.appendText(joiner);
6584 /***/ (function(module, exports, __webpack_require__) {
6588 /*---------------------------------------------------------------------------------------------
6589 * Copyright (c) Microsoft Corporation. All rights reserved.
6590 * Licensed under the MIT License. See License.txt in the project root for license information.
6591 *--------------------------------------------------------------------------------------------*/
6592 Object.defineProperty(exports, "__esModule", { value: true });
6593 exports.DisplayPartKind = exports.KindModifiers = exports.DiagnosticCategory = exports.Kind = void 0;
6596 exports.Kind = Kind;
6597 Kind.alias = 'alias';
6598 Kind.callSignature = 'call';
6599 Kind.class = 'class';
6600 Kind.const = 'const';
6601 Kind.constructorImplementation = 'constructor';
6602 Kind.constructSignature = 'construct';
6603 Kind.directory = 'directory';
6605 Kind.enumMember = 'enum member';
6606 Kind.externalModuleName = 'external module name';
6607 Kind.function = 'function';
6608 Kind.indexSignature = 'index';
6609 Kind.interface = 'interface';
6610 Kind.keyword = 'keyword';
6612 Kind.localFunction = 'local function';
6613 Kind.localVariable = 'local var';
6614 Kind.method = 'method';
6615 Kind.memberGetAccessor = 'getter';
6616 Kind.memberSetAccessor = 'setter';
6617 Kind.memberVariable = 'property';
6618 Kind.module = 'module';
6619 Kind.primitiveType = 'primitive type';
6620 Kind.script = 'script';
6622 Kind.variable = 'var';
6623 Kind.warning = 'warning';
6624 Kind.string = 'string';
6625 Kind.parameter = 'parameter';
6626 Kind.typeParameter = 'type parameter';
6627 class DiagnosticCategory {
6629 exports.DiagnosticCategory = DiagnosticCategory;
6630 DiagnosticCategory.error = 'error';
6631 DiagnosticCategory.warning = 'warning';
6632 DiagnosticCategory.suggestion = 'suggestion';
6633 class KindModifiers {
6635 exports.KindModifiers = KindModifiers;
6636 KindModifiers.optional = 'optional';
6637 KindModifiers.color = 'color';
6638 KindModifiers.dtsFile = '.d.ts';
6639 KindModifiers.tsFile = '.ts';
6640 KindModifiers.tsxFile = '.tsx';
6641 KindModifiers.jsFile = '.js';
6642 KindModifiers.jsxFile = '.jsx';
6643 KindModifiers.jsonFile = '.json';
6644 KindModifiers.fileExtensionKindModifiers = [
6645 KindModifiers.dtsFile,
6646 KindModifiers.tsFile,
6647 KindModifiers.tsxFile,
6648 KindModifiers.jsFile,
6649 KindModifiers.jsxFile,
6650 KindModifiers.jsonFile,
6652 class DisplayPartKind {
6654 exports.DisplayPartKind = DisplayPartKind;
6655 DisplayPartKind.functionName = 'functionName';
6656 DisplayPartKind.methodName = 'methodName';
6657 DisplayPartKind.parameterName = 'parameterName';
6658 DisplayPartKind.propertyName = 'propertyName';
6659 DisplayPartKind.punctuation = 'punctuation';
6660 DisplayPartKind.text = 'text';
6665 /***/ (function(module, exports, __webpack_require__) {
6669 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6670 if (k2 === undefined) k2 = k;
6671 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
6672 }) : (function(o, m, k, k2) {
6673 if (k2 === undefined) k2 = k;
6676 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
6677 Object.defineProperty(o, "default", { enumerable: true, value: v });
6678 }) : function(o, v) {
6681 var __importStar = (this && this.__importStar) || function (mod) {
6682 if (mod && mod.__esModule) return mod;
6684 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
6685 __setModuleDefault(result, mod);
6688 Object.defineProperty(exports, "__esModule", { value: true });
6689 /*---------------------------------------------------------------------------------------------
6690 * Copyright (c) Microsoft Corporation. All rights reserved.
6691 * Licensed under the MIT License. See License.txt in the project root for license information.
6692 *--------------------------------------------------------------------------------------------*/
6693 const semver = __importStar(__webpack_require__(41));
6695 constructor(versionString, version) {
6696 this.versionString = versionString;
6697 this.version = version;
6699 static fromSimpleString(value) {
6700 return new API(value, value);
6702 static fromVersionString(versionString) {
6703 let version = semver.valid(versionString);
6705 return new API('invalid version', '1.0.0');
6707 // Cut off any prerelease tag since we sometimes consume those on purpose.
6708 const index = versionString.indexOf('-');
6710 version = version.substr(0, index);
6712 return new API(versionString, version);
6715 return semver.gte(this.version, other.version);
6718 return !this.gte(other);
6721 exports.default = API;
6722 API.defaultVersion = API.fromSimpleString('1.0.0');
6723 API.v203 = API.fromSimpleString('2.0.3');
6724 API.v206 = API.fromSimpleString('2.0.6');
6725 API.v208 = API.fromSimpleString('2.0.8');
6726 API.v213 = API.fromSimpleString('2.1.3');
6727 API.v220 = API.fromSimpleString('2.2.0');
6728 API.v222 = API.fromSimpleString('2.2.2');
6729 API.v230 = API.fromSimpleString('2.3.0');
6730 API.v234 = API.fromSimpleString('2.3.4');
6731 API.v240 = API.fromSimpleString('2.4.0');
6732 API.v250 = API.fromSimpleString('2.5.0');
6733 API.v260 = API.fromSimpleString('2.6.0');
6734 API.v270 = API.fromSimpleString('2.7.0');
6735 API.v280 = API.fromSimpleString('2.8.0');
6736 API.v290 = API.fromSimpleString('2.9.0');
6737 API.v291 = API.fromSimpleString('2.9.1');
6738 API.v292 = API.fromSimpleString('2.9.2');
6739 API.v300 = API.fromSimpleString('3.0.0');
6740 API.v310 = API.fromSimpleString('3.1.0');
6741 API.v314 = API.fromSimpleString('3.1.4');
6742 API.v320 = API.fromSimpleString('3.2.0');
6743 API.v330 = API.fromSimpleString('3.3.0');
6744 API.v333 = API.fromSimpleString('3.3.3');
6745 API.v340 = API.fromSimpleString('3.4.0');
6746 API.v345 = API.fromSimpleString('3.4.5');
6747 API.v350 = API.fromSimpleString('3.5.0');
6748 API.v380 = API.fromSimpleString('3.8.0');
6749 API.v381 = API.fromSimpleString('3.8.1');
6750 API.v390 = API.fromSimpleString('3.9.0');
6755 /***/ (function(module, exports, __webpack_require__) {
6757 // just pre-load all the stuff that index.js lazily exports
6758 const internalRe = __webpack_require__(42)
6761 src: internalRe.src,
6762 tokens: internalRe.t,
6763 SEMVER_SPEC_VERSION: __webpack_require__(43).SEMVER_SPEC_VERSION,
6764 SemVer: __webpack_require__(45),
6765 compareIdentifiers: __webpack_require__(46).compareIdentifiers,
6766 rcompareIdentifiers: __webpack_require__(46).rcompareIdentifiers,
6767 parse: __webpack_require__(47),
6768 valid: __webpack_require__(48),
6769 clean: __webpack_require__(49),
6770 inc: __webpack_require__(50),
6771 diff: __webpack_require__(51),
6772 major: __webpack_require__(54),
6773 minor: __webpack_require__(55),
6774 patch: __webpack_require__(56),
6775 prerelease: __webpack_require__(57),
6776 compare: __webpack_require__(53),
6777 rcompare: __webpack_require__(58),
6778 compareLoose: __webpack_require__(59),
6779 compareBuild: __webpack_require__(60),
6780 sort: __webpack_require__(61),
6781 rsort: __webpack_require__(62),
6782 gt: __webpack_require__(63),
6783 lt: __webpack_require__(64),
6784 eq: __webpack_require__(52),
6785 neq: __webpack_require__(65),
6786 gte: __webpack_require__(66),
6787 lte: __webpack_require__(67),
6788 cmp: __webpack_require__(68),
6789 coerce: __webpack_require__(69),
6790 Comparator: __webpack_require__(70),
6791 Range: __webpack_require__(71),
6792 satisfies: __webpack_require__(72),
6793 toComparators: __webpack_require__(73),
6794 maxSatisfying: __webpack_require__(74),
6795 minSatisfying: __webpack_require__(75),
6796 minVersion: __webpack_require__(76),
6797 validRange: __webpack_require__(77),
6798 outside: __webpack_require__(78),
6799 gtr: __webpack_require__(79),
6800 ltr: __webpack_require__(80),
6801 intersects: __webpack_require__(81),
6802 simplifyRange: __webpack_require__(82),
6803 subset: __webpack_require__(83),
6809 /***/ (function(module, exports, __webpack_require__) {
6811 const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(43)
6812 const debug = __webpack_require__(44)
6813 exports = module.exports = {}
6815 // The actual regexps go on exports.re
6816 const re = exports.re = []
6817 const src = exports.src = []
6818 const t = exports.t = {}
6821 const createToken = (name, value, isGlobal) => {
6826 re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
6829 // The following Regular Expressions can be used for tokenizing,
6830 // validating, and parsing SemVer version strings.
6832 // ## Numeric Identifier
6833 // A single `0`, or a non-zero digit followed by zero or more digits.
6835 createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
6836 createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+')
6838 // ## Non-numeric Identifier
6839 // Zero or more digits, followed by a letter or hyphen, and then zero or
6840 // more letters, digits, or hyphens.
6842 createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*')
6845 // Three dot-separated numeric identifiers.
6847 createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
6848 `(${src[t.NUMERICIDENTIFIER]})\\.` +
6849 `(${src[t.NUMERICIDENTIFIER]})`)
6851 createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
6852 `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
6853 `(${src[t.NUMERICIDENTIFIERLOOSE]})`)
6855 // ## Pre-release Version Identifier
6856 // A numeric identifier, or a non-numeric identifier.
6858 createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
6859 }|${src[t.NONNUMERICIDENTIFIER]})`)
6861 createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
6862 }|${src[t.NONNUMERICIDENTIFIER]})`)
6864 // ## Pre-release Version
6865 // Hyphen, followed by one or more dot-separated pre-release version
6868 createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
6869 }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
6871 createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
6872 }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
6874 // ## Build Metadata Identifier
6875 // Any combination of digits, letters, or hyphens.
6877 createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')
6879 // ## Build Metadata
6880 // Plus sign, followed by one or more period-separated build metadata
6883 createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
6884 }(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
6886 // ## Full Version String
6887 // A main version, followed optionally by a pre-release version and
6890 // Note that the only major, minor, patch, and pre-release sections of
6891 // the version string are capturing groups. The build metadata is not a
6892 // capturing group, because it should not ever be used in version
6895 createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
6896 }${src[t.PRERELEASE]}?${
6899 createToken('FULL', `^${src[t.FULLPLAIN]}$`)
6901 // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
6902 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
6903 // common in the npm registry.
6904 createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
6905 }${src[t.PRERELEASELOOSE]}?${
6908 createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
6910 createToken('GTLT', '((?:<|>)?=?)')
6912 // Something like "2.*" or "1.2.x".
6913 // Note that "x.x" is a valid xRange identifer, meaning "any version"
6914 // Only the first item is strictly required.
6915 createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
6916 createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
6918 createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
6919 `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
6920 `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
6921 `(?:${src[t.PRERELEASE]})?${
6925 createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
6926 `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
6927 `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
6928 `(?:${src[t.PRERELEASELOOSE]})?${
6932 createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
6933 createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
6936 // Extract anything that could conceivably be a part of a valid semver
6937 createToken('COERCE', `${'(^|[^\\d])' +
6938 '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
6939 `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
6940 `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
6942 createToken('COERCERTL', src[t.COERCE], true)
6945 // Meaning is "reasonably at or greater than"
6946 createToken('LONETILDE', '(?:~>?)')
6948 createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
6949 exports.tildeTrimReplace = '$1~'
6951 createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
6952 createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
6955 // Meaning is "at least and backwards compatible with"
6956 createToken('LONECARET', '(?:\\^)')
6958 createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
6959 exports.caretTrimReplace = '$1^'
6961 createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
6962 createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
6964 // A simple gt/lt/eq thing, or just "" to indicate "any version"
6965 createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
6966 createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
6968 // An expression to strip any whitespace between the gtlt and the thing
6969 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
6970 createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
6971 }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
6972 exports.comparatorTrimReplace = '$1$2$3'
6974 // Something like `1.2.3 - 1.2.4`
6975 // Note that these all use the loose form, because they'll be
6976 // checked against either the strict or loose comparator form
6978 createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
6980 `(${src[t.XRANGEPLAIN]})` +
6983 createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
6985 `(${src[t.XRANGEPLAINLOOSE]})` +
6988 // Star ranges basically just allow anything at all.
6989 createToken('STAR', '(<|>)?=?\\s*\\*')
6990 // >=0.0.0 is like a star
6991 createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$')
6992 createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$')
6997 /***/ (function(module, exports) {
6999 // Note: this is the semver.org version of the spec that it implements
7000 // Not necessarily the package version of this code.
7001 const SEMVER_SPEC_VERSION = '2.0.0'
7003 const MAX_LENGTH = 256
7004 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
7005 /* istanbul ignore next */ 9007199254740991
7007 // Max safe segment length for coercion.
7008 const MAX_SAFE_COMPONENT_LENGTH = 16
7011 SEMVER_SPEC_VERSION,
7014 MAX_SAFE_COMPONENT_LENGTH
7020 /***/ (function(module, exports) {
7023 typeof process === 'object' &&
7025 process.env.NODE_DEBUG &&
7026 /\bsemver\b/i.test(process.env.NODE_DEBUG)
7027 ) ? (...args) => console.error('SEMVER', ...args)
7030 module.exports = debug
7035 /***/ (function(module, exports, __webpack_require__) {
7037 const debug = __webpack_require__(44)
7038 const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(43)
7039 const { re, t } = __webpack_require__(42)
7041 const { compareIdentifiers } = __webpack_require__(46)
7043 constructor (version, options) {
7044 if (!options || typeof options !== 'object') {
7047 includePrerelease: false
7050 if (version instanceof SemVer) {
7051 if (version.loose === !!options.loose &&
7052 version.includePrerelease === !!options.includePrerelease) {
7055 version = version.version
7057 } else if (typeof version !== 'string') {
7058 throw new TypeError(`Invalid Version: ${version}`)
7061 if (version.length > MAX_LENGTH) {
7062 throw new TypeError(
7063 `version is longer than ${MAX_LENGTH} characters`
7067 debug('SemVer', version, options)
7068 this.options = options
7069 this.loose = !!options.loose
7070 // this isn't actually relevant for versions, but keep it so that we
7071 // don't run into trouble passing this.options around.
7072 this.includePrerelease = !!options.includePrerelease
7074 const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
7077 throw new TypeError(`Invalid Version: ${version}`)
7082 // these are actually numbers
7087 if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
7088 throw new TypeError('Invalid major version')
7091 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
7092 throw new TypeError('Invalid minor version')
7095 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
7096 throw new TypeError('Invalid patch version')
7099 // numberify any prerelease numeric ids
7101 this.prerelease = []
7103 this.prerelease = m[4].split('.').map((id) => {
7104 if (/^[0-9]+$/.test(id)) {
7106 if (num >= 0 && num < MAX_SAFE_INTEGER) {
7114 this.build = m[5] ? m[5].split('.') : []
7119 this.version = `${this.major}.${this.minor}.${this.patch}`
7120 if (this.prerelease.length) {
7121 this.version += `-${this.prerelease.join('.')}`
7131 debug('SemVer.compare', this.version, this.options, other)
7132 if (!(other instanceof SemVer)) {
7133 if (typeof other === 'string' && other === this.version) {
7136 other = new SemVer(other, this.options)
7139 if (other.version === this.version) {
7143 return this.compareMain(other) || this.comparePre(other)
7146 compareMain (other) {
7147 if (!(other instanceof SemVer)) {
7148 other = new SemVer(other, this.options)
7152 compareIdentifiers(this.major, other.major) ||
7153 compareIdentifiers(this.minor, other.minor) ||
7154 compareIdentifiers(this.patch, other.patch)
7158 comparePre (other) {
7159 if (!(other instanceof SemVer)) {
7160 other = new SemVer(other, this.options)
7163 // NOT having a prerelease is > having one
7164 if (this.prerelease.length && !other.prerelease.length) {
7166 } else if (!this.prerelease.length && other.prerelease.length) {
7168 } else if (!this.prerelease.length && !other.prerelease.length) {
7174 const a = this.prerelease[i]
7175 const b = other.prerelease[i]
7176 debug('prerelease compare', i, a, b)
7177 if (a === undefined && b === undefined) {
7179 } else if (b === undefined) {
7181 } else if (a === undefined) {
7183 } else if (a === b) {
7186 return compareIdentifiers(a, b)
7191 compareBuild (other) {
7192 if (!(other instanceof SemVer)) {
7193 other = new SemVer(other, this.options)
7198 const a = this.build[i]
7199 const b = other.build[i]
7200 debug('prerelease compare', i, a, b)
7201 if (a === undefined && b === undefined) {
7203 } else if (b === undefined) {
7205 } else if (a === undefined) {
7207 } else if (a === b) {
7210 return compareIdentifiers(a, b)
7215 // preminor will bump the version up to the next minor release, and immediately
7216 // down to pre-release. premajor and prepatch work the same way.
7217 inc (release, identifier) {
7220 this.prerelease.length = 0
7224 this.inc('pre', identifier)
7227 this.prerelease.length = 0
7230 this.inc('pre', identifier)
7233 // If this is already a prerelease, it will bump to the next version
7234 // drop any prereleases that might already exist, since they are not
7235 // relevant at this point.
7236 this.prerelease.length = 0
7237 this.inc('patch', identifier)
7238 this.inc('pre', identifier)
7240 // If the input is a non-prerelease version, this acts the same as
7243 if (this.prerelease.length === 0) {
7244 this.inc('patch', identifier)
7246 this.inc('pre', identifier)
7250 // If this is a pre-major version, bump up to the same major version.
7251 // Otherwise increment major.
7252 // 1.0.0-5 bumps to 1.0.0
7253 // 1.1.0 bumps to 2.0.0
7257 this.prerelease.length === 0
7263 this.prerelease = []
7266 // If this is a pre-minor version, bump up to the same minor version.
7267 // Otherwise increment minor.
7268 // 1.2.0-5 bumps to 1.2.0
7269 // 1.2.1 bumps to 1.3.0
7270 if (this.patch !== 0 || this.prerelease.length === 0) {
7274 this.prerelease = []
7277 // If this is not a pre-release version, it will increment the patch.
7278 // If it is a pre-release it will bump up to the same patch version.
7279 // 1.2.0-5 patches to 1.2.0
7280 // 1.2.0 patches to 1.2.1
7281 if (this.prerelease.length === 0) {
7284 this.prerelease = []
7286 // This probably shouldn't be used publicly.
7287 // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
7289 if (this.prerelease.length === 0) {
7290 this.prerelease = [0]
7292 let i = this.prerelease.length
7294 if (typeof this.prerelease[i] === 'number') {
7295 this.prerelease[i]++
7300 // didn't increment anything
7301 this.prerelease.push(0)
7305 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
7306 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
7307 if (this.prerelease[0] === identifier) {
7308 if (isNaN(this.prerelease[1])) {
7309 this.prerelease = [identifier, 0]
7312 this.prerelease = [identifier, 0]
7318 throw new Error(`invalid increment argument: ${release}`)
7321 this.raw = this.version
7326 module.exports = SemVer
7331 /***/ (function(module, exports) {
7333 const numeric = /^[0-9]+$/
7334 const compareIdentifiers = (a, b) => {
7335 const anum = numeric.test(a)
7336 const bnum = numeric.test(b)
7344 : (anum && !bnum) ? -1
7345 : (bnum && !anum) ? 1
7350 const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
7360 /***/ (function(module, exports, __webpack_require__) {
7362 const {MAX_LENGTH} = __webpack_require__(43)
7363 const { re, t } = __webpack_require__(42)
7364 const SemVer = __webpack_require__(45)
7366 const parse = (version, options) => {
7367 if (!options || typeof options !== 'object') {
7370 includePrerelease: false
7374 if (version instanceof SemVer) {
7378 if (typeof version !== 'string') {
7382 if (version.length > MAX_LENGTH) {
7386 const r = options.loose ? re[t.LOOSE] : re[t.FULL]
7387 if (!r.test(version)) {
7392 return new SemVer(version, options)
7398 module.exports = parse
7403 /***/ (function(module, exports, __webpack_require__) {
7405 const parse = __webpack_require__(47)
7406 const valid = (version, options) => {
7407 const v = parse(version, options)
7408 return v ? v.version : null
7410 module.exports = valid
7415 /***/ (function(module, exports, __webpack_require__) {
7417 const parse = __webpack_require__(47)
7418 const clean = (version, options) => {
7419 const s = parse(version.trim().replace(/^[=v]+/, ''), options)
7420 return s ? s.version : null
7422 module.exports = clean
7427 /***/ (function(module, exports, __webpack_require__) {
7429 const SemVer = __webpack_require__(45)
7431 const inc = (version, release, options, identifier) => {
7432 if (typeof (options) === 'string') {
7433 identifier = options
7438 return new SemVer(version, options).inc(release, identifier).version
7443 module.exports = inc
7448 /***/ (function(module, exports, __webpack_require__) {
7450 const parse = __webpack_require__(47)
7451 const eq = __webpack_require__(52)
7453 const diff = (version1, version2) => {
7454 if (eq(version1, version2)) {
7457 const v1 = parse(version1)
7458 const v2 = parse(version2)
7459 const hasPre = v1.prerelease.length || v2.prerelease.length
7460 const prefix = hasPre ? 'pre' : ''
7461 const defaultResult = hasPre ? 'prerelease' : ''
7462 for (const key in v1) {
7463 if (key === 'major' || key === 'minor' || key === 'patch') {
7464 if (v1[key] !== v2[key]) {
7469 return defaultResult // may be undefined
7472 module.exports = diff
7477 /***/ (function(module, exports, __webpack_require__) {
7479 const compare = __webpack_require__(53)
7480 const eq = (a, b, loose) => compare(a, b, loose) === 0
7486 /***/ (function(module, exports, __webpack_require__) {
7488 const SemVer = __webpack_require__(45)
7489 const compare = (a, b, loose) =>
7490 new SemVer(a, loose).compare(new SemVer(b, loose))
7492 module.exports = compare
7497 /***/ (function(module, exports, __webpack_require__) {
7499 const SemVer = __webpack_require__(45)
7500 const major = (a, loose) => new SemVer(a, loose).major
7501 module.exports = major
7506 /***/ (function(module, exports, __webpack_require__) {
7508 const SemVer = __webpack_require__(45)
7509 const minor = (a, loose) => new SemVer(a, loose).minor
7510 module.exports = minor
7515 /***/ (function(module, exports, __webpack_require__) {
7517 const SemVer = __webpack_require__(45)
7518 const patch = (a, loose) => new SemVer(a, loose).patch
7519 module.exports = patch
7524 /***/ (function(module, exports, __webpack_require__) {
7526 const parse = __webpack_require__(47)
7527 const prerelease = (version, options) => {
7528 const parsed = parse(version, options)
7529 return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
7531 module.exports = prerelease
7536 /***/ (function(module, exports, __webpack_require__) {
7538 const compare = __webpack_require__(53)
7539 const rcompare = (a, b, loose) => compare(b, a, loose)
7540 module.exports = rcompare
7545 /***/ (function(module, exports, __webpack_require__) {
7547 const compare = __webpack_require__(53)
7548 const compareLoose = (a, b) => compare(a, b, true)
7549 module.exports = compareLoose
7554 /***/ (function(module, exports, __webpack_require__) {
7556 const SemVer = __webpack_require__(45)
7557 const compareBuild = (a, b, loose) => {
7558 const versionA = new SemVer(a, loose)
7559 const versionB = new SemVer(b, loose)
7560 return versionA.compare(versionB) || versionA.compareBuild(versionB)
7562 module.exports = compareBuild
7567 /***/ (function(module, exports, __webpack_require__) {
7569 const compareBuild = __webpack_require__(60)
7570 const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
7571 module.exports = sort
7576 /***/ (function(module, exports, __webpack_require__) {
7578 const compareBuild = __webpack_require__(60)
7579 const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
7580 module.exports = rsort
7585 /***/ (function(module, exports, __webpack_require__) {
7587 const compare = __webpack_require__(53)
7588 const gt = (a, b, loose) => compare(a, b, loose) > 0
7594 /***/ (function(module, exports, __webpack_require__) {
7596 const compare = __webpack_require__(53)
7597 const lt = (a, b, loose) => compare(a, b, loose) < 0
7603 /***/ (function(module, exports, __webpack_require__) {
7605 const compare = __webpack_require__(53)
7606 const neq = (a, b, loose) => compare(a, b, loose) !== 0
7607 module.exports = neq
7612 /***/ (function(module, exports, __webpack_require__) {
7614 const compare = __webpack_require__(53)
7615 const gte = (a, b, loose) => compare(a, b, loose) >= 0
7616 module.exports = gte
7621 /***/ (function(module, exports, __webpack_require__) {
7623 const compare = __webpack_require__(53)
7624 const lte = (a, b, loose) => compare(a, b, loose) <= 0
7625 module.exports = lte
7630 /***/ (function(module, exports, __webpack_require__) {
7632 const eq = __webpack_require__(52)
7633 const neq = __webpack_require__(65)
7634 const gt = __webpack_require__(63)
7635 const gte = __webpack_require__(66)
7636 const lt = __webpack_require__(64)
7637 const lte = __webpack_require__(67)
7639 const cmp = (a, op, b, loose) => {
7642 if (typeof a === 'object')
7644 if (typeof b === 'object')
7649 if (typeof a === 'object')
7651 if (typeof b === 'object')
7658 return eq(a, b, loose)
7661 return neq(a, b, loose)
7664 return gt(a, b, loose)
7667 return gte(a, b, loose)
7670 return lt(a, b, loose)
7673 return lte(a, b, loose)
7676 throw new TypeError(`Invalid operator: ${op}`)
7679 module.exports = cmp
7684 /***/ (function(module, exports, __webpack_require__) {
7686 const SemVer = __webpack_require__(45)
7687 const parse = __webpack_require__(47)
7688 const {re, t} = __webpack_require__(42)
7690 const coerce = (version, options) => {
7691 if (version instanceof SemVer) {
7695 if (typeof version === 'number') {
7696 version = String(version)
7699 if (typeof version !== 'string') {
7703 options = options || {}
7707 match = version.match(re[t.COERCE])
7709 // Find the right-most coercible string that does not share
7710 // a terminus with a more left-ward coercible string.
7711 // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
7713 // Walk through the string checking with a /g regexp
7714 // Manually set the index so as to pick up overlapping matches.
7715 // Stop when we get a match that ends at the string end, since no
7716 // coercible string can be more right-ward without the same terminus.
7718 while ((next = re[t.COERCERTL].exec(version)) &&
7719 (!match || match.index + match[0].length !== version.length)
7722 next.index + next[0].length !== match.index + match[0].length) {
7725 re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
7727 // leave it in a clean state
7728 re[t.COERCERTL].lastIndex = -1
7734 return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
7736 module.exports = coerce
7741 /***/ (function(module, exports, __webpack_require__) {
7743 const ANY = Symbol('SemVer ANY')
7744 // hoisted class for cyclic dependency
7749 constructor (comp, options) {
7750 if (!options || typeof options !== 'object') {
7753 includePrerelease: false
7757 if (comp instanceof Comparator) {
7758 if (comp.loose === !!options.loose) {
7765 debug('comparator', comp, options)
7766 this.options = options
7767 this.loose = !!options.loose
7770 if (this.semver === ANY) {
7773 this.value = this.operator + this.semver.version
7780 const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
7781 const m = comp.match(r)
7784 throw new TypeError(`Invalid comparator: ${comp}`)
7787 this.operator = m[1] !== undefined ? m[1] : ''
7788 if (this.operator === '=') {
7792 // if it literally is just '>' or '' then allow anything.
7796 this.semver = new SemVer(m[2], this.options.loose)
7805 debug('Comparator.test', version, this.options.loose)
7807 if (this.semver === ANY || version === ANY) {
7811 if (typeof version === 'string') {
7813 version = new SemVer(version, this.options)
7819 return cmp(version, this.operator, this.semver, this.options)
7822 intersects (comp, options) {
7823 if (!(comp instanceof Comparator)) {
7824 throw new TypeError('a Comparator is required')
7827 if (!options || typeof options !== 'object') {
7830 includePrerelease: false
7834 if (this.operator === '') {
7835 if (this.value === '') {
7838 return new Range(comp.value, options).test(this.value)
7839 } else if (comp.operator === '') {
7840 if (comp.value === '') {
7843 return new Range(this.value, options).test(comp.semver)
7846 const sameDirectionIncreasing =
7847 (this.operator === '>=' || this.operator === '>') &&
7848 (comp.operator === '>=' || comp.operator === '>')
7849 const sameDirectionDecreasing =
7850 (this.operator === '<=' || this.operator === '<') &&
7851 (comp.operator === '<=' || comp.operator === '<')
7852 const sameSemVer = this.semver.version === comp.semver.version
7853 const differentDirectionsInclusive =
7854 (this.operator === '>=' || this.operator === '<=') &&
7855 (comp.operator === '>=' || comp.operator === '<=')
7856 const oppositeDirectionsLessThan =
7857 cmp(this.semver, '<', comp.semver, options) &&
7858 (this.operator === '>=' || this.operator === '>') &&
7859 (comp.operator === '<=' || comp.operator === '<')
7860 const oppositeDirectionsGreaterThan =
7861 cmp(this.semver, '>', comp.semver, options) &&
7862 (this.operator === '<=' || this.operator === '<') &&
7863 (comp.operator === '>=' || comp.operator === '>')
7866 sameDirectionIncreasing ||
7867 sameDirectionDecreasing ||
7868 (sameSemVer && differentDirectionsInclusive) ||
7869 oppositeDirectionsLessThan ||
7870 oppositeDirectionsGreaterThan
7875 module.exports = Comparator
7877 const {re, t} = __webpack_require__(42)
7878 const cmp = __webpack_require__(68)
7879 const debug = __webpack_require__(44)
7880 const SemVer = __webpack_require__(45)
7881 const Range = __webpack_require__(71)
7886 /***/ (function(module, exports, __webpack_require__) {
7888 // hoisted class for cyclic dependency
7890 constructor (range, options) {
7891 if (!options || typeof options !== 'object') {
7894 includePrerelease: false
7898 if (range instanceof Range) {
7900 range.loose === !!options.loose &&
7901 range.includePrerelease === !!options.includePrerelease
7905 return new Range(range.raw, options)
7909 if (range instanceof Comparator) {
7910 // just put it in the set and return
7911 this.raw = range.value
7912 this.set = [[range]]
7917 this.options = options
7918 this.loose = !!options.loose
7919 this.includePrerelease = !!options.includePrerelease
7921 // First, split based on boolean or ||
7924 .split(/\s*\|\|\s*/)
7925 // map the range to a 2d array of comparators
7926 .map(range => this.parseRange(range.trim()))
7927 // throw out any comparator lists that are empty
7928 // this generally means that it was not a valid range, which is allowed
7929 // in loose mode, but will still throw if the WHOLE range is invalid.
7930 .filter(c => c.length)
7932 if (!this.set.length) {
7933 throw new TypeError(`Invalid SemVer Range: ${range}`)
7940 this.range = this.set
7942 return comps.join(' ').trim()
7953 parseRange (range) {
7954 const loose = this.options.loose
7955 range = range.trim()
7956 // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
7957 const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
7958 range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
7959 debug('hyphen replace', range)
7960 // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
7961 range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
7962 debug('comparator trim', range, re[t.COMPARATORTRIM])
7964 // `~ 1.2.3` => `~1.2.3`
7965 range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
7967 // `^ 1.2.3` => `^1.2.3`
7968 range = range.replace(re[t.CARETTRIM], caretTrimReplace)
7971 range = range.split(/\s+/).join(' ')
7973 // At this point, the range is completely trimmed and
7974 // ready to be split into comparators.
7976 const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
7979 .map(comp => parseComparator(comp, this.options))
7982 .map(comp => replaceGTE0(comp, this.options))
7983 // in loose mode, throw out any that are not valid comparators
7984 .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)
7985 .map(comp => new Comparator(comp, this.options))
7988 intersects (range, options) {
7989 if (!(range instanceof Range)) {
7990 throw new TypeError('a Range is required')
7993 return this.set.some((thisComparators) => {
7995 isSatisfiable(thisComparators, options) &&
7996 range.set.some((rangeComparators) => {
7998 isSatisfiable(rangeComparators, options) &&
7999 thisComparators.every((thisComparator) => {
8000 return rangeComparators.every((rangeComparator) => {
8001 return thisComparator.intersects(rangeComparator, options)
8010 // if ANY of the sets match ALL of its comparators, then pass
8016 if (typeof version === 'string') {
8018 version = new SemVer(version, this.options)
8024 for (let i = 0; i < this.set.length; i++) {
8025 if (testSet(this.set[i], version, this.options)) {
8032 module.exports = Range
8034 const Comparator = __webpack_require__(70)
8035 const debug = __webpack_require__(44)
8036 const SemVer = __webpack_require__(45)
8040 comparatorTrimReplace,
8043 } = __webpack_require__(42)
8045 // take a set of comparators and determine whether there
8046 // exists a version which can satisfy it
8047 const isSatisfiable = (comparators, options) => {
8049 const remainingComparators = comparators.slice()
8050 let testComparator = remainingComparators.pop()
8052 while (result && remainingComparators.length) {
8053 result = remainingComparators.every((otherComparator) => {
8054 return testComparator.intersects(otherComparator, options)
8057 testComparator = remainingComparators.pop()
8063 // comprised of xranges, tildes, stars, and gtlt's at this point.
8064 // already replaced the hyphen ranges
8065 // turn into a set of JUST comparators.
8066 const parseComparator = (comp, options) => {
8067 debug('comp', comp, options)
8068 comp = replaceCarets(comp, options)
8069 debug('caret', comp)
8070 comp = replaceTildes(comp, options)
8071 debug('tildes', comp)
8072 comp = replaceXRanges(comp, options)
8073 debug('xrange', comp)
8074 comp = replaceStars(comp, options)
8075 debug('stars', comp)
8079 const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
8081 // ~, ~> --> * (any, kinda silly)
8082 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
8083 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
8084 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
8085 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
8086 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
8087 const replaceTildes = (comp, options) =>
8088 comp.trim().split(/\s+/).map((comp) => {
8089 return replaceTilde(comp, options)
8092 const replaceTilde = (comp, options) => {
8093 const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
8094 return comp.replace(r, (_, M, m, p, pr) => {
8095 debug('tilde', comp, _, M, m, p, pr)
8100 } else if (isX(m)) {
8101 ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
8102 } else if (isX(p)) {
8103 // ~1.2 == >=1.2.0 <1.3.0-0
8104 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
8106 debug('replaceTilde pr', pr)
8107 ret = `>=${M}.${m}.${p}-${pr
8108 } <${M}.${+m + 1}.0-0`
8110 // ~1.2.3 == >=1.2.3 <1.3.0-0
8111 ret = `>=${M}.${m}.${p
8112 } <${M}.${+m + 1}.0-0`
8115 debug('tilde return', ret)
8120 // ^ --> * (any, kinda silly)
8121 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
8122 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
8123 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
8124 // ^1.2.3 --> >=1.2.3 <2.0.0-0
8125 // ^1.2.0 --> >=1.2.0 <2.0.0-0
8126 const replaceCarets = (comp, options) =>
8127 comp.trim().split(/\s+/).map((comp) => {
8128 return replaceCaret(comp, options)
8131 const replaceCaret = (comp, options) => {
8132 debug('caret', comp, options)
8133 const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
8134 const z = options.includePrerelease ? '-0' : ''
8135 return comp.replace(r, (_, M, m, p, pr) => {
8136 debug('caret', comp, _, M, m, p, pr)
8141 } else if (isX(m)) {
8142 ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
8143 } else if (isX(p)) {
8145 ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
8147 ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
8150 debug('replaceCaret pr', pr)
8153 ret = `>=${M}.${m}.${p}-${pr
8154 } <${M}.${m}.${+p + 1}-0`
8156 ret = `>=${M}.${m}.${p}-${pr
8157 } <${M}.${+m + 1}.0-0`
8160 ret = `>=${M}.${m}.${p}-${pr
8167 ret = `>=${M}.${m}.${p
8168 }${z} <${M}.${m}.${+p + 1}-0`
8170 ret = `>=${M}.${m}.${p
8171 }${z} <${M}.${+m + 1}.0-0`
8174 ret = `>=${M}.${m}.${p
8179 debug('caret return', ret)
8184 const replaceXRanges = (comp, options) => {
8185 debug('replaceXRanges', comp, options)
8186 return comp.split(/\s+/).map((comp) => {
8187 return replaceXRange(comp, options)
8191 const replaceXRange = (comp, options) => {
8193 const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
8194 return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
8195 debug('xRange', comp, ret, gtlt, M, m, p, pr)
8197 const xm = xM || isX(m)
8198 const xp = xm || isX(p)
8201 if (gtlt === '=' && anyX) {
8205 // if we're including prereleases in the match, then we need
8206 // to fix this to -0, the lowest possible prerelease value
8207 pr = options.includePrerelease ? '-0' : ''
8210 if (gtlt === '>' || gtlt === '<') {
8211 // nothing is allowed
8214 // nothing is forbidden
8217 } else if (gtlt && anyX) {
8218 // we know patch is an x, because we have any x at all.
8237 } else if (gtlt === '<=') {
8238 // <=0.7.x is actually <0.8.0, since any 0.7.x should
8239 // pass. Similarly, <=7.x is actually <8.0.0, etc.
8251 ret = `${gtlt + M}.${m}.${p}${pr}`
8253 ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
8255 ret = `>=${M}.${m}.0${pr
8256 } <${M}.${+m + 1}.0-0`
8259 debug('xRange return', ret)
8265 // Because * is AND-ed with everything else in the comparator,
8266 // and '' means "any version", just remove the *s entirely.
8267 const replaceStars = (comp, options) => {
8268 debug('replaceStars', comp, options)
8269 // Looseness is ignored here. star is always as loose as it gets!
8270 return comp.trim().replace(re[t.STAR], '')
8273 const replaceGTE0 = (comp, options) => {
8274 debug('replaceGTE0', comp, options)
8276 .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
8279 // This function is passed to string.replace(re[t.HYPHENRANGE])
8280 // M, m, patch, prerelease, build
8281 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
8282 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
8283 // 1.2 - 3.4 => >=1.2.0 <3.5.0-0
8284 const hyphenReplace = incPr => ($0,
8285 from, fM, fm, fp, fpr, fb,
8286 to, tM, tm, tp, tpr, tb) => {
8289 } else if (isX(fm)) {
8290 from = `>=${fM}.0.0${incPr ? '-0' : ''}`
8291 } else if (isX(fp)) {
8292 from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
8296 from = `>=${from}${incPr ? '-0' : ''}`
8301 } else if (isX(tm)) {
8302 to = `<${+tM + 1}.0.0-0`
8303 } else if (isX(tp)) {
8304 to = `<${tM}.${+tm + 1}.0-0`
8306 to = `<=${tM}.${tm}.${tp}-${tpr}`
8308 to = `<${tM}.${tm}.${+tp + 1}-0`
8313 return (`${from} ${to}`).trim()
8316 const testSet = (set, version, options) => {
8317 for (let i = 0; i < set.length; i++) {
8318 if (!set[i].test(version)) {
8323 if (version.prerelease.length && !options.includePrerelease) {
8324 // Find the set of versions that are allowed to have prereleases
8325 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
8326 // That should allow `1.2.3-pr.2` to pass.
8327 // However, `1.2.4-alpha.notready` should NOT be allowed,
8328 // even though it's within the range set by the comparators.
8329 for (let i = 0; i < set.length; i++) {
8330 debug(set[i].semver)
8331 if (set[i].semver === Comparator.ANY) {
8335 if (set[i].semver.prerelease.length > 0) {
8336 const allowed = set[i].semver
8337 if (allowed.major === version.major &&
8338 allowed.minor === version.minor &&
8339 allowed.patch === version.patch) {
8345 // Version has a -pre, but it's not one of the ones we like.
8355 /***/ (function(module, exports, __webpack_require__) {
8357 const Range = __webpack_require__(71)
8358 const satisfies = (version, range, options) => {
8360 range = new Range(range, options)
8364 return range.test(version)
8366 module.exports = satisfies
8371 /***/ (function(module, exports, __webpack_require__) {
8373 const Range = __webpack_require__(71)
8375 // Mostly just for testing and legacy API reasons
8376 const toComparators = (range, options) =>
8377 new Range(range, options).set
8378 .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
8380 module.exports = toComparators
8385 /***/ (function(module, exports, __webpack_require__) {
8387 const SemVer = __webpack_require__(45)
8388 const Range = __webpack_require__(71)
8390 const maxSatisfying = (versions, range, options) => {
8395 rangeObj = new Range(range, options)
8399 versions.forEach((v) => {
8400 if (rangeObj.test(v)) {
8401 // satisfies(v, range, options)
8402 if (!max || maxSV.compare(v) === -1) {
8403 // compare(max, v, true)
8405 maxSV = new SemVer(max, options)
8411 module.exports = maxSatisfying
8416 /***/ (function(module, exports, __webpack_require__) {
8418 const SemVer = __webpack_require__(45)
8419 const Range = __webpack_require__(71)
8420 const minSatisfying = (versions, range, options) => {
8425 rangeObj = new Range(range, options)
8429 versions.forEach((v) => {
8430 if (rangeObj.test(v)) {
8431 // satisfies(v, range, options)
8432 if (!min || minSV.compare(v) === 1) {
8433 // compare(min, v, true)
8435 minSV = new SemVer(min, options)
8441 module.exports = minSatisfying
8446 /***/ (function(module, exports, __webpack_require__) {
8448 const SemVer = __webpack_require__(45)
8449 const Range = __webpack_require__(71)
8450 const gt = __webpack_require__(63)
8452 const minVersion = (range, loose) => {
8453 range = new Range(range, loose)
8455 let minver = new SemVer('0.0.0')
8456 if (range.test(minver)) {
8460 minver = new SemVer('0.0.0-0')
8461 if (range.test(minver)) {
8466 for (let i = 0; i < range.set.length; ++i) {
8467 const comparators = range.set[i]
8469 comparators.forEach((comparator) => {
8470 // Clone to avoid manipulating the comparator's semver object.
8471 const compver = new SemVer(comparator.semver.version)
8472 switch (comparator.operator) {
8474 if (compver.prerelease.length === 0) {
8477 compver.prerelease.push(0)
8479 compver.raw = compver.format()
8483 if (!minver || gt(minver, compver)) {
8489 /* Ignore maximum versions */
8491 /* istanbul ignore next */
8493 throw new Error(`Unexpected operation: ${comparator.operator}`)
8498 if (minver && range.test(minver)) {
8504 module.exports = minVersion
8509 /***/ (function(module, exports, __webpack_require__) {
8511 const Range = __webpack_require__(71)
8512 const validRange = (range, options) => {
8514 // Return '*' instead of '' so that truthiness works.
8515 // This will throw if it's invalid anyway
8516 return new Range(range, options).range || '*'
8521 module.exports = validRange
8526 /***/ (function(module, exports, __webpack_require__) {
8528 const SemVer = __webpack_require__(45)
8529 const Comparator = __webpack_require__(70)
8530 const {ANY} = Comparator
8531 const Range = __webpack_require__(71)
8532 const satisfies = __webpack_require__(72)
8533 const gt = __webpack_require__(63)
8534 const lt = __webpack_require__(64)
8535 const lte = __webpack_require__(67)
8536 const gte = __webpack_require__(66)
8538 const outside = (version, range, hilo, options) => {
8539 version = new SemVer(version, options)
8540 range = new Range(range, options)
8542 let gtfn, ltefn, ltfn, comp, ecomp
8559 throw new TypeError('Must provide a hilo val of "<" or ">"')
8562 // If it satisifes the range it is not outside
8563 if (satisfies(version, range, options)) {
8567 // From now on, variable terms are as if we're in "gtr" mode.
8568 // but note that everything is flipped for the "ltr" function.
8570 for (let i = 0; i < range.set.length; ++i) {
8571 const comparators = range.set[i]
8576 comparators.forEach((comparator) => {
8577 if (comparator.semver === ANY) {
8578 comparator = new Comparator('>=0.0.0')
8580 high = high || comparator
8581 low = low || comparator
8582 if (gtfn(comparator.semver, high.semver, options)) {
8584 } else if (ltfn(comparator.semver, low.semver, options)) {
8589 // If the edge version comparator has a operator then our version
8591 if (high.operator === comp || high.operator === ecomp) {
8595 // If the lowest version comparator has an operator and our version
8596 // is less than it then it isn't higher than the range
8597 if ((!low.operator || low.operator === comp) &&
8598 ltefn(version, low.semver)) {
8600 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
8607 module.exports = outside
8612 /***/ (function(module, exports, __webpack_require__) {
8614 // Determine if version is greater than all the versions possible in the range.
8615 const outside = __webpack_require__(78)
8616 const gtr = (version, range, options) => outside(version, range, '>', options)
8617 module.exports = gtr
8622 /***/ (function(module, exports, __webpack_require__) {
8624 const outside = __webpack_require__(78)
8625 // Determine if version is less than all the versions possible in the range
8626 const ltr = (version, range, options) => outside(version, range, '<', options)
8627 module.exports = ltr
8632 /***/ (function(module, exports, __webpack_require__) {
8634 const Range = __webpack_require__(71)
8635 const intersects = (r1, r2, options) => {
8636 r1 = new Range(r1, options)
8637 r2 = new Range(r2, options)
8638 return r1.intersects(r2)
8640 module.exports = intersects
8645 /***/ (function(module, exports, __webpack_require__) {
8647 // given a set of versions and a range, create a "simplified" range
8648 // that includes the same versions that the original range does
8649 // If the original range is shorter than the simplified one, return that.
8650 const satisfies = __webpack_require__(72)
8651 const compare = __webpack_require__(53)
8652 module.exports = (versions, range, options) => {
8656 const v = versions.sort((a, b) => compare(a, b, options))
8657 for (const version of v) {
8658 const included = satisfies(version, range, options)
8665 set.push([min, prev])
8672 set.push([min, null])
8675 for (const [min, max] of set) {
8678 else if (!max && min === v[0])
8681 ranges.push(`>=${min}`)
8682 else if (min === v[0])
8683 ranges.push(`<=${max}`)
8685 ranges.push(`${min} - ${max}`)
8687 const simplified = ranges.join(' || ')
8688 const original = typeof range.raw === 'string' ? range.raw : String(range)
8689 return simplified.length < original.length ? simplified : range
8695 /***/ (function(module, exports, __webpack_require__) {
8697 const Range = __webpack_require__(71)
8698 const { ANY } = __webpack_require__(70)
8699 const satisfies = __webpack_require__(72)
8700 const compare = __webpack_require__(53)
8702 // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
8703 // - Every simple range `r1, r2, ...` is a subset of some `R1, R2, ...`
8705 // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
8706 // - If c is only the ANY comparator
8707 // - If C is only the ANY comparator, return true
8708 // - Else return false
8709 // - Let EQ be the set of = comparators in c
8710 // - If EQ is more than one, return true (null set)
8711 // - Let GT be the highest > or >= comparator in c
8712 // - Let LT be the lowest < or <= comparator in c
8713 // - If GT and LT, and GT.semver > LT.semver, return true (null set)
8715 // - If GT, and EQ does not satisfy GT, return true (null set)
8716 // - If LT, and EQ does not satisfy LT, return true (null set)
8717 // - If EQ satisfies every C, return true
8718 // - Else return false
8720 // - If GT is lower than any > or >= comp in C, return false
8721 // - If GT is >=, and GT.semver does not satisfy every C, return false
8723 // - If LT.semver is greater than that of any > comp in C, return false
8724 // - If LT is <=, and LT.semver does not satisfy every C, return false
8725 // - If any C is a = range, and GT or LT are set, return false
8726 // - Else return true
8728 const subset = (sub, dom, options) => {
8729 sub = new Range(sub, options)
8730 dom = new Range(dom, options)
8731 let sawNonNull = false
8733 OUTER: for (const simpleSub of sub.set) {
8734 for (const simpleDom of dom.set) {
8735 const isSub = simpleSubset(simpleSub, simpleDom, options)
8736 sawNonNull = sawNonNull || isSub !== null
8740 // the null set is a subset of everything, but null simple ranges in
8741 // a complex range should be ignored. so if we saw a non-null range,
8742 // then we know this isn't a subset, but if EVERY simple range was null,
8743 // then it is a subset.
8750 const simpleSubset = (sub, dom, options) => {
8751 if (sub.length === 1 && sub[0].semver === ANY)
8752 return dom.length === 1 && dom[0].semver === ANY
8754 const eqSet = new Set()
8756 for (const c of sub) {
8757 if (c.operator === '>' || c.operator === '>=')
8758 gt = higherGT(gt, c, options)
8759 else if (c.operator === '<' || c.operator === '<=')
8760 lt = lowerLT(lt, c, options)
8770 gtltComp = compare(gt.semver, lt.semver, options)
8773 else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<='))
8777 // will iterate one or zero times
8778 for (const eq of eqSet) {
8779 if (gt && !satisfies(eq, String(gt), options))
8782 if (lt && !satisfies(eq, String(lt), options))
8785 for (const c of dom) {
8786 if (!satisfies(eq, String(c), options))
8793 let hasDomLT, hasDomGT
8794 for (const c of dom) {
8795 hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
8796 hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
8798 if (c.operator === '>' || c.operator === '>=') {
8799 higher = higherGT(gt, c, options)
8802 } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options))
8806 if (c.operator === '<' || c.operator === '<=') {
8807 lower = lowerLT(lt, c, options)
8810 } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options))
8813 if (!c.operator && (lt || gt) && gtltComp !== 0)
8817 // if there was a < or >, and nothing in the dom, then must be false
8818 // UNLESS it was limited by another range in the other direction.
8819 // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
8820 if (gt && hasDomLT && !lt && gtltComp !== 0)
8823 if (lt && hasDomGT && !gt && gtltComp !== 0)
8829 // >=1.2.3 is lower than >1.2.3
8830 const higherGT = (a, b, options) => {
8833 const comp = compare(a.semver, b.semver, options)
8836 : b.operator === '>' && a.operator === '>=' ? b
8840 // <=1.2.3 is higher than <1.2.3
8841 const lowerLT = (a, b, options) => {
8844 const comp = compare(a.semver, b.semver, options)
8847 : b.operator === '<' && a.operator === '<=' ? b
8851 module.exports = subset
8856 /***/ (function(module, exports, __webpack_require__) {
8860 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8861 if (k2 === undefined) k2 = k;
8862 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
8863 }) : (function(o, m, k, k2) {
8864 if (k2 === undefined) k2 = k;
8867 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
8868 Object.defineProperty(o, "default", { enumerable: true, value: v });
8869 }) : function(o, v) {
8872 var __importStar = (this && this.__importStar) || function (mod) {
8873 if (mod && mod.__esModule) return mod;
8875 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
8876 __setModuleDefault(result, mod);
8879 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
8880 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8881 return new (P || (P = Promise))(function (resolve, reject) {
8882 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8883 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8884 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8885 step((generator = generator.apply(thisArg, _arguments || [])).next());
8888 Object.defineProperty(exports, "__esModule", { value: true });
8889 exports.applyCodeActionCommands = exports.applyCodeAction = exports.getEditForCodeAction = void 0;
8890 /*---------------------------------------------------------------------------------------------
8891 * Copyright (c) Microsoft Corporation. All rights reserved.
8892 * Licensed under the MIT License. See License.txt in the project root for license information.
8893 *--------------------------------------------------------------------------------------------*/
8894 const vscode_languageserver_protocol_1 = __webpack_require__(3);
8895 const coc_nvim_1 = __webpack_require__(1);
8896 const typeConverters = __importStar(__webpack_require__(37));
8897 function getEditForCodeAction(client, action) {
8898 return action.changes && action.changes.length
8899 ? typeConverters.WorkspaceEdit.fromFileCodeEdits(client, action.changes)
8902 exports.getEditForCodeAction = getEditForCodeAction;
8903 function applyCodeAction(client, action) {
8904 return __awaiter(this, void 0, void 0, function* () {
8905 const workspaceEdit = getEditForCodeAction(client, action);
8906 if (workspaceEdit) {
8907 if (!(yield coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
8911 return applyCodeActionCommands(client, action);
8914 exports.applyCodeAction = applyCodeAction;
8915 function applyCodeActionCommands(client, action) {
8916 return __awaiter(this, void 0, void 0, function* () {
8917 // make sure there is command
8918 if (action.commands && action.commands.length) {
8919 for (const command of action.commands) {
8920 const response = yield client.execute('applyCodeActionCommand', { command }, vscode_languageserver_protocol_1.CancellationToken.None);
8921 if (!response || response.type != 'response' || !response.body) {
8929 exports.applyCodeActionCommands = applyCodeActionCommands;
8934 /***/ (function(module, exports, __webpack_require__) {
8938 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8939 if (k2 === undefined) k2 = k;
8940 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
8941 }) : (function(o, m, k, k2) {
8942 if (k2 === undefined) k2 = k;
8945 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
8946 Object.defineProperty(o, "default", { enumerable: true, value: v });
8947 }) : function(o, v) {
8950 var __importStar = (this && this.__importStar) || function (mod) {
8951 if (mod && mod.__esModule) return mod;
8953 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
8954 __setModuleDefault(result, mod);
8957 Object.defineProperty(exports, "__esModule", { value: true });
8958 exports.getParameterListParts = exports.convertCompletionEntry = void 0;
8959 /*---------------------------------------------------------------------------------------------
8960 * Copyright (c) Microsoft Corporation. All rights reserved.
8961 * Licensed under the MIT License. See License.txt in the project root for license information.
8962 *--------------------------------------------------------------------------------------------*/
8963 const vscode_languageserver_protocol_1 = __webpack_require__(3);
8964 const PConst = __importStar(__webpack_require__(39));
8965 function convertCompletionEntry(tsEntry, uri, position, context) {
8966 let label = tsEntry.name;
8967 let sortText = tsEntry.sortText;
8968 let preselect = false;
8970 if (tsEntry.isRecommended) {
8973 if (tsEntry.source) {
8974 // De-prioritze auto-imports https://github.com/Microsoft/vscode/issues/40311
8975 sortText = '\uffff' + sortText;
8978 sortText = tsEntry.sortText;
8980 let kind = convertKind(tsEntry.kind);
8981 let insertTextFormat = (context.enableCallCompletions &&
8982 (kind === vscode_languageserver_protocol_1.CompletionItemKind.Function ||
8983 kind === vscode_languageserver_protocol_1.CompletionItemKind.Method)) ? vscode_languageserver_protocol_1.InsertTextFormat.Snippet : vscode_languageserver_protocol_1.InsertTextFormat.PlainText;
8984 let insertText = tsEntry.insertText;
8985 let commitCharacters = getCommitCharacters(tsEntry, context);
8986 let textEdit = null;
8987 if (tsEntry.replacementSpan) {
8988 let { start, end } = tsEntry.replacementSpan;
8989 if (start.line == end.line) {
8991 range: vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1),
8992 newText: insertText || label
8996 if (tsEntry.kindModifiers) {
8997 const kindModifiers = new Set(tsEntry.kindModifiers.split(/,|\s+/g));
8998 if (kindModifiers.has(PConst.KindModifiers.optional)) {
9002 if (kindModifiers.has(PConst.KindModifiers.color)) {
9003 kind = vscode_languageserver_protocol_1.CompletionItemKind.Color;
9005 if (tsEntry.kind === PConst.Kind.script) {
9006 for (const extModifier of PConst.KindModifiers.fileExtensionKindModifiers) {
9007 if (kindModifiers.has(extModifier)) {
9008 if (tsEntry.name.toLowerCase().endsWith(extModifier)) {
9009 detail = tsEntry.name;
9012 detail = tsEntry.name + extModifier;
9032 source: tsEntry.source || ''
9036 exports.convertCompletionEntry = convertCompletionEntry;
9037 function convertKind(kind) {
9039 case PConst.Kind.primitiveType:
9040 case PConst.Kind.keyword:
9041 return vscode_languageserver_protocol_1.CompletionItemKind.Keyword;
9042 case PConst.Kind.const:
9043 return vscode_languageserver_protocol_1.CompletionItemKind.Constant;
9044 case PConst.Kind.let:
9045 case PConst.Kind.variable:
9046 case PConst.Kind.localVariable:
9047 case PConst.Kind.alias:
9048 return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
9049 case PConst.Kind.memberVariable:
9050 case PConst.Kind.memberGetAccessor:
9051 case PConst.Kind.memberSetAccessor:
9052 return vscode_languageserver_protocol_1.CompletionItemKind.Field;
9053 case PConst.Kind.function:
9054 return vscode_languageserver_protocol_1.CompletionItemKind.Function;
9055 case PConst.Kind.method:
9056 case PConst.Kind.constructSignature:
9057 case PConst.Kind.callSignature:
9058 case PConst.Kind.indexSignature:
9059 return vscode_languageserver_protocol_1.CompletionItemKind.Method;
9060 case PConst.Kind.enum:
9061 return vscode_languageserver_protocol_1.CompletionItemKind.Enum;
9062 case PConst.Kind.module:
9063 case PConst.Kind.externalModuleName:
9064 return vscode_languageserver_protocol_1.CompletionItemKind.Module;
9065 case PConst.Kind.class:
9066 case PConst.Kind.type:
9067 return vscode_languageserver_protocol_1.CompletionItemKind.Class;
9068 case PConst.Kind.interface:
9069 return vscode_languageserver_protocol_1.CompletionItemKind.Interface;
9070 case PConst.Kind.warning:
9071 case PConst.Kind.script:
9072 return vscode_languageserver_protocol_1.CompletionItemKind.File;
9073 case PConst.Kind.directory:
9074 return vscode_languageserver_protocol_1.CompletionItemKind.Folder;
9076 return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
9078 function getCommitCharacters(tsEntry, context) {
9079 if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
9082 const commitCharacters = [];
9083 switch (tsEntry.kind) {
9084 case PConst.Kind.memberGetAccessor:
9085 case PConst.Kind.memberSetAccessor:
9086 case PConst.Kind.constructSignature:
9087 case PConst.Kind.callSignature:
9088 case PConst.Kind.indexSignature:
9089 case PConst.Kind.enum:
9090 case PConst.Kind.interface:
9091 commitCharacters.push('.', ';');
9093 case PConst.Kind.module:
9094 case PConst.Kind.alias:
9095 case PConst.Kind.const:
9096 case PConst.Kind.let:
9097 case PConst.Kind.variable:
9098 case PConst.Kind.localVariable:
9099 case PConst.Kind.memberVariable:
9100 case PConst.Kind.class:
9101 case PConst.Kind.function:
9102 case PConst.Kind.method:
9103 case PConst.Kind.keyword:
9104 case PConst.Kind.parameter:
9105 commitCharacters.push('.', ',', ';');
9106 if (context.enableCallCompletions) {
9107 commitCharacters.push('(');
9111 return commitCharacters.length === 0 ? undefined : commitCharacters;
9113 function getParameterListParts(displayParts) {
9115 let isInMethod = false;
9116 let hasOptionalParameters = false;
9119 outer: for (let i = 0; i < displayParts.length; ++i) {
9120 const part = displayParts[i];
9121 switch (part.kind) {
9122 case PConst.DisplayPartKind.methodName:
9123 case PConst.DisplayPartKind.functionName:
9124 case PConst.DisplayPartKind.text:
9125 case PConst.DisplayPartKind.propertyName:
9126 if (parenCount === 0 && braceCount === 0) {
9130 case PConst.DisplayPartKind.parameterName:
9131 if (parenCount === 1 && braceCount === 0 && isInMethod) {
9132 // Only take top level paren names
9133 const next = displayParts[i + 1];
9134 // Skip optional parameters
9135 const nameIsFollowedByOptionalIndicator = next && next.text === '?';
9136 if (!nameIsFollowedByOptionalIndicator) {
9139 hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator;
9142 case PConst.DisplayPartKind.punctuation:
9143 if (part.text === '(') {
9146 else if (part.text === ')') {
9148 if (parenCount <= 0 && isInMethod) {
9152 else if (part.text === '...' && parenCount === 1) {
9153 // Found rest parmeter. Do not fill in any further arguments
9154 hasOptionalParameters = true;
9157 else if (part.text === '{') {
9160 else if (part.text === '}') {
9166 return { hasOptionalParameters, parts };
9168 exports.getParameterListParts = getParameterListParts;
9173 /***/ (function(module, exports, __webpack_require__) {
9177 /*---------------------------------------------------------------------------------------------
9178 * Copyright (c) Microsoft Corporation. All rights reserved.
9179 * Licensed under the MIT License. See License.txt in the project root for license information.
9180 *--------------------------------------------------------------------------------------------*/
9181 Object.defineProperty(exports, "__esModule", { value: true });
9182 exports.markdownDocumentation = exports.tagsMarkdownPreview = exports.plain = void 0;
9183 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9184 function getTagBodyText(tag) {
9191 // Convert to markdown code block if it not already one
9192 if (tag.text.match(/^\s*[~`]{3}/g)) {
9195 return '```\n' + tag.text + '\n```';
9199 function getTagDocumentation(tag) {
9202 const body = (tag.text || '').split(/^([\w\.]+)\s*/);
9203 if (body && body.length === 3) {
9204 const param = body[1];
9205 const doc = body[2];
9206 const label = `*@${tag.name}* \`${param}\``;
9210 return label + (doc.match(/\r\n|\n/g) ? '\n' + doc : ` — ${doc}`);
9214 const label = `*@${tag.name}*`;
9215 const text = getTagBodyText(tag);
9219 return label + (text.match(/\r\n|\n/g) ? '\n' + text : ` — ${text}`);
9221 function plain(parts) {
9222 if (!parts || !parts.length)
9224 return parts.map(part => part.text).join('');
9226 exports.plain = plain;
9227 function tagsMarkdownPreview(tags) {
9228 return (tags || []).map(getTagDocumentation).join(' \n\n');
9230 exports.tagsMarkdownPreview = tagsMarkdownPreview;
9231 function markdownDocumentation(documentation, tags) {
9232 let out = plain(documentation);
9233 const tagsPreview = tagsMarkdownPreview(tags);
9235 out = out + ('\n\n' + tagsPreview);
9238 kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
9242 exports.markdownDocumentation = markdownDocumentation;
9247 /***/ (function(module, exports, __webpack_require__) {
9251 Object.defineProperty(exports, "__esModule", { value: true });
9252 class SnippetString {
9253 constructor(value) {
9255 this.value = value || '';
9257 static isSnippetString(thing) {
9258 if (thing instanceof SnippetString) {
9264 return typeof thing.value === 'string';
9266 static _escape(value) {
9267 return value.replace(/\$|}|\\/g, '\\$&');
9270 this.value += SnippetString._escape(str);
9273 appendTabstop(n = this._tabstop++) {
9278 appendPlaceholder(value, n = this._tabstop++) {
9279 if (typeof value === 'function') {
9280 const nested = new SnippetString();
9281 nested._tabstop = this._tabstop;
9283 this._tabstop = nested._tabstop;
9284 value = nested.value;
9287 value = SnippetString._escape(value);
9292 this.value += value;
9296 appendVariable(name, defaultValue) {
9297 if (typeof defaultValue === 'function') {
9298 const nested = new SnippetString();
9299 nested._tabstop = this._tabstop;
9300 defaultValue(nested);
9301 this._tabstop = nested._tabstop;
9302 defaultValue = nested.value;
9304 else if (typeof defaultValue === 'string') {
9305 defaultValue = defaultValue.replace(/\$|}/g, '\\$&');
9311 this.value += defaultValue;
9317 exports.default = SnippetString;
9322 /***/ (function(module, exports, __webpack_require__) {
9326 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9327 if (k2 === undefined) k2 = k;
9328 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9329 }) : (function(o, m, k, k2) {
9330 if (k2 === undefined) k2 = k;
9333 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9334 Object.defineProperty(o, "default", { enumerable: true, value: v });
9335 }) : function(o, v) {
9338 var __importStar = (this && this.__importStar) || function (mod) {
9339 if (mod && mod.__esModule) return mod;
9341 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9342 __setModuleDefault(result, mod);
9345 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9346 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
9347 return new (P || (P = Promise))(function (resolve, reject) {
9348 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
9349 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9350 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9351 step((generator = generator.apply(thisArg, _arguments || [])).next());
9354 Object.defineProperty(exports, "__esModule", { value: true });
9355 const typeConverters = __importStar(__webpack_require__(37));
9356 class TypeScriptDefinitionProvider {
9357 constructor(client) {
9358 this.client = client;
9360 getSymbolLocations(definitionType, document, position, token) {
9361 return __awaiter(this, void 0, void 0, function* () {
9362 const filepath = this.client.toPath(document.uri);
9366 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
9368 const response = yield this.client.execute(definitionType, args, token);
9369 const locations = (response.type == 'response' && response.body) || [];
9370 return locations.map(location => typeConverters.Location.fromTextSpan(this.client.toResource(location.file), location));
9377 provideDefinition(document, position, token) {
9378 return this.getSymbolLocations('definition', document, position, token);
9380 provideTypeDefinition(document, position, token) {
9381 return this.getSymbolLocations('typeDefinition', document, position, token);
9383 provideImplementation(document, position, token) {
9384 return this.getSymbolLocations('implementation', document, position, token);
9387 exports.default = TypeScriptDefinitionProvider;
9392 /***/ (function(module, exports, __webpack_require__) {
9396 var __importDefault = (this && this.__importDefault) || function (mod) {
9397 return (mod && mod.__esModule) ? mod : { "default": mod };
9399 Object.defineProperty(exports, "__esModule", { value: true });
9400 /*---------------------------------------------------------------------------------------------
9401 * Copyright (c) Microsoft Corporation. All rights reserved.
9402 * Licensed under the MIT License. See License.txt in the project root for license information.
9403 *--------------------------------------------------------------------------------------------*/
9404 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9405 const coc_nvim_1 = __webpack_require__(1);
9406 const api_1 = __importDefault(__webpack_require__(40));
9407 const tsDirectives = [
9410 description: 'Enables semantic checking in a JavaScript file. Must be at the top of a file.'
9413 value: '@ts-nocheck',
9414 description: 'Disables semantic checking in a JavaScript file. Must be at the top of a file.'
9417 value: '@ts-ignore',
9418 description: 'Suppresses @ts-check errors on the next line of a file.'
9421 const tsDirectives390 = [
9424 value: '@ts-expect-error',
9425 description: 'Suppresses @ts-check errors on the next line of a file, expecting at least one to exist.'
9428 class DirectiveCommentCompletionProvider {
9429 constructor(client) {
9430 this.client = client;
9432 provideCompletionItems(document, position, _token, context) {
9433 if (context.triggerCharacter != '@') {
9436 const file = this.client.toPath(document.uri);
9440 const doc = coc_nvim_1.workspace.getDocument(document.uri);
9441 const line = doc.getline(position.line);
9442 const prefix = line.slice(0, position.character);
9443 const match = prefix.match(/^\s*\/\/+\s?(@[a-zA-Z\-]*)?$/);
9445 const directives = this.client.apiVersion.gte(api_1.default.v390)
9448 let items = directives.map(directive => {
9449 const item = vscode_languageserver_protocol_1.CompletionItem.create(directive.value);
9450 item.kind = vscode_languageserver_protocol_1.CompletionItemKind.Snippet;
9451 item.detail = directive.description;
9453 range: vscode_languageserver_protocol_1.Range.create(position.line, Math.max(0, position.character - (match[1] ? match[1].length : 0)), position.line, position.character),
9454 newText: directive.value
9459 isIncomplete: false,
9462 res.startcol = doc.fixStartcol(position, ['@']);
9468 exports.default = DirectiveCommentCompletionProvider;
9473 /***/ (function(module, exports, __webpack_require__) {
9477 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9478 if (k2 === undefined) k2 = k;
9479 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9480 }) : (function(o, m, k, k2) {
9481 if (k2 === undefined) k2 = k;
9484 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9485 Object.defineProperty(o, "default", { enumerable: true, value: v });
9486 }) : function(o, v) {
9489 var __importStar = (this && this.__importStar) || function (mod) {
9490 if (mod && mod.__esModule) return mod;
9492 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9493 __setModuleDefault(result, mod);
9496 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9497 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
9498 return new (P || (P = Promise))(function (resolve, reject) {
9499 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
9500 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9501 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9502 step((generator = generator.apply(thisArg, _arguments || [])).next());
9505 Object.defineProperty(exports, "__esModule", { value: true });
9506 /*---------------------------------------------------------------------------------------------
9507 * Copyright (c) Microsoft Corporation. All rights reserved.
9508 * Licensed under the MIT License. See License.txt in the project root for license information.
9509 *--------------------------------------------------------------------------------------------*/
9510 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9511 const typeConverters = __importStar(__webpack_require__(37));
9512 const arrays_1 = __webpack_require__(91);
9513 class TypeScriptDocumentHighlightProvider {
9514 constructor(client) {
9515 this.client = client;
9517 provideDocumentHighlights(resource, position, token) {
9518 return __awaiter(this, void 0, void 0, function* () {
9519 const file = this.client.toPath(resource.uri);
9522 const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { filesToSearch: [file] });
9524 const response = yield this.client.execute('documentHighlights', args, token);
9525 if (response.type !== 'response' || !response.body) {
9528 return arrays_1.flatten(response.body
9529 .filter(highlight => highlight.file === file)
9530 .map(convertDocumentHighlight));
9538 exports.default = TypeScriptDocumentHighlightProvider;
9539 function convertDocumentHighlight(highlight) {
9540 return highlight.highlightSpans.map(span => {
9542 range: typeConverters.Range.fromTextSpan(span),
9543 kind: span.kind === 'writtenReference' ? vscode_languageserver_protocol_1.DocumentHighlightKind.Write : vscode_languageserver_protocol_1.DocumentHighlightKind.Read
9551 /***/ (function(module, exports, __webpack_require__) {
9555 Object.defineProperty(exports, "__esModule", { value: true });
9556 exports.flatten = exports.equals = void 0;
9557 /*---------------------------------------------------------------------------------------------
9558 * Copyright (c) Microsoft Corporation. All rights reserved.
9559 * Licensed under the MIT License. See License.txt in the project root for license information.
9560 *--------------------------------------------------------------------------------------------*/
9561 function equals(one, other, itemEquals = (a, b) => a === b) {
9562 if (one.length !== other.length) {
9565 for (let i = 0, len = one.length; i < len; i++) {
9566 if (!itemEquals(one[i], other[i])) {
9572 exports.equals = equals;
9573 function flatten(arr) {
9574 return [].concat.apply([], arr);
9576 exports.flatten = flatten;
9581 /***/ (function(module, exports, __webpack_require__) {
9585 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9586 if (k2 === undefined) k2 = k;
9587 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9588 }) : (function(o, m, k, k2) {
9589 if (k2 === undefined) k2 = k;
9592 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9593 Object.defineProperty(o, "default", { enumerable: true, value: v });
9594 }) : function(o, v) {
9597 var __importStar = (this && this.__importStar) || function (mod) {
9598 if (mod && mod.__esModule) return mod;
9600 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9601 __setModuleDefault(result, mod);
9604 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9605 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
9606 return new (P || (P = Promise))(function (resolve, reject) {
9607 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
9608 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9609 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9610 step((generator = generator.apply(thisArg, _arguments || [])).next());
9613 Object.defineProperty(exports, "__esModule", { value: true });
9614 /*---------------------------------------------------------------------------------------------
9615 * Copyright (c) Microsoft Corporation. All rights reserved.
9616 * Licensed under the MIT License. See License.txt in the project root for license information.
9617 *--------------------------------------------------------------------------------------------*/
9618 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9619 const PConst = __importStar(__webpack_require__(39));
9620 const typeConverters = __importStar(__webpack_require__(37));
9621 const getSymbolKind = (kind) => {
9623 case PConst.Kind.module:
9624 return vscode_languageserver_protocol_1.SymbolKind.Module;
9625 case PConst.Kind.class:
9626 return vscode_languageserver_protocol_1.SymbolKind.Class;
9627 case PConst.Kind.enum:
9628 return vscode_languageserver_protocol_1.SymbolKind.Enum;
9629 case PConst.Kind.interface:
9630 return vscode_languageserver_protocol_1.SymbolKind.Interface;
9631 case PConst.Kind.method:
9632 return vscode_languageserver_protocol_1.SymbolKind.Method;
9633 case PConst.Kind.memberVariable:
9634 return vscode_languageserver_protocol_1.SymbolKind.Property;
9635 case PConst.Kind.memberGetAccessor:
9636 return vscode_languageserver_protocol_1.SymbolKind.Property;
9637 case PConst.Kind.memberSetAccessor:
9638 return vscode_languageserver_protocol_1.SymbolKind.Property;
9639 case PConst.Kind.variable:
9640 return vscode_languageserver_protocol_1.SymbolKind.Variable;
9641 case PConst.Kind.const:
9642 return vscode_languageserver_protocol_1.SymbolKind.Variable;
9643 case PConst.Kind.localVariable:
9644 return vscode_languageserver_protocol_1.SymbolKind.Variable;
9645 case PConst.Kind.variable:
9646 return vscode_languageserver_protocol_1.SymbolKind.Variable;
9647 case PConst.Kind.constructSignature:
9648 case PConst.Kind.constructorImplementation:
9649 case PConst.Kind.function:
9650 case PConst.Kind.localFunction:
9651 return vscode_languageserver_protocol_1.SymbolKind.Function;
9653 return vscode_languageserver_protocol_1.SymbolKind.Variable;
9655 class TypeScriptDocumentSymbolProvider {
9656 constructor(client) {
9657 this.client = client;
9659 provideDocumentSymbols(resource, token) {
9660 return __awaiter(this, void 0, void 0, function* () {
9661 const filepath = this.client.toPath(resource.uri);
9668 const response = yield this.client.execute('navtree', args, token);
9669 if (response.type == 'response' && response.body) {
9670 // The root represents the file. Ignore this when showing in the UI
9671 const tree = response.body;
9672 if (tree.childItems) {
9673 const result = new Array();
9674 tree.childItems.forEach(item => TypeScriptDocumentSymbolProvider.convertNavTree(result, item));
9685 static convertNavTree(bucket, item) {
9686 let shouldInclude = TypeScriptDocumentSymbolProvider.shouldInclueEntry(item);
9687 const children = new Set(item.childItems || []);
9688 for (const span of item.spans) {
9689 const range = typeConverters.Range.fromTextSpan(span);
9690 const symbolInfo = vscode_languageserver_protocol_1.DocumentSymbol.create(item.text, '', getSymbolKind(item.kind), range, range);
9691 symbolInfo.children = children.size > 0 ? [] : null;
9692 for (const child of children) {
9693 if (child.spans.some(span => !!containsRange(range, typeConverters.Range.fromTextSpan(span)))) {
9694 const includedChild = TypeScriptDocumentSymbolProvider.convertNavTree(symbolInfo.children, child);
9695 shouldInclude = shouldInclude || includedChild;
9696 children.delete(child);
9699 if (shouldInclude) {
9700 bucket.push(symbolInfo);
9703 return shouldInclude;
9705 static shouldInclueEntry(item) {
9706 if (item.kind === PConst.Kind.alias) {
9709 return !!(item.text &&
9710 item.text !== '<function>' &&
9711 item.text !== '<class>');
9714 exports.default = TypeScriptDocumentSymbolProvider;
9715 function containsRange(range, otherRange) {
9716 if (otherRange.start.line < range.start.line || otherRange.end.line < range.start.line) {
9719 if (otherRange.start.line > range.end.line || otherRange.end.line > range.end.line) {
9722 if (otherRange.start.line === range.start.line && otherRange.start.character < range.start.character) {
9725 if (otherRange.end.line === range.end.line && otherRange.end.character > range.end.character) {
9734 /***/ (function(module, exports, __webpack_require__) {
9738 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9739 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
9740 return new (P || (P = Promise))(function (resolve, reject) {
9741 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
9742 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9743 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9744 step((generator = generator.apply(thisArg, _arguments || [])).next());
9747 var __importDefault = (this && this.__importDefault) || function (mod) {
9748 return (mod && mod.__esModule) ? mod : { "default": mod };
9750 Object.defineProperty(exports, "__esModule", { value: true });
9751 /*---------------------------------------------------------------------------------------------
9752 * Copyright (c) Microsoft Corporation. All rights reserved.
9753 * Licensed under the MIT License. See License.txt in the project root for license information.
9754 *--------------------------------------------------------------------------------------------*/
9755 const coc_nvim_1 = __webpack_require__(1);
9756 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9757 const api_1 = __importDefault(__webpack_require__(40));
9758 function objAreEqual(a, b) {
9759 let keys = Object.keys(a);
9760 for (let i = 0; i < keys.length; i++) { // tslint:disable-line
9762 if (a[key] !== b[key]) {
9768 class FileConfigurationManager {
9769 constructor(client) {
9770 this.client = client;
9771 this.cachedMap = new Map();
9773 ensureConfigurationOptions(document, insertSpaces, tabSize) {
9774 return __awaiter(this, void 0, void 0, function* () {
9775 const file = this.client.toPath(document.uri);
9780 let cachedOption = this.cachedMap.get(document.uri);
9781 const currentOptions = this.getFileOptions(options, document);
9783 && objAreEqual(cachedOption.formatOptions, currentOptions.formatOptions)
9784 && objAreEqual(cachedOption.preferences, currentOptions.preferences))
9786 this.cachedMap.set(document.uri, currentOptions);
9787 const args = Object.assign({ file }, currentOptions);
9788 yield this.client.execute('configure', args, vscode_languageserver_protocol_1.CancellationToken.None);
9791 ensureConfigurationForDocument(document) {
9792 return __awaiter(this, void 0, void 0, function* () {
9793 let opts = yield coc_nvim_1.workspace.getFormatOptions(document.uri);
9794 return this.ensureConfigurationOptions(document, opts.insertSpaces, opts.tabSize);
9798 this.cachedMap.clear();
9800 getLanguageConfiguration(languageId) {
9801 return coc_nvim_1.workspace.getConfiguration(languageId);
9803 isTypeScriptDocument(languageId) {
9804 return languageId.startsWith('typescript');
9806 formatEnabled(document) {
9807 let { languageId, uri } = document;
9808 let language = languageId.startsWith('typescript') ? 'typescript' : 'javascript';
9809 const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
9810 return config.get('enabled');
9812 enableJavascript() {
9813 const config = coc_nvim_1.workspace.getConfiguration('tsserver');
9814 return !!config.get('enableJavascript');
9816 getFileOptions(options, document) {
9817 const lang = this.isTypeScriptDocument(document.languageId) ? 'typescript' : 'javascript';
9819 formatOptions: this.getFormatOptions(options, lang, document.uri),
9820 preferences: this.getPreferences(lang, document.uri)
9823 getFormatOptions(options, language, uri) {
9824 const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
9826 tabSize: options.tabSize,
9827 indentSize: options.tabSize,
9828 convertTabsToSpaces: options.insertSpaces,
9829 // We can use \n here since the editor normalizes later on to its line endings.
9830 newLineCharacter: '\n',
9831 insertSpaceAfterCommaDelimiter: config.get('insertSpaceAfterCommaDelimiter'),
9832 insertSpaceAfterConstructor: config.get('insertSpaceAfterConstructor'),
9833 insertSpaceAfterSemicolonInForStatements: config.get('insertSpaceAfterSemicolonInForStatements'),
9834 insertSpaceBeforeAndAfterBinaryOperators: config.get('insertSpaceBeforeAndAfterBinaryOperators'),
9835 insertSpaceAfterKeywordsInControlFlowStatements: config.get('insertSpaceAfterKeywordsInControlFlowStatements'),
9836 insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get('insertSpaceAfterFunctionKeywordForAnonymousFunctions'),
9837 insertSpaceBeforeFunctionParenthesis: config.get('insertSpaceBeforeFunctionParenthesis'),
9838 insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis'),
9839 insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets'),
9840 insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces'),
9841 insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces'),
9842 insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces'),
9843 insertSpaceAfterTypeAssertion: config.get('insertSpaceAfterTypeAssertion'),
9844 placeOpenBraceOnNewLineForFunctions: config.get('placeOpenBraceOnNewLineForFunctions'),
9845 placeOpenBraceOnNewLineForControlBlocks: config.get('placeOpenBraceOnNewLineForControlBlocks'),
9846 semicolons: config.get('semicolons', undefined)
9849 getCompleteOptions(languageId) {
9850 const lang = this.isTypeScriptDocument(languageId) ? 'typescript' : 'javascript';
9851 const config = coc_nvim_1.workspace.getConfiguration(`${lang}.suggest`);
9853 enabled: config.get('enabled', true),
9854 names: config.get('names', true),
9855 paths: config.get('paths', true),
9856 completeFunctionCalls: config.get('completeFunctionCalls', true),
9857 autoImports: config.get('autoImports', true),
9858 includeAutomaticOptionalChainCompletions: config.get('includeAutomaticOptionalChainCompletions', true)
9861 getPreferences(language, uri) {
9862 if (this.client.apiVersion.lt(api_1.default.v290)) {
9865 const config = coc_nvim_1.workspace.getConfiguration(`${language}.preferences`, uri);
9866 // getImportModuleSpecifierEndingPreference available on ts 2.9.0
9867 const preferences = {
9868 quotePreference: this.getQuoteStyle(config),
9869 importModuleSpecifierPreference: getImportModuleSpecifier(config),
9870 importModuleSpecifierEnding: getImportModuleSpecifierEndingPreference(config),
9871 allowTextChangesInNewFiles: uri.startsWith('file:'),
9872 allowRenameOfImportPath: true,
9873 providePrefixAndSuffixTextForRename: true,
9877 getQuoteStyle(config) {
9878 let quoteStyle = config.get('quoteStyle', 'auto');
9879 if (this.client.apiVersion.gte(api_1.default.v333) || quoteStyle != 'auto')
9884 exports.default = FileConfigurationManager;
9885 function getImportModuleSpecifier(config) {
9886 let val = config.get('importModuleSpecifier');
9890 case 'non-relative':
9891 return 'non-relative';
9896 function getImportModuleSpecifierEndingPreference(config) {
9897 switch (config.get('importModuleSpecifierEnding')) {
9898 case 'minimal': return 'minimal';
9899 case 'index': return 'index';
9900 case 'js': return 'js';
9901 default: return 'auto';
9908 /***/ (function(module, exports, __webpack_require__) {
9912 /*---------------------------------------------------------------------------------------------
9913 * Copyright (c) Microsoft Corporation. All rights reserved.
9914 * Licensed under the MIT License. See License.txt in the project root for license information.
9915 *--------------------------------------------------------------------------------------------*/
9916 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9917 if (k2 === undefined) k2 = k;
9918 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9919 }) : (function(o, m, k, k2) {
9920 if (k2 === undefined) k2 = k;
9923 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9924 Object.defineProperty(o, "default", { enumerable: true, value: v });
9925 }) : function(o, v) {
9928 var __importStar = (this && this.__importStar) || function (mod) {
9929 if (mod && mod.__esModule) return mod;
9931 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9932 __setModuleDefault(result, mod);
9935 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9936 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
9937 return new (P || (P = Promise))(function (resolve, reject) {
9938 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
9939 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9940 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9941 step((generator = generator.apply(thisArg, _arguments || [])).next());
9944 Object.defineProperty(exports, "__esModule", { value: true });
9945 const vscode_languageserver_types_1 = __webpack_require__(18);
9946 const coc_nvim_1 = __webpack_require__(1);
9947 const typeConverters = __importStar(__webpack_require__(37));
9948 class TypeScriptFoldingProvider {
9949 constructor(client) {
9950 this.client = client;
9952 provideFoldingRanges(document, _context, token) {
9953 return __awaiter(this, void 0, void 0, function* () {
9954 const file = this.client.toPath(document.uri);
9958 const args = { file };
9959 const res = yield this.client.execute('getOutliningSpans', args, token);
9960 if (res.type != 'response') {
9963 const { body } = res;
9968 .map(span => this.convertOutliningSpan(span, document))
9969 .filter(foldingRange => !!foldingRange);
9972 convertOutliningSpan(span, document) {
9973 const range = typeConverters.Range.fromTextSpan(span.textSpan);
9974 const kind = TypeScriptFoldingProvider.getFoldingRangeKind(span);
9975 // Workaround for #49904
9976 if (span.kind === 'comment') {
9977 let doc = coc_nvim_1.workspace.getDocument(document.uri);
9978 const line = doc.getline(range.start.line);
9979 if (line.match(/\/\/\s*#endregion/gi)) {
9983 let { start, end } = range;
9984 return vscode_languageserver_types_1.FoldingRange.create(start.line, end.line, start.character, end.character, kind);
9986 static getFoldingRangeKind(span) {
9987 switch (span.kind) {
9998 exports.default = TypeScriptFoldingProvider;
10003 /***/ (function(module, exports, __webpack_require__) {
10007 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10008 if (k2 === undefined) k2 = k;
10009 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10010 }) : (function(o, m, k, k2) {
10011 if (k2 === undefined) k2 = k;
10014 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10015 Object.defineProperty(o, "default", { enumerable: true, value: v });
10016 }) : function(o, v) {
10019 var __importStar = (this && this.__importStar) || function (mod) {
10020 if (mod && mod.__esModule) return mod;
10022 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10023 __setModuleDefault(result, mod);
10026 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
10027 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10028 return new (P || (P = Promise))(function (resolve, reject) {
10029 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10030 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10031 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10032 step((generator = generator.apply(thisArg, _arguments || [])).next());
10035 Object.defineProperty(exports, "__esModule", { value: true });
10036 /*---------------------------------------------------------------------------------------------
10037 * Copyright (c) Microsoft Corporation. All rights reserved.
10038 * Licensed under the MIT License. See License.txt in the project root for license information.
10039 *--------------------------------------------------------------------------------------------*/
10040 const coc_nvim_1 = __webpack_require__(1);
10041 const typeConverters = __importStar(__webpack_require__(37));
10042 class TypeScriptFormattingProvider {
10043 constructor(client, formattingOptionsManager) {
10044 this.client = client;
10045 this.formattingOptionsManager = formattingOptionsManager;
10047 enabled(document) {
10048 return this.formattingOptionsManager.formatEnabled(document);
10050 doFormat(document, options, args, token) {
10051 return __awaiter(this, void 0, void 0, function* () {
10052 if (!this.enabled(document))
10054 yield this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize);
10056 const response = yield this.client.execute('format', args, token);
10057 if (response.type == 'response' && response.body) {
10058 let edits = response.body.map(typeConverters.TextEdit.fromCodeEdit);
10068 provideDocumentRangeFormattingEdits(document, range, options, token) {
10069 return __awaiter(this, void 0, void 0, function* () {
10070 if (!this.enabled(document))
10072 const filepath = this.client.toPath(document.uri);
10077 line: range.start.line + 1,
10078 offset: range.start.character + 1,
10079 endLine: range.end.line + 1,
10080 endOffset: range.end.character + 1
10082 return this.doFormat(document, options, args, token);
10085 provideDocumentFormattingEdits(document, options, token) {
10086 return __awaiter(this, void 0, void 0, function* () {
10087 if (!this.enabled(document))
10089 const filepath = this.client.toPath(document.uri);
10096 endLine: document.lineCount + 1,
10099 return this.doFormat(document, options, args, token);
10102 provideOnTypeFormattingEdits(document, position, ch, options, token) {
10103 return __awaiter(this, void 0, void 0, function* () {
10104 if (!this.enabled(document))
10106 if (!this.client.configuration.formatOnType)
10108 const file = this.client.toPath(document.uri);
10111 yield this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize);
10112 const doc = coc_nvim_1.workspace.getDocument(document.uri);
10113 const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { key: ch });
10115 const res = yield this.client.execute('formatonkey', args, token);
10116 if (res.type != 'response') {
10119 const { body } = res;
10120 const edits = body;
10125 for (const edit of edits) {
10126 const textEdit = typeConverters.TextEdit.fromCodeEdit(edit);
10127 const range = textEdit.range;
10128 // Work around for https://github.com/Microsoft/TypeScript/issues/6700.
10129 // Check if we have an edit at the beginning of the line which only removes white spaces and leaves
10130 // an empty line. Drop those edits
10131 if (range.start.character === 0 &&
10132 range.start.line === range.end.line &&
10133 textEdit.newText === '') {
10134 const lText = doc.getline(range.start.line);
10135 // If the edit leaves something on the line keep the edit (note that the end character is exclusive).
10136 // Keep it also if it removes something else than whitespace
10137 if (lText.trim().length > 0 || lText.length > range.end.character) {
10138 result.push(textEdit);
10142 result.push(textEdit);
10154 exports.default = TypeScriptFormattingProvider;
10159 /***/ (function(module, exports, __webpack_require__) {
10163 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10164 if (k2 === undefined) k2 = k;
10165 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10166 }) : (function(o, m, k, k2) {
10167 if (k2 === undefined) k2 = k;
10170 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10171 Object.defineProperty(o, "default", { enumerable: true, value: v });
10172 }) : function(o, v) {
10175 var __importStar = (this && this.__importStar) || function (mod) {
10176 if (mod && mod.__esModule) return mod;
10178 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10179 __setModuleDefault(result, mod);
10182 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
10183 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10184 return new (P || (P = Promise))(function (resolve, reject) {
10185 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10186 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10187 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10188 step((generator = generator.apply(thisArg, _arguments || [])).next());
10191 Object.defineProperty(exports, "__esModule", { value: true });
10192 const previewer_1 = __webpack_require__(86);
10193 const typeConverters = __importStar(__webpack_require__(37));
10194 class TypeScriptHoverProvider {
10195 constructor(client) {
10196 this.client = client;
10198 provideHover(document, position, token) {
10199 return __awaiter(this, void 0, void 0, function* () {
10200 const filepath = this.client.toPath(document.uri);
10204 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
10206 const response = yield this.client.interruptGetErr(() => this.client.execute('quickinfo', args, token));
10207 if (response && response.type == 'response' && response.body) {
10208 const data = response.body;
10210 contents: TypeScriptHoverProvider.getContents(data),
10211 range: typeConverters.Range.fromTextSpan(data)
10221 static getContents(data) {
10223 if (data.displayString) {
10224 parts.push({ language: 'typescript', value: data.displayString });
10226 const tags = previewer_1.tagsMarkdownPreview(data.tags);
10227 parts.push(data.documentation + (tags ? '\n\n' + tags : ''));
10231 exports.default = TypeScriptHoverProvider;
10236 /***/ (function(module, exports, __webpack_require__) {
10240 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10241 if (k2 === undefined) k2 = k;
10242 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10243 }) : (function(o, m, k, k2) {
10244 if (k2 === undefined) k2 = k;
10247 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10248 Object.defineProperty(o, "default", { enumerable: true, value: v });
10249 }) : function(o, v) {
10252 var __importStar = (this && this.__importStar) || function (mod) {
10253 if (mod && mod.__esModule) return mod;
10255 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10256 __setModuleDefault(result, mod);
10259 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
10260 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10261 return new (P || (P = Promise))(function (resolve, reject) {
10262 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10263 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10264 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10265 step((generator = generator.apply(thisArg, _arguments || [])).next());
10268 Object.defineProperty(exports, "__esModule", { value: true });
10269 const PConst = __importStar(__webpack_require__(39));
10270 const typeConverters = __importStar(__webpack_require__(37));
10271 const baseCodeLensProvider_1 = __webpack_require__(35);
10272 class TypeScriptImplementationsCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
10273 resolveCodeLens(codeLens, token) {
10274 return __awaiter(this, void 0, void 0, function* () {
10275 let { uri } = codeLens.data;
10276 let filepath = this.client.toPath(uri);
10277 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
10279 const response = yield this.client.execute('implementation', args, token, true);
10280 if (response && response.type == 'response' && response.body) {
10281 const locations = response.body
10282 .map(reference => {
10284 uri: this.client.toResource(reference.file),
10286 start: typeConverters.Position.fromLocation(reference.start),
10288 line: reference.start.line,
10294 // Exclude original from implementations
10295 .filter(location => !(location.uri.toString() === uri &&
10296 location.range.start.line === codeLens.range.start.line &&
10297 location.range.start.character ===
10298 codeLens.range.start.character));
10299 codeLens.command = this.getCommand(locations, codeLens);
10306 codeLens.command = {
10307 title: '0 implementations',
10313 getCommand(locations, codeLens) {
10314 let { uri } = codeLens.data;
10316 title: this.getTitle(locations),
10317 command: locations.length ? 'editor.action.showReferences' : '',
10318 arguments: [uri, codeLens.range.start, locations]
10321 getTitle(locations) {
10322 return locations.length === 1 ? '1 implementation' : `${locations.length} implementations`;
10324 extractSymbol(document, item, _parent) {
10325 switch (item.kind) {
10326 case PConst.Kind.interface:
10327 return super.getSymbolRange(document, item);
10328 case PConst.Kind.class:
10329 case PConst.Kind.method:
10330 case PConst.Kind.memberVariable:
10331 case PConst.Kind.memberGetAccessor:
10332 case PConst.Kind.memberSetAccessor:
10333 if (item.kindModifiers.match(/\babstract\b/g)) {
10334 return super.getSymbolRange(document, item);
10341 exports.default = TypeScriptImplementationsCodeLensProvider;
10346 /***/ (function(module, exports, __webpack_require__) {
10350 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10351 if (k2 === undefined) k2 = k;
10352 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10353 }) : (function(o, m, k, k2) {
10354 if (k2 === undefined) k2 = k;
10357 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10358 Object.defineProperty(o, "default", { enumerable: true, value: v });
10359 }) : function(o, v) {
10362 var __importStar = (this && this.__importStar) || function (mod) {
10363 if (mod && mod.__esModule) return mod;
10365 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10366 __setModuleDefault(result, mod);
10369 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
10370 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10371 return new (P || (P = Promise))(function (resolve, reject) {
10372 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10373 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10374 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10375 step((generator = generator.apply(thisArg, _arguments || [])).next());
10378 var __importDefault = (this && this.__importDefault) || function (mod) {
10379 return (mod && mod.__esModule) ? mod : { "default": mod };
10381 Object.defineProperty(exports, "__esModule", { value: true });
10382 /*---------------------------------------------------------------------------------------------
10383 * Copyright (c) Microsoft Corporation. All rights reserved.
10384 * Licensed under the MIT License. See License.txt in the project root for license information.
10385 *--------------------------------------------------------------------------------------------*/
10386 const coc_nvim_1 = __webpack_require__(1);
10387 const vscode_languageserver_protocol_1 = __webpack_require__(3);
10388 const api_1 = __importDefault(__webpack_require__(40));
10389 const codeAction_1 = __webpack_require__(84);
10390 const typeConverters = __importStar(__webpack_require__(37));
10391 class ApplyCodeActionCommand {
10392 constructor(client) {
10393 this.client = client;
10394 this.id = ApplyCodeActionCommand.ID;
10397 return __awaiter(this, void 0, void 0, function* () {
10398 return codeAction_1.applyCodeActionCommands(this.client, action);
10402 ApplyCodeActionCommand.ID = '_typescript.applyCodeActionCommand';
10403 class ApplyFixAllCodeAction {
10404 constructor(client) {
10405 this.client = client;
10406 this.id = ApplyFixAllCodeAction.ID;
10408 execute(file, tsAction) {
10409 return __awaiter(this, void 0, void 0, function* () {
10410 if (!tsAction.fixId) {
10418 fixId: tsAction.fixId
10421 const res = yield this.client.execute('getCombinedCodeFix', args, vscode_languageserver_protocol_1.CancellationToken.None);
10422 if (res.type != 'response') {
10425 let { body } = res;
10426 const edit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.changes);
10427 yield coc_nvim_1.workspace.applyEdit(edit);
10428 const token = vscode_languageserver_protocol_1.CancellationToken.None;
10429 const { commands } = body;
10430 if (commands && commands.length) {
10431 for (const command of commands) {
10432 yield this.client.execute('applyCodeActionCommand', { command }, token);
10442 ApplyFixAllCodeAction.ID = '_typescript.applyFixAllCodeAction';
10444 * Unique set of diagnostics keyed on diagnostic range and error code.
10446 class DiagnosticsSet {
10447 constructor(_values) {
10448 this._values = _values;
10450 static from(diagnostics) {
10451 const values = new Map();
10452 for (const diagnostic of diagnostics) {
10453 values.set(DiagnosticsSet.key(diagnostic), diagnostic);
10455 return new DiagnosticsSet(values);
10457 static key(diagnostic) {
10458 const { start, end } = diagnostic.range;
10459 return `${diagnostic.code}-${start.line},${start.character}-${end.line},${end.character}`;
10462 return this._values.values();
10465 class SupportedCodeActionProvider {
10466 constructor(client) {
10467 this.client = client;
10469 getFixableDiagnosticsForContext(context) {
10470 return __awaiter(this, void 0, void 0, function* () {
10471 const supportedActions = yield this.supportedCodeActions;
10472 const fixableDiagnostics = DiagnosticsSet.from(context.diagnostics.filter(diagnostic => supportedActions.has(+diagnostic.code)));
10473 return Array.from(fixableDiagnostics.values);
10476 get supportedCodeActions() {
10477 if (!this._supportedCodeActions) {
10478 return new Promise((resolve, reject) => {
10479 this.client.execute('getSupportedCodeFixes', null, vscode_languageserver_protocol_1.CancellationToken.None).then(res => {
10480 if (res.type !== 'response') {
10481 resolve(new Set());
10484 let codes = res.body.map(code => +code).filter(code => !isNaN(code));
10485 resolve(new Set(codes));
10489 return Promise.resolve(this._supportedCodeActions);
10492 class TypeScriptQuickFixProvider {
10493 constructor(client) {
10494 this.client = client;
10495 coc_nvim_1.commands.register(new ApplyCodeActionCommand(client));
10496 coc_nvim_1.commands.register(new ApplyFixAllCodeAction(client));
10497 this.supportedCodeActionProvider = new SupportedCodeActionProvider(client);
10499 provideCodeActions(document, _range, context, token) {
10500 return __awaiter(this, void 0, void 0, function* () {
10501 if (!this.client.apiVersion.gte(api_1.default.v213)) {
10504 const file = this.client.toPath(document.uri);
10508 const fixableDiagnostics = yield this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context);
10509 if (!fixableDiagnostics.length) {
10512 if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
10515 const results = [];
10516 for (const diagnostic of fixableDiagnostics) {
10517 results.push(...(yield this.getFixesForDiagnostic(document, file, diagnostic, token)));
10522 getFixesForDiagnostic(document, file, diagnostic, token) {
10523 return __awaiter(this, void 0, void 0, function* () {
10524 const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+diagnostic.code] });
10525 const codeFixesResponse = yield this.client.execute('getCodeFixes', args, token);
10526 if (codeFixesResponse.type != 'response') {
10529 if (codeFixesResponse.body) {
10530 const results = [];
10531 for (const tsCodeFix of codeFixesResponse.body) {
10532 results.push(...(yield this.getAllFixesForTsCodeAction(document, file, diagnostic, tsCodeFix)));
10539 getAllFixesForTsCodeAction(document, file, diagnostic, tsAction) {
10540 return __awaiter(this, void 0, void 0, function* () {
10541 const singleFix = this.getSingleFixForTsCodeAction(diagnostic, tsAction);
10542 const fixAll = yield this.getFixAllForTsCodeAction(document, file, diagnostic, tsAction);
10543 return fixAll ? [singleFix, fixAll] : [singleFix];
10546 getSingleFixForTsCodeAction(diagnostic, tsAction) {
10547 const codeAction = {
10548 title: tsAction.description,
10549 kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
10551 codeAction.edit = codeAction_1.getEditForCodeAction(this.client, tsAction);
10552 codeAction.diagnostics = [diagnostic];
10553 codeAction.isPrefered = true;
10554 if (tsAction.commands) {
10555 codeAction.command = {
10556 command: ApplyCodeActionCommand.ID,
10557 arguments: [tsAction],
10558 title: tsAction.description
10563 getFixAllForTsCodeAction(document, file, diagnostic, tsAction) {
10564 return __awaiter(this, void 0, void 0, function* () {
10565 if (!tsAction.fixId || !this.client.apiVersion.gte(api_1.default.v270)) {
10568 // Make sure there are multiple diagnostics of the same type in the file
10569 if (!this.client.diagnosticsManager
10570 .getDiagnostics(document.uri)
10571 .some(x => x.code === diagnostic.code && x !== diagnostic)) {
10575 title: tsAction.fixAllDescription || 'Fix all in file',
10576 kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
10578 action.diagnostics = [diagnostic];
10580 command: ApplyFixAllCodeAction.ID,
10581 arguments: [file, tsAction],
10588 exports.default = TypeScriptQuickFixProvider;
10593 /***/ (function(module, exports, __webpack_require__) {
10597 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
10598 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10599 return new (P || (P = Promise))(function (resolve, reject) {
10600 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10601 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10602 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10603 step((generator = generator.apply(thisArg, _arguments || [])).next());
10606 Object.defineProperty(exports, "__esModule", { value: true });
10607 const coc_nvim_1 = __webpack_require__(1);
10608 const vscode_languageserver_protocol_1 = __webpack_require__(3);
10609 const helper_1 = __webpack_require__(100);
10610 class ImportFixProvider {
10611 constructor(bufferSyncSupport) {
10612 this.bufferSyncSupport = bufferSyncSupport;
10614 provideCodeActions(document, _range, context, _token) {
10615 return __awaiter(this, void 0, void 0, function* () {
10616 if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
10619 let diagnostics = context.diagnostics.filter(d => d.code == 2304);
10620 if (!diagnostics.length)
10624 let doc = coc_nvim_1.workspace.getDocument(document.uri);
10626 for (const diagnostic of diagnostics) {
10627 let { range } = diagnostic;
10628 let line = doc.getline(range.start.line);
10629 let name = line.slice(range.start.character, range.end.character);
10630 if (names.indexOf(name) !== -1)
10632 if (helper_1.nodeModules.indexOf(name) !== -1) {
10635 range: vscode_languageserver_protocol_1.Range.create(0, 0, 0, 0),
10636 newText: `import ${name} from '${name}'\n`
10638 command = 'tsserver.organizeImports';
10643 [document.uri]: edits
10649 title: `fix import`,
10650 command: 'tsserver.organizeImports'
10653 title: `Add import ${names.join(', ')}`,
10660 exports.default = ImportFixProvider;
10665 /***/ (function(module, exports, __webpack_require__) {
10669 Object.defineProperty(exports, "__esModule", { value: true });
10670 exports.nodeModules = void 0;
10671 exports.nodeModules = [
10705 /***/ (function(module, exports, __webpack_require__) {
10709 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10710 if (k2 === undefined) k2 = k;
10711 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10712 }) : (function(o, m, k, k2) {
10713 if (k2 === undefined) k2 = k;
10716 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10717 Object.defineProperty(o, "default", { enumerable: true, value: v });
10718 }) : function(o, v) {
10721 var __importStar = (this && this.__importStar) || function (mod) {
10722 if (mod && mod.__esModule) return mod;
10724 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10725 __setModuleDefault(result, mod);
10728 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
10729 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10730 return new (P || (P = Promise))(function (resolve, reject) {
10731 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10732 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10733 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10734 step((generator = generator.apply(thisArg, _arguments || [])).next());
10737 Object.defineProperty(exports, "__esModule", { value: true });
10738 /*---------------------------------------------------------------------------------------------
10739 * Copyright (c) Microsoft Corporation. All rights reserved.
10740 * Licensed under the MIT License. See License.txt in the project root for license information.
10741 *--------------------------------------------------------------------------------------------*/
10742 const vscode_languageserver_protocol_1 = __webpack_require__(3);
10743 const coc_nvim_1 = __webpack_require__(1);
10744 const typeConverters = __importStar(__webpack_require__(37));
10745 class ApplyRefactoringCommand {
10746 constructor(client) {
10747 this.client = client;
10748 this.id = ApplyRefactoringCommand.ID;
10750 execute(document, file, refactor, action, range) {
10751 return __awaiter(this, void 0, void 0, function* () {
10752 const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, range)), { refactor,
10754 const response = yield this.client.execute('getEditsForRefactor', args, vscode_languageserver_protocol_1.CancellationToken.None);
10755 const body = response && response.body;
10756 if (!body || !body.edits.length) {
10759 const workspaceEdit = yield this.toWorkspaceEdit(body);
10760 if (!(yield coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
10763 const renameLocation = body.renameLocation;
10764 if (renameLocation) {
10765 coc_nvim_1.commands.executeCommand('editor.action.rename', document.uri, typeConverters.Position.fromLocation(renameLocation));
10770 toWorkspaceEdit(body) {
10771 return __awaiter(this, void 0, void 0, function* () {
10772 for (const edit of body.edits) {
10773 yield coc_nvim_1.workspace.createFile(edit.fileName, { ignoreIfExists: true });
10775 let workspaceEdit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.edits);
10776 return workspaceEdit;
10780 ApplyRefactoringCommand.ID = '_typescript.applyRefactoring';
10781 class SelectRefactorCommand {
10782 constructor(doRefactoring) {
10783 this.doRefactoring = doRefactoring;
10784 this.id = SelectRefactorCommand.ID;
10786 execute(document, file, info, range) {
10787 return __awaiter(this, void 0, void 0, function* () {
10788 let { actions } = info;
10789 const idx = actions.length == 1 ? 0 : yield coc_nvim_1.workspace.showQuickpick(actions.map(action => action.description || action.name));
10792 let label = info.actions[idx].name;
10795 return this.doRefactoring.execute(document, file, info.name, label, range);
10799 SelectRefactorCommand.ID = '_typescript.selectRefactoring';
10800 class TypeScriptRefactorProvider {
10801 constructor(client, formattingOptionsManager) {
10802 this.client = client;
10803 this.formattingOptionsManager = formattingOptionsManager;
10804 const doRefactoringCommand = coc_nvim_1.commands.register(new ApplyRefactoringCommand(this.client));
10805 coc_nvim_1.commands.register(new SelectRefactorCommand(doRefactoringCommand));
10807 provideCodeActions(document, range, context, token) {
10808 return __awaiter(this, void 0, void 0, function* () {
10809 if (!this.shouldTrigger(context)) {
10812 const file = this.client.toPath(document.uri);
10815 yield this.formattingOptionsManager.ensureConfigurationForDocument(document);
10816 const args = typeConverters.Range.toFileRangeRequestArgs(file, range);
10819 response = yield this.client.interruptGetErr(() => {
10820 return this.client.execute('getApplicableRefactors', args, token);
10822 if (!response || !response.body) {
10829 return this.convertApplicableRefactors(response.body, document, file, range);
10832 convertApplicableRefactors(body, document, file, rangeOrSelection) {
10833 const actions = [];
10834 for (const info of body) {
10835 if (!info.inlineable) {
10836 const codeAction = {
10837 title: info.description,
10838 kind: vscode_languageserver_protocol_1.CodeActionKind.Refactor
10840 codeAction.command = {
10841 title: info.description,
10842 command: SelectRefactorCommand.ID,
10843 arguments: [document, file, info, rangeOrSelection]
10845 actions.push(codeAction);
10848 for (const action of info.actions) {
10849 actions.push(this.refactorActionToCodeAction(action, document, file, info, rangeOrSelection));
10855 refactorActionToCodeAction(action, document, file, info, rangeOrSelection) {
10856 const codeAction = {
10857 title: action.description,
10858 kind: TypeScriptRefactorProvider.getKind(action)
10860 codeAction.command = {
10861 title: action.description,
10862 command: ApplyRefactoringCommand.ID,
10863 arguments: [document, file, info.name, action.name, rangeOrSelection]
10867 shouldTrigger(context) {
10868 if (context.only &&
10869 context.only.indexOf(vscode_languageserver_protocol_1.CodeActionKind.Refactor) == -1) {
10874 static getKind(refactor) {
10875 if (refactor.name.startsWith('function_')) {
10876 return TypeScriptRefactorProvider.extractFunctionKind;
10878 else if (refactor.name.startsWith('constant_')) {
10879 return TypeScriptRefactorProvider.extractConstantKind;
10881 else if (refactor.name.startsWith('Move')) {
10882 return TypeScriptRefactorProvider.moveKind;
10884 return vscode_languageserver_protocol_1.CodeActionKind.Refactor;
10887 exports.default = TypeScriptRefactorProvider;
10888 TypeScriptRefactorProvider.extractFunctionKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.function';
10889 TypeScriptRefactorProvider.extractConstantKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.constant';
10890 TypeScriptRefactorProvider.moveKind = vscode_languageserver_protocol_1.CodeActionKind.Refactor + '.move';
10891 TypeScriptRefactorProvider.metadata = {
10892 providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.Refactor]
10898 /***/ (function(module, exports, __webpack_require__) {
10902 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10903 if (k2 === undefined) k2 = k;
10904 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10905 }) : (function(o, m, k, k2) {
10906 if (k2 === undefined) k2 = k;
10909 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10910 Object.defineProperty(o, "default", { enumerable: true, value: v });
10911 }) : function(o, v) {
10914 var __importStar = (this && this.__importStar) || function (mod) {
10915 if (mod && mod.__esModule) return mod;
10917 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10918 __setModuleDefault(result, mod);
10921 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
10922 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10923 return new (P || (P = Promise))(function (resolve, reject) {
10924 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10925 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10926 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10927 step((generator = generator.apply(thisArg, _arguments || [])).next());
10930 Object.defineProperty(exports, "__esModule", { value: true });
10931 const typeConverters = __importStar(__webpack_require__(37));
10932 class TypeScriptReferences {
10933 constructor(client) {
10934 this.client = client;
10936 provideReferences(document, position, context, token) {
10937 return __awaiter(this, void 0, void 0, function* () {
10938 const filepath = this.client.toPath(document.uri);
10941 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
10943 const msg = yield this.client.execute('references', args, token);
10944 if (!msg || msg.type != 'response' || !msg.body) {
10948 for (const ref of msg.body.refs) {
10949 if (!context.includeDeclaration && ref.isDefinition) {
10952 const url = this.client.toResource(ref.file);
10953 const location = typeConverters.Location.fromTextSpan(url, ref);
10954 result.push(location);
10964 exports.default = TypeScriptReferences;
10969 /***/ (function(module, exports, __webpack_require__) {
10973 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10974 if (k2 === undefined) k2 = k;
10975 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10976 }) : (function(o, m, k, k2) {
10977 if (k2 === undefined) k2 = k;
10980 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10981 Object.defineProperty(o, "default", { enumerable: true, value: v });
10982 }) : function(o, v) {
10985 var __importStar = (this && this.__importStar) || function (mod) {
10986 if (mod && mod.__esModule) return mod;
10988 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10989 __setModuleDefault(result, mod);
10992 Object.defineProperty(exports, "__esModule", { value: true });
10993 const PConst = __importStar(__webpack_require__(39));
10994 const typeConverters = __importStar(__webpack_require__(37));
10995 const baseCodeLensProvider_1 = __webpack_require__(35);
10996 class TypeScriptReferencesCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
10997 resolveCodeLens(codeLens, token) {
10998 let { uri } = codeLens.data;
10999 let filepath = this.client.toPath(uri);
11000 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
11002 .execute('references', args, token, true)
11003 .then(response => {
11004 if (!response || response.type != 'response' || !response.body) {
11007 const locations = response.body.refs
11008 .map(reference => typeConverters.Location.fromTextSpan(this.client.toResource(reference.file), reference))
11009 .filter(location =>
11010 // Exclude original definition from references
11011 !(location.uri.toString() === uri &&
11012 location.range.start.line === codeLens.range.start.line &&
11013 location.range.start.character ===
11014 codeLens.range.start.character));
11015 codeLens.command = {
11016 title: locations.length === 1 ? '1 reference' : `${locations.length} references`,
11017 command: locations.length ? 'editor.action.showReferences' : '',
11018 arguments: [uri, codeLens.range.start, locations]
11023 codeLens.command = {
11024 title: '0 references',
11030 extractSymbol(document, item, parent) {
11031 if (parent && parent.kind === PConst.Kind.enum) {
11032 return super.getSymbolRange(document, item);
11034 switch (item.kind) {
11035 case PConst.Kind.const:
11036 case PConst.Kind.let:
11037 case PConst.Kind.variable:
11038 case PConst.Kind.function:
11039 // Only show references for exported variables
11040 if (!item.kindModifiers.match(/\bexport\b/)) {
11044 case PConst.Kind.class:
11045 if (item.text === '<class>') {
11049 case PConst.Kind.method:
11050 case PConst.Kind.memberVariable:
11051 case PConst.Kind.memberGetAccessor:
11052 case PConst.Kind.memberSetAccessor:
11053 case PConst.Kind.constructorImplementation:
11054 case PConst.Kind.interface:
11055 case PConst.Kind.type:
11056 case PConst.Kind.enum:
11057 return super.getSymbolRange(document, item);
11062 exports.default = TypeScriptReferencesCodeLensProvider;
11067 /***/ (function(module, exports, __webpack_require__) {
11071 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11072 if (k2 === undefined) k2 = k;
11073 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11074 }) : (function(o, m, k, k2) {
11075 if (k2 === undefined) k2 = k;
11078 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11079 Object.defineProperty(o, "default", { enumerable: true, value: v });
11080 }) : function(o, v) {
11083 var __importStar = (this && this.__importStar) || function (mod) {
11084 if (mod && mod.__esModule) return mod;
11086 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11087 __setModuleDefault(result, mod);
11090 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11091 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11092 return new (P || (P = Promise))(function (resolve, reject) {
11093 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11094 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11095 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11096 step((generator = generator.apply(thisArg, _arguments || [])).next());
11099 var __importDefault = (this && this.__importDefault) || function (mod) {
11100 return (mod && mod.__esModule) ? mod : { "default": mod };
11102 Object.defineProperty(exports, "__esModule", { value: true });
11103 /*---------------------------------------------------------------------------------------------
11104 * Copyright (c) Microsoft Corporation. All rights reserved.
11105 * Licensed under the MIT License. See License.txt in the project root for license information.
11106 *--------------------------------------------------------------------------------------------*/
11107 const coc_nvim_1 = __webpack_require__(1);
11108 const path_1 = __importDefault(__webpack_require__(13));
11109 const api_1 = __importDefault(__webpack_require__(40));
11110 const typeConverters = __importStar(__webpack_require__(37));
11111 class TypeScriptRenameProvider {
11112 constructor(client) {
11113 this.client = client;
11115 prepareRename(document, position, token) {
11116 return __awaiter(this, void 0, void 0, function* () {
11117 const response = yield this.execRename(document, position, token);
11118 if (!response || response.type !== 'response' || !response.body) {
11121 const renameInfo = response.body.info;
11122 if (!renameInfo.canRename) {
11123 return Promise.reject(new Error('Invalid location for rename.'));
11125 if (this.client.apiVersion.gte(api_1.default.v310)) {
11126 const triggerSpan = renameInfo.triggerSpan;
11128 const range = typeConverters.Range.fromTextSpan(triggerSpan);
11135 provideRenameEdits(document, position, newName, token) {
11136 return __awaiter(this, void 0, void 0, function* () {
11137 const response = yield this.execRename(document, position, token);
11138 if (!response || response.type !== 'response' || !response.body) {
11141 const renameInfo = response.body.info;
11142 if (!renameInfo.canRename) {
11143 return Promise.reject(new Error('Invalid location for rename.'));
11145 if (this.client.apiVersion.gte(api_1.default.v310)) {
11146 if (renameInfo.fileToRename) {
11147 const edits = yield this.renameFile(renameInfo.fileToRename, newName, token);
11152 return Promise.reject(new Error('An error occurred while renaming file'));
11156 return this.toWorkspaceEdit(response.body.locs, newName);
11159 execRename(document, position, token) {
11160 return __awaiter(this, void 0, void 0, function* () {
11161 const file = this.client.toPath(document.uri);
11164 const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { findInStrings: false, findInComments: false });
11165 return this.client.interruptGetErr(() => {
11166 return this.client.execute('rename', args, token);
11170 toWorkspaceEdit(locations, newName) {
11172 for (const spanGroup of locations) {
11173 const uri = this.client.toResource(spanGroup.file);
11176 for (const textSpan of spanGroup.locs) {
11177 changes[uri].push({
11178 range: typeConverters.Range.fromTextSpan(textSpan),
11179 newText: (textSpan.prefixText || '') + newName + (textSpan.suffixText || '')
11184 return { changes };
11186 renameFile(fileToRename, newName, token) {
11187 return __awaiter(this, void 0, void 0, function* () {
11188 // Make sure we preserve file exension if none provided
11189 if (!path_1.default.extname(newName)) {
11190 newName += path_1.default.extname(fileToRename);
11192 const dirname = path_1.default.dirname(fileToRename);
11193 const newFilePath = path_1.default.join(dirname, newName);
11195 file: fileToRename,
11196 oldFilePath: fileToRename,
11199 const response = yield this.client.execute('getEditsForFileRename', args, token);
11200 if (response.type !== 'response' || !response.body) {
11203 const edits = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, response.body);
11204 edits.documentChanges = edits.documentChanges || [];
11205 edits.documentChanges.push({
11207 oldUri: coc_nvim_1.Uri.file(fileToRename).toString(),
11208 newUri: coc_nvim_1.Uri.file(newFilePath).toString(),
11211 ignoreIfExists: true
11218 exports.default = TypeScriptRenameProvider;
11223 /***/ (function(module, exports, __webpack_require__) {
11227 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11228 if (k2 === undefined) k2 = k;
11229 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11230 }) : (function(o, m, k, k2) {
11231 if (k2 === undefined) k2 = k;
11234 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11235 Object.defineProperty(o, "default", { enumerable: true, value: v });
11236 }) : function(o, v) {
11239 var __importStar = (this && this.__importStar) || function (mod) {
11240 if (mod && mod.__esModule) return mod;
11242 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11243 __setModuleDefault(result, mod);
11246 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11247 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11248 return new (P || (P = Promise))(function (resolve, reject) {
11249 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11250 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11251 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11252 step((generator = generator.apply(thisArg, _arguments || [])).next());
11255 Object.defineProperty(exports, "__esModule", { value: true });
11256 const Previewer = __importStar(__webpack_require__(86));
11257 const typeConverters = __importStar(__webpack_require__(37));
11258 class TypeScriptSignatureHelpProvider {
11259 constructor(client) {
11260 this.client = client;
11262 provideSignatureHelp(document, position, token) {
11263 return __awaiter(this, void 0, void 0, function* () {
11264 const filepath = this.client.toPath(document.uri);
11268 const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
11271 response = yield this.client.interruptGetErr(() => this.client.execute('signatureHelp', args, token));
11276 if (response.type !== 'response' || !response.body) {
11279 let info = response.body;
11281 activeSignature: info.selectedItemIndex,
11282 activeParameter: this.getActiveParmeter(info),
11283 signatures: info.items.map(signature => {
11284 return this.convertSignature(signature);
11290 getActiveParmeter(info) {
11291 const activeSignature = info.items[info.selectedItemIndex];
11292 if (activeSignature && activeSignature.isVariadic) {
11293 return Math.min(info.argumentIndex, activeSignature.parameters.length - 1);
11295 return info.argumentIndex;
11297 convertSignature(item) {
11298 let parameters = item.parameters.map(p => {
11300 label: Previewer.plain(p.displayParts),
11301 documentation: Previewer.markdownDocumentation(p.documentation, [])
11304 let label = Previewer.plain(item.prefixDisplayParts);
11305 label += parameters.map(parameter => parameter.label).join(Previewer.plain(item.separatorDisplayParts));
11306 label += Previewer.plain(item.suffixDisplayParts);
11309 documentation: Previewer.markdownDocumentation(item.documentation, item.tags.filter(x => x.name !== 'param')),
11314 exports.default = TypeScriptSignatureHelpProvider;
11315 TypeScriptSignatureHelpProvider.triggerCharacters = ['(', ',', '<'];
11320 /***/ (function(module, exports, __webpack_require__) {
11324 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11325 if (k2 === undefined) k2 = k;
11326 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11327 }) : (function(o, m, k, k2) {
11328 if (k2 === undefined) k2 = k;
11331 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11332 Object.defineProperty(o, "default", { enumerable: true, value: v });
11333 }) : function(o, v) {
11336 var __importStar = (this && this.__importStar) || function (mod) {
11337 if (mod && mod.__esModule) return mod;
11339 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11340 __setModuleDefault(result, mod);
11343 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11344 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11345 return new (P || (P = Promise))(function (resolve, reject) {
11346 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11347 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11348 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11349 step((generator = generator.apply(thisArg, _arguments || [])).next());
11352 Object.defineProperty(exports, "__esModule", { value: true });
11353 /*---------------------------------------------------------------------------------------------
11354 * Copyright (c) Microsoft Corporation. All rights reserved.
11355 * Licensed under the MIT License. See License.txt in the project root for license information.
11356 *--------------------------------------------------------------------------------------------*/
11357 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11358 const coc_nvim_1 = __webpack_require__(1);
11359 const typeConverters = __importStar(__webpack_require__(37));
11360 const mutex_1 = __webpack_require__(107);
11361 function wait(ms) {
11362 return new Promise(resolve => {
11368 class UpdateImportsOnFileRenameHandler {
11369 constructor(client, fileConfigurationManager, languageId) {
11370 this.client = client;
11371 this.fileConfigurationManager = fileConfigurationManager;
11372 this.disposables = [];
11373 let glob = languageId == 'typescript' ? '**/*.{ts,tsx}' : '**/*.{js,jsx}';
11374 const watcher = coc_nvim_1.workspace.createFileSystemWatcher(glob);
11375 this.disposables.push(watcher);
11376 let mutex = new mutex_1.Mutex();
11377 watcher.onDidRename((e) => __awaiter(this, void 0, void 0, function* () {
11378 let release = yield mutex.acquire();
11380 yield this.doRename(e.oldUri, e.newUri);
11384 this.client.logger.error('Error on rename:', e);
11387 }), null, this.disposables);
11390 coc_nvim_1.disposeAll(this.disposables);
11392 doRename(oldResource, newResource) {
11393 return __awaiter(this, void 0, void 0, function* () {
11394 if (oldResource.scheme !== 'file' || newResource.scheme !== 'file') {
11397 const targetFile = newResource.fsPath;
11398 const oldFile = oldResource.fsPath;
11399 const newUri = newResource.toString();
11400 let oldDocument = coc_nvim_1.workspace.getDocument(oldResource.toString());
11402 yield coc_nvim_1.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`);
11404 let document = coc_nvim_1.workspace.getDocument(newUri);
11406 yield coc_nvim_1.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`);
11409 document = yield coc_nvim_1.workspace.loadFile(newUri);
11413 const edits = yield this.getEditsForFileRename(document.textDocument, oldFile, targetFile);
11416 if (yield this.promptUser(newResource)) {
11417 yield coc_nvim_1.workspace.applyEdit(edits);
11421 promptUser(newResource) {
11422 return __awaiter(this, void 0, void 0, function* () {
11423 return yield coc_nvim_1.workspace.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`);
11426 getEditsForFileRename(document, oldFile, newFile) {
11427 return __awaiter(this, void 0, void 0, function* () {
11428 yield this.fileConfigurationManager.ensureConfigurationForDocument(document);
11429 const response = yield this.client.interruptGetErr(() => {
11431 oldFilePath: oldFile,
11432 newFilePath: newFile,
11434 return this.client.execute('getEditsForFileRename', args, vscode_languageserver_protocol_1.CancellationToken.None);
11436 if (!response || response.type != 'response' || !response.body) {
11440 for (const edit of response.body) {
11441 // Workaround for https://github.com/Microsoft/vscode/issues/52675
11442 if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) {
11445 for (const change of edit.textChanges) {
11446 if (change.newText.match(/\/node_modules\//gi)) {
11452 return typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, edits);
11456 exports.default = UpdateImportsOnFileRenameHandler;
11461 /***/ (function(module, exports, __webpack_require__) {
11465 Object.defineProperty(exports, "__esModule", { value: true });
11466 exports.Mutex = void 0;
11473 if (this.count > 0 && this.tasks.length > 0) {
11475 let next = this.tasks.shift();
11480 return this.count == 0;
11482 // tslint:disable-next-line: typedef
11484 return new Promise(res => {
11486 let released = false;
11495 this.tasks.push(task);
11496 process.nextTick(this.sched.bind(this));
11500 return this.acquire()
11514 exports.Mutex = Mutex;
11519 /***/ (function(module, exports, __webpack_require__) {
11523 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11524 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11525 return new (P || (P = Promise))(function (resolve, reject) {
11526 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11527 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11528 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11529 step((generator = generator.apply(thisArg, _arguments || [])).next());
11532 var __importDefault = (this && this.__importDefault) || function (mod) {
11533 return (mod && mod.__esModule) ? mod : { "default": mod };
11535 Object.defineProperty(exports, "__esModule", { value: true });
11536 const coc_nvim_1 = __webpack_require__(1);
11537 const path_1 = __importDefault(__webpack_require__(13));
11538 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11539 const countRegex = /Found\s+(\d+)\s+error/;
11540 const errorRegex = /^(.+)\((\d+),(\d+)\):\s(\w+)\sTS(\d+):\s*(.+)$/;
11542 (function (TscStatus) {
11543 TscStatus[TscStatus["INIT"] = 0] = "INIT";
11544 TscStatus[TscStatus["COMPILING"] = 1] = "COMPILING";
11545 TscStatus[TscStatus["RUNNING"] = 2] = "RUNNING";
11546 TscStatus[TscStatus["ERROR"] = 3] = "ERROR";
11547 })(TscStatus || (TscStatus = {}));
11548 class WatchProject {
11549 constructor(commandManager, client) {
11550 this.client = client;
11551 this.disposables = [];
11552 this.statusItem = coc_nvim_1.workspace.createStatusBarItem(1, { progress: true });
11553 let task = this.task = coc_nvim_1.workspace.createTask('TSC');
11554 this.disposables.push(commandManager.registerCommand(WatchProject.id, () => __awaiter(this, void 0, void 0, function* () {
11555 let opts = this.options = yield this.getOptions();
11556 yield this.start(opts);
11558 task.onExit(code => {
11560 coc_nvim_1.workspace.showMessage(`TSC exit with code ${code}`, 'warning');
11564 task.onStdout(lines => {
11565 for (let line of lines) {
11569 task.onStderr(lines => {
11570 coc_nvim_1.workspace.showMessage(`TSC error: ` + lines.join('\n'), 'error');
11572 this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => {
11575 this.check().catch(_e => {
11580 return __awaiter(this, void 0, void 0, function* () {
11581 let running = yield this.task.running;
11583 this.options = yield this.getOptions();
11584 this.statusItem.isProgress = false;
11585 this.statusItem.text = '?';
11586 this.statusItem.show();
11594 return __awaiter(this, void 0, void 0, function* () {
11595 yield this.task.start(options);
11599 this.statusItem.hide();
11602 this.statusItem.text = 'compiling';
11603 this.statusItem.isProgress = true;
11604 this.statusItem.show();
11605 coc_nvim_1.workspace.nvim.call('setqflist', [[]], true);
11608 if (countRegex.test(line)) {
11609 let ms = line.match(countRegex);
11610 this.statusItem.text = ms[1] == '0' ? '✓' : '✗';
11611 this.statusItem.isProgress = false;
11613 else if (WatchProject.startTexts.findIndex(s => line.indexOf(s) !== -1) != -1) {
11617 let ms = line.match(errorRegex);
11620 let fullpath = path_1.default.join(this.options.cwd, ms[1]);
11621 let uri = coc_nvim_1.Uri.file(fullpath).toString();
11622 let doc = coc_nvim_1.workspace.getDocument(uri);
11623 let bufnr = doc ? doc.bufnr : null;
11625 filename: fullpath,
11626 lnum: Number(ms[2]),
11627 col: Number(ms[3]),
11628 text: `[tsc ${ms[5]}] ${ms[6]}`,
11629 type: /error/i.test(ms[4]) ? 'E' : 'W'
11632 item.bufnr = bufnr;
11633 coc_nvim_1.workspace.nvim.call('setqflist', [[item], 'a']);
11637 return __awaiter(this, void 0, void 0, function* () {
11638 let { tscPath } = this.client;
11640 coc_nvim_1.workspace.showMessage(`Local & global tsc not found`, 'error');
11643 let find = yield coc_nvim_1.workspace.findUp(['tsconfig.json']);
11645 coc_nvim_1.workspace.showMessage('tsconfig.json not found!', 'error');
11648 let root = path_1.default.dirname(find);
11651 args: ['-p', 'tsconfig.json', '--watch', 'true', '--pretty', 'false'],
11657 coc_nvim_1.disposeAll(this.disposables);
11660 exports.default = WatchProject;
11661 WatchProject.id = 'tsserver.watchBuild';
11662 WatchProject.startTexts = ['Starting compilation in watch mode', 'Starting incremental compilation'];
11667 /***/ (function(module, exports, __webpack_require__) {
11671 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11672 if (k2 === undefined) k2 = k;
11673 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11674 }) : (function(o, m, k, k2) {
11675 if (k2 === undefined) k2 = k;
11678 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11679 Object.defineProperty(o, "default", { enumerable: true, value: v });
11680 }) : function(o, v) {
11683 var __importStar = (this && this.__importStar) || function (mod) {
11684 if (mod && mod.__esModule) return mod;
11686 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11687 __setModuleDefault(result, mod);
11690 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11691 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11692 return new (P || (P = Promise))(function (resolve, reject) {
11693 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11694 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11695 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11696 step((generator = generator.apply(thisArg, _arguments || [])).next());
11699 var __importDefault = (this && this.__importDefault) || function (mod) {
11700 return (mod && mod.__esModule) ? mod : { "default": mod };
11702 Object.defineProperty(exports, "__esModule", { value: true });
11703 /*---------------------------------------------------------------------------------------------
11704 * Copyright (c) Microsoft Corporation. All rights reserved.
11705 * Licensed under the MIT License. See License.txt in the project root for license information.
11706 *--------------------------------------------------------------------------------------------*/
11707 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11708 const coc_nvim_1 = __webpack_require__(1);
11709 const typeConverters = __importStar(__webpack_require__(37));
11710 const api_1 = __importDefault(__webpack_require__(40));
11711 function getSymbolKind(item) {
11712 switch (item.kind) {
11714 return vscode_languageserver_protocol_1.SymbolKind.Method;
11716 return vscode_languageserver_protocol_1.SymbolKind.Enum;
11718 return vscode_languageserver_protocol_1.SymbolKind.Function;
11720 return vscode_languageserver_protocol_1.SymbolKind.Class;
11722 return vscode_languageserver_protocol_1.SymbolKind.Interface;
11724 return vscode_languageserver_protocol_1.SymbolKind.Variable;
11726 return vscode_languageserver_protocol_1.SymbolKind.Variable;
11729 class TypeScriptWorkspaceSymbolProvider {
11730 constructor(client, languageIds) {
11731 this.client = client;
11732 this.languageIds = languageIds;
11734 provideWorkspaceSymbols(search, token) {
11735 return __awaiter(this, void 0, void 0, function* () {
11737 if (this.searchAllOpenProjects) {
11738 filepath = undefined;
11741 let uri = this.getUri();
11742 filepath = uri ? this.client.toPath(uri) : undefined;
11743 if (!filepath && this.client.apiVersion.lt(api_1.default.v390)) {
11749 searchValue: search,
11750 maxResultCount: 256,
11752 const response = yield this.client.execute('navto', args, token);
11753 if (response.type !== 'response' || response.body == null)
11756 for (const item of response.body) {
11757 if (!item.containerName && item.kind === 'alias') {
11760 const label = TypeScriptWorkspaceSymbolProvider.getLabel(item);
11762 start: typeConverters.Position.fromLocation(item.start),
11763 end: typeConverters.Position.fromLocation(item.end),
11765 const symbolInfo = vscode_languageserver_protocol_1.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file));
11766 result.push(symbolInfo);
11771 static getLabel(item) {
11772 let label = item.name;
11773 if (item.kind === 'method' || item.kind === 'function') {
11779 // typescript wants to have a resource even when asking
11780 // general questions so we check the active editor. If this
11781 // doesn't match we take the first TS document.
11782 const documents = coc_nvim_1.workspace.textDocuments;
11783 for (const document of documents) {
11784 if (this.languageIds.indexOf(document.languageId) >= 0) {
11785 return document.uri;
11790 get searchAllOpenProjects() {
11791 return this.client.apiVersion.gte(api_1.default.v390)
11792 && coc_nvim_1.workspace.getConfiguration('typescript').get('workspaceSymbols.scope', 'allOpenProjects') === 'allOpenProjects';
11795 exports.default = TypeScriptWorkspaceSymbolProvider;
11800 /***/ (function(module, exports, __webpack_require__) {
11804 /*---------------------------------------------------------------------------------------------
11805 * Copyright (c) Microsoft Corporation. All rights reserved.
11806 * Licensed under the MIT License. See License.txt in the project root for license information.
11807 *--------------------------------------------------------------------------------------------*/
11808 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11809 if (k2 === undefined) k2 = k;
11810 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11811 }) : (function(o, m, k, k2) {
11812 if (k2 === undefined) k2 = k;
11815 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11816 Object.defineProperty(o, "default", { enumerable: true, value: v });
11817 }) : function(o, v) {
11820 var __importStar = (this && this.__importStar) || function (mod) {
11821 if (mod && mod.__esModule) return mod;
11823 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11824 __setModuleDefault(result, mod);
11827 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11828 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11829 return new (P || (P = Promise))(function (resolve, reject) {
11830 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11831 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11832 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11833 step((generator = generator.apply(thisArg, _arguments || [])).next());
11836 Object.defineProperty(exports, "__esModule", { value: true });
11837 const typeConverters = __importStar(__webpack_require__(37));
11838 class SmartSelection {
11839 constructor(client) {
11840 this.client = client;
11842 provideSelectionRanges(document, positions, token) {
11843 return __awaiter(this, void 0, void 0, function* () {
11844 const file = this.client.toPath(document.uri);
11850 locations: positions.map(typeConverters.Position.toLocation)
11852 const response = yield this.client.execute('selectionRange', args, token);
11853 if (response.type !== 'response' || !response.body) {
11856 return response.body.map(SmartSelection.convertSelectionRange);
11859 static convertSelectionRange(selectionRange) {
11861 range: typeConverters.Range.fromTextSpan(selectionRange.textSpan),
11862 parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : undefined,
11866 exports.default = SmartSelection;
11871 /***/ (function(module, exports, __webpack_require__) {
11875 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11876 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11877 return new (P || (P = Promise))(function (resolve, reject) {
11878 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11879 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11880 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11881 step((generator = generator.apply(thisArg, _arguments || [])).next());
11884 Object.defineProperty(exports, "__esModule", { value: true });
11885 const coc_nvim_1 = __webpack_require__(1);
11886 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11887 const modules_1 = __webpack_require__(112);
11888 class InstallModuleCommand {
11890 this.id = InstallModuleCommand.ID;
11892 execute(uri, name) {
11893 return __awaiter(this, void 0, void 0, function* () {
11894 yield modules_1.installModules(uri, [name]);
11898 InstallModuleCommand.ID = '_tsserver.installModule';
11899 class InstallModuleProvider {
11900 constructor(client) {
11901 this.client = client;
11902 coc_nvim_1.commands.register(new InstallModuleCommand(), true);
11904 provideCodeActions(document, _range, context, _token) {
11905 return __awaiter(this, void 0, void 0, function* () {
11906 const uri = coc_nvim_1.Uri.parse(document.uri);
11907 if (uri.scheme != 'file')
11909 let { diagnostics } = context;
11910 let diags = diagnostics.filter(s => s.code == 2307);
11911 let names = diags.map(o => {
11912 let ms = o.message.match(/module\s'(.+)'\./);
11913 return ms ? ms[1] : null;
11915 names = names.filter(s => s != null);
11919 for (let name of names) {
11920 let title = `install ${name}`;
11922 title: `install ${name}`,
11923 command: InstallModuleCommand.ID,
11924 arguments: [document.uri, name]
11926 let codeAction = vscode_languageserver_protocol_1.CodeAction.create(title, command);
11927 actions.push(codeAction);
11933 exports.default = InstallModuleProvider;
11938 /***/ (function(module, exports, __webpack_require__) {
11942 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11943 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11944 return new (P || (P = Promise))(function (resolve, reject) {
11945 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11946 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11947 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11948 step((generator = generator.apply(thisArg, _arguments || [])).next());
11951 var __importDefault = (this && this.__importDefault) || function (mod) {
11952 return (mod && mod.__esModule) ? mod : { "default": mod };
11954 Object.defineProperty(exports, "__esModule", { value: true });
11955 exports.installModules = exports.distinct = exports.moduleExists = exports.runCommand = void 0;
11956 const child_process_1 = __webpack_require__(113);
11957 const path_1 = __importDefault(__webpack_require__(13));
11958 const coc_nvim_1 = __webpack_require__(1);
11959 function runCommand(cmd, cwd, timeout) {
11960 return new Promise((resolve, reject) => {
11963 timer = setTimeout(() => {
11964 reject(new Error(`timeout after ${timeout}s`));
11965 }, timeout * 1000);
11967 child_process_1.exec(cmd, { cwd }, (err, stdout) => {
11969 clearTimeout(timer);
11971 reject(new Error(`exited with ${err.code}`));
11978 exports.runCommand = runCommand;
11979 function getManager() {
11980 return __awaiter(this, void 0, void 0, function* () {
11981 let res = yield coc_nvim_1.workspace.findUp(['yarn.lock', 'package-lock.json']);
11984 return res.endsWith('yarn.lock') ? 'yarn' : 'npm';
11987 function getRoot() {
11988 return __awaiter(this, void 0, void 0, function* () {
11989 let res = yield coc_nvim_1.workspace.findUp(['package.json']);
11992 return path_1.default.dirname(res);
11995 function moduleExists(name) {
11996 return __awaiter(this, void 0, void 0, function* () {
11998 let content = yield runCommand(`npm info ${name} --json`, process.cwd());
12001 let obj = JSON.parse(content);
12002 if (obj.error != null)
12012 exports.moduleExists = moduleExists;
12014 * Removes duplicates from the given array. The optional keyFn allows to specify
12015 * how elements are checked for equalness by returning a unique string for each.
12017 function distinct(array, keyFn) {
12019 return array.filter((element, position) => {
12020 return array.indexOf(element) === position;
12023 const seen = Object.create(null);
12024 return array.filter(elem => {
12025 const key = keyFn(elem);
12033 exports.distinct = distinct;
12034 function installModules(uri, names) {
12035 return __awaiter(this, void 0, void 0, function* () {
12036 names = distinct(names);
12037 let root = yield getRoot();
12039 coc_nvim_1.workspace.showMessage(`package.json not found from cwd: ${coc_nvim_1.workspace.cwd}`, 'error');
12042 let arr = names.concat(names.map(s => `@types/${s}`));
12043 let statusItem = coc_nvim_1.workspace.createStatusBarItem(99, { progress: true });
12044 statusItem.text = `Checking module ${arr.join(' ')}`;
12046 let exists = yield Promise.all(arr.map(name => {
12047 return moduleExists(name).then(exists => {
12048 return exists ? name : null;
12051 let manager = yield getManager();
12052 exists = exists.filter(s => s != null);
12053 if (!exists.length)
12055 let devs = exists.filter(s => s.startsWith('@types'));
12056 let deps = exists.filter(s => devs.indexOf(s) == -1);
12057 statusItem.text = `Installing ${exists.join(' ')}`;
12059 yield Promise.all([deps, devs].map((names, i) => {
12060 let cmd = manager == 'npm' ? `npm i ${names.join(' ')}` : `yarn add ${names.join(' ')} --ignore-scripts --no-default-rc`;
12062 cmd = cmd + ' --dev';
12063 return runCommand(cmd, root);
12067 statusItem.dispose();
12068 coc_nvim_1.workspace.showMessage(`Install error ${e.message}`, 'error');
12071 statusItem.dispose();
12072 coc_nvim_1.workspace.showMessage(`Installed: ${exists.join(' ')}`, 'more');
12075 exports.installModules = installModules;
12080 /***/ (function(module, exports) {
12082 module.exports = require("child_process");
12086 /***/ (function(module, exports, __webpack_require__) {
12090 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12091 if (k2 === undefined) k2 = k;
12092 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
12093 }) : (function(o, m, k, k2) {
12094 if (k2 === undefined) k2 = k;
12097 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
12098 Object.defineProperty(o, "default", { enumerable: true, value: v });
12099 }) : function(o, v) {
12102 var __importStar = (this && this.__importStar) || function (mod) {
12103 if (mod && mod.__esModule) return mod;
12105 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
12106 __setModuleDefault(result, mod);
12109 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
12110 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
12111 return new (P || (P = Promise))(function (resolve, reject) {
12112 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12113 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
12114 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12115 step((generator = generator.apply(thisArg, _arguments || [])).next());
12118 Object.defineProperty(exports, "__esModule", { value: true });
12119 exports.OrganizeImportsCodeActionProvider = exports.OrganizeImportsCommand = void 0;
12120 /*---------------------------------------------------------------------------------------------
12121 * Copyright (c) Microsoft Corporation. All rights reserved.
12122 * Licensed under the MIT License. See License.txt in the project root for license information.
12123 *--------------------------------------------------------------------------------------------*/
12124 const coc_nvim_1 = __webpack_require__(1);
12125 const vscode_languageserver_protocol_1 = __webpack_require__(3);
12126 const languageDescription_1 = __webpack_require__(115);
12127 const languageModeIds_1 = __webpack_require__(116);
12128 const typeconverts = __importStar(__webpack_require__(37));
12129 class OrganizeImportsCommand {
12130 constructor(client) {
12131 this.client = client;
12132 this.id = 'tsserver.organizeImports';
12134 getTextEdits(document) {
12135 return __awaiter(this, void 0, void 0, function* () {
12136 let client = this.client;
12137 let file = client.toPath(document.uri);
12146 const response = yield this.client.interruptGetErr(() => this.client.execute('organizeImports', args, vscode_languageserver_protocol_1.CancellationToken.None));
12147 if (!response || response.type != 'response' || !response.success) {
12150 const edit = typeconverts.WorkspaceEdit.fromFileCodeEdits(client, response.body);
12151 let desc = languageDescription_1.standardLanguageDescriptions.find(o => o.modeIds.indexOf(document.languageId) !== -1);
12157 execute(document) {
12158 return __awaiter(this, void 0, void 0, function* () {
12160 let doc = yield coc_nvim_1.workspace.document;
12161 if (languageModeIds_1.languageIds.indexOf(doc.filetype) == -1)
12163 document = doc.textDocument;
12165 let edit = yield this.getTextEdits(document);
12167 yield coc_nvim_1.workspace.applyEdit(edit);
12172 exports.OrganizeImportsCommand = OrganizeImportsCommand;
12173 class OrganizeImportsCodeActionProvider {
12174 // public static readonly minVersion = API.v280
12175 constructor(client, fileConfigManager) {
12176 this.client = client;
12177 this.fileConfigManager = fileConfigManager;
12179 providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]
12182 provideCodeActions(document, _range, context, _token) {
12183 if (languageModeIds_1.languageIds.indexOf(document.languageId) == -1)
12185 if (!context.only || !context.only.includes(vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports)) {
12188 const action = vscode_languageserver_protocol_1.CodeAction.create('Organize Imports', {
12190 command: 'tsserver.organizeImports',
12191 arguments: [document]
12192 }, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports);
12196 exports.OrganizeImportsCodeActionProvider = OrganizeImportsCodeActionProvider;
12201 /***/ (function(module, exports, __webpack_require__) {
12205 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12206 if (k2 === undefined) k2 = k;
12207 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
12208 }) : (function(o, m, k, k2) {
12209 if (k2 === undefined) k2 = k;
12212 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
12213 Object.defineProperty(o, "default", { enumerable: true, value: v });
12214 }) : function(o, v) {
12217 var __importStar = (this && this.__importStar) || function (mod) {
12218 if (mod && mod.__esModule) return mod;
12220 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
12221 __setModuleDefault(result, mod);
12224 Object.defineProperty(exports, "__esModule", { value: true });
12225 exports.standardLanguageDescriptions = void 0;
12226 /*---------------------------------------------------------------------------------------------
12227 * Copyright (c) Microsoft Corporation. All rights reserved.
12228 * Licensed under the MIT License. See License.txt in the project root for license information.
12229 *--------------------------------------------------------------------------------------------*/
12230 const languageModeIds = __importStar(__webpack_require__(116));
12231 exports.standardLanguageDescriptions = [
12234 diagnosticSource: 'ts',
12235 diagnosticOwner: 'typescript',
12236 modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact,
12237 languageModeIds.typescripttsx, languageModeIds.typescriptjsx],
12238 diagnosticLanguage: 1 /* TypeScript */,
12239 configFile: 'tsconfig.json'
12243 diagnosticSource: 'ts',
12244 diagnosticOwner: 'typescript',
12245 modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact],
12246 diagnosticLanguage: 0 /* JavaScript */,
12247 configFile: 'jsconfig.json'
12254 /***/ (function(module, exports, __webpack_require__) {
12258 /*---------------------------------------------------------------------------------------------
12259 * Copyright (c) Microsoft Corporation. All rights reserved.
12260 * Licensed under the MIT License. See License.txt in the project root for license information.
12261 *--------------------------------------------------------------------------------------------*/
12262 Object.defineProperty(exports, "__esModule", { value: true });
12263 exports.languageIds = exports.jsxTags = exports.javascriptjsx = exports.javascriptreact = exports.javascript = exports.typescriptjsx = exports.typescripttsx = exports.typescriptreact = exports.typescript = void 0;
12264 exports.typescript = 'typescript';
12265 exports.typescriptreact = 'typescriptreact';
12266 exports.typescripttsx = 'typescript.tsx';
12267 exports.typescriptjsx = 'typescript.jsx';
12268 exports.javascript = 'javascript';
12269 exports.javascriptreact = 'javascriptreact';
12270 exports.javascriptjsx = 'javascript.jsx';
12271 exports.jsxTags = 'jsx-tags';
12272 exports.languageIds = [exports.typescript, exports.typescriptreact, exports.javascript, exports.javascriptreact, exports.javascriptjsx, exports.typescripttsx, exports.jsxTags];
12277 /***/ (function(module, exports, __webpack_require__) {
12281 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
12282 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
12283 return new (P || (P = Promise))(function (resolve, reject) {
12284 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12285 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
12286 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12287 step((generator = generator.apply(thisArg, _arguments || [])).next());
12290 var __importDefault = (this && this.__importDefault) || function (mod) {
12291 return (mod && mod.__esModule) ? mod : { "default": mod };
12293 Object.defineProperty(exports, "__esModule", { value: true });
12294 const fs_1 = __importDefault(__webpack_require__(118));
12295 const os_1 = __importDefault(__webpack_require__(14));
12296 const path_1 = __importDefault(__webpack_require__(13));
12297 const vscode_languageserver_protocol_1 = __webpack_require__(3);
12298 const which_1 = __importDefault(__webpack_require__(119));
12299 const coc_nvim_1 = __webpack_require__(1);
12300 const fileConfigurationManager_1 = __importDefault(__webpack_require__(93));
12301 const typescriptService_1 = __webpack_require__(123);
12302 const api_1 = __importDefault(__webpack_require__(40));
12303 const configuration_1 = __webpack_require__(124);
12304 const logger_1 = __importDefault(__webpack_require__(125));
12305 const process_1 = __webpack_require__(127);
12306 const tracer_1 = __importDefault(__webpack_require__(128));
12307 const tsconfig_1 = __webpack_require__(129);
12308 const versionProvider_1 = __webpack_require__(130);
12309 const versionStatus_1 = __importDefault(__webpack_require__(131));
12310 const wireProtocol_1 = __webpack_require__(132);
12311 const callbackMap_1 = __webpack_require__(133);
12312 const requestQueue_1 = __webpack_require__(134);
12313 const bufferSyncSupport_1 = __importDefault(__webpack_require__(135));
12314 const diagnostics_1 = __webpack_require__(137);
12315 class ForkedTsServerProcess {
12316 constructor(childProcess) {
12317 this.childProcess = childProcess;
12320 this.childProcess.on('error', cb);
12323 this.childProcess.on('exit', cb);
12325 write(serverRequest) {
12326 this.childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
12328 createReader(callback, onError) {
12329 // tslint:disable-next-line:no-unused-expression
12330 new wireProtocol_1.Reader(this.childProcess.stdout, callback, onError);
12333 this.childProcess.kill();
12336 class TypeScriptServiceClient {
12337 constructor(pluginManager) {
12338 this.pluginManager = pluginManager;
12339 this.state = coc_nvim_1.ServiceStat.Initial;
12340 this.logger = new logger_1.default();
12341 this.tsServerLogFile = null;
12342 this.cancellationPipeName = null;
12343 this._callbacks = new callbackMap_1.CallbackMap();
12344 this._requestQueue = new requestQueue_1.RequestQueue();
12345 this._pendingResponses = new Set();
12346 this._onTsServerStarted = new vscode_languageserver_protocol_1.Emitter();
12347 this._onProjectLanguageServiceStateChanged = new vscode_languageserver_protocol_1.Emitter();
12348 this._onDidBeginInstallTypings = new vscode_languageserver_protocol_1.Emitter();
12349 this._onDidEndInstallTypings = new vscode_languageserver_protocol_1.Emitter();
12350 this._onTypesInstallerInitializationFailed = new vscode_languageserver_protocol_1.Emitter();
12351 this.disposables = [];
12352 this.isRestarting = false;
12353 this._onDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
12354 this._onConfigDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
12355 this._onResendModelsRequested = new vscode_languageserver_protocol_1.Emitter();
12356 this.pathSeparator = path_1.default.sep;
12357 this.lastStart = Date.now();
12358 this.servicePromise = null;
12359 this.lastError = null;
12360 this.numberRestarts = 0;
12361 this.fileConfigurationManager = new fileConfigurationManager_1.default(this);
12362 this._configuration = configuration_1.TypeScriptServiceConfiguration.loadFromWorkspace();
12363 this.versionProvider = new versionProvider_1.TypeScriptVersionProvider(this._configuration);
12364 this._apiVersion = api_1.default.defaultVersion;
12365 this.tracer = new tracer_1.default(this.logger);
12366 this.versionStatus = new versionStatus_1.default(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript());
12367 pluginManager.onDidUpdateConfig(update => {
12368 this.configurePlugin(update.pluginId, update.config);
12369 }, null, this.disposables);
12370 pluginManager.onDidChangePlugins(() => {
12371 this.restartTsServer();
12372 }, null, this.disposables);
12373 this.bufferSyncSupport = new bufferSyncSupport_1.default(this);
12374 this.onTsServerStarted(() => {
12375 this.bufferSyncSupport.listen();
12377 this.diagnosticsManager = new diagnostics_1.DiagnosticsManager();
12378 this.bufferSyncSupport.onDelete(resource => {
12379 this.diagnosticsManager.delete(resource);
12380 }, null, this.disposables);
12382 get onDiagnosticsReceived() {
12383 return this._onDiagnosticsReceived.event;
12385 get onConfigDiagnosticsReceived() {
12386 return this._onConfigDiagnosticsReceived.event;
12388 get onResendModelsRequested() {
12389 return this._onResendModelsRequested.event;
12391 get configuration() {
12392 return this._configuration;
12395 if (this.servicePromise) {
12396 this.servicePromise
12397 .then(childProcess => {
12398 childProcess.kill();
12400 .then(undefined, () => void 0);
12402 this.bufferSyncSupport.dispose();
12403 coc_nvim_1.disposeAll(this.disposables);
12404 this.logger.dispose();
12405 this._onTsServerStarted.dispose();
12406 this._onResendModelsRequested.dispose();
12407 this.versionStatus.dispose();
12409 info(message, data) {
12410 this.logger.info(message, data);
12412 error(message, data) {
12413 this.logger.error(message, data);
12415 restartTsServer() {
12416 const start = () => {
12417 this.servicePromise = this.startService(true);
12418 return this.servicePromise;
12420 if (this.servicePromise) {
12421 return Promise.resolve(this.servicePromise.then(childProcess => {
12422 this.state = coc_nvim_1.ServiceStat.Stopping;
12423 this.info('Killing TS Server');
12424 this.isRestarting = true;
12425 childProcess.kill();
12426 this.servicePromise = null;
12430 return Promise.resolve(start());
12434 if (!this.servicePromise)
12436 return new Promise((resolve, reject) => {
12437 this.servicePromise.then(childProcess => {
12438 if (this.state == coc_nvim_1.ServiceStat.Running) {
12439 this.info('Killing TS Server');
12440 childProcess.onExit(() => {
12443 childProcess.kill();
12444 this.servicePromise = null;
12452 get onTsServerStarted() {
12453 return this._onTsServerStarted.event;
12455 get onProjectLanguageServiceStateChanged() {
12456 return this._onProjectLanguageServiceStateChanged.event;
12458 get onDidBeginInstallTypings() {
12459 return this._onDidBeginInstallTypings.event;
12461 get onDidEndInstallTypings() {
12462 return this._onDidEndInstallTypings.event;
12464 get onTypesInstallerInitializationFailed() {
12465 return this._onTypesInstallerInitializationFailed.event;
12468 return this._apiVersion;
12471 return this._tscPath;
12474 if (this.servicePromise) {
12475 return this.servicePromise;
12477 if (this.lastError) {
12478 return Promise.reject(this.lastError);
12480 return this.startService().then(() => {
12481 if (this.servicePromise) {
12482 return this.servicePromise;
12486 ensureServiceStarted() {
12487 if (!this.servicePromise) {
12488 this.startService().catch(err => {
12489 coc_nvim_1.workspace.showMessage(`TSServer start failed: ${err.message}`, 'error');
12490 this.error(`Service start failed: ${err.stack}`);
12494 startService(resendModels = false) {
12495 return __awaiter(this, void 0, void 0, function* () {
12496 const { ignoreLocalTsserver } = this.configuration;
12497 let currentVersion;
12498 if (!ignoreLocalTsserver)
12499 currentVersion = this.versionProvider.getLocalVersion();
12500 if (!currentVersion || !fs_1.default.existsSync(currentVersion.tsServerPath)) {
12501 currentVersion = this.versionProvider.getDefaultVersion();
12503 if (!currentVersion || !currentVersion.isValid) {
12504 if (this.configuration.globalTsdk) {
12505 coc_nvim_1.workspace.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, 'error');
12508 coc_nvim_1.workspace.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, 'error');
12512 this._apiVersion = currentVersion.version;
12513 this._tscPath = currentVersion.tscPath;
12514 this.versionStatus.onDidChangeTypeScriptVersion(currentVersion);
12515 this.lastError = null;
12516 const tsServerForkArgs = yield this.getTsServerArgs();
12517 const debugPort = this._configuration.debugPort;
12518 const maxTsServerMemory = this._configuration.maxTsServerMemory;
12521 ...(debugPort ? [`--inspect=${debugPort}`] : []),
12522 ...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []),
12524 cwd: coc_nvim_1.workspace.root
12526 this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels);
12527 return this.servicePromise;
12530 startProcess(currentVersion, args, options, resendModels) {
12531 this.state = coc_nvim_1.ServiceStat.Starting;
12532 return new Promise((resolve, reject) => {
12534 process_1.fork(currentVersion.tsServerPath, args, options, this.logger, (err, childProcess) => {
12535 if (err || !childProcess) {
12536 this.state = coc_nvim_1.ServiceStat.StartFailed;
12537 this.lastError = err;
12538 this.error('Starting TSServer failed with error.', err.stack);
12541 this.state = coc_nvim_1.ServiceStat.Running;
12542 this.info('Started TSServer', JSON.stringify(currentVersion, null, 2));
12543 const handle = new ForkedTsServerProcess(childProcess);
12544 this.lastStart = Date.now();
12545 handle.onError((err) => {
12546 this.lastError = err;
12547 this.error('TSServer errored with error.', err);
12548 this.error(`TSServer log file: ${this.tsServerLogFile || ''}`);
12549 coc_nvim_1.workspace.showMessage(`TSServer errored with error. ${err.message}`, 'error');
12550 this.serviceExited(false);
12552 handle.onExit((code) => {
12553 if (code == null) {
12554 this.info('TSServer normal exit');
12557 this.error(`TSServer exited with code: ${code}`);
12559 this.info(`TSServer log file: ${this.tsServerLogFile || ''}`);
12560 this.serviceExited(!this.isRestarting);
12561 this.isRestarting = false;
12563 handle.createReader(msg => {
12564 this.dispatchMessage(msg);
12566 this.error('ReaderError', error);
12569 this.serviceStarted(resendModels);
12570 this._onTsServerStarted.fire(currentVersion.version);
12578 openTsServerLogFile() {
12579 return __awaiter(this, void 0, void 0, function* () {
12580 const isRoot = process.getuid && process.getuid() == 0;
12581 let echoErr = (msg) => {
12582 coc_nvim_1.workspace.showMessage(msg, 'error');
12585 echoErr('Log disabled for root user.');
12588 if (!this.apiVersion.gte(api_1.default.v222)) {
12589 echoErr('TS Server logging requires TS 2.2.2+');
12592 if (this._configuration.tsServerLogLevel === configuration_1.TsServerLogLevel.Off) {
12593 echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`);
12596 if (!this.tsServerLogFile) {
12597 echoErr('TS Server has not started logging.');
12601 yield coc_nvim_1.workspace.nvim.command(`edit ${this.tsServerLogFile}`);
12605 echoErr('Could not open TS Server log file');
12610 serviceStarted(resendModels) {
12611 const watchOptions = this.apiVersion.gte(api_1.default.v380)
12612 ? this.configuration.watchOptions
12614 const configureOptions = {
12615 hostInfo: 'coc-nvim',
12617 providePrefixAndSuffixTextForRename: true,
12618 allowRenameOfImportPath: true,
12622 this.executeWithoutWaitingForResponse('configure', configureOptions); // tslint:disable-line
12623 this.setCompilerOptionsForInferredProjects(this._configuration);
12624 if (resendModels) {
12625 this._onResendModelsRequested.fire(void 0);
12626 this.diagnosticsManager.reInitialize();
12627 this.bufferSyncSupport.reinitialize();
12629 // Reconfigure any plugins
12630 for (const [config, pluginName] of this.pluginManager.configurations()) {
12631 this.configurePlugin(config, pluginName);
12634 setCompilerOptionsForInferredProjects(configuration) {
12635 if (!this.apiVersion.gte(api_1.default.v206))
12638 options: this.getCompilerOptionsForInferredProjects(configuration)
12640 this.executeWithoutWaitingForResponse('compilerOptionsForInferredProjects', args); // tslint:disable-line
12642 getCompilerOptionsForInferredProjects(configuration) {
12643 return Object.assign(Object.assign({}, tsconfig_1.inferredProjectConfig(configuration)), { allowJs: true, allowSyntheticDefaultImports: true, allowNonTsExtensions: true });
12645 serviceExited(restart) {
12646 this.state = coc_nvim_1.ServiceStat.Stopped;
12647 this.servicePromise = null;
12648 this.tsServerLogFile = null;
12649 this._callbacks.destroy('Service died.');
12650 this._callbacks = new callbackMap_1.CallbackMap();
12651 this._requestQueue = new requestQueue_1.RequestQueue();
12652 this._pendingResponses = new Set();
12654 const diff = Date.now() - this.lastStart;
12655 this.numberRestarts++;
12656 let startService = true;
12657 if (this.numberRestarts > 5) {
12658 this.numberRestarts = 0;
12659 if (diff < 10 * 1000 /* 10 seconds */) {
12660 this.lastStart = Date.now();
12661 startService = false;
12662 coc_nvim_1.workspace.showMessage('The TypeScript language service died 5 times right after it got started.', 'error'); // tslint:disable-line
12664 else if (diff < 60 * 1000 /* 1 Minutes */) {
12665 this.lastStart = Date.now();
12666 coc_nvim_1.workspace.showMessage('The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.', 'error'); // tslint:disable-line
12669 if (startService) {
12670 this.startService(true); // tslint:disable-line
12675 return this.normalizePath(coc_nvim_1.Uri.parse(uri));
12677 toResource(filepath) {
12678 if (this._apiVersion.gte(api_1.default.v213)) {
12679 if (filepath.startsWith('untitled:')) {
12680 let resource = coc_nvim_1.Uri.parse(filepath);
12681 if (this.inMemoryResourcePrefix) {
12682 const dirName = path_1.default.dirname(resource.path);
12683 const fileName = path_1.default.basename(resource.path);
12684 if (fileName.startsWith(this.inMemoryResourcePrefix)) {
12685 resource = resource.with({ path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) });
12688 return resource.toString();
12691 return coc_nvim_1.Uri.file(filepath).toString();
12693 normalizePath(resource) {
12694 if (this._apiVersion.gte(api_1.default.v213)) {
12695 if (resource.scheme == 'untitled') {
12696 const dirName = path_1.default.dirname(resource.path);
12697 const fileName = this.inMemoryResourcePrefix + path_1.default.basename(resource.path);
12699 .with({ path: path_1.default.posix.join(dirName, fileName) })
12703 const result = resource.fsPath;
12706 // Both \ and / must be escaped in regular expressions
12707 return result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/');
12709 get inMemoryResourcePrefix() {
12710 return this._apiVersion.gte(api_1.default.v270) ? '^' : '';
12713 if (this._apiVersion.gte(api_1.default.v213)) {
12714 if (filepath.startsWith('untitled:')) {
12715 let resource = coc_nvim_1.Uri.parse(filepath);
12716 if (this.inMemoryResourcePrefix) {
12717 const dirName = path_1.default.dirname(resource.path);
12718 const fileName = path_1.default.basename(resource.path);
12719 if (fileName.startsWith(this.inMemoryResourcePrefix)) {
12720 resource = resource.with({
12721 path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length))
12728 return coc_nvim_1.Uri.file(filepath);
12730 execute(command, args, token, lowPriority) {
12731 return this.executeImpl(command, args, {
12734 expectsResult: true,
12738 executeAsync(command, args, token) {
12739 return this.executeImpl(command, args, {
12742 expectsResult: true
12745 executeWithoutWaitingForResponse(command, args) {
12746 this.executeImpl(command, args, {
12749 expectsResult: false
12752 executeImpl(command, args, executeInfo) {
12753 if (this.servicePromise == null) {
12754 return Promise.resolve(undefined);
12756 this.bufferSyncSupport.beforeCommand(command);
12757 const request = this._requestQueue.createRequest(command, args);
12758 const requestInfo = {
12760 expectsResponse: executeInfo.expectsResult,
12761 isAsync: executeInfo.isAsync,
12762 queueingType: getQueueingType(command, executeInfo.lowPriority)
12765 if (executeInfo.expectsResult) {
12766 result = new Promise((resolve, reject) => {
12767 this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync);
12768 if (executeInfo.token) {
12769 executeInfo.token.onCancellationRequested(() => {
12770 this.tryCancelRequest(request.seq, command);
12773 }).catch((err) => {
12777 this._requestQueue.enqueue(requestInfo);
12778 this.sendNextRequests();
12781 sendNextRequests() {
12782 while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
12783 const item = this._requestQueue.dequeue();
12785 this.sendRequest(item);
12789 sendRequest(requestItem) {
12790 const serverRequest = requestItem.request;
12791 this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
12792 if (requestItem.expectsResponse && !requestItem.isAsync) {
12793 this._pendingResponses.add(requestItem.request.seq);
12795 this.service().then(childProcess => {
12797 childProcess.write(serverRequest);
12800 const callback = this.fetchCallback(serverRequest.seq);
12802 callback.onError(err);
12807 tryCancelRequest(seq, command) {
12809 if (this._requestQueue.tryDeletePendingRequest(seq)) {
12810 this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
12813 if (this.cancellationPipeName) {
12814 this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
12816 fs_1.default.writeFileSync(this.cancellationPipeName + seq, '');
12823 this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
12827 const callback = this.fetchCallback(seq);
12829 callback.onSuccess(new typescriptService_1.ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`));
12833 fetchCallback(seq) {
12834 const callback = this._callbacks.fetch(seq);
12838 this._pendingResponses.delete(seq);
12841 dispatchMessage(message) {
12843 switch (message.type) {
12845 this.dispatchResponse(message);
12848 const event = message;
12849 if (event.event === 'requestCompleted') {
12850 const seq = event.body.request_seq;
12851 const p = this._callbacks.fetch(seq);
12853 this.tracer.traceRequestCompleted('requestCompleted', seq, p.startTime);
12854 p.onSuccess(undefined);
12858 this.tracer.traceEvent(event);
12859 this.dispatchEvent(event);
12863 throw new Error(`Unknown message type ${message.type} received`);
12867 this.sendNextRequests();
12870 dispatchResponse(response) {
12871 const callback = this.fetchCallback(response.request_seq);
12875 this.tracer.traceResponse(response, callback.startTime);
12876 if (response.success) {
12877 callback.onSuccess(response);
12879 else if (response.message === 'No content available.') {
12880 // Special case where response itself is successful but there is not any data to return.
12881 callback.onSuccess(typescriptService_1.ServerResponse.NoContent);
12884 callback.onError(new Error(response.message));
12887 dispatchEvent(event) {
12888 switch (event.event) {
12890 case 'semanticDiag':
12891 case 'suggestionDiag':
12892 const diagnosticEvent = event;
12893 if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) {
12894 this._onDiagnosticsReceived.fire({
12895 kind: getDiagnosticsKind(event),
12896 resource: this.asUrl(diagnosticEvent.body.file),
12897 diagnostics: diagnosticEvent.body.diagnostics
12901 case 'configFileDiag':
12902 this._onConfigDiagnosticsReceived.fire(event);
12904 case 'projectLanguageServiceState':
12906 this._onProjectLanguageServiceStateChanged.fire(event.body);
12909 case 'beginInstallTypes':
12911 this._onDidBeginInstallTypings.fire(event.body);
12914 case 'endInstallTypes':
12916 this._onDidEndInstallTypings.fire(event.body);
12919 case 'projectsUpdatedInBackground':
12920 const body = event.body;
12921 const resources = body.openFiles.map(coc_nvim_1.Uri.file);
12922 this.bufferSyncSupport.getErr(resources);
12924 case 'typesInstallerInitializationFailed':
12926 this._onTypesInstallerInitializationFailed.fire(event.body);
12929 case 'projectLoadingStart':
12930 this.versionStatus.loading = true;
12932 case 'projectLoadingFinish':
12933 this.versionStatus.loading = false;
12937 getTsServerArgs() {
12938 return __awaiter(this, void 0, void 0, function* () {
12940 args.push('--allowLocalPluginLoads');
12941 if (this.apiVersion.gte(api_1.default.v250)) {
12942 args.push('--useInferredProjectPerProjectRoot');
12945 args.push('--useSingleInferredProject');
12947 if (this.apiVersion.gte(api_1.default.v206) && this._configuration.disableAutomaticTypeAcquisition) {
12948 args.push('--disableAutomaticTypingAcquisition');
12950 if (this.apiVersion.gte(api_1.default.v222)) {
12951 this.cancellationPipeName = process_1.getTempFile(`tscancellation-${process_1.makeRandomHexString(20)}`);
12952 args.push('--cancellationPipeName', this.cancellationPipeName + '*');
12954 if (this.apiVersion.gte(api_1.default.v222)) {
12955 const isRoot = process.getuid && process.getuid() == 0;
12956 if (this._configuration.tsServerLogLevel !== configuration_1.TsServerLogLevel.Off && !isRoot) {
12957 const logDir = process_1.getTempDirectory();
12959 this.tsServerLogFile = path_1.default.join(logDir, `tsserver.log`);
12960 this.info('TSServer log file :', this.tsServerLogFile);
12963 this.tsServerLogFile = null;
12964 this.error('Could not create TSServer log directory');
12966 if (this.tsServerLogFile) {
12967 args.push('--logVerbosity', configuration_1.TsServerLogLevel.toString(this._configuration.tsServerLogLevel));
12968 args.push('--logFile', this.tsServerLogFile);
12972 if (this.apiVersion.gte(api_1.default.v230)) {
12973 const pluginNames = this.pluginManager.plugins.map(x => x.name);
12974 const pluginRoot = this._configuration.tsServerPluginRoot;
12975 const pluginPaths = pluginRoot ? [pluginRoot] : [];
12976 if (pluginNames.length) {
12977 args.push('--globalPlugins', pluginNames.join(','));
12978 for (const plugin of this.pluginManager.plugins) {
12979 pluginPaths.push(plugin.path);
12982 if (pluginPaths.length) {
12983 args.push('--pluginProbeLocations', pluginPaths.join(','));
12986 if (this._configuration.typingsCacheLocation) {
12987 args.push('--globalTypingsCacheLocation', `"${this._configuration.typingsCacheLocation}"`);
12989 if (this.apiVersion.gte(api_1.default.v234)) {
12990 if (this._configuration.npmLocation) {
12991 args.push('--npmLocation', `"${this._configuration.npmLocation}"`);
12995 args.push('--npmLocation', `"${which_1.default.sync('npm')}"`);
12997 catch (e) { } // tslint:disable-line
13000 if (this.apiVersion.gte(api_1.default.v291)) {
13001 args.push('--noGetErrOnBackgroundUpdate');
13003 if (this.apiVersion.gte(api_1.default.v345)) {
13004 args.push('--validateDefaultNpmLocation');
13009 getProjectRootPath(uri) {
13010 let root = coc_nvim_1.workspace.cwd;
13011 let u = coc_nvim_1.Uri.parse(uri);
13012 if (u.scheme == 'file') {
13013 let folder = coc_nvim_1.workspace.getWorkspaceFolder(uri);
13015 root = coc_nvim_1.Uri.parse(folder.uri).fsPath;
13018 let filepath = coc_nvim_1.Uri.parse(uri).fsPath;
13019 if (!filepath.startsWith(root)) {
13020 root = path_1.default.dirname(filepath);
13024 if (root == os_1.default.homedir())
13028 configurePlugin(pluginName, configuration) {
13029 if (this.apiVersion.gte(api_1.default.v314)) {
13030 if (!this.servicePromise)
13032 this.servicePromise.then(() => {
13033 // tslint:disable-next-line: no-floating-promises
13034 this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration });
13038 interruptGetErr(f) {
13039 return this.bufferSyncSupport.interuptGetErr(f);
13042 exports.default = TypeScriptServiceClient;
13043 function getDiagnosticsKind(event) {
13044 switch (event.event) {
13046 return diagnostics_1.DiagnosticKind.Syntax;
13047 case 'semanticDiag':
13048 return diagnostics_1.DiagnosticKind.Semantic;
13049 case 'suggestionDiag':
13050 return diagnostics_1.DiagnosticKind.Suggestion;
13052 throw new Error('Unknown dignostics kind');
13054 const fenceCommands = new Set(['change', 'close', 'open']);
13055 function getQueueingType(command, lowPriority) {
13056 if (fenceCommands.has(command)) {
13057 return requestQueue_1.RequestQueueingType.Fence;
13059 return lowPriority ? requestQueue_1.RequestQueueingType.LowPriority : requestQueue_1.RequestQueueingType.Normal;
13065 /***/ (function(module, exports) {
13067 module.exports = require("fs");
13071 /***/ (function(module, exports, __webpack_require__) {
13073 const isWindows = process.platform === 'win32' ||
13074 process.env.OSTYPE === 'cygwin' ||
13075 process.env.OSTYPE === 'msys'
13077 const path = __webpack_require__(13)
13078 const COLON = isWindows ? ';' : ':'
13079 const isexe = __webpack_require__(120)
13081 const getNotFoundError = (cmd) =>
13082 Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })
13084 const getPathInfo = (cmd, opt) => {
13085 const colon = opt.colon || COLON
13087 // If it has a slash, then we don't bother searching the pathenv.
13088 // just check the file itself, and that's it.
13089 const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
13092 // windows always checks the cwd first
13093 ...(isWindows ? [process.cwd()] : []),
13094 ...(opt.path || process.env.PATH ||
13095 /* istanbul ignore next: very unusual */ '').split(colon),
13098 const pathExtExe = isWindows
13099 ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
13101 const pathExt = isWindows ? pathExtExe.split(colon) : ['']
13104 if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
13105 pathExt.unshift('')
13115 const which = (cmd, opt, cb) => {
13116 if (typeof opt === 'function') {
13123 const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
13126 const step = i => new Promise((resolve, reject) => {
13127 if (i === pathEnv.length)
13128 return opt.all && found.length ? resolve(found)
13129 : reject(getNotFoundError(cmd))
13131 const ppRaw = pathEnv[i]
13132 const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
13134 const pCmd = path.join(pathPart, cmd)
13135 const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
13138 resolve(subStep(p, i, 0))
13141 const subStep = (p, i, ii) => new Promise((resolve, reject) => {
13142 if (ii === pathExt.length)
13143 return resolve(step(i + 1))
13144 const ext = pathExt[ii]
13145 isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
13148 found.push(p + ext)
13150 return resolve(p + ext)
13152 return resolve(subStep(p, i, ii + 1))
13156 return cb ? step(0).then(res => cb(null, res), cb) : step(0)
13159 const whichSync = (cmd, opt) => {
13162 const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
13165 for (let i = 0; i < pathEnv.length; i ++) {
13166 const ppRaw = pathEnv[i]
13167 const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
13169 const pCmd = path.join(pathPart, cmd)
13170 const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
13173 for (let j = 0; j < pathExt.length; j ++) {
13174 const cur = p + pathExt[j]
13176 const is = isexe.sync(cur, { pathExt: pathExtExe })
13187 if (opt.all && found.length)
13193 throw getNotFoundError(cmd)
13196 module.exports = which
13197 which.sync = whichSync
13202 /***/ (function(module, exports, __webpack_require__) {
13204 var fs = __webpack_require__(118)
13206 if (process.platform === 'win32' || global.TESTING_WINDOWS) {
13207 core = __webpack_require__(121)
13209 core = __webpack_require__(122)
13212 module.exports = isexe
13215 function isexe (path, options, cb) {
13216 if (typeof options === 'function') {
13222 if (typeof Promise !== 'function') {
13223 throw new TypeError('callback not provided')
13226 return new Promise(function (resolve, reject) {
13227 isexe(path, options || {}, function (er, is) {
13237 core(path, options || {}, function (er, is) {
13238 // ignore EACCES because that just means we aren't allowed to run it
13240 if (er.code === 'EACCES' || options && options.ignoreErrors) {
13249 function sync (path, options) {
13250 // my kingdom for a filtered catch
13252 return core.sync(path, options || {})
13254 if (options && options.ignoreErrors || er.code === 'EACCES') {
13265 /***/ (function(module, exports, __webpack_require__) {
13267 module.exports = isexe
13270 var fs = __webpack_require__(118)
13272 function checkPathExt (path, options) {
13273 var pathext = options.pathExt !== undefined ?
13274 options.pathExt : process.env.PATHEXT
13280 pathext = pathext.split(';')
13281 if (pathext.indexOf('') !== -1) {
13284 for (var i = 0; i < pathext.length; i++) {
13285 var p = pathext[i].toLowerCase()
13286 if (p && path.substr(-p.length).toLowerCase() === p) {
13293 function checkStat (stat, path, options) {
13294 if (!stat.isSymbolicLink() && !stat.isFile()) {
13297 return checkPathExt(path, options)
13300 function isexe (path, options, cb) {
13301 fs.stat(path, function (er, stat) {
13302 cb(er, er ? false : checkStat(stat, path, options))
13306 function sync (path, options) {
13307 return checkStat(fs.statSync(path), path, options)
13313 /***/ (function(module, exports, __webpack_require__) {
13315 module.exports = isexe
13318 var fs = __webpack_require__(118)
13320 function isexe (path, options, cb) {
13321 fs.stat(path, function (er, stat) {
13322 cb(er, er ? false : checkStat(stat, options))
13326 function sync (path, options) {
13327 return checkStat(fs.statSync(path), options)
13330 function checkStat (stat, options) {
13331 return stat.isFile() && checkMode(stat, options)
13334 function checkMode (stat, options) {
13335 var mod = stat.mode
13339 var myUid = options.uid !== undefined ?
13340 options.uid : process.getuid && process.getuid()
13341 var myGid = options.gid !== undefined ?
13342 options.gid : process.getgid && process.getgid()
13344 var u = parseInt('100', 8)
13345 var g = parseInt('010', 8)
13346 var o = parseInt('001', 8)
13349 var ret = (mod & o) ||
13350 (mod & g) && gid === myGid ||
13351 (mod & u) && uid === myUid ||
13352 (mod & ug) && myUid === 0
13360 /***/ (function(module, exports, __webpack_require__) {
13364 Object.defineProperty(exports, "__esModule", { value: true });
13365 exports.ServerResponse = void 0;
13366 var ServerResponse;
13367 (function (ServerResponse) {
13369 constructor(reason) {
13370 this.reason = reason;
13371 this.type = 'cancelled';
13374 ServerResponse.Cancelled = Cancelled;
13375 // tslint:disable-next-line: new-parens
13376 ServerResponse.NoContent = new class {
13378 this.type = 'noContent';
13381 })(ServerResponse = exports.ServerResponse || (exports.ServerResponse = {}));
13386 /***/ (function(module, exports, __webpack_require__) {
13390 var __importDefault = (this && this.__importDefault) || function (mod) {
13391 return (mod && mod.__esModule) ? mod : { "default": mod };
13393 Object.defineProperty(exports, "__esModule", { value: true });
13394 exports.TypeScriptServiceConfiguration = exports.TsServerLogLevel = void 0;
13395 const coc_nvim_1 = __webpack_require__(1);
13396 const which_1 = __importDefault(__webpack_require__(119));
13397 var TsServerLogLevel;
13398 (function (TsServerLogLevel) {
13399 TsServerLogLevel[TsServerLogLevel["Off"] = 0] = "Off";
13400 TsServerLogLevel[TsServerLogLevel["Normal"] = 1] = "Normal";
13401 TsServerLogLevel[TsServerLogLevel["Terse"] = 2] = "Terse";
13402 TsServerLogLevel[TsServerLogLevel["Verbose"] = 3] = "Verbose";
13403 })(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
13404 (function (TsServerLogLevel) {
13405 function fromString(value) {
13406 switch (value && value.toLowerCase()) {
13408 return TsServerLogLevel.Normal;
13410 return TsServerLogLevel.Terse;
13412 return TsServerLogLevel.Verbose;
13415 return TsServerLogLevel.Off;
13418 TsServerLogLevel.fromString = fromString;
13419 function toString(value) {
13421 case TsServerLogLevel.Normal:
13423 case TsServerLogLevel.Terse:
13425 case TsServerLogLevel.Verbose:
13427 case TsServerLogLevel.Off:
13432 TsServerLogLevel.toString = toString;
13433 })(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
13434 class TypeScriptServiceConfiguration {
13436 this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
13437 coc_nvim_1.workspace.onDidChangeConfiguration(() => {
13438 this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
13442 return this._configuration.get('locale', null);
13445 return this._configuration.get('tsdk', null);
13447 get ignoreLocalTsserver() {
13448 return this._configuration.get('ignoreLocalTsserver', false);
13450 get tsServerLogLevel() {
13451 return TsServerLogLevel.fromString(this._configuration.get('log', null));
13453 // public readonly watchOptions: protocol.WatchOptions | undefined;
13454 get watchOptions() {
13455 return this._configuration.get('watchOptions');
13457 get typingsCacheLocation() {
13458 return this._configuration.get('typingsCacheLocation', '');
13460 get tsServerPluginRoot() {
13461 return this._configuration.get('tsServerPluginRoot', null);
13464 return this._configuration.get('implicitProjectConfig.checkJs', false);
13466 get experimentalDecorators() {
13467 return this._configuration.get('implicitProjectConfig.experimentalDecorators', false);
13469 get disableAutomaticTypeAcquisition() {
13470 return this._configuration.get('disableAutomaticTypeAcquisition', false);
13472 get formatOnType() {
13473 return this._configuration.get('formatOnType', false);
13475 get maxTsServerMemory() {
13476 return this._configuration.get('maxTsServerMemory', 0);
13479 return this._configuration.get('debugPort', parseInt(process.env['TSS_DEBUG'], 10));
13481 get npmLocation() {
13482 let path = this._configuration.get('npm', '');
13486 path = which_1.default.sync('npm');
13493 static loadFromWorkspace() {
13494 return new TypeScriptServiceConfiguration();
13497 exports.TypeScriptServiceConfiguration = TypeScriptServiceConfiguration;
13502 /***/ (function(module, exports, __webpack_require__) {
13506 /*---------------------------------------------------------------------------------------------
13507 * Copyright (c) Microsoft Corporation. All rights reserved.
13508 * Licensed under the MIT License. See License.txt in the project root for license information.
13509 *--------------------------------------------------------------------------------------------*/
13510 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13511 if (k2 === undefined) k2 = k;
13512 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
13513 }) : (function(o, m, k, k2) {
13514 if (k2 === undefined) k2 = k;
13517 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
13518 Object.defineProperty(o, "default", { enumerable: true, value: v });
13519 }) : function(o, v) {
13522 var __importStar = (this && this.__importStar) || function (mod) {
13523 if (mod && mod.__esModule) return mod;
13525 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
13526 __setModuleDefault(result, mod);
13529 Object.defineProperty(exports, "__esModule", { value: true });
13530 const coc_nvim_1 = __webpack_require__(1);
13531 const is = __importStar(__webpack_require__(126));
13534 if (this._channel) {
13535 return this._channel;
13537 this._channel = coc_nvim_1.workspace.createOutputChannel('tsserver');
13538 return this._channel;
13541 if (this._channel) {
13542 this._channel.dispose();
13545 data2String(data) {
13546 if (data instanceof Error) {
13547 if (is.string(data.stack)) {
13550 return data.message;
13552 if (is.boolean(data.success) && !data.success && is.string(data.message)) {
13553 return data.message;
13555 if (is.string(data)) {
13558 return data.toString();
13560 info(message, data) {
13561 this.logLevel('Info', message, data);
13563 warn(message, data) {
13564 this.logLevel('Warn', message, data);
13566 error(message, data) {
13567 // See https://github.com/Microsoft/TypeScript/issues/10496
13568 if (data && data.message === 'No content available.') {
13571 this.logLevel('Error', message, data);
13573 logLevel(level, message, data) {
13574 this.output.appendLine(`[${level} - ${new Date().toLocaleTimeString()}] ${message}`);
13576 this.output.appendLine(this.data2String(data));
13580 exports.default = Logger;
13585 /***/ (function(module, exports, __webpack_require__) {
13589 /*---------------------------------------------------------------------------------------------
13590 * Copyright (c) Microsoft Corporation. All rights reserved.
13591 * Licensed under the MIT License. See License.txt in the project root for license information.
13592 *--------------------------------------------------------------------------------------------*/
13593 Object.defineProperty(exports, "__esModule", { value: true });
13594 exports.string = exports.boolean = exports.defined = void 0;
13595 const toString = Object.prototype.toString;
13596 function defined(value) {
13597 return typeof value !== 'undefined';
13599 exports.defined = defined;
13600 function boolean(value) {
13601 return value === true || value === false;
13603 exports.boolean = boolean;
13604 function string(value) {
13605 return toString.call(value) === '[object String]';
13607 exports.string = string;
13612 /***/ (function(module, exports, __webpack_require__) {
13616 var __importDefault = (this && this.__importDefault) || function (mod) {
13617 return (mod && mod.__esModule) ? mod : { "default": mod };
13619 Object.defineProperty(exports, "__esModule", { value: true });
13620 exports.fork = exports.getTempFile = exports.getTempDirectory = exports.makeRandomHexString = void 0;
13621 /*---------------------------------------------------------------------------------------------
13622 * Copyright (c) Microsoft Corporation. All rights reserved.
13623 * Licensed under the MIT License. See License.txt in the project root for license information.
13624 *--------------------------------------------------------------------------------------------*/
13625 const child_process_1 = __importDefault(__webpack_require__(113));
13626 const net_1 = __importDefault(__webpack_require__(16));
13627 const os_1 = __importDefault(__webpack_require__(14));
13628 const path_1 = __importDefault(__webpack_require__(13));
13629 const fs_1 = __importDefault(__webpack_require__(118));
13630 function makeRandomHexString(length) {
13631 let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
13633 for (let i = 0; i < length; i++) {
13634 const idx = Math.floor(chars.length * Math.random());
13635 result += chars[idx];
13639 exports.makeRandomHexString = makeRandomHexString;
13640 function getTempDirectory() {
13641 let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`);
13642 if (!fs_1.default.existsSync(dir)) {
13643 fs_1.default.mkdirSync(dir);
13647 exports.getTempDirectory = getTempDirectory;
13648 function generatePipeName() {
13649 return getPipeName(makeRandomHexString(40));
13651 function getPipeName(name) {
13652 const fullName = 'coc-tsc-' + name;
13653 if (process.platform === 'win32') {
13654 return '\\\\.\\pipe\\' + fullName + '-sock';
13656 const tmpdir = getTempDirectory();
13657 // Mac/Unix: use socket file
13658 return path_1.default.join(tmpdir, fullName + '.sock');
13660 function getTempFile(name) {
13661 const fullName = 'coc-nvim-' + name;
13662 return path_1.default.join(getTempDirectory(), fullName + '.sock');
13664 exports.getTempFile = getTempFile;
13665 function generatePatchedEnv(env, stdInPipeName, stdOutPipeName, stdErrPipeName) {
13666 const newEnv = Object.assign({}, env);
13667 // Set the two unique pipe names and the electron flag as process env
13668 newEnv['STDIN_PIPE_NAME'] = stdInPipeName; // tslint:disable-line
13669 newEnv['STDOUT_PIPE_NAME'] = stdOutPipeName; // tslint:disable-line
13670 newEnv['STDERR_PIPE_NAME'] = stdErrPipeName; // tslint:disable-line
13671 newEnv['TSS_LOG'] = `-level verbose -file ${path_1.default.join(os_1.default.tmpdir(), 'coc-nvim-tsc.log')}`; // tslint:disable-line
13672 // Ensure we always have a PATH set
13673 newEnv['PATH'] = newEnv['PATH'] || process.env.PATH; // tslint:disable-line
13676 function fork(modulePath, args, options, logger, callback) {
13677 let callbackCalled = false;
13678 const resolve = (result) => {
13679 if (callbackCalled) {
13682 callbackCalled = true;
13683 callback(null, result);
13685 const reject = (err) => {
13686 if (callbackCalled) {
13689 callbackCalled = true;
13690 callback(err, null);
13692 // Generate three unique pipe names
13693 const stdInPipeName = generatePipeName();
13694 const stdOutPipeName = generatePipeName();
13695 const stdErrPipeName = generatePipeName();
13696 const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName);
13697 newEnv['NODE_PATH'] = path_1.default.join(modulePath, '..', '..', '..'); // tslint:disable-line
13699 // Begin listening to stderr pipe
13700 let stdErrServer = net_1.default.createServer(stdErrStream => {
13701 // From now on the childProcess.stderr is available for reading
13702 childProcess.stderr = stdErrStream;
13704 stdErrServer.listen(stdErrPipeName);
13705 // Begin listening to stdout pipe
13706 let stdOutServer = net_1.default.createServer(stdOutStream => {
13707 // The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe
13708 stdOutStream.once('data', (_chunk) => {
13709 // The child process is sending me the `ready` chunk, time to connect to the stdin pipe
13710 childProcess.stdin = net_1.default.connect(stdInPipeName);
13711 // From now on the childProcess.stdout is available for reading
13712 childProcess.stdout = stdOutStream;
13713 resolve(childProcess);
13716 stdOutServer.listen(stdOutPipeName);
13717 let serverClosed = false;
13718 const closeServer = () => {
13719 if (serverClosed) {
13722 serverClosed = true;
13723 stdOutServer.close();
13724 stdErrServer.close();
13726 // Create the process
13727 logger.info('Forking TSServer', `PATH: ${newEnv['PATH']} `);
13728 const bootstrapperPath = path_1.default.resolve(__dirname, '../bin/tsserverForkStart');
13729 childProcess = child_process_1.default.fork(bootstrapperPath, [modulePath].concat(args), {
13732 execArgv: options.execArgv
13734 childProcess.once('error', (err) => {
13738 childProcess.once('exit', (err) => {
13743 exports.fork = fork;
13748 /***/ (function(module, exports, __webpack_require__) {
13752 Object.defineProperty(exports, "__esModule", { value: true });
13753 /*---------------------------------------------------------------------------------------------
13754 * Copyright (c) Microsoft Corporation. All rights reserved.
13755 * Licensed under the MIT License. See License.txt in the project root for license information.
13756 *--------------------------------------------------------------------------------------------*/
13757 const coc_nvim_1 = __webpack_require__(1);
13759 (function (Trace) {
13760 Trace[Trace["Off"] = 0] = "Off";
13761 Trace[Trace["Messages"] = 1] = "Messages";
13762 Trace[Trace["Verbose"] = 2] = "Verbose";
13763 })(Trace || (Trace = {}));
13764 (function (Trace) {
13765 function fromString(value) {
13766 value = value || '';
13767 value = value.toLowerCase();
13772 return Trace.Messages;
13774 return Trace.Verbose;
13779 Trace.fromString = fromString;
13780 })(Trace || (Trace = {}));
13782 constructor(logger) {
13783 this.logger = logger;
13784 this.trace = Tracer.readTrace();
13786 static readTrace() {
13787 let result = Trace.fromString(coc_nvim_1.workspace.getConfiguration('tsserver').get('trace.server', 'off'));
13788 if (result === Trace.Off && !!process.env.TSS_TRACE) {
13789 result = Trace.Messages;
13793 traceRequest(request, responseExpected, queueLength) {
13794 if (this.trace === Trace.Off)
13797 if (this.trace === Trace.Verbose && request.arguments) {
13798 data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
13800 this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${queueLength}`, data);
13802 traceResponse(response, startTime) {
13803 if (this.trace === Trace.Off) {
13807 if (this.trace === Trace.Verbose && response.body) {
13808 data = `Result: ${JSON.stringify(response.body, null, 4)}`;
13810 this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data);
13812 traceEvent(event) {
13813 if (this.trace === Trace.Off) {
13817 if (this.trace === Trace.Verbose && event.body) {
13818 data = `Data: ${JSON.stringify(event.body, null, 4)}`;
13820 this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
13822 logTrace(message, data) {
13823 if (this.trace !== Trace.Off) {
13824 this.logger.logLevel('Trace', message, data);
13827 traceRequestCompleted(command, request_seq, startTime) {
13828 if (this.trace === Trace.Off) {
13831 this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`);
13834 exports.default = Tracer;
13839 /***/ (function(module, exports, __webpack_require__) {
13843 Object.defineProperty(exports, "__esModule", { value: true });
13844 exports.inferredProjectConfig = void 0;
13845 function inferredProjectConfig(config) {
13847 module: 'commonjs',
13851 if (config.checkJs) {
13852 base.checkJs = true;
13854 if (config.experimentalDecorators) {
13855 base.experimentalDecorators = true;
13859 exports.inferredProjectConfig = inferredProjectConfig;
13864 /***/ (function(module, exports, __webpack_require__) {
13868 var __importDefault = (this && this.__importDefault) || function (mod) {
13869 return (mod && mod.__esModule) ? mod : { "default": mod };
13871 Object.defineProperty(exports, "__esModule", { value: true });
13872 exports.TypeScriptVersionProvider = exports.TypeScriptVersion = void 0;
13873 /*---------------------------------------------------------------------------------------------
13874 * Copyright (c) Microsoft Corporation. All rights reserved.
13875 * Licensed under the MIT License. See License.txt in the project root for license information.
13876 *--------------------------------------------------------------------------------------------*/
13877 const fs_1 = __importDefault(__webpack_require__(118));
13878 const path_1 = __importDefault(__webpack_require__(13));
13879 const coc_nvim_1 = __webpack_require__(1);
13880 const api_1 = __importDefault(__webpack_require__(40));
13881 const requireFunc = true ? require : undefined;
13882 class TypeScriptVersion {
13883 constructor(path, _pathLabel) {
13885 this._pathLabel = _pathLabel;
13889 return path_1.default.resolve(this.path, '../bin/tsc');
13891 get tsServerPath() {
13892 return path_1.default.resolve(this.path, 'tsserver.js');
13895 return typeof this._pathLabel === 'undefined' ? this.path : this._pathLabel;
13898 return this.version != null;
13903 let api = this._api = this.getTypeScriptVersion(this.tsServerPath);
13906 get versionString() {
13907 const version = this.version;
13908 return version ? version.versionString : null;
13910 getTypeScriptVersion(serverPath) {
13911 if (!fs_1.default.existsSync(serverPath)) {
13914 const p = serverPath.split(path_1.default.sep);
13915 if (p.length <= 2) {
13918 const p2 = p.slice(0, -2);
13919 const modulePath = p2.join(path_1.default.sep);
13920 let fileName = path_1.default.join(modulePath, 'package.json');
13921 if (!fs_1.default.existsSync(fileName)) {
13922 // Special case for ts dev versions
13923 if (path_1.default.basename(modulePath) === 'built') {
13924 fileName = path_1.default.join(modulePath, '..', 'package.json');
13927 if (!fs_1.default.existsSync(fileName)) {
13930 const contents = fs_1.default.readFileSync(fileName).toString();
13933 desc = JSON.parse(contents);
13938 if (!desc || !desc.version) {
13941 return desc.version ? api_1.default.fromVersionString(desc.version) : undefined;
13944 exports.TypeScriptVersion = TypeScriptVersion;
13945 const MODULE_FOLDERS = ['node_modules/typescript/lib', '.vscode/pnpify/typescript/lib'];
13946 class TypeScriptVersionProvider {
13947 constructor(configuration) {
13948 this.configuration = configuration;
13950 updateConfiguration(configuration) {
13951 this.configuration = configuration;
13953 getDefaultVersion() {
13954 // tsdk from configuration
13955 let { globalTsdk } = this.configuration;
13957 return new TypeScriptVersion(globalTsdk);
13958 return this.bundledVersion;
13960 get globalVersion() {
13961 let { globalTsdk } = this.configuration;
13963 return new TypeScriptVersion(globalTsdk);
13966 getLocalVersion() {
13967 let folders = coc_nvim_1.workspace.workspaceFolders.map(f => coc_nvim_1.Uri.parse(f.uri).fsPath);
13968 for (let p of folders) {
13969 for (let folder of MODULE_FOLDERS) {
13970 let libFolder = path_1.default.join(p, folder);
13971 if (fs_1.default.existsSync(libFolder)) {
13972 let version = new TypeScriptVersion(libFolder);
13973 if (version.isValid)
13980 get bundledVersion() {
13982 const file = requireFunc.resolve('typescript');
13983 const bundledVersion = new TypeScriptVersion(path_1.default.dirname(file), '');
13984 return bundledVersion;
13987 coc_nvim_1.workspace.showMessage('Bundled typescript module not found', 'error');
13992 exports.TypeScriptVersionProvider = TypeScriptVersionProvider;
13997 /***/ (function(module, exports, __webpack_require__) {
14001 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14002 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14003 return new (P || (P = Promise))(function (resolve, reject) {
14004 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
14005 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
14006 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14007 step((generator = generator.apply(thisArg, _arguments || [])).next());
14010 Object.defineProperty(exports, "__esModule", { value: true });
14011 const coc_nvim_1 = __webpack_require__(1);
14012 class VersionStatus {
14013 constructor(_normalizePath, enableJavascript) {
14014 this._normalizePath = _normalizePath;
14015 this.enableJavascript = enableJavascript;
14016 this._versionBarEntry = coc_nvim_1.workspace.createStatusBarItem(99);
14017 this._onChangeEditorSub = coc_nvim_1.events.on('BufEnter', this.onBufEnter, this);
14018 this._versionBarEntry.show();
14021 this._versionBarEntry.dispose();
14022 this._onChangeEditorSub.dispose();
14024 onDidChangeTypeScriptVersion(_version) {
14025 this._versionBarEntry.text = `TSC`;
14027 set loading(isLoading) {
14028 this._versionBarEntry.isProgress = isLoading;
14030 checkFiletype(filetype) {
14031 if (filetype.startsWith('javascript') && this.enableJavascript) {
14034 return filetype.startsWith('typescript');
14036 onBufEnter(bufnr) {
14037 return __awaiter(this, void 0, void 0, function* () {
14038 let filetype = yield coc_nvim_1.workspace.nvim.call('getbufvar', [bufnr, '&filetype', '']);
14039 if (this.checkFiletype(filetype)) {
14040 this._versionBarEntry.show();
14043 this._versionBarEntry.hide();
14048 exports.default = VersionStatus;
14053 /***/ (function(module, exports, __webpack_require__) {
14057 Object.defineProperty(exports, "__esModule", { value: true });
14058 exports.Reader = void 0;
14059 const DefaultSize = 8192;
14060 const ContentLength = 'Content-Length: ';
14061 const ContentLengthSize = Buffer.byteLength(ContentLength, 'utf8');
14062 const Blank = Buffer.from(' ', 'utf8')[0];
14063 const BackslashR = Buffer.from('\r', 'utf8')[0];
14064 const BackslashN = Buffer.from('\n', 'utf8')[0];
14065 class ProtocolBuffer {
14068 this.buffer = Buffer.allocUnsafe(DefaultSize);
14071 let toAppend = null;
14072 if (Buffer.isBuffer(data)) {
14076 toAppend = Buffer.from(data, 'utf8');
14078 if (this.buffer.length - this.index >= toAppend.length) {
14079 toAppend.copy(this.buffer, this.index, 0, toAppend.length);
14082 let newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) *
14084 if (this.index === 0) {
14085 this.buffer = Buffer.allocUnsafe(newSize);
14086 toAppend.copy(this.buffer, 0, 0, toAppend.length);
14089 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
14092 this.index += toAppend.length;
14094 tryReadContentLength() {
14097 // we are utf8 encoding...
14098 while (current < this.index &&
14099 (this.buffer[current] === Blank ||
14100 this.buffer[current] === BackslashR ||
14101 this.buffer[current] === BackslashN)) {
14104 if (this.index < current + ContentLengthSize) {
14107 current += ContentLengthSize;
14108 let start = current;
14109 while (current < this.index && this.buffer[current] !== BackslashR) {
14112 if (current + 3 >= this.index ||
14113 this.buffer[current + 1] !== BackslashN ||
14114 this.buffer[current + 2] !== BackslashR ||
14115 this.buffer[current + 3] !== BackslashN) {
14118 let data = this.buffer.toString('utf8', start, current);
14119 result = parseInt(data, 10);
14120 this.buffer = this.buffer.slice(current + 4);
14121 this.index = this.index - (current + 4);
14124 tryReadContent(length) {
14125 if (this.index < length) {
14128 let result = this.buffer.toString('utf8', 0, length);
14129 let sourceStart = length;
14130 while (sourceStart < this.index &&
14131 (this.buffer[sourceStart] === BackslashR ||
14132 this.buffer[sourceStart] === BackslashN)) {
14135 this.buffer.copy(this.buffer, 0, sourceStart);
14136 this.index = this.index - sourceStart;
14141 constructor(readable, callback, onError) {
14142 this.readable = readable;
14143 this.callback = callback;
14144 this.onError = onError;
14145 this.buffer = new ProtocolBuffer();
14146 this.nextMessageLength = -1;
14147 this.readable.on('data', (data) => {
14148 this.onLengthData(data);
14151 onLengthData(data) {
14153 this.buffer.append(data);
14155 if (this.nextMessageLength === -1) {
14156 this.nextMessageLength = this.buffer.tryReadContentLength();
14157 if (this.nextMessageLength === -1) {
14161 const msg = this.buffer.tryReadContent(this.nextMessageLength);
14162 if (msg === null) {
14165 this.nextMessageLength = -1;
14166 const json = JSON.parse(msg);
14167 this.callback(json);
14175 exports.Reader = Reader;
14180 /***/ (function(module, exports, __webpack_require__) {
14184 /*---------------------------------------------------------------------------------------------
14185 * Copyright (c) Microsoft Corporation. All rights reserved.
14186 * Licensed under the MIT License. See License.txt in the project root for license information.
14187 *--------------------------------------------------------------------------------------------*/
14188 Object.defineProperty(exports, "__esModule", { value: true });
14189 exports.CallbackMap = void 0;
14190 const typescriptService_1 = __webpack_require__(123);
14191 class CallbackMap {
14193 this._callbacks = new Map();
14194 this._asyncCallbacks = new Map();
14197 const cancellation = new typescriptService_1.ServerResponse.Cancelled(cause);
14198 for (const callback of this._callbacks.values()) {
14199 callback.onSuccess(cancellation);
14201 this._callbacks.clear();
14202 for (const callback of this._asyncCallbacks.values()) {
14203 callback.onSuccess(cancellation);
14205 this._asyncCallbacks.clear();
14207 add(seq, callback, isAsync) {
14209 this._asyncCallbacks.set(seq, callback);
14212 this._callbacks.set(seq, callback);
14216 const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
14221 if (!this._callbacks.delete(seq)) {
14222 this._asyncCallbacks.delete(seq);
14226 exports.CallbackMap = CallbackMap;
14231 /***/ (function(module, exports, __webpack_require__) {
14235 /*---------------------------------------------------------------------------------------------
14236 * Copyright (c) Microsoft Corporation. All rights reserved.
14237 * Licensed under the MIT License. See License.txt in the project root for license information.
14238 *--------------------------------------------------------------------------------------------*/
14239 Object.defineProperty(exports, "__esModule", { value: true });
14240 exports.RequestQueue = exports.RequestQueueingType = void 0;
14241 var RequestQueueingType;
14242 (function (RequestQueueingType) {
14244 * Normal request that is executed in order.
14246 RequestQueueingType[RequestQueueingType["Normal"] = 1] = "Normal";
14248 * Request that normal requests jump in front of in the queue.
14250 RequestQueueingType[RequestQueueingType["LowPriority"] = 2] = "LowPriority";
14252 * A fence that blocks request reordering.
14254 * Fences are not reordered. Unlike a normal request, a fence will never jump in front of a low priority request
14255 * in the request queue.
14257 RequestQueueingType[RequestQueueingType["Fence"] = 3] = "Fence";
14258 })(RequestQueueingType = exports.RequestQueueingType || (exports.RequestQueueingType = {}));
14259 class RequestQueue {
14262 this.sequenceNumber = 0;
14265 return this.queue.length;
14268 if (item.queueingType === RequestQueueingType.Normal) {
14269 let index = this.queue.length - 1;
14270 while (index >= 0) {
14271 if (this.queue[index].queueingType !== RequestQueueingType.LowPriority) {
14276 this.queue.splice(index + 1, 0, item);
14279 // Only normal priority requests can be reordered. All other requests just go to the end.
14280 this.queue.push(item);
14284 return this.queue.shift();
14286 tryDeletePendingRequest(seq) {
14287 for (let i = 0; i < this.queue.length; i++) {
14288 if (this.queue[i].request.seq === seq) {
14289 this.queue.splice(i, 1);
14295 createRequest(command, args) {
14297 seq: this.sequenceNumber++,
14304 exports.RequestQueue = RequestQueue;
14309 /***/ (function(module, exports, __webpack_require__) {
14313 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14314 if (k2 === undefined) k2 = k;
14315 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
14316 }) : (function(o, m, k, k2) {
14317 if (k2 === undefined) k2 = k;
14320 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14321 Object.defineProperty(o, "default", { enumerable: true, value: v });
14322 }) : function(o, v) {
14325 var __importStar = (this && this.__importStar) || function (mod) {
14326 if (mod && mod.__esModule) return mod;
14328 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
14329 __setModuleDefault(result, mod);
14332 var __importDefault = (this && this.__importDefault) || function (mod) {
14333 return (mod && mod.__esModule) ? mod : { "default": mod };
14335 Object.defineProperty(exports, "__esModule", { value: true });
14336 /*---------------------------------------------------------------------------------------------
14337 * Copyright (c) Microsoft Corporation. All rights reserved.
14338 * Licensed under the MIT License. See License.txt in the project root for license information.
14339 *--------------------------------------------------------------------------------------------*/
14340 const coc_nvim_1 = __webpack_require__(1);
14341 const vscode_languageserver_protocol_1 = __webpack_require__(3);
14342 const api_1 = __importDefault(__webpack_require__(40));
14343 const async_1 = __webpack_require__(136);
14344 const typeConverters = __importStar(__webpack_require__(37));
14345 const languageModeIds = __importStar(__webpack_require__(116));
14346 function mode2ScriptKind(mode) {
14348 case languageModeIds.typescript:
14350 case languageModeIds.typescripttsx:
14352 case languageModeIds.typescriptjsx:
14354 case languageModeIds.typescriptreact:
14356 case languageModeIds.javascript:
14358 case languageModeIds.javascriptreact:
14364 * Manages synchronization of buffers with the TS server.
14366 * If supported, batches together file changes. This allows the TS server to more efficiently process changes.
14368 class BufferSynchronizer {
14369 constructor(client) {
14370 this.client = client;
14371 this._pending = {};
14372 this._pendingFiles = new Set();
14375 this.client.executeWithoutWaitingForResponse('open', args);
14378 const args = { file: filepath };
14379 this.client.executeWithoutWaitingForResponse('close', args);
14381 change(filepath, events) {
14382 if (!events.length) {
14385 if (this.supportsBatching) {
14386 this.updatePending(filepath, pending => {
14387 if (!pending.changedFiles) {
14388 pending.changedFiles = [];
14390 pending.changedFiles.push({
14391 fileName: filepath,
14392 textChanges: events.map((change) => ({
14393 newText: change.text,
14394 start: typeConverters.Position.toLocation(change.range.start),
14395 end: typeConverters.Position.toLocation(change.range.end),
14401 for (const event of events) {
14402 const args = Object.assign({ insertString: event.text }, typeConverters.Range.toFormattingRequestArgs(filepath, event.range));
14403 this.client.executeWithoutWaitingForResponse('change', args);
14407 beforeCommand(command) {
14408 if (command === 'updateOpen') {
14414 if (!this.supportsBatching) {
14415 // We've already eagerly synchronized
14418 if (this._pending.changedFiles) {
14419 this.client.executeWithoutWaitingForResponse('updateOpen', this._pending);
14420 this._pending = {};
14421 this._pendingFiles.clear();
14424 get supportsBatching() {
14425 return this.client.apiVersion.gte(api_1.default.v340) && coc_nvim_1.workspace.getConfiguration('tsserver').get('useBatchedBufferSync', true);
14427 updatePending(filepath, f) {
14428 if (this.supportsBatching && this._pendingFiles.has(filepath)) {
14430 this._pendingFiles.clear();
14432 this._pendingFiles.add(filepath);
14439 this._pending = {};
14440 this._pendingFiles.clear();
14443 class BufferSyncSupport {
14444 constructor(client) {
14445 this.uris = new Set();
14446 this.disposables = [];
14447 this.pendingDiagnostics = new Map();
14448 this._validateJavaScript = true;
14449 this._validateTypeScript = true;
14450 this.listening = false;
14451 this._onDelete = new vscode_languageserver_protocol_1.Emitter();
14452 this.onDelete = this._onDelete.event;
14453 this.client = client;
14454 this.synchronizer = new BufferSynchronizer(client);
14455 this.modeIds = new Set(languageModeIds.languageIds);
14456 this.diagnosticDelayer = new async_1.Delayer(300);
14459 if (this.listening) {
14462 this.listening = true;
14463 coc_nvim_1.workspace.onDidOpenTextDocument(this.onDidOpenTextDocument, this, this.disposables);
14464 coc_nvim_1.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, this.disposables);
14465 coc_nvim_1.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, this.disposables);
14466 coc_nvim_1.workspace.textDocuments.forEach(this.onDidOpenTextDocument, this);
14467 this.updateConfiguration();
14468 coc_nvim_1.workspace.onDidChangeConfiguration(this.updateConfiguration, this, this.disposables);
14471 this.pendingDiagnostics.clear();
14472 coc_nvim_1.disposeAll(this.disposables);
14474 onDidOpenTextDocument(document) {
14475 if (!this.modeIds.has(document.languageId))
14477 let { uri } = document;
14478 let filepath = this.client.toPath(uri);
14479 this.uris.add(uri);
14482 fileContent: document.getText()
14484 if (this.client.apiVersion.gte(api_1.default.v203)) {
14485 const scriptKind = mode2ScriptKind(document.languageId);
14487 args.scriptKindName = scriptKind;
14490 if (this.client.apiVersion.gte(api_1.default.v230)) {
14491 let root = this.client.getProjectRootPath(document.uri);
14493 args.projectRootPath = root;
14495 this.synchronizer.open(args);
14496 // this.client.executeWithoutWaitingForResponse('open', args)
14497 this.requestDiagnostic(uri);
14499 onDidCloseTextDocument(document) {
14500 let { uri } = document;
14501 if (!this.uris.has(uri))
14503 let filepath = this.client.toPath(uri);
14504 this.uris.delete(uri);
14505 this.pendingDiagnostics.delete(uri);
14506 this.synchronizer.close(filepath);
14507 this._onDelete.fire(uri);
14508 this.requestAllDiagnostics();
14509 // this.client.executeWithoutWaitingForResponse('close', args)
14511 onDidChangeTextDocument(e) {
14512 let { textDocument, contentChanges } = e;
14513 let { uri } = textDocument;
14514 if (!this.uris.has(uri))
14516 let filepath = this.client.toPath(uri);
14517 this.synchronizer.change(filepath, contentChanges);
14518 const didTrigger = this.requestDiagnostic(uri);
14519 if (!didTrigger && this.pendingGetErr) {
14520 // In this case we always want to re-trigger all diagnostics
14521 this.pendingGetErr.cancel();
14522 this.pendingGetErr = undefined;
14523 this.triggerDiagnostics();
14526 beforeCommand(command) {
14527 this.synchronizer.beforeCommand(command);
14529 interuptGetErr(f) {
14530 if (!this.pendingGetErr) {
14533 this.pendingGetErr.cancel();
14534 this.pendingGetErr = undefined;
14535 const result = f();
14536 this.triggerDiagnostics();
14539 getErr(resources) {
14540 const handledResources = resources.filter(resource => this.uris.has(resource.toString()));
14541 if (!handledResources.length) {
14544 for (const resource of handledResources) {
14545 let uri = resource.toString();
14546 if (this.shouldValidate(uri)) {
14547 this.pendingDiagnostics.set(uri, Date.now());
14550 this.triggerDiagnostics();
14553 return this.uris.has(uri);
14555 triggerDiagnostics(delay = 200) {
14556 this.diagnosticDelayer.trigger(() => {
14557 this.sendPendingDiagnostics();
14560 requestAllDiagnostics() {
14561 for (const uri of this.uris) {
14562 if (this.shouldValidate(uri)) {
14563 this.pendingDiagnostics.set(uri, Date.now());
14566 this.diagnosticDelayer.trigger(() => {
14567 this.sendPendingDiagnostics();
14570 requestDiagnostic(uri) {
14571 let document = coc_nvim_1.workspace.getDocument(uri);
14572 if (!document || !this.shouldValidate(uri))
14574 this.pendingDiagnostics.set(uri, Date.now());
14575 const lineCount = document.lineCount;
14576 const delay = Math.min(Math.max(Math.ceil(lineCount / 20), 300), 800);
14577 this.triggerDiagnostics(delay);
14580 hasPendingDiagnostics(uri) {
14581 return this.pendingDiagnostics.has(uri);
14583 sendPendingDiagnostics() {
14584 const uris = Array.from(this.pendingDiagnostics.entries())
14585 .sort((a, b) => a[1] - b[1])
14586 .map(entry => entry[0]);
14587 // Add all open TS buffers to the geterr request. They might be visible
14588 for (const uri of this.uris) {
14589 if (uris.indexOf(uri) == -1) {
14593 let files = uris.map(uri => this.client.toPath(uri));
14594 if (files.length) {
14595 if (this.pendingGetErr)
14596 this.pendingGetErr.cancel();
14597 const getErr = this.pendingGetErr = GetErrRequest.executeGetErrRequest(this.client, files, () => {
14598 if (this.pendingGetErr === getErr) {
14599 this.pendingGetErr = undefined;
14603 this.pendingDiagnostics.clear();
14605 updateConfiguration() {
14606 const jsConfig = coc_nvim_1.workspace.getConfiguration('javascript', null);
14607 const tsConfig = coc_nvim_1.workspace.getConfiguration('typescript', null);
14608 this._validateJavaScript = jsConfig.get('validate.enable', true);
14609 this._validateTypeScript = tsConfig.get('validate.enable', true);
14611 shouldValidate(uri) {
14612 let doc = coc_nvim_1.workspace.getDocument(uri);
14615 if (languageModeIds.languageIds.indexOf(doc.filetype) == -1) {
14618 if (doc.filetype.startsWith('javascript')) {
14619 return this._validateJavaScript;
14621 return this._validateTypeScript;
14625 this.pendingDiagnostics.clear();
14626 (_a = this.pendingGetErr) === null || _a === void 0 ? void 0 : _a.cancel();
14627 this.synchronizer.reset();
14628 for (let doc of coc_nvim_1.workspace.documents) {
14629 this.onDidOpenTextDocument(doc.textDocument);
14633 exports.default = BufferSyncSupport;
14634 class GetErrRequest {
14635 constructor(client, files, _token, onDone) {
14636 this.files = files;
14637 this._token = _token;
14638 this._done = false;
14643 const done = () => {
14650 client.executeAsync('geterr', args, _token.token).then(done, done);
14652 static executeGetErrRequest(client, files, onDone) {
14653 const token = new vscode_languageserver_protocol_1.CancellationTokenSource();
14654 return new GetErrRequest(client, files, token, onDone);
14658 this._token.cancel();
14660 this._token.dispose();
14667 /***/ (function(module, exports, __webpack_require__) {
14671 Object.defineProperty(exports, "__esModule", { value: true });
14672 exports.Delayer = void 0;
14674 constructor(defaultDelay) {
14675 this.defaultDelay = defaultDelay;
14676 this.timeout = null;
14677 this.completionPromise = null;
14678 this.onSuccess = null;
14681 trigger(task, delay = this.defaultDelay) {
14684 this.cancelTimeout();
14686 if (!this.completionPromise) {
14687 this.completionPromise = new Promise(resolve => {
14688 this.onSuccess = resolve;
14690 this.completionPromise = null;
14691 this.onSuccess = null;
14692 let result = this.task && this.task();
14697 if (delay >= 0 || this.timeout === null) {
14698 this.timeout = setTimeout(() => {
14699 this.timeout = null;
14700 if (this.onSuccess) {
14701 this.onSuccess(undefined);
14703 }, delay >= 0 ? delay : this.defaultDelay);
14705 return this.completionPromise;
14708 if (this.timeout !== null) {
14709 clearTimeout(this.timeout);
14710 this.timeout = null;
14714 exports.Delayer = Delayer;
14719 /***/ (function(module, exports, __webpack_require__) {
14723 Object.defineProperty(exports, "__esModule", { value: true });
14724 exports.DiagnosticsManager = exports.DiagnosticKind = exports.DiagnosticSet = void 0;
14725 const coc_nvim_1 = __webpack_require__(1);
14726 const resourceMap_1 = __webpack_require__(138);
14727 class DiagnosticSet {
14729 this._map = new resourceMap_1.ResourceMap();
14731 set(uri, diagnostics) {
14732 this._map.set(uri, diagnostics);
14735 return this._map.get(uri) || [];
14738 this._map = new resourceMap_1.ResourceMap();
14741 exports.DiagnosticSet = DiagnosticSet;
14742 var DiagnosticKind;
14743 (function (DiagnosticKind) {
14744 DiagnosticKind[DiagnosticKind["Syntax"] = 0] = "Syntax";
14745 DiagnosticKind[DiagnosticKind["Semantic"] = 1] = "Semantic";
14746 DiagnosticKind[DiagnosticKind["Suggestion"] = 2] = "Suggestion";
14747 })(DiagnosticKind = exports.DiagnosticKind || (exports.DiagnosticKind = {}));
14748 const allDiagnosticKinds = [
14749 DiagnosticKind.Syntax,
14750 DiagnosticKind.Semantic,
14751 DiagnosticKind.Suggestion
14753 class DiagnosticsManager {
14755 this._diagnostics = new Map();
14756 this._pendingUpdates = new resourceMap_1.ResourceMap();
14757 this._enableJavascriptSuggestions = true;
14758 this._enableTypescriptSuggestions = true;
14759 this.updateDelay = 200;
14760 for (const kind of allDiagnosticKinds) {
14761 this._diagnostics.set(kind, new DiagnosticSet());
14763 this._currentDiagnostics = coc_nvim_1.languages.createDiagnosticCollection('tsserver');
14766 this._currentDiagnostics.dispose();
14767 for (const value of this._pendingUpdates.values) {
14768 clearTimeout(value);
14770 this._pendingUpdates = new resourceMap_1.ResourceMap();
14773 this._currentDiagnostics.clear();
14774 for (const diagnosticSet of this._diagnostics.values()) {
14775 diagnosticSet.clear();
14778 setEnableSuggestions(languageId, value) {
14779 let curr = languageId == 'javascript' ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions;
14780 if (curr == value) {
14783 if (languageId == 'javascript') {
14784 this._enableJavascriptSuggestions = value;
14787 this._enableTypescriptSuggestions = value;
14790 diagnosticsReceived(kind, uri, diagnostics) {
14791 const collection = this._diagnostics.get(kind);
14794 if (diagnostics.length === 0) {
14795 const existing = collection.get(uri);
14796 if (existing.length === 0) {
14797 // No need to update
14801 collection.set(uri, diagnostics);
14802 this.scheduleDiagnosticsUpdate(uri);
14804 configFileDiagnosticsReceived(uri, diagnostics) {
14805 this._currentDiagnostics.set(uri, diagnostics);
14808 this._currentDiagnostics.delete(uri);
14810 getDiagnostics(uri) {
14811 return this._currentDiagnostics.get(uri) || [];
14814 scheduleDiagnosticsUpdate(uri) {
14815 if (!this._pendingUpdates.has(uri)) {
14816 this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay));
14819 updateCurrentDiagnostics(uri) {
14820 if (this._pendingUpdates.has(uri)) {
14821 clearTimeout(this._pendingUpdates.get(uri));
14822 this._pendingUpdates.delete(uri);
14824 const allDiagnostics = [
14825 ...this._diagnostics.get(DiagnosticKind.Syntax).get(uri),
14826 ...this._diagnostics.get(DiagnosticKind.Semantic).get(uri),
14827 ...this.getSuggestionDiagnostics(uri)
14829 this._currentDiagnostics.set(uri, allDiagnostics);
14831 getSuggestionDiagnostics(uri) {
14832 const enabled = this.suggestionsEnabled(uri);
14833 return this._diagnostics
14834 .get(DiagnosticKind.Suggestion)
14838 // Still show unused
14839 return x.code == 6133;
14844 suggestionsEnabled(uri) {
14845 let doc = coc_nvim_1.workspace.getDocument(uri);
14848 if (doc.filetype.startsWith('javascript')) {
14849 return this._enableJavascriptSuggestions;
14851 if (doc.filetype.startsWith('typescript')) {
14852 return this._enableTypescriptSuggestions;
14857 exports.DiagnosticsManager = DiagnosticsManager;
14862 /***/ (function(module, exports, __webpack_require__) {
14866 /*---------------------------------------------------------------------------------------------
14867 * Copyright (c) Microsoft Corporation. All rights reserved.
14868 * Licensed under the MIT License. See License.txt in the project root for license information.
14869 *--------------------------------------------------------------------------------------------*/
14870 Object.defineProperty(exports, "__esModule", { value: true });
14871 exports.isWindowsPath = exports.ResourceMap = void 0;
14873 * Maps of file resources
14875 * Attempts to handle correct mapping on both case sensitive and case in-sensitive
14878 class ResourceMap {
14879 constructor(_normalizePath) {
14880 this._normalizePath = _normalizePath;
14881 this._map = new Map();
14884 const file = this.toKey(resource);
14885 return !!file && this._map.has(file);
14888 const file = this.toKey(resource);
14889 return file ? this._map.get(file) : undefined;
14891 set(resource, value) {
14892 const file = this.toKey(resource);
14894 this._map.set(file, value);
14898 const file = this.toKey(resource);
14900 this._map.delete(file);
14904 return this._map.values();
14907 return this._map.keys();
14910 const key = this._normalizePath
14911 ? this._normalizePath(resource)
14916 return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
14918 isCaseInsensitivePath(path) {
14919 if (isWindowsPath(path)) {
14922 return path[0] === '/' && this.onIsCaseInsenitiveFileSystem;
14924 get onIsCaseInsenitiveFileSystem() {
14925 if (process.platform === 'win32') {
14928 if (process.platform === 'darwin') {
14934 exports.ResourceMap = ResourceMap;
14935 function isWindowsPath(path) {
14936 return /^[a-zA-Z]:\\/.test(path);
14938 exports.isWindowsPath = isWindowsPath;
14943 /***/ (function(module, exports, __webpack_require__) {
14947 Object.defineProperty(exports, "__esModule", { value: true });
14948 exports.AtaProgressReporter = void 0;
14949 /*---------------------------------------------------------------------------------------------
14950 * Copyright (c) Microsoft Corporation. All rights reserved.
14951 * Licensed under the MIT License. See License.txt in the project root for license information.
14952 *--------------------------------------------------------------------------------------------*/
14953 const vscode_languageserver_protocol_1 = __webpack_require__(3);
14954 const coc_nvim_1 = __webpack_require__(1);
14955 const typingsInstallTimeout = 30 * 1000;
14956 class TypingsStatus {
14957 constructor(client) {
14958 this._acquiringTypings = Object.create({});
14959 this._subscriptions = [];
14960 this._client = client;
14961 this._subscriptions.push(this._client.onDidBeginInstallTypings(event => this.onBeginInstallTypings(event.eventId)));
14962 this._subscriptions.push(this._client.onDidEndInstallTypings(event => this.onEndInstallTypings(event.eventId)));
14965 this._subscriptions.forEach(x => x.dispose());
14966 for (const eventId of Object.keys(this._acquiringTypings)) {
14967 clearTimeout(this._acquiringTypings[eventId]);
14970 get isAcquiringTypings() {
14971 return Object.keys(this._acquiringTypings).length > 0;
14973 onBeginInstallTypings(eventId) {
14974 if (this._acquiringTypings[eventId]) {
14977 this._acquiringTypings[eventId] = setTimeout(() => {
14978 this.onEndInstallTypings(eventId);
14979 }, typingsInstallTimeout);
14981 onEndInstallTypings(eventId) {
14982 const timer = this._acquiringTypings[eventId];
14984 clearTimeout(timer);
14986 delete this._acquiringTypings[eventId];
14989 exports.default = TypingsStatus;
14990 class AtaProgressReporter {
14991 constructor(client) {
14992 this._promises = new Map();
14993 this._invalid = false;
14994 this.statusItem = coc_nvim_1.workspace.createStatusBarItem(10, { progress: true });
14995 const disposables = [];
14996 disposables.push(client.onDidBeginInstallTypings(e => this._onBegin(e.eventId)));
14997 disposables.push(client.onDidEndInstallTypings(e => this._onEndOrTimeout(e.eventId)));
14998 disposables.push(client.onTypesInstallerInitializationFailed(_ => this.onTypesInstallerInitializationFailed()));
14999 this._disposable = vscode_languageserver_protocol_1.Disposable.create(() => {
15000 disposables.forEach(disposable => {
15001 disposable.dispose();
15006 this._disposable.dispose();
15007 this._promises.forEach(value => value());
15009 _onBegin(eventId) {
15010 const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout);
15011 new Promise(resolve => {
15012 this._promises.set(eventId, () => {
15013 clearTimeout(handle);
15017 this.statusItem.text = 'Fetching data for better TypeScript IntelliSense';
15018 this.statusItem.show();
15020 _onEndOrTimeout(eventId) {
15021 this.statusItem.hide();
15022 const resolve = this._promises.get(eventId);
15024 this._promises.delete(eventId);
15028 onTypesInstallerInitializationFailed() {
15029 this.statusItem.hide();
15030 if (!this._invalid) {
15031 coc_nvim_1.workspace.showMessage('Could not install typings files for JavaScript language features. Please ensure that NPM is installed', 'error');
15033 this._invalid = true;
15036 exports.AtaProgressReporter = AtaProgressReporter;
15041 /***/ (function(module, exports, __webpack_require__) {
15045 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15046 if (k2 === undefined) k2 = k;
15047 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
15048 }) : (function(o, m, k, k2) {
15049 if (k2 === undefined) k2 = k;
15052 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15053 Object.defineProperty(o, "default", { enumerable: true, value: v });
15054 }) : function(o, v) {
15057 var __importStar = (this && this.__importStar) || function (mod) {
15058 if (mod && mod.__esModule) return mod;
15060 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
15061 __setModuleDefault(result, mod);
15064 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
15065 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15066 return new (P || (P = Promise))(function (resolve, reject) {
15067 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
15068 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
15069 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
15070 step((generator = generator.apply(thisArg, _arguments || [])).next());
15073 Object.defineProperty(exports, "__esModule", { value: true });
15074 exports.ConfigurePluginCommand = exports.AutoFixCommand = exports.TypeScriptGoToProjectConfigCommand = exports.OpenTsServerLogCommand = exports.ReloadProjectsCommand = void 0;
15075 const coc_nvim_1 = __webpack_require__(1);
15076 const vscode_languageserver_protocol_1 = __webpack_require__(3);
15077 const typeConverters = __importStar(__webpack_require__(37));
15078 const vscode_languageserver_types_1 = __webpack_require__(18);
15079 const modules_1 = __webpack_require__(112);
15080 const helper_1 = __webpack_require__(100);
15081 const languageModeIds_1 = __webpack_require__(116);
15082 class ReloadProjectsCommand {
15083 constructor(client) {
15084 this.client = client;
15085 this.id = 'tsserver.reloadProjects';
15088 this.client.reloadProjects();
15089 coc_nvim_1.workspace.showMessage('projects reloaded');
15092 exports.ReloadProjectsCommand = ReloadProjectsCommand;
15093 class OpenTsServerLogCommand {
15094 constructor(client) {
15095 this.client = client;
15096 this.id = 'tsserver.openTsServerLog';
15099 this.client.serviceClient.openTsServerLogFile(); // tslint:disable-line
15102 exports.OpenTsServerLogCommand = OpenTsServerLogCommand;
15103 class TypeScriptGoToProjectConfigCommand {
15104 constructor(client) {
15105 this.client = client;
15106 this.id = 'tsserver.goToProjectConfig';
15109 return __awaiter(this, void 0, void 0, function* () {
15110 let doc = yield coc_nvim_1.workspace.document;
15111 let { filetype } = doc;
15112 if (languageModeIds_1.languageIds.indexOf(filetype) == -1) {
15113 coc_nvim_1.workspace.showMessage(`Could not determine TypeScript or JavaScript project. Unsupported file type: ${filetype}`, 'warning');
15117 yield goToProjectConfig(this.client, doc.uri);
15121 exports.TypeScriptGoToProjectConfigCommand = TypeScriptGoToProjectConfigCommand;
15122 function goToProjectConfig(clientHost, uri) {
15123 return __awaiter(this, void 0, void 0, function* () {
15124 const client = clientHost.serviceClient;
15125 const file = client.toPath(uri);
15128 res = yield client.execute('projectInfo', { file, needFileNameList: false }, vscode_languageserver_protocol_1.CancellationToken.None);
15133 if (!res || !res.body) {
15134 coc_nvim_1.workspace.showMessage('Could not determine TypeScript or JavaScript project.', 'warning');
15137 const { configFileName } = res.body;
15138 if (configFileName && !isImplicitProjectConfigFile(configFileName)) {
15139 yield coc_nvim_1.workspace.openResource(coc_nvim_1.Uri.file(configFileName).toString());
15142 coc_nvim_1.workspace.showMessage('Config file not found', 'warning');
15145 function isImplicitProjectConfigFile(configFileName) {
15146 return configFileName.indexOf('/dev/null/') === 0;
15148 const autoFixableDiagnosticCodes = new Set([
15153 class AutoFixCommand {
15154 constructor(client) {
15155 this.client = client;
15156 this.id = 'tsserver.executeAutofix';
15159 return __awaiter(this, void 0, void 0, function* () {
15160 let document = yield coc_nvim_1.workspace.document;
15161 let { uri } = document;
15162 if (!this.client.handles(uri)) {
15163 coc_nvim_1.workspace.showMessage(`Document ${uri} is not handled by tsserver.`, 'warning');
15166 let file = this.client.serviceClient.toPath(document.uri);
15167 let diagnostics = coc_nvim_1.diagnosticManager.getDiagnostics(document.uri);
15168 let missingDiagnostics = diagnostics.filter(o => o.code == 2307);
15169 if (missingDiagnostics.length) {
15170 let names = missingDiagnostics.map(o => {
15171 let ms = o.message.match(/module\s'(.+)'\./);
15172 return ms ? ms[1] : null;
15174 names = names.filter(s => s != null);
15175 if (names.length) {
15176 modules_1.installModules(document.uri, names).catch(e => {
15177 console.error(e.message); // tslint:disable-line
15181 diagnostics = diagnostics.filter(x => autoFixableDiagnosticCodes.has(x.code));
15182 if (diagnostics.length == 0)
15184 diagnostics = diagnostics.reduce((arr, curr) => {
15185 if (curr.code == 2304 && arr.findIndex(o => o.message == curr.message) != -1)
15190 let client = this.client.serviceClient;
15194 for (let diagnostic of diagnostics) {
15195 const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+(diagnostic.code)] });
15196 const response = yield client.execute('getCodeFixes', args, vscode_languageserver_protocol_1.CancellationToken.None);
15197 if (response.type !== 'response' || !response.body || response.body.length < 1) {
15198 if (diagnostic.code == 2304) {
15199 let { range } = diagnostic;
15200 let line = document.getline(range.start.line);
15201 let name = line.slice(range.start.character, range.end.character);
15202 if (helper_1.nodeModules.indexOf(name) !== -1 && names.indexOf(name) == -1) {
15205 range: vscode_languageserver_types_1.Range.create(0, 0, 0, 0),
15206 newText: `import ${name} from '${name}'\n`
15208 command = 'tsserver.organizeImports';
15213 const fix = response.body[0];
15214 for (let change of fix.changes) {
15215 if (change.fileName != file)
15218 for (let ch of change.textChanges) {
15220 range: typeConverters.Range.fromTextSpan(ch),
15221 newText: ch.newText
15227 yield document.applyEdits(coc_nvim_1.workspace.nvim, edits);
15229 coc_nvim_1.commands.executeCommand(command);
15233 exports.AutoFixCommand = AutoFixCommand;
15234 class ConfigurePluginCommand {
15235 constructor(pluginManager) {
15236 this.pluginManager = pluginManager;
15237 this.id = '_typescript.configurePlugin';
15239 execute(pluginId, configuration) {
15240 this.pluginManager.setConfiguration(pluginId, configuration);
15243 exports.ConfigurePluginCommand = ConfigurePluginCommand;
15248 /***/ (function(module, exports, __webpack_require__) {
15252 /*---------------------------------------------------------------------------------------------
15253 * Copyright (c) Microsoft Corporation. All rights reserved.
15254 * Licensed under the MIT License. See License.txt in the project root for license information.
15255 *--------------------------------------------------------------------------------------------*/
15256 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15257 if (k2 === undefined) k2 = k;
15258 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
15259 }) : (function(o, m, k, k2) {
15260 if (k2 === undefined) k2 = k;
15263 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15264 Object.defineProperty(o, "default", { enumerable: true, value: v });
15265 }) : function(o, v) {
15268 var __importStar = (this && this.__importStar) || function (mod) {
15269 if (mod && mod.__esModule) return mod;
15271 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
15272 __setModuleDefault(result, mod);
15275 Object.defineProperty(exports, "__esModule", { value: true });
15276 exports.PluginManager = void 0;
15277 const coc_nvim_1 = __webpack_require__(1);
15278 const arrays = __importStar(__webpack_require__(91));
15279 const vscode_languageserver_protocol_1 = __webpack_require__(3);
15280 var TypeScriptServerPlugin;
15281 (function (TypeScriptServerPlugin) {
15282 function equals(a, b) {
15283 return a.path === b.path
15284 && a.name === b.name
15285 && a.enableForWorkspaceTypeScriptVersions === b.enableForWorkspaceTypeScriptVersions
15286 && arrays.equals(a.languages, b.languages);
15288 TypeScriptServerPlugin.equals = equals;
15289 })(TypeScriptServerPlugin || (TypeScriptServerPlugin = {}));
15290 class PluginManager {
15292 this._pluginConfigurations = new Map();
15293 this._disposables = [];
15294 this._onDidUpdatePlugins = this._register(new vscode_languageserver_protocol_1.Emitter());
15295 this.onDidChangePlugins = this._onDidUpdatePlugins.event;
15296 this._onDidUpdateConfig = this._register(new vscode_languageserver_protocol_1.Emitter());
15297 this.onDidUpdateConfig = this._onDidUpdateConfig.event;
15298 let loadPlugins = () => {
15299 if (!this._plugins) {
15302 const newPlugins = this.readPlugins();
15303 if (!arrays.equals(arrays.flatten(Array.from(this._plugins.values())), arrays.flatten(Array.from(newPlugins.values())), TypeScriptServerPlugin.equals)) {
15304 this._plugins = newPlugins;
15305 this._onDidUpdatePlugins.fire(this);
15308 coc_nvim_1.extensions.onDidActiveExtension(loadPlugins, undefined, this._disposables);
15309 coc_nvim_1.extensions.onDidUnloadExtension(loadPlugins, undefined, this._disposables);
15312 coc_nvim_1.disposeAll(this._disposables);
15315 if (!this._plugins) {
15316 this._plugins = this.readPlugins();
15318 return arrays.flatten(Array.from(this._plugins.values()));
15321 this._disposables.push(value);
15324 setConfiguration(pluginId, config) {
15325 this._pluginConfigurations.set(pluginId, config);
15326 this._onDidUpdateConfig.fire({ pluginId, config });
15329 return this._pluginConfigurations.entries();
15332 const pluginMap = new Map();
15333 for (const extension of coc_nvim_1.extensions.all) {
15334 const pack = extension.packageJSON;
15335 if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
15336 const plugins = [];
15337 for (const plugin of pack.contributes.typescriptServerPlugins) {
15340 enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
15341 path: extension.extensionPath,
15342 languages: Array.isArray(plugin.languages) ? plugin.languages : [],
15345 if (plugins.length) {
15346 pluginMap.set(extension.id, plugins);
15353 exports.PluginManager = PluginManager;